@turbobase/cli 1.33.0 → 1.34.1

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,49 +1,49 @@
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 kT=Object.create;var wl=Object.defineProperty;var ST=Object.getOwnPropertyDescriptor;var $T=Object.getOwnPropertyNames;var TT=Object.getPrototypeOf,RT=Object.prototype.hasOwnProperty;var Yo=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var B=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Xo=(t,e)=>{for(var r in e)wl(t,r,{get:e[r],enumerable:!0})},ET=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $T(e))!RT.call(t,o)&&o!==r&&wl(t,o,{get:()=>e[o],enumerable:!(n=ST(e,o))||n.enumerable});return t};var _l=(t,e,r)=>(r=t!=null?kT(TT(t)):{},ET(e||!t||!t.__esModule?wl(r,"default",{value:t,enumerable:!0}):r,t));var Qo=B(xl=>{var Pi=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}},vl=class extends Pi{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};xl.CommanderError=Pi;xl.InvalidArgumentError=vl});var Ai=B(Sl=>{var{InvalidArgumentError:PT}=Qo(),kl=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 PT(`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 AT(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Sl.Argument=kl;Sl.humanReadableArgName=AT});var Tl=B(fg=>{var{humanReadableArgName:CT}=Ai(),$l=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=>CT(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,w){if(w){let S=`${m.padEnd(n+i)}${w}`;return r.wrap(S,o-s,n+i)}return m}function c(m){return m.join(`
5
- `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,o,0),""]));let p=r.visibleArguments(e).map(m=>a(r.argumentTerm(m),r.argumentDescription(m)));p.length>0&&(l=l.concat(["Arguments:",c(p),""]));let y=r.visibleOptions(e).map(m=>a(r.optionTerm(m),r.optionDescription(m)));if(y.length>0&&(l=l.concat(["Options:",c(y),""])),this.showGlobalOptions){let m=r.visibleGlobalOptions(e).map(w=>a(r.optionTerm(w),r.optionDescription(w)));m.length>0&&(l=l.concat(["Global Options:",c(m),""]))}let h=r.visibleCommands(e).map(m=>a(r.subcommandTerm(m),r.subcommandDescription(m)));return h.length>0&&(l=l.concat(["Commands:",c(h),""])),l.join(`
4
+ var zT=Object.create;var vl=Object.defineProperty;var LT=Object.getOwnPropertyDescriptor;var jT=Object.getOwnPropertyNames;var DT=Object.getPrototypeOf,MT=Object.prototype.hasOwnProperty;var Qo=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var O=(t,e)=>()=>(t&&(e=t(t=0)),e);var F=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),es=(t,e)=>{for(var r in e)vl(t,r,{get:e[r],enumerable:!0})},UT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of jT(e))!MT.call(t,o)&&o!==r&&vl(t,o,{get:()=>e[o],enumerable:!(n=LT(e,o))||n.enumerable});return t};var xl=(t,e,r)=>(r=t!=null?zT(DT(t)):{},UT(e||!t||!t.__esModule?vl(r,"default",{value:t,enumerable:!0}):r,t));var ts=F(Sl=>{var Ci=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}},kl=class extends Ci{constructor(e){super(1,"commander.invalidArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Sl.CommanderError=Ci;Sl.InvalidArgumentError=kl});var Ii=F(Tl=>{var{InvalidArgumentError:qT}=ts(),$l=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 qT(`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 BT(t){let e=t.name()+(t.variadic===!0?"...":"");return t.required?"<"+e+">":"["+e+"]"}Tl.Argument=$l;Tl.humanReadableArgName=BT});var El=F(bg=>{var{humanReadableArgName:FT}=Ii(),Rl=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=>FT(n)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(r?" "+r:"")}optionTerm(e){return e.flags}argumentTerm(e){return e.name()}longestSubcommandTermLength(e,r){return r.visibleCommands(e).reduce((n,o)=>Math.max(n,r.subcommandTerm(o).length),0)}longestOptionTermLength(e,r){return r.visibleOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestGlobalOptionTermLength(e,r){return r.visibleGlobalOptions(e).reduce((n,o)=>Math.max(n,r.optionTerm(o).length),0)}longestArgumentTermLength(e,r){return r.visibleArguments(e).reduce((n,o)=>Math.max(n,r.argumentTerm(o).length),0)}commandUsage(e){let r=e._name;e._aliases[0]&&(r=r+"|"+e._aliases[0]);let n="";for(let o=e.parent;o;o=o.parent)n=o.name()+" "+n;return n+r+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.summary()||e.description()}optionDescription(e){let r=[];return e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&(e.required||e.optional||e.isBoolean()&&typeof e.defaultValue=="boolean")&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),e.presetArg!==void 0&&e.optional&&r.push(`preset: ${JSON.stringify(e.presetArg)}`),e.envVar!==void 0&&r.push(`env: ${e.envVar}`),r.length>0?`${e.description} (${r.join(", ")})`:e.description}argumentDescription(e){let r=[];if(e.argChoices&&r.push(`choices: ${e.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),e.defaultValue!==void 0&&r.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),r.length>0){let n=`(${r.join(", ")})`;return e.description?`${e.description} ${n}`:n}return e.description}formatHelp(e,r){let n=r.padWidth(e,r),o=r.helpWidth||80,s=2,i=2;function a(h,w){if(w){let S=`${h.padEnd(n+i)}${w}`;return r.wrap(S,o-s,n+i)}return h}function c(h){return h.join(`
5
+ `).replace(/^/gm," ".repeat(s))}let l=[`Usage: ${r.commandUsage(e)}`,""],u=r.commandDescription(e);u.length>0&&(l=l.concat([r.wrap(u,o,0),""]));let p=r.visibleArguments(e).map(h=>a(r.argumentTerm(h),r.argumentDescription(h)));p.length>0&&(l=l.concat(["Arguments:",c(p),""]));let b=r.visibleOptions(e).map(h=>a(r.optionTerm(h),r.optionDescription(h)));if(b.length>0&&(l=l.concat(["Options:",c(b),""])),this.showGlobalOptions){let h=r.visibleGlobalOptions(e).map(w=>a(r.optionTerm(w),r.optionDescription(w)));h.length>0&&(l=l.concat(["Global Options:",c(h),""]))}let m=r.visibleCommands(e).map(h=>a(r.subcommandTerm(h),r.subcommandDescription(h)));return m.length>0&&(l=l.concat(["Commands:",c(m),""])),l.join(`
6
6
  `)}padWidth(e,r){return Math.max(r.longestOptionTermLength(e,r),r.longestGlobalOptionTermLength(e,r),r.longestSubcommandTermLength(e,r),r.longestArgumentTermLength(e,r))}wrap(e,r,n,o=40){let s=" \\f\\t\\v\xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF",i=new RegExp(`[\\n][${s}]+`);if(e.match(i))return e;let a=r-n;if(a<o)return e;let c=e.slice(0,n),l=e.slice(n).replace(`\r
7
7
  `,`
8
- `),u=" ".repeat(n),y="\\s\u200B",h=new RegExp(`
9
- |.{1,${a-1}}([${y}]|$)|[^${y}]+?([${y}]|$)`,"g"),m=l.match(h)||[];return c+m.map((w,S)=>w===`
8
+ `),u=" ".repeat(n),b="\\s\u200B",m=new RegExp(`
9
+ |.{1,${a-1}}([${b}]|$)|[^${b}]+?([${b}]|$)`,"g"),h=l.match(m)||[];return c+h.map((w,S)=>w===`
10
10
  `?"":(S>0?u:"")+w.trimEnd()).join(`
11
- `)}};fg.Help=$l});var Pl=B(Ci=>{var{InvalidArgumentError:IT}=Qo(),Rl=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=gg(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 IT(`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 OT(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},El=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 OT(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function gg(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}}Ci.Option=Rl;Ci.splitOptionFlags=gg;Ci.DualOptions=El});var bg=B(yg=>{function NT(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 zT(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=NT(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
+ `)}};bg.Help=Rl});var Cl=F(Oi=>{var{InvalidArgumentError:ZT}=ts(),Pl=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=wg(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 ZT(`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 VT(this.name().replace(/^no-/,""))}is(e){return this.short===e||this.long===e}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Al=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 VT(t){return t.split("-").reduce((e,r)=>e+r[0].toUpperCase()+r.slice(1))}function wg(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}}Oi.Option=Pl;Oi.splitOptionFlags=wg;Oi.DualOptions=Al});var vg=F(_g=>{function HT(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 KT(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=HT(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]}?)`:""}yg.suggestSimilar=zT});var Sg=B(kg=>{var LT=Yo("events").EventEmitter,Al=Yo("child_process"),Sr=Yo("path"),Cl=Yo("fs"),Ue=Yo("process"),{Argument:jT,humanReadableArgName:DT}=Ai(),{CommanderError:Il}=Qo(),{Help:MT}=Tl(),{Option:wg,splitOptionFlags:UT,DualOptions:qT}=Pl(),{suggestSimilar:_g}=bg(),Ol=class t extends LT{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=e||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._outputConfiguration={writeOut:r=>Ue.stdout.write(r),writeErr:r=>Ue.stderr.write(r),getOutHelpWidth:()=>Ue.stdout.isTTY?Ue.stdout.columns:void 0,getErrHelpWidth:()=>Ue.stderr.isTTY?Ue.stderr.columns:void 0,outputError:(r,n)=>n(r)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}copyInheritedSettings(e){return this._outputConfiguration=e._outputConfiguration,this._hasHelpOption=e._hasHelpOption,this._helpFlags=e._helpFlags,this._helpDescription=e._helpDescription,this._helpShortFlag=e._helpShortFlag,this._helpLongFlag=e._helpLongFlag,this._helpCommandName=e._helpCommandName,this._helpCommandnameAndArgs=e._helpCommandnameAndArgs,this._helpCommandDescription=e._helpCommandDescription,this._helpConfiguration=e._helpConfiguration,this._exitCallback=e._exitCallback,this._storeOptionsAsProperties=e._storeOptionsAsProperties,this._combineFlagAndOptionalValue=e._combineFlagAndOptionalValue,this._allowExcessArguments=e._allowExcessArguments,this._enablePositionalOptions=e._enablePositionalOptions,this._showHelpAfterError=e._showHelpAfterError,this._showSuggestionAfterError=e._showSuggestionAfterError,this}_getCommandAndAncestors(){let e=[];for(let r=this;r;r=r.parent)e.push(r);return e}command(e,r,n){let o=r,s=n;typeof o=="object"&&o!==null&&(s=o,o=null),s=s||{};let[,i,a]=e.match(/([^ ]+) *(.*)/),c=this.createCommand(i);return o&&(c.description(o),c._executableHandler=!0),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this.commands.push(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(e){return new t(e)}createHelp(){return Object.assign(new MT,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 jT(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 Il(e,r,n)),Ue.exit(e)}action(e){let r=n=>{let o=this.registeredArguments.length,s=n.slice(0,o);return this._storeOptionsAsProperties?s[o]=this:s[o]=this.opts(),s.push(this),e.apply(this,s)};return this._actionHandler=r,this}createOption(e,r){return new 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=Ue.argv,Ue.versions&&Ue.versions.electron&&(r.from="electron")),this.rawArgs=e.slice();let n;switch(r.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":Ue.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${r.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(e,r){let n=this._prepareUserArgs(e,r);return this._parseCommand([],n),this}async parseAsync(e,r){let n=this._prepareUserArgs(e,r);return await this._parseCommand([],n),this}_executeSubCommand(e,r){r=r.slice();let n=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function s(u,p){let y=Sr.resolve(u,p);if(Cl.existsSync(y))return y;if(o.includes(Sr.extname(p)))return;let h=o.find(m=>Cl.existsSync(`${y}${m}`));if(h)return`${y}${h}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Cl.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=Sr.resolve(Sr.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let p=Sr.basename(this._scriptPath,Sr.extname(this._scriptPath));p!==this._name&&(u=s(a,`${p}-${e._name}`))}i=u||i}n=o.includes(Sr.extname(i));let c;Ue.platform!=="win32"?n?(r.unshift(i),r=xg(Ue.execArgv).concat(r),c=Al.spawn(Ue.argv[0],r,{stdio:"inherit"})):c=Al.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=xg(Ue.execArgv).concat(r),c=Al.spawn(Ue.execPath,r,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{Ue.on(p,()=>{c.killed===!1&&c.exitCode===null&&c.kill(p)})});let l=this._exitCallback;l?c.on("close",()=>{l(new Il(Ue.exitCode||0,"commander.executeSubCommandAsync","(close)"))}):c.on("close",Ue.exit.bind(Ue)),c.on("error",u=>{if(u.code==="ENOENT"){let p=a?`searched for local subcommand relative to directory '${a}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",y=`'${i}' does not exist
13
+ (Did you mean ${n[0]}?)`:""}_g.suggestSimilar=KT});var Rg=F(Tg=>{var WT=Qo("events").EventEmitter,Il=Qo("child_process"),$r=Qo("path"),Ol=Qo("fs"),Be=Qo("process"),{Argument:GT,humanReadableArgName:JT}=Ii(),{CommanderError:Nl}=ts(),{Help:YT}=El(),{Option:xg,splitOptionFlags:XT,DualOptions:QT}=Cl(),{suggestSimilar:kg}=vg(),zl=class t extends WT{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 YT,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 GT(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 Nl(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 xg(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 xg)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 b=$r.resolve(u,p);if(Ol.existsSync(b))return b;if(o.includes($r.extname(p)))return;let m=o.find(h=>Ol.existsSync(`${b}${h}`));if(m)return`${b}${m}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let i=e._executableFile||`${this._name}-${e._name}`,a=this._executableDir||"";if(this._scriptPath){let u;try{u=Ol.realpathSync(this._scriptPath)}catch{u=this._scriptPath}a=$r.resolve($r.dirname(u),a)}if(a){let u=s(a,i);if(!u&&!e._executableFile&&this._scriptPath){let p=$r.basename(this._scriptPath,$r.extname(this._scriptPath));p!==this._name&&(u=s(a,`${p}-${e._name}`))}i=u||i}n=o.includes($r.extname(i));let c;Be.platform!=="win32"?n?(r.unshift(i),r=$g(Be.execArgv).concat(r),c=Il.spawn(Be.argv[0],r,{stdio:"inherit"})):c=Il.spawn(i,r,{stdio:"inherit"}):(r.unshift(i),r=$g(Be.execArgv).concat(r),c=Il.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 Nl(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",b=`'${i}' does not exist
16
16
  - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
17
17
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
18
- - ${p}`;throw new Error(y)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Ue.exit(1);else{let p=new Il(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 vg(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),vg(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(b)}else if(u.code==="EACCES")throw new Error(`'${i}' not executable`);if(!l)Be.exit(1);else{let p=new Nl(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 Sg(this,r),this._dispatchSubcommand(this._defaultCommandName,e,r);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),Sg(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 Ue.env){let r=e.attributeName();(this.getOptionValue(r)===void 0||["default","config","env"].includes(this.getOptionValueSource(r)))&&(e.required||e.optional?this.emit(`optionEnv:${e.name()}`,Ue.env[e.envVar]):this.emit(`optionEnv:${e.name()}`))}})}_parseOptionsImplied(){let e=new qT(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=_g(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=_g(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=>DT(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=Sr.basename(e,Sr.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=UT(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let r=Ue.exitCode||0;r===0&&e&&typeof e!="function"&&e.error&&(r=1),this._exit(r,"commander.help","(outputHelp)")}addHelpText(e,r){let n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.
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 QT(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=kg(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=kg(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=>JT(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=$r.basename(e,$r.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=XT(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 vg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function xg(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})}kg.Command=Ol});var Eg=B((Jt,Rg)=>{var{Argument:FT}=Ai(),{Command:$g}=Sg(),{CommanderError:BT,InvalidArgumentError:Tg}=Qo(),{Help:ZT}=Tl(),{Option:VT}=Pl();Jt=Rg.exports=new $g;Jt.program=Jt;Jt.Command=$g;Jt.Option=VT;Jt.Argument=FT;Jt.Help=ZT;Jt.CommanderError=BT;Jt.InvalidArgumentError=Tg;Jt.InvalidOptionArgumentError=Tg});function hn(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var es=O(()=>{});var ye,Nl,H,pr,ts=O(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ye||(ye={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Nl||(Nl={}));H=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pr=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 M,HT,vt,Ii=O(()=>{ts();M=ye.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"]),HT=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),vt=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,ye.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()}};vt.create=t=>new vt(t)});var KT,$r,zl=O(()=>{Ii();ts();KT=(t,e)=>{let r;switch(t.code){case M.invalid_type:t.received===H.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case M.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ye.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:r=`Unrecognized key(s) in object: ${ye.joinValues(t.keys,", ")}`;break;case M.invalid_union:r="Invalid input";break;case M.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ye.joinValues(t.options)}`;break;case M.invalid_enum_value:r=`Invalid enum value. Expected ${ye.joinValues(t.options)}, received '${t.received}'`;break;case M.invalid_arguments:r="Invalid function arguments";break;case M.invalid_return_type:r="Invalid function return type";break;case M.invalid_date:r="Invalid date";break;case M.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}"`:ye.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case M.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 M.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 M.custom:r="Invalid input";break;case M.invalid_intersection_types:r="Intersection results could not be merged";break;case M.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case M.not_finite:r="Number must be finite";break;default:r=e.defaultError,ye.assertNever(t)}return{message:r}},$r=KT});function WT(t){Cg=t}function ro(){return Cg}var Cg,Oi=O(()=>{zl();Cg=$r});function Z(t,e){let r=ro(),n=rs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===$r?void 0:$r].filter(o=>!!o)});t.common.issues.push(n)}var rs,GT,nt,oe,fn,pt,Ni,zi,qr,no,Ll=O(()=>{Oi();zl();rs=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}},GT=[];nt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return 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"}),fn=t=>({status:"dirty",value:t}),pt=t=>({status:"valid",value:t}),Ni=t=>t.status==="aborted",zi=t=>t.status==="dirty",qr=t=>t.status==="valid",no=t=>typeof Promise<"u"&&t instanceof Promise});var Ig=O(()=>{});var G,Og=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(G||(G={}))});function ue(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 jg(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 pR(t){return new RegExp(`^${jg(t)}$`)}function Dg(t){let e=`${Lg}T${jg(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 mR(t,e){return!!((e==="v4"||!e)&&sR.test(t)||(e==="v6"||!e)&&aR.test(t))}function hR(t,e){if(!tR.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 fR(t,e){return!!((e==="v4"||!e)&&iR.test(t)||(e==="v6"||!e)&&cR.test(t))}function gR(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 oo(t){if(t instanceof kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(oo(n))}return new kt({...t._def,shape:()=>e})}else return t instanceof Er?new Er({...t._def,type:oo(t.element)}):t instanceof xt?xt.create(oo(t.unwrap())):t instanceof hr?hr.create(oo(t.unwrap())):t instanceof mr?mr.create(t.items.map(e=>oo(e))):t}function Dl(t,e){let r=pr(t),n=pr(e);if(t===e)return{valid:!0,data:t};if(r===H.object&&n===H.object){let o=ye.objectKeys(e),s=ye.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Dl(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=Dl(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 Mg(t,e){return new Tn({values:t,typeName:U.ZodEnum,...ue(e)})}function zg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Ug(t,e={},r){return t?Br.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=zg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=zg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Br.create()}var Lt,Ng,pe,JT,YT,XT,QT,eR,tR,rR,nR,oR,jl,sR,iR,aR,cR,lR,uR,Lg,dR,Fr,gn,yn,bn,wn,so,_n,vn,Br,Rr,Yt,io,Er,kt,xn,Tr,Li,kn,mr,ji,ao,co,Di,Sn,$n,Tn,Rn,Zr,jt,xt,hr,En,Pn,lo,yR,ns,os,An,bR,U,wR,qg,Fg,_R,vR,Bg,xR,kR,SR,$R,TR,RR,ER,PR,AR,Ml,CR,IR,OR,NR,zR,LR,jR,DR,MR,UR,qR,FR,BR,ZR,VR,HR,KR,WR,GR,JR,YR,XR,QR,eE,Zg=O(()=>{Ii();Oi();Og();Ll();ts();Lt=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}},Ng=(t,e)=>{if(qr(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 vt(t.common.issues);return this._error=r,this._error}}};pe=class{get description(){return this._def.description}_getType(e){return pr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new nt,ctx:{common:e.parent.common,data:e.data,parsedType:pr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(no(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:pr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return Ng(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return qr(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=>qr(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:pr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(no(o)?o:Promise.resolve(o));return Ng(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:M.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new jt({schema:this,typeName:U.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return xt.create(this,this._def)}nullable(){return hr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Er.create(this)}promise(){return Zr.create(this,this._def)}or(e){return xn.create([this,e],this._def)}and(e){return kn.create(this,e,this._def)}transform(e){return new jt({...ue(this._def),schema:this,typeName:U.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new En({...ue(this._def),innerType:this,defaultValue:r,typeName:U.ZodDefault})}brand(){return new ns({typeName:U.ZodBranded,type:this,...ue(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Pn({...ue(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 os.create(this,e)}readonly(){return An.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},JT=/^c[^\s-]{8,}$/i,YT=/^[0-9a-z]+$/,XT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,QT=/^[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,eR=/^[a-z0-9_-]{21}$/i,tR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rR=/^[-+]?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)?)??$/,nR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",sR=/^(?:(?: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])$/,iR=/^(?:(?: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])$/,aR=/^(([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]))$/,cR=/^(([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])$/,lR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,uR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Lg="((\\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])))",dR=new RegExp(`^${Lg}$`);Fr=class t extends pe{_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:M.invalid_type,expected:H.string,received:s.parsedType}),oe}let n=new nt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:M.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:M.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:M.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Z(o,{code:M.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")nR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")jl||(jl=new RegExp(oR,"u")),jl.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")QT.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")eR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")JT.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")YT.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:M.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")XT.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:M.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:M.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:M.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:M.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:M.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:M.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Dg(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:M.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?dR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:M.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?pR(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:M.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?rR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?mR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?hR(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?fR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?lR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:M.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?uR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:M.invalid_string,message:s.message}),n.dirty()):ye.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:M.invalid_string,...G.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...G.errToObj(e)})}url(e){return this._addCheck({kind:"url",...G.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...G.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...G.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...G.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...G.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...G.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...G.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...G.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...G.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...G.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...G.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...G.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,...G.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,...G.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...G.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...G.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...G.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...G.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...G.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...G.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...G.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...G.errToObj(r)})}nonempty(e){return this.min(1,G.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}};Fr.create=t=>new Fr({checks:[],typeName:U.ZodString,coerce:t?.coerce??!1,...ue(t)});gn=class t extends pe{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:M.invalid_type,expected:H.number,received:s.parsedType}),oe}let n,o=new nt;for(let s of this._def.checks)s.kind==="int"?ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:M.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:M.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:M.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?gR(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Z(n,{code:M.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:M.not_finite,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:G.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:G.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:G.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:G.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"&&ye.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)}};gn.create=t=>new gn({checks:[],typeName:U.ZodNumber,coerce:t?.coerce||!1,...ue(t)});yn=class t extends pe{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 nt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:M.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:M.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:M.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return Z(r,{code:M.invalid_type,expected:H.bigint,received:r.parsedType}),oe}gte(e,r){return this.setLimit("min",e,!0,G.toString(r))}gt(e,r){return this.setLimit("min",e,!1,G.toString(r))}lte(e,r){return this.setLimit("max",e,!0,G.toString(r))}lt(e,r){return this.setLimit("max",e,!1,G.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:G.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:G.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:G.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:G.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:G.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:G.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}};yn.create=t=>new yn({checks:[],typeName:U.ZodBigInt,coerce:t?.coerce??!1,...ue(t)});bn=class extends pe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==H.boolean){let n=this._getOrReturnCtx(e);return Z(n,{code:M.invalid_type,expected:H.boolean,received:n.parsedType}),oe}return pt(e.data)}};bn.create=t=>new bn({typeName:U.ZodBoolean,coerce:t?.coerce||!1,...ue(t)});wn=class t extends pe{_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:M.invalid_type,expected:H.date,received:s.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Z(s,{code:M.invalid_date}),oe}let n=new nt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:M.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:M.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ye.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:G.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:G.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}};wn.create=t=>new wn({checks:[],coerce:t?.coerce||!1,typeName:U.ZodDate,...ue(t)});so=class extends pe{_parse(e){if(this._getType(e)!==H.symbol){let n=this._getOrReturnCtx(e);return Z(n,{code:M.invalid_type,expected:H.symbol,received:n.parsedType}),oe}return pt(e.data)}};so.create=t=>new so({typeName:U.ZodSymbol,...ue(t)});_n=class extends pe{_parse(e){if(this._getType(e)!==H.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:M.invalid_type,expected:H.undefined,received:n.parsedType}),oe}return pt(e.data)}};_n.create=t=>new _n({typeName:U.ZodUndefined,...ue(t)});vn=class extends pe{_parse(e){if(this._getType(e)!==H.null){let n=this._getOrReturnCtx(e);return Z(n,{code:M.invalid_type,expected:H.null,received:n.parsedType}),oe}return pt(e.data)}};vn.create=t=>new vn({typeName:U.ZodNull,...ue(t)});Br=class extends pe{constructor(){super(...arguments),this._any=!0}_parse(e){return pt(e.data)}};Br.create=t=>new Br({typeName:U.ZodAny,...ue(t)});Rr=class extends pe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return pt(e.data)}};Rr.create=t=>new Rr({typeName:U.ZodUnknown,...ue(t)});Yt=class extends pe{_parse(e){let r=this._getOrReturnCtx(e);return Z(r,{code:M.invalid_type,expected:H.never,received:r.parsedType}),oe}};Yt.create=t=>new Yt({typeName:U.ZodNever,...ue(t)});io=class extends pe{_parse(e){if(this._getType(e)!==H.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:M.invalid_type,expected:H.void,received:n.parsedType}),oe}return pt(e.data)}};io.create=t=>new io({typeName:U.ZodVoid,...ue(t)});Er=class t extends pe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==H.array)return Z(r,{code:M.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?M.too_big:M.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:M.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:M.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 Lt(r,i,r.path,a)))).then(i=>nt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Lt(r,i,r.path,a)));return nt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:G.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:G.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:G.toString(r)}})}nonempty(e){return this.min(1,e)}};Er.create=(t,e)=>new Er({type:t,minLength:null,maxLength:null,exactLength:null,typeName:U.ZodArray,...ue(e)});kt=class t extends pe{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=ye.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:M.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 Yt&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Lt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Yt){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(Z(o,{code:M.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 Lt(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,y=await u.value;l.push({key:p,value:y,alwaysSet:u.alwaysSet})}return l}).then(l=>nt.mergeObjectSync(n,l)):nt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return G.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:G.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 ye.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 ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return oo(this)}partial(e){let r={};for(let n of ye.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 ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof xt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Mg(ye.objectKeys(this.shape))}};kt.create=(t,e)=>new kt({shape:()=>t,unknownKeys:"strip",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});kt.strictCreate=(t,e)=>new kt({shape:()=>t,unknownKeys:"strict",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});kt.lazycreate=(t,e)=>new kt({shape:t,unknownKeys:"strip",catchall:Yt.create(),typeName:U.ZodObject,...ue(e)});xn=class extends pe{_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 vt(a.ctx.common.issues));return Z(r,{code:M.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 vt(c));return Z(r,{code:M.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}};xn.create=(t,e)=>new xn({options:t,typeName:U.ZodUnion,...ue(e)});Tr=t=>t instanceof Sn?Tr(t.schema):t instanceof jt?Tr(t.innerType()):t instanceof $n?[t.value]:t instanceof Tn?t.options:t instanceof Rn?ye.objectValues(t.enum):t instanceof En?Tr(t._def.innerType):t instanceof _n?[void 0]:t instanceof vn?[null]:t instanceof xt?[void 0,...Tr(t.unwrap())]:t instanceof hr?[null,...Tr(t.unwrap())]:t instanceof ns||t instanceof An?Tr(t.unwrap()):t instanceof Pn?Tr(t._def.innerType):[],Li=class t extends pe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==H.object)return Z(r,{code:M.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:M.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=Tr(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,...ue(n)})}};kn=class extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ni(s)||Ni(i))return oe;let a=Dl(s.value,i.value);return a.valid?((zi(s)||zi(i))&&r.dirty(),{status:r.value,value:a.data}):(Z(n,{code:M.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}))}};kn.create=(t,e,r)=>new kn({left:t,right:e,typeName:U.ZodIntersection,...ue(r)});mr=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.array)return Z(n,{code:M.invalid_type,expected:H.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return Z(n,{code:M.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:M.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 Lt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>nt.mergeArray(r,i)):nt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};mr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mr({items:t,typeName:U.ZodTuple,rest:null,...ue(e)})};ji=class t extends pe{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:M.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 Lt(n,a,n.path,a)),value:i._parse(new Lt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?nt.mergeObjectAsync(r,o):nt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof pe?new t({keyType:e,valueType:r,typeName:U.ZodRecord,...ue(n)}):new t({keyType:Fr.create(),valueType:e,typeName:U.ZodRecord,...ue(r)})}},ao=class extends pe{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:M.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 Lt(n,a,n.path,[l,"key"])),value:s._parse(new Lt(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}}}};ao.create=(t,e,r)=>new ao({valueType:e,keyType:t,typeName:U.ZodMap,...ue(r)});co=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==H.set)return Z(n,{code:M.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:M.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:M.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 Lt(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:G.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:G.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};co.create=(t,e)=>new co({valueType:t,minSize:null,maxSize:null,typeName:U.ZodSet,...ue(e)});Di=class t extends pe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==H.function)return Z(r,{code:M.invalid_type,expected:H.function,received:r.parsedType}),oe;function n(a,c){return rs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ro(),$r].filter(l=>!!l),issueData:{code:M.invalid_arguments,argumentsError:c}})}function o(a,c){return rs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ro(),$r].filter(l=>!!l),issueData:{code:M.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Zr){let a=this;return pt(async function(...c){let l=new vt([]),u=await a._def.args.parseAsync(c,s).catch(h=>{throw l.addIssue(n(c,h)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(h=>{throw l.addIssue(o(p,h)),l})})}else{let a=this;return pt(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new vt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new vt([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:mr.create(e).rest(Rr.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||mr.create([]).rest(Rr.create()),returns:r||Rr.create(),typeName:U.ZodFunction,...ue(n)})}},Sn=class extends pe{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})}};Sn.create=(t,e)=>new Sn({getter:t,typeName:U.ZodLazy,...ue(e)});$n=class extends pe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Z(r,{received:r.data,code:M.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};$n.create=(t,e)=>new $n({value:t,typeName:U.ZodLiteral,...ue(e)});Tn=class t extends pe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return Z(r,{expected:ye.joinValues(n),received:r.parsedType,code:M.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:M.invalid_enum_value,options:n}),oe}return pt(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})}};Tn.create=Mg;Rn=class extends pe{_parse(e){let r=ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==H.string&&n.parsedType!==H.number){let o=ye.objectValues(r);return Z(n,{expected:ye.joinValues(o),received:n.parsedType,code:M.invalid_type}),oe}if(this._cache||(this._cache=new Set(ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ye.objectValues(r);return Z(n,{received:n.data,code:M.invalid_enum_value,options:o}),oe}return pt(e.data)}get enum(){return this._def.values}};Rn.create=(t,e)=>new Rn({values:t,typeName:U.ZodNativeEnum,...ue(e)});Zr=class extends pe{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:M.invalid_type,expected:H.promise,received:r.parsedType}),oe;let n=r.parsedType===H.promise?r.data:Promise.resolve(r.data);return pt(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Zr.create=(t,e)=>new Zr({type:t,typeName:U.ZodPromise,...ue(e)});jt=class extends pe{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"?fn(c.value):r.value==="dirty"?fn(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"?fn(a.value):r.value==="dirty"?fn(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(!qr(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=>qr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):oe);ye.assertNever(o)}};jt.create=(t,e,r)=>new jt({schema:t,typeName:U.ZodEffects,effect:e,...ue(r)});jt.createWithPreprocess=(t,e,r)=>new jt({schema:e,effect:{type:"preprocess",transform:t},typeName:U.ZodEffects,...ue(r)});xt=class extends pe{_parse(e){return this._getType(e)===H.undefined?pt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:U.ZodOptional,...ue(e)});hr=class extends pe{_parse(e){return this._getType(e)===H.null?pt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};hr.create=(t,e)=>new hr({innerType:t,typeName:U.ZodNullable,...ue(e)});En=class extends pe{_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}};En.create=(t,e)=>new En({innerType:t,typeName:U.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ue(e)});Pn=class extends pe{_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 no(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new vt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new vt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Pn.create=(t,e)=>new Pn({innerType:t,typeName:U.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ue(e)});lo=class extends pe{_parse(e){if(this._getType(e)!==H.nan){let n=this._getOrReturnCtx(e);return Z(n,{code:M.invalid_type,expected:H.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}};lo.create=t=>new lo({typeName:U.ZodNaN,...ue(t)});yR=Symbol("zod_brand"),ns=class extends pe{_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}},os=class t extends pe{_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(),fn(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})}},An=class extends pe{_parse(e){let r=this._def.innerType._parse(e),n=o=>(qr(o)&&(o.value=Object.freeze(o.value)),o);return no(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};An.create=(t,e)=>new An({innerType:t,typeName:U.ZodReadonly,...ue(e)});bR={object:kt.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(U||(U={}));wR=(t,e={message:`Input not instance of ${t.name}`})=>Ug(r=>r instanceof t,e),qg=Fr.create,Fg=gn.create,_R=lo.create,vR=yn.create,Bg=bn.create,xR=wn.create,kR=so.create,SR=_n.create,$R=vn.create,TR=Br.create,RR=Rr.create,ER=Yt.create,PR=io.create,AR=Er.create,Ml=kt.create,CR=kt.strictCreate,IR=xn.create,OR=Li.create,NR=kn.create,zR=mr.create,LR=ji.create,jR=ao.create,DR=co.create,MR=Di.create,UR=Sn.create,qR=$n.create,FR=Tn.create,BR=Rn.create,ZR=Zr.create,VR=jt.create,HR=xt.create,KR=hr.create,WR=jt.createWithPreprocess,GR=os.create,JR=()=>qg().optional(),YR=()=>Fg().optional(),XR=()=>Bg().optional(),QR={string:(t=>Fr.create({...t,coerce:!0})),number:(t=>gn.create({...t,coerce:!0})),boolean:(t=>bn.create({...t,coerce:!0})),bigint:(t=>yn.create({...t,coerce:!0})),date:(t=>wn.create({...t,coerce:!0}))},eE=oe});var A={};Xo(A,{BRAND:()=>yR,DIRTY:()=>fn,EMPTY_PATH:()=>GT,INVALID:()=>oe,NEVER:()=>eE,OK:()=>pt,ParseStatus:()=>nt,Schema:()=>pe,ZodAny:()=>Br,ZodArray:()=>Er,ZodBigInt:()=>yn,ZodBoolean:()=>bn,ZodBranded:()=>ns,ZodCatch:()=>Pn,ZodDate:()=>wn,ZodDefault:()=>En,ZodDiscriminatedUnion:()=>Li,ZodEffects:()=>jt,ZodEnum:()=>Tn,ZodError:()=>vt,ZodFirstPartyTypeKind:()=>U,ZodFunction:()=>Di,ZodIntersection:()=>kn,ZodIssueCode:()=>M,ZodLazy:()=>Sn,ZodLiteral:()=>$n,ZodMap:()=>ao,ZodNaN:()=>lo,ZodNativeEnum:()=>Rn,ZodNever:()=>Yt,ZodNull:()=>vn,ZodNullable:()=>hr,ZodNumber:()=>gn,ZodObject:()=>kt,ZodOptional:()=>xt,ZodParsedType:()=>H,ZodPipeline:()=>os,ZodPromise:()=>Zr,ZodReadonly:()=>An,ZodRecord:()=>ji,ZodSchema:()=>pe,ZodSet:()=>co,ZodString:()=>Fr,ZodSymbol:()=>so,ZodTransformer:()=>jt,ZodTuple:()=>mr,ZodType:()=>pe,ZodUndefined:()=>_n,ZodUnion:()=>xn,ZodUnknown:()=>Rr,ZodVoid:()=>io,addIssueToContext:()=>Z,any:()=>TR,array:()=>AR,bigint:()=>vR,boolean:()=>Bg,coerce:()=>QR,custom:()=>Ug,date:()=>xR,datetimeRegex:()=>Dg,defaultErrorMap:()=>$r,discriminatedUnion:()=>OR,effect:()=>VR,enum:()=>FR,function:()=>MR,getErrorMap:()=>ro,getParsedType:()=>pr,instanceof:()=>wR,intersection:()=>NR,isAborted:()=>Ni,isAsync:()=>no,isDirty:()=>zi,isValid:()=>qr,late:()=>bR,lazy:()=>UR,literal:()=>qR,makeIssue:()=>rs,map:()=>jR,nan:()=>_R,nativeEnum:()=>BR,never:()=>ER,null:()=>$R,nullable:()=>KR,number:()=>Fg,object:()=>Ml,objectUtil:()=>Nl,oboolean:()=>XR,onumber:()=>YR,optional:()=>HR,ostring:()=>JR,pipeline:()=>GR,preprocess:()=>WR,promise:()=>ZR,quotelessJson:()=>HT,record:()=>LR,set:()=>DR,setErrorMap:()=>WT,strictObject:()=>CR,string:()=>qg,symbol:()=>kR,transformer:()=>VR,tuple:()=>zR,undefined:()=>SR,union:()=>IR,unknown:()=>RR,util:()=>ye,void:()=>PR});var Mi=O(()=>{Oi();Ll();Ig();ts();Zg();Ii()});var Cn=O(()=>{Mi();Mi()});function Ui(t){let e=Ul.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function ql(t,e){let r=Ul.safeParse(t);if(!r.success)throw new Vr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Vg.test(e))throw new Vr('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(Vg.test(n))throw new Vr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Hg,Kg,Ul,Vr,Vg,Wg=O(()=>{Cn();Hg=A.object({type:A.literal("connection"),source_system:A.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:A.string().min(1).max(200).optional()}),Kg=A.discriminatedUnion("type",[Hg]),Ul=A.object({inputs:A.array(Kg).optional()}).passthrough(),Vr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Vg=/\bconnection[_-]?id\b["']?\s*[:=]/i});var qi,Fl=O(()=>{qi=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var Bl,Gg,Jg=O(()=>{Cn();es();Fl();Bl=A.object({id:A.string().min(1,"hook id must be non-empty"),recordType:A.union([A.string().min(1),A.array(A.string().min(1)).min(1),A.literal("*")]),event:A.enum(qi),source:A.string().min(1).optional(),when:A.unknown().optional(),run:A.unknown(),failClosed:A.boolean().optional(),timeoutMs:A.number().int().positive().optional(),description:A.string().optional(),systemReserved:A.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"})}),Gg=hn({kind:"hook",schema:Bl,factoryName:"defineHook"})});var Yg=O(()=>{Jg();Fl()});var Fi,Zl=O(()=>{Fi=["after_canonicalize_inbound","after_sync_success_outbound"]});var Xg,nE,Qg,Vl,ey,ty=O(()=>{Cn();es();Zl();Xg=A.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),nE=A.object({recordType:A.string().min(1,"reads[].recordType must be non-empty"),source:A.string().min(1).optional(),columns:A.array(Xg).min(1,"reads[].columns must name at least one column"),by:A.array(Xg).optional(),maxRows:A.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),Qg=A.object({source:A.string().min(1,"to.source must be non-empty"),recordType:A.string().min(1,"to.recordType must be non-empty")}),Vl=A.object({id:A.string().min(1,"conduit id must be non-empty"),on:A.enum(Fi),from:A.object({source:A.string().min(1,"from.source must be non-empty"),recordType:A.string().min(1,"from.recordType must be non-empty"),when:A.unknown().optional()}),to:Qg.optional(),mode:A.enum(["dual-bind","one-shot"]).optional(),transform:A.unknown().optional(),sequence:A.array(A.object({to:Qg,transform:A.unknown(),awaitSource:A.boolean().optional()})).optional(),reads:A.array(nE).optional(),maxQueriesPerRun:A.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:A.unknown().optional(),cycleBudget:A.number().int().positive().optional(),conflictStrategy:A.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:A.number().int().positive().optional(),description:A.string().optional(),systemReserved:A.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=hn({kind:"conduit",schema:Vl,factoryName:"defineConduit"})});var ry=O(()=>{ty();Zl()});var Hl,ny,oy=O(()=>{Cn();es();Hl=A.object({id:A.string().min(1,"process id must be non-empty"),input:A.object({type:A.literal("object"),properties:A.record(A.unknown()).optional(),required:A.array(A.string()).optional()}).passthrough(),steps:A.array(A.object({id:A.string().min(1,"step id must be non-empty"),recordType:A.string().min(1,"step.recordType must be non-empty"),awaitSource:A.boolean().optional(),build:A.unknown(),description:A.string().optional()})).min(1,"a process needs at least one step"),eachRow:A.object({outstanding:A.unknown(),key:A.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:A.enum(["stop","rollback"]).optional(),description:A.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(typeof a.build!="function"&&e.addIssue({code:"custom",path:["steps",i,"build"],message:"build must be a function"}),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=hn({kind:"process",schema:Hl,factoryName:"defineProcess"})});var sy=O(()=>{});var iy=O(()=>{oy();sy()});async function mE(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 Vi(t,e={}){return(e.transform??mE)(t)}var Kl=O(()=>{});function Wl(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 ay(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Gl(t){return`${ay(t.source)}${ay(t.recordType)}`}function hE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function fE(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 Jl(t){let e=Gl(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 Sg(t,e){t._hasHelpOption&&e.find(n=>n===t._helpLongFlag||n===t._helpShortFlag)&&(t.outputHelp(),t._exit(0,"commander.helpDisplayed","(outputHelp)"))}function $g(t){return t.map(e=>{if(!e.startsWith("--inspect"))return e;let r,n="127.0.0.1",o="9229",s;return(s=e.match(/^(--inspect(-brk)?)$/))!==null?r=s[1]:(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(r=s[1],/^\d+$/.test(s[3])?o=s[3]:n=s[3]):(s=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(r=s[1],n=s[3],o=s[4]),r&&o!=="0"?`${r}=${n}:${parseInt(o)+1}`:e})}Tg.Command=zl});var Cg=F((Yt,Ag)=>{var{Argument:eR}=Ii(),{Command:Eg}=Rg(),{CommanderError:tR,InvalidArgumentError:Pg}=ts(),{Help:rR}=El(),{Option:nR}=Cl();Yt=Ag.exports=new Eg;Yt.program=Yt;Yt.Command=Eg;Yt.Option=nR;Yt.Argument=eR;Yt.Help=rR;Yt.CommanderError=tR;Yt.InvalidArgumentError=Pg;Yt.InvalidOptionArgumentError=Pg});function fn(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var rs=O(()=>{});var we,Ll,V,hr,ns=O(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(we||(we={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ll||(Ll={}));V=we.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hr=t=>{switch(typeof t){case"undefined":return V.undefined;case"string":return V.string;case"number":return Number.isNaN(t)?V.nan:V.number;case"boolean":return V.boolean;case"function":return V.function;case"bigint":return V.bigint;case"symbol":return V.symbol;case"object":return Array.isArray(t)?V.array:t===null?V.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?V.promise:typeof Map<"u"&&t instanceof Map?V.map:typeof Set<"u"&&t instanceof Set?V.set:typeof Date<"u"&&t instanceof Date?V.date:V.object;default:return V.unknown}}});var j,oR,xt,Ni=O(()=>{ns();j=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"]),oR=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xt=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()}};xt.create=t=>new xt(t)});var sR,Tr,jl=O(()=>{Ni();ns();sR=(t,e)=>{let r;switch(t.code){case j.invalid_type:t.received===V.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case j.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,we.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:r=`Unrecognized key(s) in object: ${we.joinValues(t.keys,", ")}`;break;case j.invalid_union:r="Invalid input";break;case j.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${we.joinValues(t.options)}`;break;case j.invalid_enum_value:r=`Invalid enum value. Expected ${we.joinValues(t.options)}, received '${t.received}'`;break;case j.invalid_arguments:r="Invalid function arguments";break;case j.invalid_return_type:r="Invalid function return type";break;case j.invalid_date:r="Invalid date";break;case j.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:we.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case j.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case j.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case j.custom:r="Invalid input";break;case j.invalid_intersection_types:r="Intersection results could not be merged";break;case j.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case j.not_finite:r="Number must be finite";break;default:r=e.defaultError,we.assertNever(t)}return{message:r}},Tr=sR});function iR(t){Ng=t}function ro(){return Ng}var Ng,zi=O(()=>{jl();Ng=Tr});function Z(t,e){let r=ro(),n=os({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Tr?void 0:Tr].filter(o=>!!o)});t.common.issues.push(n)}var os,aR,st,oe,gn,ht,Li,ji,Br,no,Dl=O(()=>{zi();jl();os=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}},aR=[];st=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"}),gn=t=>({status:"dirty",value:t}),ht=t=>({status:"valid",value:t}),Li=t=>t.status==="aborted",ji=t=>t.status==="dirty",Br=t=>t.status==="valid",no=t=>typeof Promise<"u"&&t instanceof Promise});var zg=O(()=>{});var W,Lg=O(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(W||(W={}))});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 Ug(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 SR(t){return new RegExp(`^${Ug(t)}$`)}function qg(t){let e=`${Mg}T${Ug(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 $R(t,e){return!!((e==="v4"||!e)&&yR.test(t)||(e==="v6"||!e)&&wR.test(t))}function TR(t,e){if(!hR.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 RR(t,e){return!!((e==="v4"||!e)&&bR.test(t)||(e==="v6"||!e)&&_R.test(t))}function ER(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 oo(t){if(t instanceof St){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=kt.create(oo(n))}return new St({...t._def,shape:()=>e})}else return t instanceof Pr?new Pr({...t._def,type:oo(t.element)}):t instanceof kt?kt.create(oo(t.unwrap())):t instanceof fr?fr.create(oo(t.unwrap())):t instanceof mr?mr.create(t.items.map(e=>oo(e))):t}function Ul(t,e){let r=hr(t),n=hr(e);if(t===e)return{valid:!0,data:t};if(r===V.object&&n===V.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=Ul(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===V.array&&n===V.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=Ul(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===V.date&&n===V.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function Bg(t,e){return new Rn({values:t,typeName:D.ZodEnum,...de(e)})}function Dg(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Fg(t,e={},r){return t?Zr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Dg(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Dg(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Zr.create()}var jt,jg,he,cR,lR,uR,dR,pR,hR,mR,fR,gR,Ml,yR,bR,wR,_R,vR,xR,Mg,kR,Fr,yn,bn,wn,_n,so,vn,xn,Zr,Er,Xt,io,Pr,St,kn,Rr,Di,Sn,mr,Mi,ao,co,Ui,$n,Tn,Rn,En,Vr,Dt,kt,fr,Pn,An,lo,PR,ss,is,Cn,AR,D,CR,Zg,Vg,IR,OR,Hg,NR,zR,LR,jR,DR,MR,UR,qR,BR,ql,FR,ZR,VR,HR,KR,WR,GR,JR,YR,XR,QR,eE,tE,rE,nE,oE,sE,iE,aE,cE,lE,uE,dE,pE,Kg=O(()=>{Ni();zi();Lg();Dl();ns();jt=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}},jg=(t,e)=>{if(Br(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 xt(t.common.issues);return this._error=r,this._error}}};he=class{get description(){return this._def.description}_getType(e){return hr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:hr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new st,ctx:{common:e.parent.common,data:e.data,parsedType:hr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(no(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:hr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return jg(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Br(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=>Br(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:hr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(no(o)?o:Promise.resolve(o));return jg(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:j.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Dt({schema:this,typeName:D.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return kt.create(this,this._def)}nullable(){return fr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Pr.create(this)}promise(){return Vr.create(this,this._def)}or(e){return kn.create([this,e],this._def)}and(e){return Sn.create(this,e,this._def)}transform(e){return new Dt({...de(this._def),schema:this,typeName:D.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Pn({...de(this._def),innerType:this,defaultValue:r,typeName:D.ZodDefault})}brand(){return new ss({typeName:D.ZodBranded,type:this,...de(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new An({...de(this._def),innerType:this,catchValue:r,typeName:D.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return is.create(this,e)}readonly(){return Cn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},cR=/^c[^\s-]{8,}$/i,lR=/^[0-9a-z]+$/,uR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,dR=/^[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,pR=/^[a-z0-9_-]{21}$/i,hR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mR=/^[-+]?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)?)??$/,fR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",yR=/^(?:(?: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])$/,bR=/^(?:(?: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])$/,wR=/^(([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]))$/,_R=/^(([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])$/,vR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Mg="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",kR=new RegExp(`^${Mg}$`);Fr=class t extends he{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==V.string){let s=this._getOrReturnCtx(e);return Z(s,{code:j.invalid_type,expected:V.string,received:s.parsedType}),oe}let n=new st,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:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?Z(o,{code:j.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&Z(o,{code:j.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")fR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Ml||(Ml=new RegExp(gR,"u")),Ml.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")dR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")pR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")cR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")lR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")uR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:j.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Z(o,{validation:"url",code:j.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"regex",code:j.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?qg(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?kR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?SR(s).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:j.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?mR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?$R(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?TR(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?RR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?vR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:j.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?xR.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:j.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:j.invalid_string,...W.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...W.errToObj(e)})}url(e){return this._addCheck({kind:"url",...W.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...W.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...W.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...W.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...W.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...W.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...W.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...W.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...W.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...W.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...W.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...W.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...W.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...W.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...W.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...W.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...W.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...W.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...W.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...W.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...W.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...W.errToObj(r)})}nonempty(e){return this.min(1,W.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Fr.create=t=>new Fr({checks:[],typeName:D.ZodString,coerce:t?.coerce??!1,...de(t)});yn=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)!==V.number){let s=this._getOrReturnCtx(e);return Z(s,{code:j.invalid_type,expected:V.number,received:s.parsedType}),oe}let n,o=new st;for(let s of this._def.checks)s.kind==="int"?we.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:j.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ER(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),Z(n,{code:j.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,W.toString(r))}gt(e,r){return this.setLimit("min",e,!1,W.toString(r))}lte(e,r){return this.setLimit("max",e,!0,W.toString(r))}lt(e,r){return this.setLimit("max",e,!1,W.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:W.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:W.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:W.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:W.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:W.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:W.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&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)}};yn.create=t=>new yn({checks:[],typeName:D.ZodNumber,coerce:t?.coerce||!1,...de(t)});bn=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)!==V.bigint)return this._getInvalidInput(e);let n,o=new st;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:j.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),Z(n,{code:j.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:j.invalid_type,expected:V.bigint,received:r.parsedType}),oe}gte(e,r){return this.setLimit("min",e,!0,W.toString(r))}gt(e,r){return this.setLimit("min",e,!1,W.toString(r))}lte(e,r){return this.setLimit("max",e,!0,W.toString(r))}lt(e,r){return this.setLimit("max",e,!1,W.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:W.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:W.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:W.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:W.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:W.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:W.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};bn.create=t=>new bn({checks:[],typeName:D.ZodBigInt,coerce:t?.coerce??!1,...de(t)});wn=class extends he{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==V.boolean){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.boolean,received:n.parsedType}),oe}return ht(e.data)}};wn.create=t=>new wn({typeName:D.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)!==V.date){let s=this._getOrReturnCtx(e);return Z(s,{code:j.invalid_type,expected:V.date,received:s.parsedType}),oe}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return Z(s,{code:j.invalid_date}),oe}let n=new st,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:j.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:j.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:W.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:W.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};_n.create=t=>new _n({checks:[],coerce:t?.coerce||!1,typeName:D.ZodDate,...de(t)});so=class extends he{_parse(e){if(this._getType(e)!==V.symbol){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.symbol,received:n.parsedType}),oe}return ht(e.data)}};so.create=t=>new so({typeName:D.ZodSymbol,...de(t)});vn=class extends he{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.undefined,received:n.parsedType}),oe}return ht(e.data)}};vn.create=t=>new vn({typeName:D.ZodUndefined,...de(t)});xn=class extends he{_parse(e){if(this._getType(e)!==V.null){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.null,received:n.parsedType}),oe}return ht(e.data)}};xn.create=t=>new xn({typeName:D.ZodNull,...de(t)});Zr=class extends he{constructor(){super(...arguments),this._any=!0}_parse(e){return ht(e.data)}};Zr.create=t=>new Zr({typeName:D.ZodAny,...de(t)});Er=class extends he{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ht(e.data)}};Er.create=t=>new Er({typeName:D.ZodUnknown,...de(t)});Xt=class extends he{_parse(e){let r=this._getOrReturnCtx(e);return Z(r,{code:j.invalid_type,expected:V.never,received:r.parsedType}),oe}};Xt.create=t=>new Xt({typeName:D.ZodNever,...de(t)});io=class extends he{_parse(e){if(this._getType(e)!==V.undefined){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.void,received:n.parsedType}),oe}return ht(e.data)}};io.create=t=>new io({typeName:D.ZodVoid,...de(t)});Pr=class t extends he{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==V.array)return Z(r,{code:j.invalid_type,expected:V.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?j.too_big:j.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(Z(r,{code:j.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(Z(r,{code:j.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new jt(r,i,r.path,a)))).then(i=>st.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new jt(r,i,r.path,a)));return st.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:W.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:W.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:W.toString(r)}})}nonempty(e){return this.min(1,e)}};Pr.create=(t,e)=>new Pr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:D.ZodArray,...de(e)});St=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)!==V.object){let l=this._getOrReturnCtx(e);return Z(l,{code:j.invalid_type,expected:V.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 Xt&&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 jt(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Xt){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:j.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new jt(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,b=await u.value;l.push({key:p,value:b,alwaysSet:u.alwaysSet})}return l}).then(l=>st.mergeObjectSync(n,l)):st.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return W.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:W.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:D.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of 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 oo(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 kt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Bg(we.objectKeys(this.shape))}};St.create=(t,e)=>new St({shape:()=>t,unknownKeys:"strip",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});St.strictCreate=(t,e)=>new St({shape:()=>t,unknownKeys:"strict",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});St.lazycreate=(t,e)=>new St({shape:t,unknownKeys:"strip",catchall:Xt.create(),typeName:D.ZodObject,...de(e)});kn=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 xt(a.ctx.common.issues));return Z(r,{code:j.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 xt(c));return Z(r,{code:j.invalid_union,unionErrors:a}),oe}}get options(){return this._def.options}};kn.create=(t,e)=>new kn({options:t,typeName:D.ZodUnion,...de(e)});Rr=t=>t instanceof $n?Rr(t.schema):t instanceof Dt?Rr(t.innerType()):t instanceof Tn?[t.value]:t instanceof Rn?t.options:t instanceof En?we.objectValues(t.enum):t instanceof Pn?Rr(t._def.innerType):t instanceof vn?[void 0]:t instanceof xn?[null]:t instanceof kt?[void 0,...Rr(t.unwrap())]:t instanceof fr?[null,...Rr(t.unwrap())]:t instanceof ss||t instanceof Cn?Rr(t.unwrap()):t instanceof An?Rr(t._def.innerType):[],Di=class t extends he{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.object)return Z(r,{code:j.invalid_type,expected:V.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:j.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=Rr(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:D.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...de(n)})}};Sn=class extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Li(s)||Li(i))return oe;let a=Ul(s.value,i.value);return a.valid?((ji(s)||ji(i))&&r.dirty(),{status:r.value,value:a.data}):(Z(n,{code:j.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}))}};Sn.create=(t,e,r)=>new Sn({left:t,right:e,typeName:D.ZodIntersection,...de(r)});mr=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.array)return Z(n,{code:j.invalid_type,expected:V.array,received:n.parsedType}),oe;if(n.data.length<this._def.items.length)return Z(n,{code:j.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:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new jt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>st.mergeArray(r,i)):st.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};mr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mr({items:t,typeName:D.ZodTuple,rest:null,...de(e)})};Mi=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!==V.object)return Z(n,{code:j.invalid_type,expected:V.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 jt(n,a,n.path,a)),value:i._parse(new jt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?st.mergeObjectAsync(r,o):st.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:D.ZodRecord,...de(n)}):new t({keyType:Fr.create(),valueType:e,typeName:D.ZodRecord,...de(r)})}},ao=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!==V.map)return Z(n,{code:j.invalid_type,expected:V.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 jt(n,a,n.path,[l,"key"])),value:s._parse(new jt(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}}}};ao.create=(t,e,r)=>new ao({valueType:e,keyType:t,typeName:D.ZodMap,...de(r)});co=class t extends he{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==V.set)return Z(n,{code:j.invalid_type,expected:V.set,received:n.parsedType}),oe;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(Z(n,{code:j.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(Z(n,{code:j.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return 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 jt(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:W.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:W.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};co.create=(t,e)=>new co({valueType:t,minSize:null,maxSize:null,typeName:D.ZodSet,...de(e)});Ui=class t extends he{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.function)return Z(r,{code:j.invalid_type,expected:V.function,received:r.parsedType}),oe;function n(a,c){return os({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ro(),Tr].filter(l=>!!l),issueData:{code:j.invalid_arguments,argumentsError:c}})}function o(a,c){return os({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ro(),Tr].filter(l=>!!l),issueData:{code:j.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Vr){let a=this;return ht(async function(...c){let l=new xt([]),u=await a._def.args.parseAsync(c,s).catch(m=>{throw l.addIssue(n(c,m)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(m=>{throw l.addIssue(o(p,m)),l})})}else{let a=this;return ht(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new xt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new xt([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:mr.create(e).rest(Er.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||mr.create([]).rest(Er.create()),returns:r||Er.create(),typeName:D.ZodFunction,...de(n)})}},$n=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})}};$n.create=(t,e)=>new $n({getter:t,typeName:D.ZodLazy,...de(e)});Tn=class extends he{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return Z(r,{received:r.data,code:j.invalid_literal,expected:this._def.value}),oe}return{status:"valid",value:e.data}}get value(){return this._def.value}};Tn.create=(t,e)=>new Tn({value:t,typeName:D.ZodLiteral,...de(e)});Rn=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:j.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:j.invalid_enum_value,options:n}),oe}return ht(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})}};Rn.create=Bg;En=class extends he{_parse(e){let r=we.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==V.string&&n.parsedType!==V.number){let o=we.objectValues(r);return Z(n,{expected:we.joinValues(o),received:n.parsedType,code:j.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:j.invalid_enum_value,options:o}),oe}return ht(e.data)}get enum(){return this._def.values}};En.create=(t,e)=>new En({values:t,typeName:D.ZodNativeEnum,...de(e)});Vr=class extends he{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==V.promise&&r.common.async===!1)return Z(r,{code:j.invalid_type,expected:V.promise,received:r.parsedType}),oe;let n=r.parsedType===V.promise?r.data:Promise.resolve(r.data);return ht(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Vr.create=(t,e)=>new Vr({type:t,typeName:D.ZodPromise,...de(e)});Dt=class extends he{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===D.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{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"?gn(c.value):r.value==="dirty"?gn(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"?gn(a.value):r.value==="dirty"?gn(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(!Br(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=>Br(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):oe);we.assertNever(o)}};Dt.create=(t,e,r)=>new Dt({schema:t,typeName:D.ZodEffects,effect:e,...de(r)});Dt.createWithPreprocess=(t,e,r)=>new Dt({schema:e,effect:{type:"preprocess",transform:t},typeName:D.ZodEffects,...de(r)});kt=class extends he{_parse(e){return this._getType(e)===V.undefined?ht(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};kt.create=(t,e)=>new kt({innerType:t,typeName:D.ZodOptional,...de(e)});fr=class extends he{_parse(e){return this._getType(e)===V.null?ht(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};fr.create=(t,e)=>new fr({innerType:t,typeName:D.ZodNullable,...de(e)});Pn=class extends he{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===V.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Pn.create=(t,e)=>new Pn({innerType:t,typeName:D.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...de(e)});An=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 no(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};An.create=(t,e)=>new An({innerType:t,typeName:D.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...de(e)});lo=class extends he{_parse(e){if(this._getType(e)!==V.nan){let n=this._getOrReturnCtx(e);return Z(n,{code:j.invalid_type,expected:V.nan,received:n.parsedType}),oe}return{status:"valid",value:e.data}}};lo.create=t=>new lo({typeName:D.ZodNaN,...de(t)});PR=Symbol("zod_brand"),ss=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}},is=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(),gn(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:D.ZodPipeline})}},Cn=class extends he{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Br(o)&&(o.value=Object.freeze(o.value)),o);return no(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Cn.create=(t,e)=>new Cn({innerType:t,typeName:D.ZodReadonly,...de(e)});AR={object:St.lazycreate};(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(D||(D={}));CR=(t,e={message:`Input not instance of ${t.name}`})=>Fg(r=>r instanceof t,e),Zg=Fr.create,Vg=yn.create,IR=lo.create,OR=bn.create,Hg=wn.create,NR=_n.create,zR=so.create,LR=vn.create,jR=xn.create,DR=Zr.create,MR=Er.create,UR=Xt.create,qR=io.create,BR=Pr.create,ql=St.create,FR=St.strictCreate,ZR=kn.create,VR=Di.create,HR=Sn.create,KR=mr.create,WR=Mi.create,GR=ao.create,JR=co.create,YR=Ui.create,XR=$n.create,QR=Tn.create,eE=Rn.create,tE=En.create,rE=Vr.create,nE=Dt.create,oE=kt.create,sE=fr.create,iE=Dt.createWithPreprocess,aE=is.create,cE=()=>Zg().optional(),lE=()=>Vg().optional(),uE=()=>Hg().optional(),dE={string:(t=>Fr.create({...t,coerce:!0})),number:(t=>yn.create({...t,coerce:!0})),boolean:(t=>wn.create({...t,coerce:!0})),bigint:(t=>bn.create({...t,coerce:!0})),date:(t=>_n.create({...t,coerce:!0}))},pE=oe});var A={};es(A,{BRAND:()=>PR,DIRTY:()=>gn,EMPTY_PATH:()=>aR,INVALID:()=>oe,NEVER:()=>pE,OK:()=>ht,ParseStatus:()=>st,Schema:()=>he,ZodAny:()=>Zr,ZodArray:()=>Pr,ZodBigInt:()=>bn,ZodBoolean:()=>wn,ZodBranded:()=>ss,ZodCatch:()=>An,ZodDate:()=>_n,ZodDefault:()=>Pn,ZodDiscriminatedUnion:()=>Di,ZodEffects:()=>Dt,ZodEnum:()=>Rn,ZodError:()=>xt,ZodFirstPartyTypeKind:()=>D,ZodFunction:()=>Ui,ZodIntersection:()=>Sn,ZodIssueCode:()=>j,ZodLazy:()=>$n,ZodLiteral:()=>Tn,ZodMap:()=>ao,ZodNaN:()=>lo,ZodNativeEnum:()=>En,ZodNever:()=>Xt,ZodNull:()=>xn,ZodNullable:()=>fr,ZodNumber:()=>yn,ZodObject:()=>St,ZodOptional:()=>kt,ZodParsedType:()=>V,ZodPipeline:()=>is,ZodPromise:()=>Vr,ZodReadonly:()=>Cn,ZodRecord:()=>Mi,ZodSchema:()=>he,ZodSet:()=>co,ZodString:()=>Fr,ZodSymbol:()=>so,ZodTransformer:()=>Dt,ZodTuple:()=>mr,ZodType:()=>he,ZodUndefined:()=>vn,ZodUnion:()=>kn,ZodUnknown:()=>Er,ZodVoid:()=>io,addIssueToContext:()=>Z,any:()=>DR,array:()=>BR,bigint:()=>OR,boolean:()=>Hg,coerce:()=>dE,custom:()=>Fg,date:()=>NR,datetimeRegex:()=>qg,defaultErrorMap:()=>Tr,discriminatedUnion:()=>VR,effect:()=>nE,enum:()=>eE,function:()=>YR,getErrorMap:()=>ro,getParsedType:()=>hr,instanceof:()=>CR,intersection:()=>HR,isAborted:()=>Li,isAsync:()=>no,isDirty:()=>ji,isValid:()=>Br,late:()=>AR,lazy:()=>XR,literal:()=>QR,makeIssue:()=>os,map:()=>GR,nan:()=>IR,nativeEnum:()=>tE,never:()=>UR,null:()=>jR,nullable:()=>sE,number:()=>Vg,object:()=>ql,objectUtil:()=>Ll,oboolean:()=>uE,onumber:()=>lE,optional:()=>oE,ostring:()=>cE,pipeline:()=>aE,preprocess:()=>iE,promise:()=>rE,quotelessJson:()=>oR,record:()=>WR,set:()=>JR,setErrorMap:()=>iR,strictObject:()=>FR,string:()=>Zg,symbol:()=>zR,transformer:()=>nE,tuple:()=>KR,undefined:()=>LR,union:()=>ZR,unknown:()=>MR,util:()=>we,void:()=>qR});var qi=O(()=>{zi();Dl();zg();ns();Kg();Ni()});var In=O(()=>{qi();qi()});function Bi(t){let e=Bl.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Fl(t,e){let r=Bl.safeParse(t);if(!r.success)throw new Hr(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Wg.test(e))throw new Hr('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(Wg.test(n))throw new Hr("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Gg,Jg,Bl,Hr,Wg,Yg=O(()=>{In();Gg=A.object({type:A.literal("connection"),source_system:A.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:A.string().min(1).max(200).optional()}),Jg=A.discriminatedUnion("type",[Gg]),Bl=A.object({inputs:A.array(Jg).optional()}).passthrough(),Hr=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Wg=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Fi,Zl=O(()=>{Fi=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});var Vl,Xg,Qg=O(()=>{In();rs();Zl();Vl=A.object({id:A.string().min(1,"hook id must be non-empty"),recordType:A.union([A.string().min(1),A.array(A.string().min(1)).min(1),A.literal("*")]),event:A.enum(Fi),source:A.string().min(1).optional(),when:A.unknown().optional(),run:A.unknown(),failClosed:A.boolean().optional(),timeoutMs:A.number().int().positive().optional(),description:A.string().optional(),systemReserved:A.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"})}),Xg=fn({kind:"hook",schema:Vl,factoryName:"defineHook"})});var ey=O(()=>{Qg();Zl()});var Zi,Hl=O(()=>{Zi=["after_canonicalize_inbound","after_sync_success_outbound"]});var ty,fE,ry,Kl,ny,oy=O(()=>{In();rs();Hl();ty=A.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),fE=A.object({recordType:A.string().min(1,"reads[].recordType must be non-empty"),source:A.string().min(1).optional(),columns:A.array(ty).min(1,"reads[].columns must name at least one column"),by:A.array(ty).optional(),maxRows:A.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),ry=A.object({source:A.string().min(1,"to.source must be non-empty"),recordType:A.string().min(1,"to.recordType must be non-empty")}),Kl=A.object({id:A.string().min(1,"conduit id must be non-empty"),on:A.enum(Zi),from:A.object({source:A.string().min(1,"from.source must be non-empty"),recordType:A.string().min(1,"from.recordType must be non-empty"),when:A.unknown().optional()}),to:ry.optional(),mode:A.enum(["dual-bind","one-shot"]).optional(),transform:A.unknown().optional(),sequence:A.array(A.object({to:ry,transform:A.unknown(),awaitSource:A.boolean().optional()})).optional(),reads:A.array(fE).optional(),maxQueriesPerRun:A.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:A.unknown().optional(),cycleBudget:A.number().int().positive().optional(),conflictStrategy:A.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:A.number().int().positive().optional(),description:A.string().optional(),systemReserved:A.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"})}),ny=fn({kind:"conduit",schema:Kl,factoryName:"defineConduit"})});var sy=O(()=>{oy();Hl()});var Wl,iy,ay=O(()=>{In();rs();Wl=A.object({id:A.string().min(1,"process id must be non-empty"),input:A.object({type:A.literal("object"),properties:A.record(A.unknown()).optional(),required:A.array(A.string()).optional()}).passthrough(),steps:A.array(A.object({id:A.string().min(1,"step id must be non-empty"),recordType:A.string().min(1,"step.recordType must be non-empty"),awaitSource:A.boolean().optional(),build:A.unknown(),description:A.string().optional()})).min(1,"a process needs at least one step"),eachRow:A.object({outstanding:A.unknown(),key:A.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:A.enum(["stop","rollback"]).optional(),description:A.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(typeof a.build!="function"&&e.addIssue({code:"custom",path:["steps",i,"build"],message:"build must be a function"}),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)}})}),iy=fn({kind:"process",schema:Wl,factoryName:"defineProcess"})});var cy=O(()=>{});var ly=O(()=>{ay();cy()});async function $E(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 Ki(t,e={}){return(e.transform??$E)(t)}var Gl=O(()=>{});function Jl(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 uy(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Yl(t){return`${uy(t.source)}${uy(t.recordType)}`}function TE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function RE(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 Xl(t){let e=Yl(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=Wl(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${fE(s)} */
32
- ${hE(s.name)}${a}: ${i}${c};`});return`${n}
31
+ }`;let o=t.columns.map(s=>{let i=Jl(s.pgType),a=s.nullable?"?":"",c=s.nullable?" | null":"";return` /** ${RE(s)} */
32
+ ${TE(s.name)}${a}: ${i}${c};`});return`${n}
33
33
  export interface ${e} {
34
34
  ${o.join(`
35
35
  `)}
36
- }`}function Hi(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Jl).join(`
36
+ }`}function Wi(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Xl).join(`
37
37
 
38
- `)}function cy(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function gE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Yl(t){let e=cy(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${gE(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
39
- `)}var Xl=O(()=>{});function yE(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function ly(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 In(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=yE(t.baseUrl),n=await ly(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=Hi(n),s=[bE,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Yl(n)];if(!t.recordsOnly){let i=await ly(r.openapi,t.token,e),a=await Vi(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
38
+ `)}function dy(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function EE(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Ql(t){let e=dy(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` ${EE(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
39
+ `)}var eu=O(()=>{});function PE(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function py(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 On(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=PE(t.baseUrl),n=await py(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=Wi(n),s=[AE,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Ql(n)];if(!t.recordsOnly){let i=await py(r.openapi,t.token,e),a=await Ki(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
40
40
 
41
41
  `)+`
42
- `}var bE,uy=O(()=>{Kl();Xl();Xl();Kl();bE=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
43
- `)});var Ql=O(()=>{es();Wg();Yg();ry();iy();uy()});import{homedir as wE}from"node:os";import{join as dy}from"node:path";import{promises as eu}from"node:fs";function Dt(t){return t.trim().replace(/\/+$/,"")}function Ki(){let t=process.env.TURBOBASE_HOME??dy(wE(),".turbobase");return{dir:t,file:dy(t,"credentials")}}function py(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function ss(){let{file:t}=Ki(),e;try{let s=await eu.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))py(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))py(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:_E(n),tenants:n}}function _E(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 tu(t){let{dir:e,file:r}=Ki();await eu.mkdir(e,{recursive:!0,mode:448}),await eu.writeFile(r,JSON.stringify(t,null,2)+`
44
- `,{mode:384})}async function my(t){let e=Dt(t.baseUrl),r=await ss(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await tu(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Xt(t){let e=await ss();if(t){let s=Dt(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 Wi(t){let e=Dt(t),r=await ss(),n=r.tenants[e];return n?(r.active=e,await tu(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ru(t){let e=await ss(),r=t?Dt(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 tu(e),r}async function Pr(){let t=await ss();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var is=O(()=>{});function ou(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function vE(t){if(t)try{return JSON.parse(t)}catch{return t}}function xE(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 kE(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function SE(t,e){let r=xE(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=vE(n),s=ou(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??kE(n),error:i}}function $E(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 nu(t){return`${Math.round(t/1e3)}s`}function TE(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${nu(t.delayMs)} before retrying (${nu(t.remainingMs)} of the retry budget left).
45
- `)}function RE(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${nu(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
46
- `)}function Gi(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??TE,a=e.onGiveUp??RE;return async(l,u)=>{let p=s(),y=0;for(;;){let h=await t(l,u);if(h.status!==503||u&&!$E(u.body))return h;let m=r-(s()-p),{maintenance:w,delayMs:S,error:R}=await SE(h,s());if(!w)return h;if(m<=0)return y>0&&a({waitedMs:s()-p,attempts:y,host:hy(l),error:R}),h;let P=S??n;P=Math.min(Math.max(P,1e3),12e4),P=Math.min(P,m),y+=1,i({attempt:y,delayMs:P,remainingMs:m,host:hy(l),error:R}),await o(P)}}}var su=O(()=>{});function fy(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim():""}function EE(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function gy(t){let e=fy(t);return typeof t=="string"&&EE(e)?PE:e.slice(0,200)}function yy(t,e){return ou(t,e)}function by(t){return t instanceof ce&&yy(t.status,t.body)}function CE(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function wy(t){return t.replace(/\/+$/,"")}function iu(t=process.env){let e=(t[uo]??"").trim(),r=(t[Ji]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function au(t){let e;try{e=new URL(t)}catch{return`${uo} 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:`${uo} 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 ce,PE,AE,J,uo,Ji,as,Qt=O(()=>{su();ce=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};PE="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";AE="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";J=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=wy(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:Gi(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(CE()){let l=fy(a);throw new ce(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}if(yy(s.status,a))throw new ce(AE,s.status,a);let c=gy(a);throw new ce(`${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 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??[],roles:e.roles??[],labels:e.labels??[]})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},uo="TURBOBASE_REGISTRY_URL",Ji="TURBOBASE_REGISTRY_TOKEN";as=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=wy(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 ce(`${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 IE,statSync as OE}from"node:fs";import{resolve as Yi,sep as _y}from"node:path";function vy(t){if(zE.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function jE(t,e,r){let n=Yi(e,r),o=Yi(t);if(n!==o&&!n.startsWith(o+_y))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+_y)&&IE(i)&&OE(i).isFile())return i;return null}function xy(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(vy(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=jE(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:")||ME(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:LE,loader:"js"}))}}}function ME(t){let e=t.startsWith("node:")?t.slice(5):t;return DE.has(e.split("/")[0])}function ky(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 Sy(){try{return(await import("esbuild")).build}catch(t){throw ky("esbuild",t)}}async function UE(){try{return(await import("isolated-vm")).default}catch(t){throw ky("isolated-vm",t)}}async function ea(t,e={}){let r=await Sy(),n=e.resolveDir?Yi(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:[xy(n)]})}catch(s){let a=s.errors?.map(c=>c.text).filter(Boolean).join("; ");throw new Xi(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function cu(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Sy(),n=Yi(e),o=xy(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},c=>c.kind==="entry-point"?null:vy(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 Xi(l||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function cs(t,e,r={}){let n=r.timeoutMs??Qi,o=r.memoryLimitMb??NE,s=r.member??"run",i={patches:[],logs:[]},a=await UE(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(F=>{let W=JSON.parse(String(F));i.rejection||(i.rejection=W)}),y=new a.Callback(F=>{i.patches.push(JSON.parse(String(F)))}),h=new a.Callback(F=>{let W=JSON.parse(String(F));i.logs.push(W)}),m=new a.Callback(F=>{i.result=JSON.parse(String(F))}),w=r.query,S=new a.Reference(async F=>{if(!w)throw new Error("ctx.query is not available in this context");return JSON.stringify(await w(String(F)))});await u.set("__tb_reject",p),await u.set("__tb_patch",y),await u.set("__tb_log",h),await u.set("__tb_result",m),await u.set("__tb_query",S),await u.set("__tb_ctx_json",JSON.stringify(qE(e)));let R=BE(t,s,r.stepIndex??0,!!r.query),z=await(await c.compileScript(R)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!z}:{effects:i}}finally{c.isDisposed||c.dispose()}}function qE(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 FE(t){return`
42
+ `}var AE,hy=O(()=>{Gl();eu();eu();Gl();AE=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
43
+ `)});var tu=O(()=>{rs();Yg();ey();sy();ly();hy()});import{homedir as CE}from"node:os";import{join as my}from"node:path";import{promises as ru}from"node:fs";function Mt(t){return t.trim().replace(/\/+$/,"")}function Gi(){let t=process.env.TURBOBASE_HOME??my(CE(),".turbobase");return{dir:t,file:my(t,"credentials")}}function fy(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function as(){let{file:t}=Gi(),e;try{let s=await ru.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))fy(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))fy(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:IE(n),tenants:n}}function IE(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 nu(t){let{dir:e,file:r}=Gi();await ru.mkdir(e,{recursive:!0,mode:448}),await ru.writeFile(r,JSON.stringify(t,null,2)+`
44
+ `,{mode:384})}async function gy(t){let e=Mt(t.baseUrl),r=await as(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await nu(r),{baseUrl:e,token:t.token,updatedAt:n}}async function Qt(t){let e=await as();if(t){let s=Mt(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 Ji(t){let e=Mt(t),r=await as(),n=r.tenants[e];return n?(r.active=e,await nu(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ou(t){let e=await as(),r=t?Mt(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 nu(e),r}async function Ar(){let t=await as();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var cs=O(()=>{});function iu(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function OE(t){if(t)try{return JSON.parse(t)}catch{return t}}function NE(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 zE(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function LE(t,e){let r=NE(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=OE(n),s=iu(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??zE(n),error:i}}function jE(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 yy(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 su(t){return`${Math.round(t/1e3)}s`}function DE(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${su(t.delayMs)} before retrying (${su(t.remainingMs)} of the retry budget left).
45
+ `)}function ME(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${su(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
46
+ `)}function Yi(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??DE,a=e.onGiveUp??ME;return async(l,u)=>{let p=s(),b=0;for(;;){let m=await t(l,u);if(m.status!==503||u&&!jE(u.body))return m;let h=r-(s()-p),{maintenance:w,delayMs:S,error:R}=await LE(m,s());if(!w)return m;if(h<=0)return b>0&&a({waitedMs:s()-p,attempts:b,host:yy(l),error:R}),m;let P=S??n;P=Math.min(Math.max(P,1e3),12e4),P=Math.min(P,h),b+=1,i({attempt:b,delayMs:P,remainingMs:h,host:yy(l),error:R}),await o(P)}}}var au=O(()=>{});function by(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim():""}function UE(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function wy(t){let e=by(t);return typeof t=="string"&&UE(e)?qE:e.slice(0,200)}function _y(t,e){return iu(t,e)}function vy(t){return t instanceof le&&_y(t.status,t.body)}function FE(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function xy(t){return t.replace(/\/+$/,"")}function cu(t=process.env){let e=(t[uo]??"").trim(),r=(t[Xi]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function lu(t){let e;try{e=new URL(t)}catch{return`${uo} 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:`${uo} 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 le,qE,BE,G,uo,Xi,ls,er=O(()=>{au();le=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};qE="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";BE="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";G=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:Yi(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(FE()){let l=by(a);throw new le(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}if(_y(s.status,a))throw new le(BE,s.status,a);let c=wy(a);throw new le(`${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 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})}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`)}},uo="TURBOBASE_REGISTRY_URL",Xi="TURBOBASE_REGISTRY_TOKEN";ls=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=wy(a);throw new le(`${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 ZE,statSync as VE}from"node:fs";import{resolve as Qi,sep as ky}from"node:path";function Sy(t){if(KE.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function GE(t,e,r){let n=Qi(e,r),o=Qi(t);if(n!==o&&!n.startsWith(o+ky))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+ky)&&ZE(i)&&VE(i).isFile())return i;return null}function $y(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Sy(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=GE(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:")||YE(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:WE,loader:"js"}))}}}function YE(t){let e=t.startsWith("node:")?t.slice(5):t;return JE.has(e.split("/")[0])}function Ty(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 Ry(){try{return(await import("esbuild")).build}catch(t){throw Ty("esbuild",t)}}async function XE(){try{return(await import("isolated-vm")).default}catch(t){throw Ty("isolated-vm",t)}}async function ra(t,e={}){let r=await Ry(),n=e.resolveDir?Qi(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:[$y(n)]})}catch(s){let a=s.errors?.map(c=>c.text).filter(Boolean).join("; ");throw new ea(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function uu(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Ry(),n=Qi(e),o=$y(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},c=>c.kind==="entry-point"?null:Sy(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 ea(l||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function us(t,e,r={}){let n=r.timeoutMs??ta,o=r.memoryLimitMb??HE,s=r.member??"run",i={patches:[],logs:[]},a=await XE(),c=new a.Isolate({memoryLimit:o});try{let l=await c.createContext(),u=l.global,p=new a.Callback(B=>{let K=JSON.parse(String(B));i.rejection||(i.rejection=K)}),b=new a.Callback(B=>{i.patches.push(JSON.parse(String(B)))}),m=new a.Callback(B=>{let K=JSON.parse(String(B));i.logs.push(K)}),h=new a.Callback(B=>{i.result=JSON.parse(String(B))}),w=r.query,S=new a.Reference(async B=>{if(!w)throw new Error("ctx.query is not available in this context");return JSON.stringify(await w(String(B)))});await u.set("__tb_reject",p),await u.set("__tb_patch",b),await u.set("__tb_log",m),await u.set("__tb_result",h),await u.set("__tb_query",S),await u.set("__tb_ctx_json",JSON.stringify(QE(e)));let R=t0(t,s,r.stepIndex??0,!!r.query),z=await(await c.compileScript(R)).run(l,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!z}:{effects:i}}finally{c.isDisposed||c.dispose()}}function QE(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 e0(t){return`
47
47
  "use strict";
48
48
  (async () => {
49
49
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -66,7 +66,7 @@ ${o.join(`
66
66
  __tb_result(JSON.stringify(out == null ? null : String(out)));
67
67
  return undefined;
68
68
  })()
69
- `}function BE(t,e,r,n=!1){return e==="build"?ZE(t,r):e==="outstanding"?FE(t):`
69
+ `}function t0(t,e,r,n=!1){return e==="build"?r0(t,r):e==="outstanding"?e0(t):`
70
70
  "use strict";
71
71
  (async () => {
72
72
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -147,7 +147,7 @@ ${o.join(`
147
147
  ${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":e==="idempotencyKey"?"__tb_result(JSON.stringify(out == null ? null : String(out)));":""}
148
148
  return ${e==="when"?"out":"undefined"};
149
149
  })()
150
- `}function ZE(t,e){return`
150
+ `}function r0(t,e){return`
151
151
  "use strict";
152
152
  (async () => {
153
153
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -189,37 +189,37 @@ ${o.join(`
189
189
  __tb_result(JSON.stringify(out == null ? null : out));
190
190
  return undefined;
191
191
  })()
192
- `}var Qi,NE,zE,LE,Xi,DE,ta=O(()=>{Qi=200,NE=16,zE=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"]);LE=`
192
+ `}var ta,HE,KE,WE,ea,JE,na=O(()=>{ta=200,HE=16,KE=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"]);WE=`
193
193
  export const defineHook = (def) => def;
194
194
  export const defineConduit = (def) => def;
195
195
  export const defineProcess = (def) => def;
196
196
  export default defineHook;
197
- `;Xi=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};DE=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 lu}from"node:fs";import{join as VE}from"node:path";function HE(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 KE(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await cs(t,HE(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 ra(t,e,r={}){let n=await ea(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await KE(n,e[s],`sample[${s}]`));return o}async function ls(t){let e;try{e=await lu.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 lu.readFile(VE(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 us(t){return lu.readFile(t,"utf8")}var uu=O(()=>{ta()});function $t(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function z0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
197
+ `;ea=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};JE=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 du}from"node:fs";import{join as n0}from"node:path";function o0(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 s0(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await us(t,o0(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 oa(t,e,r={}){let n=await ra(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await s0(n,e[s],`sample[${s}]`));return o}async function ds(t){let e;try{e=await du.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 du.readFile(n0(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 ps(t){return du.readFile(t,"utf8")}var pu=O(()=>{na()});function Tt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function K0(t){let e=t.recordType;if(!e)throw new Rt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
198
198
  source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
199
199
  run: (ctx) => {
200
200
  // Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
201
201
  // with ctx.patch({...}); observe with ctx.log('info', '...').
202
- },`,a="custom";else if(n==="require-field"){let y=t.field;if(!y)throw new Tt("require-field template needs --field=<name>");i=`
202
+ },`,a="custom";else if(n==="require-field"){let b=t.field;if(!b)throw new Rt("require-field template needs --field=<name>");i=`
203
203
  run: (ctx) => {
204
- const v = ctx.payload[${JSON.stringify(y)}];
204
+ const v = ctx.payload[${JSON.stringify(b)}];
205
205
  if (v === undefined || v === null || v === '') {
206
206
  ctx.reject({
207
207
  code: 'MANDATORY_FIELD_MISSING',
208
- field: ${JSON.stringify(y)},
209
- message: ${JSON.stringify(`${y} is required`)},
208
+ field: ${JSON.stringify(b)},
209
+ message: ${JSON.stringify(`${b} is required`)},
210
210
  });
211
211
  }
212
- },`,a=`require-field-${y}`}else if(n==="enforce-format"){let y=t.field;if(!y)throw new Tt("enforce-format template needs --field=<name>");if(!t.regex)throw new Tt("enforce-format template needs --regex=<pattern>");i=`
212
+ },`,a=`require-field-${b}`}else if(n==="enforce-format"){let b=t.field;if(!b)throw new Rt("enforce-format template needs --field=<name>");if(!t.regex)throw new Rt("enforce-format template needs --regex=<pattern>");i=`
213
213
  run: (ctx) => {
214
- const v = ctx.payload[${JSON.stringify(y)}];
214
+ const v = ctx.payload[${JSON.stringify(b)}];
215
215
  if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
216
216
  ctx.reject({
217
217
  code: 'INVALID_FORMAT',
218
- field: ${JSON.stringify(y)},
219
- message: ${JSON.stringify(`${y} does not match expected format`)},
218
+ field: ${JSON.stringify(b)},
219
+ message: ${JSON.stringify(`${b} does not match expected format`)},
220
220
  });
221
221
  }
222
- },`,a=`enforce-format-${y}`}else throw new Tt(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${$t(t.regex).slice(0,24)}`:""}`,u=`/**
222
+ },`,a=`enforce-format-${b}`}else throw new Rt(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let c=t.id??`custom:${e}:${a}${t.regex?`-${Tt(t.regex).slice(0,24)}`:""}`,u=`/**
223
223
  * ${t.description??`${a} on ${e}.${r}`}
224
224
  *
225
225
  * Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
@@ -232,7 +232,7 @@ export default defineHook<Record<string, unknown>>({
232
232
  recordType: ${JSON.stringify(e)},
233
233
  event: ${JSON.stringify(r)},${s}${i}
234
234
  });
235
- `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function L0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Tt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Tt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Tt(`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??`${$t(r)}2${$t(n)}:${$t(e)}`,c=`/**
235
+ `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:u}}function W0(t){let e=t.recordType;if(!e)throw new Rt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Rt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Rt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Rt(`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??`${Tt(r)}2${Tt(n)}:${Tt(e)}`,c=`/**
236
236
  * ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
237
237
  *
238
238
  * Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
@@ -275,14 +275,14 @@ export default defineConduit<Record<string, unknown>>({
275
275
  },
276
276
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
277
277
  });
278
- `;return{relativePath:`conduits/${$t(r)}-${$t(e)}-to-${$t(n)}-${$t(o)}.ts`,content:c}}function j0(t){let e=t.recordType;if(!e)throw new Tt("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Tt(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${$t(e)}-then-${$t(r)}`:$t(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?`
278
+ `;return{relativePath:`conduits/${Tt(r)}-${Tt(e)}-to-${Tt(n)}-${Tt(o)}.ts`,content:c}}function G0(t){let e=t.recordType;if(!e)throw new Rt("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Rt(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${Tt(e)}-then-${Tt(r)}`:Tt(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?`
279
279
  {
280
- id: ${JSON.stringify($t(r))},
280
+ id: ${JSON.stringify(Tt(r))},
281
281
  recordType: ${JSON.stringify(r)},
282
282
  build: (ctx) => ({
283
283
  parent: {
284
284
  // The first step declared awaitSource, so its source-minted id is here.
285
- created_from_id: ctx.steps[${JSON.stringify($t(e))}]?.externalId ?? null,
285
+ created_from_id: ctx.steps[${JSON.stringify(Tt(e))}]?.externalId ?? null,
286
286
  // ...mapped fields from ctx.input...
287
287
  },
288
288
  }),
@@ -312,7 +312,7 @@ export default defineProcess({
312
312
  },
313
313
  steps: [
314
314
  {
315
- id: ${JSON.stringify($t(e))},
315
+ id: ${JSON.stringify(Tt(e))},
316
316
  recordType: ${JSON.stringify(e)},${r?`
317
317
  awaitSource: true,`:""}
318
318
  build: (ctx) => ({
@@ -324,7 +324,7 @@ export default defineProcess({
324
324
  ],
325
325
  onFailure: ${JSON.stringify(n)},
326
326
  });
327
- `;return{relativePath:`processes/${o}.ts`,content:c}}function fr(t,e){let r=D0[t];if(!r)throw new Tt(`unknown extension kind '${t}'. Scaffoldable kinds: ${Qy.join(", ")}.`);return r(e)}var Qy,Tt,D0,aa=O(()=>{Qy=["hook","conduit","process"];Tt=class extends Error{};D0={hook:z0,conduit:L0,process:j0}});var Cu,Iu=O(()=>{Cu=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function XA(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 QA(t){return vw[XA(t)%vw.length]}function eC(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 xw(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function kw(t,e){let[r,n]=QA(t),o=xw(eC(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${xw(e)}">
327
+ `;return{relativePath:`processes/${o}.ts`,content:c}}function gr(t,e){let r=J0[t];if(!r)throw new Rt(`unknown extension kind '${t}'. Scaffoldable kinds: ${rb.join(", ")}.`);return r(e)}var rb,Rt,J0,la=O(()=>{rb=["hook","conduit","process"];Rt=class extends Error{};J0={hook:K0,conduit:W0,process:G0}});var Nu,zu=O(()=>{Nu=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function fC(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 gC(t){return Iw[fC(t)%Iw.length]}function yC(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 Ow(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Nw(t,e){let[r,n]=gC(t),o=Ow(yC(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Ow(e)}">
328
328
  <defs>
329
329
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
330
330
  <stop offset="0" stop-color="${r}"/>
@@ -334,9 +334,9 @@ export default defineProcess({
334
334
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
335
335
  <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>
336
336
  </svg>
337
- `}var vw,Sw=O(()=>{vw=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Uw={};Xo(Uw,{CN_UTIL:()=>Aw,COMPONENTS_JSON:()=>Pw,MAIN_TSX:()=>Iw,STYLES_CSS:()=>Ow,TSCONFIG:()=>Ew,TURBOBASE_CLIENT:()=>$w,UI_BADGE:()=>Lw,UI_BUTTON:()=>Nw,UI_CARD:()=>zw,UI_INPUT:()=>Dw,UI_LABEL:()=>Mw,UI_TABLE:()=>jw,indexHtml:()=>Cw,instanceOriginFromEnv:()=>lC,packageJson:()=>Tw,scaffoldAppFiles:()=>dC,starterApp:()=>pC,viteConfig:()=>Rw});function nC(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 oC(t){let e={name:nC(t.title,rC)},r=(t.description??"").trim().slice(0,tC);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Cu},JSON.stringify(e,null,2)+`
338
- `}function Tw(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:sC},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"}},null,2)}
339
- `}function cC(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 lC(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Rw(t,e={}){let r=cC(e.instanceOrigin);return`import { defineConfig } from 'vite';
337
+ `}var Iw,zw=O(()=>{Iw=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Yw={};es(Yw,{CN_UTIL:()=>qw,COMPONENTS_JSON:()=>Uw,MAIN_TSX:()=>Fw,STYLES_CSS:()=>Zw,TSCONFIG:()=>Mw,TURBOBASE_CLIENT:()=>Lw,UI_BADGE:()=>Kw,UI_BUTTON:()=>Vw,UI_CARD:()=>Hw,UI_INPUT:()=>Gw,UI_LABEL:()=>Jw,UI_TABLE:()=>Ww,indexHtml:()=>Bw,instanceOriginFromEnv:()=>TC,packageJson:()=>jw,scaffoldAppFiles:()=>EC,starterApp:()=>PC,viteConfig:()=>Dw});function _C(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 vC(t){let e={name:_C(t.title,wC)},r=(t.description??"").trim().slice(0,bC);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Nu},JSON.stringify(e,null,2)+`
338
+ `}function jw(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:xC},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"}},null,2)}
339
+ `}function $C(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 TC(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Dw(t,e={}){let r=$C(e.instanceOrigin);return`import { defineConfig } from 'vite';
340
340
  import { fileURLToPath, URL } from 'node:url';
341
341
  import react from '@vitejs/plugin-react';
342
342
  // Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
@@ -355,8 +355,8 @@ import tailwindcss from '@tailwindcss/vite';
355
355
  // you sign in, and the cookies land on localhost:3000. Override the targets
356
356
  // with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
357
357
  // them at boot; restart the dev server after changing one).
358
- const TENANT = process.env.SUPABASE_URL || '${r??iC}'; // /rest + the Realtime WS
359
- const API = process.env.TURBOBASE_API_URL || '${r??aC}'; // /v1, /auth, /login, /_app
358
+ const TENANT = process.env.SUPABASE_URL || '${r??kC}'; // /rest + the Realtime WS
359
+ const API = process.env.TURBOBASE_API_URL || '${r??SC}'; // /v1, /auth, /login, /_app
360
360
 
361
361
  // Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
362
362
  // this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
@@ -394,7 +394,7 @@ export default defineConfig({
394
394
  },
395
395
  build: { outDir: 'dist' },
396
396
  });
397
- `}function Cw(t){return`<!doctype html>
397
+ `}function Bw(t){return`<!doctype html>
398
398
  <html lang="en">
399
399
  <head>
400
400
  <meta charset="UTF-8" />
@@ -407,7 +407,7 @@ export default defineConfig({
407
407
  <script type="module" src="/src/main.tsx"></script>
408
408
  </body>
409
409
  </html>
410
- `}function dC(t){return{"package.json":Tw(t.slug),"vite.config.ts":Rw(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":uC,"tsconfig.json":Ew,"index.html":Cw(t.title),"public/turbobase.json":oC(t),"public/favicon.svg":kw(t.slug,t.title),"src/main.tsx":Iw,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":$w,"src/styles.css":Ow,"components.json":Pw,"src/lib/utils.ts":Aw,"src/components/ui/button.tsx":Nw,"src/components/ui/card.tsx":zw,"src/components/ui/badge.tsx":Lw,"src/components/ui/table.tsx":jw,"src/components/ui/input.tsx":Dw,"src/components/ui/label.tsx":Mw,"README.md":`# ${t.title}
410
+ `}function EC(t){return{"package.json":jw(t.slug),"vite.config.ts":Dw(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":RC,"tsconfig.json":Mw,"index.html":Bw(t.title),"public/turbobase.json":vC(t),"public/favicon.svg":Nw(t.slug,t.title),"src/main.tsx":Fw,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Lw,"src/styles.css":Zw,"components.json":Uw,"src/lib/utils.ts":qw,"src/components/ui/button.tsx":Vw,"src/components/ui/card.tsx":Hw,"src/components/ui/badge.tsx":Kw,"src/components/ui/table.tsx":Ww,"src/components/ui/input.tsx":Gw,"src/components/ui/label.tsx":Jw,"README.md":`# ${t.title}
411
411
 
412
412
  \`\`\`sh
413
413
  npm install
@@ -428,7 +428,7 @@ every read comes back "permission denied", which looks like an RLS problem.
428
428
 
429
429
  \`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
430
430
  live access token and is gitignored \u2014 keep it that way.
431
- `}}function pC(t){return`import React from 'react';
431
+ `}}function PC(t){return`import React from 'react';
432
432
  import { Loader2, Trash2 } from 'lucide-react';
433
433
 
434
434
  import { select, write, del } from '@/lib/turbobase';
@@ -653,7 +653,7 @@ export default function App() {
653
653
  </main>
654
654
  );
655
655
  }
656
- `}var tC,rC,$w,_s,sC,iC,aC,uC,Ew,Pw,Aw,Iw,Ow,Nw,zw,Lw,jw,Dw,Mw,qw=O(()=>{Sw();Iu();tC=200,rC=60;$w=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
656
+ `}var bC,wC,Lw,ks,xC,kC,SC,RC,Mw,Uw,qw,Fw,Zw,Vw,Hw,Kw,Ww,Gw,Jw,Xw=O(()=>{zw();zu();bC=200,wC=60;Lw=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
657
657
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
658
658
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
659
659
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -1683,7 +1683,7 @@ export async function selectPage<T = unknown>(
1683
1683
  }
1684
1684
  return { rows, nextCursor };
1685
1685
  }
1686
- `,_s="src/types.ts",sC=`turbobase project types -o ${_s} || node -e "if(require('node:fs').existsSync('${_s}')){console.error('turbobase: could not refresh ${_s} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${_s} 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 ${_s}');process.exit(1)}"`;iC="http://localhost:54331",aC="http://localhost:4100";uC=`node_modules/
1686
+ `,ks="src/types.ts",xC=`turbobase project types -o ${ks} || node -e "if(require('node:fs').existsSync('${ks}')){console.error('turbobase: could not refresh ${ks} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${ks} 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 ${ks}');process.exit(1)}"`;kC="http://localhost:54331",SC="http://localhost:4100";RC=`node_modules/
1687
1687
  dist/
1688
1688
  build/
1689
1689
 
@@ -1695,9 +1695,9 @@ build/
1695
1695
  !.env.example
1696
1696
 
1697
1697
  .DS_Store
1698
- `,Ew=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
1699
- `,Pw=`${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)}
1700
- `,Aw=`import { clsx, type ClassValue } from 'clsx';
1698
+ `,Mw=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
1699
+ `,Uw=`${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)}
1700
+ `,qw=`import { clsx, type ClassValue } from 'clsx';
1701
1701
  import { twMerge } from 'tailwind-merge';
1702
1702
 
1703
1703
  /**
@@ -1711,7 +1711,7 @@ import { twMerge } from 'tailwind-merge';
1711
1711
  export function cn(...inputs: ClassValue[]) {
1712
1712
  return twMerge(clsx(inputs));
1713
1713
  }
1714
- `;Iw=`import React from 'react';
1714
+ `;Fw=`import React from 'react';
1715
1715
  import { createRoot } from 'react-dom/client';
1716
1716
  import App from './App';
1717
1717
  import './styles.css';
@@ -1721,7 +1721,7 @@ createRoot(document.getElementById('root')!).render(
1721
1721
  <App />
1722
1722
  </React.StrictMode>,
1723
1723
  );
1724
- `,Ow=`@import 'tailwindcss';
1724
+ `,Zw=`@import 'tailwindcss';
1725
1725
  @import 'tw-animate-css';
1726
1726
 
1727
1727
  /* Inter, self-hosted \u2014 the design system's font.
@@ -1809,7 +1809,7 @@ createRoot(document.getElementById('root')!).render(
1809
1809
  transition-duration: 0.01ms !important;
1810
1810
  }
1811
1811
  }
1812
- `,Nw=`import * as React from 'react';
1812
+ `,Vw=`import * as React from 'react';
1813
1813
  import { cva, type VariantProps } from 'class-variance-authority';
1814
1814
 
1815
1815
  import { cn } from '@/lib/utils';
@@ -1849,7 +1849,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
1849
1849
  Button.displayName = 'Button';
1850
1850
 
1851
1851
  export { Button, buttonVariants };
1852
- `,zw=`import * as React from 'react';
1852
+ `,Hw=`import * as React from 'react';
1853
1853
 
1854
1854
  import { cn } from '@/lib/utils';
1855
1855
 
@@ -1887,7 +1887,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
1887
1887
  CardContent.displayName = 'CardContent';
1888
1888
 
1889
1889
  export { Card, CardHeader, CardTitle, CardDescription, CardContent };
1890
- `,Lw=`import * as React from 'react';
1890
+ `,Kw=`import * as React from 'react';
1891
1891
  import { cva, type VariantProps } from 'class-variance-authority';
1892
1892
 
1893
1893
  import { cn } from '@/lib/utils';
@@ -1922,7 +1922,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
1922
1922
  }
1923
1923
 
1924
1924
  export { Badge, badgeVariants };
1925
- `,jw=`import * as React from 'react';
1925
+ `,Ww=`import * as React from 'react';
1926
1926
 
1927
1927
  import { cn } from '@/lib/utils';
1928
1928
 
@@ -1981,7 +1981,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
1981
1981
  TableCell.displayName = 'TableCell';
1982
1982
 
1983
1983
  export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
1984
- `,Dw=`import * as React from 'react';
1984
+ `,Gw=`import * as React from 'react';
1985
1985
 
1986
1986
  import { cn } from '@/lib/utils';
1987
1987
 
@@ -2001,7 +2001,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
2001
2001
  Input.displayName = 'Input';
2002
2002
 
2003
2003
  export { Input };
2004
- `,Mw=`import * as React from 'react';
2004
+ `,Jw=`import * as React from 'react';
2005
2005
 
2006
2006
  import { cn } from '@/lib/utils';
2007
2007
 
@@ -2018,78 +2018,78 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
2018
2018
  Label.displayName = 'Label';
2019
2019
 
2020
2020
  export { Label };
2021
- `});var vs=O(()=>{Mi()});function I(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Ot(t){return t&&Object.assign(va,t),va}var hC,Or,va,vo=O(()=>{hC=Object.freeze({status:"aborted"});Or=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},va={}});var we={};Xo(we,{BIGINT_FORMAT_RANGES:()=>Bw,Class:()=>Vu,NUMBER_FORMAT_RANGES:()=>Xu,aborted:()=>Ln,allowsEval:()=>Gu,assert:()=>wC,assertEqual:()=>fC,assertIs:()=>yC,assertNever:()=>bC,assertNotEqual:()=>gC,assignProp:()=>Wu,cached:()=>Ss,captureStackTrace:()=>ka,cleanEnum:()=>IC,cleanRegex:()=>Ts,clone:()=>Nt,createTransparentProxy:()=>$C,defineLazy:()=>Ne,esc:()=>zn,escapeRegex:()=>Jr,extend:()=>EC,finalizeIssue:()=>rr,floatSafeRemainder:()=>Ku,getElementAtPath:()=>_C,getEnumValues:()=>ks,getLengthableOrigin:()=>Rs,getParsedType:()=>SC,getSizableOrigin:()=>Zw,isObject:()=>xo,isPlainObject:()=>ko,issue:()=>Qu,joinValues:()=>xa,jsonStringifyReplacer:()=>Hu,merge:()=>PC,normalizeParams:()=>ie,nullish:()=>$s,numKeys:()=>kC,omit:()=>RC,optionalKeys:()=>Yu,partial:()=>AC,pick:()=>TC,prefixIssues:()=>gr,primitiveTypes:()=>Fw,promiseAllObject:()=>vC,propertyKeyTypes:()=>Ju,randomString:()=>xC,required:()=>CC,stringifyPrimitive:()=>Sa,unwrapMessage:()=>xs});function fC(t){return t}function gC(t){return t}function yC(t){}function bC(t){throw new Error}function wC(t){}function ks(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 xa(t,e="|"){return t.map(r=>Sa(r)).join(e)}function Hu(t,e){return typeof e=="bigint"?e.toString():e}function Ss(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function $s(t){return t==null}function Ts(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ku(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 Ne(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 Wu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function _C(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function vC(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 xC(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function zn(t){return JSON.stringify(t)}function xo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ko(t){if(xo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(xo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function kC(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Jr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ie(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 $C(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 Sa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Yu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function TC(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 Nt(t,{...t._zod.def,shape:r,checks:[]})}function RC(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 Nt(t,{...t._zod.def,shape:r,checks:[]})}function EC(t,e){if(!ko(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 Wu(this,"shape",n),n},checks:[]};return Nt(t,r)}function PC(t,e){return Nt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Wu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function AC(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 Nt(e,{...e._zod.def,shape:o,checks:[]})}function CC(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 Nt(e,{...e._zod.def,shape:o,checks:[]})}function Ln(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function gr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function xs(t){return typeof t=="string"?t:t?.message}function rr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=xs(t.inst?._zod.def?.error?.(t))??xs(e?.error?.(t))??xs(r.customError?.(t))??xs(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Zw(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Rs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Qu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function IC(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var ka,Gu,SC,Ju,Fw,Xu,Bw,Vu,yr=O(()=>{ka=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Gu=Ss(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});SC=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}`)}},Ju=new Set(["string","number","symbol"]),Fw=new Set(["string","number","bigint","boolean","symbol","undefined"]);Xu={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]},Bw={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Vu=class{constructor(...e){}}});function ed(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 td(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 Vw,$a,Es,rd=O(()=>{vo();yr();Vw=(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,Hu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},$a=I("$ZodError",Vw),Es=I("$ZodError",Vw,{Parent:Error})});var nd,od,sd,id,ad,jn,cd,Dn,ld=O(()=>{vo();rd();yr();nd=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 Or;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>rr(c,s,Ot())));throw ka(a,o?.callee),a}return i.value},od=nd(Es),sd=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=>rr(c,s,Ot())));throw ka(a,o?.callee),a}return i.value},id=sd(Es),ad=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 Or;return s.issues.length?{success:!1,error:new(t??$a)(s.issues.map(i=>rr(i,o,Ot())))}:{success:!0,data:s.value}},jn=ad(Es),cd=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=>rr(i,o,Ot())))}:{success:!0,data:s.value}},Dn=cd(Es)});function t_(){return new RegExp(NC,"u")}function d_(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 p_(t){return new RegExp(`^${d_(t)}$`)}function m_(t){let e=d_({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(`^${l_}T(?:${n})$`)}var Hw,Kw,Ww,Gw,Jw,Yw,Xw,Qw,ud,e_,NC,r_,n_,o_,s_,i_,dd,a_,c_,l_,u_,h_,f_,g_,y_,b_,w_,__,Ra=O(()=>{Hw=/^[cC][^\s-]{8,}$/,Kw=/^[0-9a-z]+$/,Ww=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Gw=/^[0-9a-vA-V]{20}$/,Jw=/^[A-Za-z0-9]{27}$/,Yw=/^[a-zA-Z0-9_-]{21}$/,Xw=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Qw=/^([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})$/,ud=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)$/,e_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,NC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";r_=/^(?:(?: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])$/,n_=/^(([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})$/,o_=/^((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])$/,s_=/^(([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])$/,i_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,dd=/^[A-Za-z0-9_-]*$/,a_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,c_=/^\+(?:[0-9]){6,14}[0-9]$/,l_="(?:(?:\\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])))",u_=new RegExp(`^${l_}$`);h_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},f_=/^\d+$/,g_=/^-?\d+(?:\.\d+)?/i,y_=/true|false/i,b_=/null/i,w_=/^[^A-Z]*$/,__=/^[^a-z]*$/});var it,v_,pd,md,x_,k_,S_,$_,T_,Ps,R_,E_,P_,A_,C_,I_,O_,Ea=O(()=>{vo();Ra();yr();it=I("$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"},pd=I("$ZodCheckLessThan",(t,e)=>{it.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})}}),md=I("$ZodCheckGreaterThan",(t,e)=>{it.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})}}),x_=I("$ZodCheckMultipleOf",(t,e)=>{it.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):Ku(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})}}),k_=I("$ZodCheckNumberFormat",(t,e)=>{it.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Xu[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=f_)}),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})}}),S_=I("$ZodCheckMaxLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Rs(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),$_=I("$ZodCheckMinLength",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Rs(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),T_=I("$ZodCheckLengthEquals",(t,e)=>{var r;it.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!$s(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=Rs(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})}}),Ps=I("$ZodCheckStringFormat",(t,e)=>{var r,n;it.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=()=>{})}),R_=I("$ZodCheckRegex",(t,e)=>{Ps.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})}}),E_=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=w_),Ps.init(t,e)}),P_=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=__),Ps.init(t,e)}),A_=I("$ZodCheckIncludes",(t,e)=>{it.init(t,e);let r=Jr(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})}}),C_=I("$ZodCheckStartsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`^${Jr(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})}}),I_=I("$ZodCheckEndsWith",(t,e)=>{it.init(t,e);let r=new RegExp(`.*${Jr(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})}}),O_=I("$ZodCheckOverwrite",(t,e)=>{it.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Pa,hd=O(()=>{Pa=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(`
2021
+ `});var Ss=O(()=>{qi()});function I(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Nt(t){return t&&Object.assign(ka,t),ka}var CC,Nr,ka,xo=O(()=>{CC=Object.freeze({status:"aborted"});Nr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ka={}});var ve={};es(ve,{BIGINT_FORMAT_RANGES:()=>e_,Class:()=>Wu,NUMBER_FORMAT_RANGES:()=>td,aborted:()=>jn,allowsEval:()=>Xu,assert:()=>LC,assertEqual:()=>IC,assertIs:()=>NC,assertNever:()=>zC,assertNotEqual:()=>OC,assignProp:()=>Yu,cached:()=>Rs,captureStackTrace:()=>$a,cleanEnum:()=>GC,cleanRegex:()=>Ps,clone:()=>zt,createTransparentProxy:()=>BC,defineLazy:()=>Le,esc:()=>Ln,escapeRegex:()=>Yr,extend:()=>VC,finalizeIssue:()=>nr,floatSafeRemainder:()=>Ju,getElementAtPath:()=>jC,getEnumValues:()=>Ts,getLengthableOrigin:()=>As,getParsedType:()=>qC,getSizableOrigin:()=>t_,isObject:()=>ko,isPlainObject:()=>So,issue:()=>rd,joinValues:()=>Sa,jsonStringifyReplacer:()=>Gu,merge:()=>HC,normalizeParams:()=>ie,nullish:()=>Es,numKeys:()=>UC,omit:()=>ZC,optionalKeys:()=>ed,partial:()=>KC,pick:()=>FC,prefixIssues:()=>yr,primitiveTypes:()=>Qw,promiseAllObject:()=>DC,propertyKeyTypes:()=>Qu,randomString:()=>MC,required:()=>WC,stringifyPrimitive:()=>Ta,unwrapMessage:()=>$s});function IC(t){return t}function OC(t){return t}function NC(t){}function zC(t){throw new Error}function LC(t){}function Ts(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 Sa(t,e="|"){return t.map(r=>Ta(r)).join(e)}function Gu(t,e){return typeof e=="bigint"?e.toString():e}function Rs(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Es(t){return t==null}function Ps(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Ju(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 Yu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function jC(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function DC(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 MC(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Ln(t){return JSON.stringify(t)}function ko(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function So(t){if(ko(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(ko(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function UC(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Yr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function zt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function ie(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 BC(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 Ta(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ed(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function FC(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 zt(t,{...t._zod.def,shape:r,checks:[]})}function ZC(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 zt(t,{...t._zod.def,shape:r,checks:[]})}function VC(t,e){if(!So(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Yu(this,"shape",n),n},checks:[]};return zt(t,r)}function HC(t,e){return zt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Yu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function KC(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 zt(e,{...e._zod.def,shape:o,checks:[]})}function WC(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 zt(e,{...e._zod.def,shape:o,checks:[]})}function jn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function yr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function $s(t){return typeof t=="string"?t:t?.message}function nr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=$s(t.inst?._zod.def?.error?.(t))??$s(e?.error?.(t))??$s(r.customError?.(t))??$s(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function t_(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function As(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function rd(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function GC(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var $a,Xu,qC,Qu,Qw,td,e_,Wu,br=O(()=>{$a=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Xu=Rs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});qC=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}`)}},Qu=new Set(["string","number","symbol"]),Qw=new Set(["string","number","bigint","boolean","symbol","undefined"]);td={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]},e_={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Wu=class{constructor(...e){}}});function nd(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 od(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 r_,Ra,Cs,sd=O(()=>{xo();br();r_=(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,Gu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ra=I("$ZodError",r_),Cs=I("$ZodError",r_,{Parent:Error})});var id,ad,cd,ld,ud,Dn,dd,Mn,pd=O(()=>{xo();sd();br();id=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 Nr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>nr(c,s,Nt())));throw $a(a,o?.callee),a}return i.value},ad=id(Cs),cd=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=>nr(c,s,Nt())));throw $a(a,o?.callee),a}return i.value},ld=cd(Cs),ud=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 Nr;return s.issues.length?{success:!1,error:new(t??Ra)(s.issues.map(i=>nr(i,o,Nt())))}:{success:!0,data:s.value}},Dn=ud(Cs),dd=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=>nr(i,o,Nt())))}:{success:!0,data:s.value}},Mn=dd(Cs)});function p_(){return new RegExp(YC,"u")}function x_(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 k_(t){return new RegExp(`^${x_(t)}$`)}function S_(t){let e=x_({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(`^${__}T(?:${n})$`)}var n_,o_,s_,i_,a_,c_,l_,u_,hd,d_,YC,h_,m_,f_,g_,y_,md,b_,w_,__,v_,$_,T_,R_,E_,P_,A_,C_,Pa=O(()=>{n_=/^[cC][^\s-]{8,}$/,o_=/^[0-9a-z]+$/,s_=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,i_=/^[0-9a-vA-V]{20}$/,a_=/^[A-Za-z0-9]{27}$/,c_=/^[a-zA-Z0-9_-]{21}$/,l_=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,u_=/^([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})$/,hd=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)$/,d_=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,YC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";h_=/^(?:(?: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])$/,m_=/^(([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})$/,f_=/^((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])$/,g_=/^(([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])$/,y_=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,md=/^[A-Za-z0-9_-]*$/,b_=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,w_=/^\+(?:[0-9]){6,14}[0-9]$/,__="(?:(?:\\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])))",v_=new RegExp(`^${__}$`);$_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},T_=/^\d+$/,R_=/^-?\d+(?:\.\d+)?/i,E_=/true|false/i,P_=/null/i,A_=/^[^A-Z]*$/,C_=/^[^a-z]*$/});var ct,I_,fd,gd,O_,N_,z_,L_,j_,Is,D_,M_,U_,q_,B_,F_,Z_,Aa=O(()=>{xo();Pa();br();ct=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),I_={number:"number",bigint:"bigint",object:"date"},fd=I("$ZodCheckLessThan",(t,e)=>{ct.init(t,e);let r=I_[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})}}),gd=I("$ZodCheckGreaterThan",(t,e)=>{ct.init(t,e);let r=I_[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})}}),O_=I("$ZodCheckMultipleOf",(t,e)=>{ct.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):Ju(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})}}),N_=I("$ZodCheckNumberFormat",(t,e)=>{ct.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=td[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=T_)}),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})}}),z_=I("$ZodCheckMaxLength",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Es(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=As(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),L_=I("$ZodCheckMinLength",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Es(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=As(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),j_=I("$ZodCheckLengthEquals",(t,e)=>{var r;ct.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Es(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=As(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Is=I("$ZodCheckStringFormat",(t,e)=>{var r,n;ct.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=()=>{})}),D_=I("$ZodCheckRegex",(t,e)=>{Is.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})}}),M_=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=A_),Is.init(t,e)}),U_=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=C_),Is.init(t,e)}),q_=I("$ZodCheckIncludes",(t,e)=>{ct.init(t,e);let r=Yr(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})}}),B_=I("$ZodCheckStartsWith",(t,e)=>{ct.init(t,e);let r=new RegExp(`^${Yr(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})}}),F_=I("$ZodCheckEndsWith",(t,e)=>{ct.init(t,e);let r=new RegExp(`.*${Yr(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})}}),Z_=I("$ZodCheckOverwrite",(t,e)=>{ct.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ca,yd=O(()=>{Ca=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(`
2022
2022
  `).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(`
2023
- `))}}});var z_,fd=O(()=>{z_={major:4,minor:0,patch:0}});function G_(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function zC(t){if(!dd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return G_(r)}function LC(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 L_(t,e,r){t.issues.length&&e.issues.push(...gr(r,t.issues)),e.value[r]=t.value}function Aa(t,e,r){t.issues.length&&e.issues.push(...gr(r,t.issues)),e.value[r]=t.value}function j_(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(...gr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function D_(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=>rr(s,n,Ot())))}),e}function gd(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(ko(t)&&ko(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=gd(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=gd(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 M_(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Ln(t))return t;let n=gd(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 U_(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function q_(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 F_(t,e,r){return Ln(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function B_(t){return t.value=Object.freeze(t.value),t}function Z_(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(Qu(o))}}var Ae,As,ze,yd,bd,wd,_d,vd,xd,kd,Sd,$d,Td,Rd,V_,H_,K_,W_,Ed,Pd,Ad,Cd,Id,Od,Nd,zd,Ca,Ld,jd,Dd,Md,Ud,qd,Ia,Oa,Fd,Bd,Zd,Vd,Hd,Kd,Wd,Gd,Jd,Yd,Xd,Qd,ep,tp,rp,J_=O(()=>{Ea();vo();hd();ld();Ra();yr();fd();yr();Ae=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=z_;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=Ln(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,y=u._zod.check(s);if(y instanceof Promise&&a?.async===!1)throw new Or;if(l||y instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await y,s.issues.length!==p&&(c||(c=Ln(s,p)))});else{if(s.issues.length===p)continue;c||(c=Ln(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 Or;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=jn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Dn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),As=I("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??h_(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}}),ze=I("$ZodStringFormat",(t,e)=>{Ps.init(t,e),As.init(t,e)}),yd=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Qw),ze.init(t,e)}),bd=I("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ud(n))}else e.pattern??(e.pattern=ud());ze.init(t,e)}),wd=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=e_),ze.init(t,e)}),_d=I("$ZodURL",(t,e)=>{ze.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:a_.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})}}}),vd=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=t_()),ze.init(t,e)}),xd=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Yw),ze.init(t,e)}),kd=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Hw),ze.init(t,e)}),Sd=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Kw),ze.init(t,e)}),$d=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ww),ze.init(t,e)}),Td=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Gw),ze.init(t,e)}),Rd=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Jw),ze.init(t,e)}),V_=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=m_(e)),ze.init(t,e)}),H_=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=u_),ze.init(t,e)}),K_=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=p_(e)),ze.init(t,e)}),W_=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Xw),ze.init(t,e)}),Ed=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=r_),ze.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Pd=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=n_),ze.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})}}}),Ad=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=o_),ze.init(t,e)}),Cd=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=s_),ze.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})}}});Id=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=i_),ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{G_(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Od=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=dd),ze.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{zC(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Nd=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=c_),ze.init(t,e)});zd=I("$ZodJWT",(t,e)=>{ze.init(t,e),t._zod.check=r=>{LC(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ca=I("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??g_,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}}),Ld=I("$ZodNumber",(t,e)=>{k_.init(t,e),Ca.init(t,e)}),jd=I("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=y_,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}}),Dd=I("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=b_,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}}),Md=I("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),Ud=I("$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)});qd=I("$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=>L_(l,r,i))):L_(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Ia=I("$ZodObject",(t,e)=>{Ae.init(t,e);let r=Ss(()=>{let p=Object.keys(e.shape);for(let h of p)if(!(e.shape[h]instanceof Ae))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let y=Yu(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(y)}});Ne(t._zod,"propValues",()=>{let p=e.shape,y={};for(let h in p){let m=p[h]._zod;if(m.values){y[h]??(y[h]=new Set);for(let w of m.values)y[h].add(w)}}return y});let n=p=>{let y=new Pa(["shape","payload","ctx"]),h=r.value,m=P=>{let z=zn(P);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};y.write("const input = payload.value;");let w=Object.create(null),S=0;for(let P of h.keys)w[P]=`key_${S++}`;y.write("const newResult = {}");for(let P of h.keys)if(h.optionalKeys.has(P)){let z=w[P];y.write(`const ${z} = ${m(P)};`);let F=zn(P);y.write(`
2023
+ `))}}});var H_,bd=O(()=>{H_={major:4,minor:0,patch:0}});function iv(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function XC(t){if(!md.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return iv(r)}function QC(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 K_(t,e,r){t.issues.length&&e.issues.push(...yr(r,t.issues)),e.value[r]=t.value}function Ia(t,e,r){t.issues.length&&e.issues.push(...yr(r,t.issues)),e.value[r]=t.value}function W_(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(...yr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function G_(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=>nr(s,n,Nt())))}),e}function wd(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(So(t)&&So(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=wd(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=wd(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 J_(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),jn(t))return t;let n=wd(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 Y_(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function X_(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 Q_(t,e,r){return jn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function ev(t){return t.value=Object.freeze(t.value),t}function tv(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(rd(o))}}var Ie,Os,je,_d,vd,xd,kd,Sd,$d,Td,Rd,Ed,Pd,Ad,rv,nv,ov,sv,Cd,Id,Od,Nd,zd,Ld,jd,Dd,Oa,Md,Ud,qd,Bd,Fd,Zd,Na,za,Vd,Hd,Kd,Wd,Gd,Jd,Yd,Xd,Qd,ep,tp,rp,np,op,sp,av=O(()=>{Aa();xo();yd();pd();Pa();br();bd();br();Ie=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=H_;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=jn(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,b=u._zod.check(s);if(b instanceof Promise&&a?.async===!1)throw new Nr;if(l||b instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await b,s.issues.length!==p&&(c||(c=jn(s,p)))});else{if(s.issues.length===p)continue;c||(c=jn(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 Nr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Dn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Mn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Os=I("$ZodString",(t,e)=>{Ie.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??$_(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=I("$ZodStringFormat",(t,e)=>{Is.init(t,e),Os.init(t,e)}),_d=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=u_),je.init(t,e)}),vd=I("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=hd(n))}else e.pattern??(e.pattern=hd());je.init(t,e)}),xd=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=d_),je.init(t,e)}),kd=I("$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:b_.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})}}}),Sd=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=p_()),je.init(t,e)}),$d=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=c_),je.init(t,e)}),Td=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=n_),je.init(t,e)}),Rd=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=o_),je.init(t,e)}),Ed=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=s_),je.init(t,e)}),Pd=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=i_),je.init(t,e)}),Ad=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=a_),je.init(t,e)}),rv=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=S_(e)),je.init(t,e)}),nv=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=v_),je.init(t,e)}),ov=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=k_(e)),je.init(t,e)}),sv=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=l_),je.init(t,e)}),Cd=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=h_),je.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Id=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=m_),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})}}}),Od=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=f_),je.init(t,e)}),Nd=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=g_),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})}}});zd=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=y_),je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{iv(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Ld=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=md),je.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{XC(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),jd=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=w_),je.init(t,e)});Dd=I("$ZodJWT",(t,e)=>{je.init(t,e),t._zod.check=r=>{QC(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Oa=I("$ZodNumber",(t,e)=>{Ie.init(t,e),t._zod.pattern=t._zod.bag.pattern??R_,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Md=I("$ZodNumber",(t,e)=>{N_.init(t,e),Oa.init(t,e)}),Ud=I("$ZodBoolean",(t,e)=>{Ie.init(t,e),t._zod.pattern=E_,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}}),qd=I("$ZodNull",(t,e)=>{Ie.init(t,e),t._zod.pattern=P_,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Bd=I("$ZodUnknown",(t,e)=>{Ie.init(t,e),t._zod.parse=r=>r}),Fd=I("$ZodNever",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Zd=I("$ZodArray",(t,e)=>{Ie.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=>K_(l,r,i))):K_(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Na=I("$ZodObject",(t,e)=>{Ie.init(t,e);let r=Rs(()=>{let p=Object.keys(e.shape);for(let m of p)if(!(e.shape[m]instanceof Ie))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let b=ed(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(b)}});Le(t._zod,"propValues",()=>{let p=e.shape,b={};for(let m in p){let h=p[m]._zod;if(h.values){b[m]??(b[m]=new Set);for(let w of h.values)b[m].add(w)}}return b});let n=p=>{let b=new Ca(["shape","payload","ctx"]),m=r.value,h=P=>{let z=Ln(P);return`shape[${z}]._zod.run({ value: input[${z}], issues: [] }, ctx)`};b.write("const input = payload.value;");let w=Object.create(null),S=0;for(let P of m.keys)w[P]=`key_${S++}`;b.write("const newResult = {}");for(let P of m.keys)if(m.optionalKeys.has(P)){let z=w[P];b.write(`const ${z} = ${h(P)};`);let B=Ln(P);b.write(`
2024
2024
  if (${z}.issues.length) {
2025
- if (input[${F}] === undefined) {
2026
- if (${F} in input) {
2027
- newResult[${F}] = undefined;
2025
+ if (input[${B}] === undefined) {
2026
+ if (${B} in input) {
2027
+ newResult[${B}] = undefined;
2028
2028
  }
2029
2029
  } else {
2030
2030
  payload.issues = payload.issues.concat(
2031
2031
  ${z}.issues.map((iss) => ({
2032
2032
  ...iss,
2033
- path: iss.path ? [${F}, ...iss.path] : [${F}],
2033
+ path: iss.path ? [${B}, ...iss.path] : [${B}],
2034
2034
  }))
2035
2035
  );
2036
2036
  }
2037
2037
  } else if (${z}.value === undefined) {
2038
- if (${F} in input) newResult[${F}] = undefined;
2038
+ if (${B} in input) newResult[${B}] = undefined;
2039
2039
  } else {
2040
- newResult[${F}] = ${z}.value;
2040
+ newResult[${B}] = ${z}.value;
2041
2041
  }
2042
- `)}else{let z=w[P];y.write(`const ${z} = ${m(P)};`),y.write(`
2042
+ `)}else{let z=w[P];b.write(`const ${z} = ${h(P)};`),b.write(`
2043
2043
  if (${z}.issues.length) payload.issues = payload.issues.concat(${z}.issues.map(iss => ({
2044
2044
  ...iss,
2045
- path: iss.path ? [${zn(P)}, ...iss.path] : [${zn(P)}]
2046
- })));`),y.write(`newResult[${zn(P)}] = ${z}.value`)}y.write("payload.value = newResult;"),y.write("return payload;");let R=y.compile();return(P,z)=>R(p,P,z)},o,s=xo,i=!va.jitless,c=i&&Gu.value,l=e.catchall,u;t._zod.parse=(p,y)=>{u??(u=r.value);let h=p.value;if(!s(h))return p.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),p;let m=[];if(i&&c&&y?.async===!1&&y.jitless!==!0)o||(o=n(e.shape)),p=o(p,y);else{p.value={};let z=u.shape;for(let F of u.keys){let W=z[F],Ke=W._zod.run({value:h[F],issues:[]},y),Ye=W._zod.optin==="optional"&&W._zod.optout==="optional";Ke instanceof Promise?m.push(Ke.then(Gt=>Ye?j_(Gt,p,F,h):Aa(Gt,p,F))):Ye?j_(Ke,p,F,h):Aa(Ke,p,F)}}if(!l)return m.length?Promise.all(m).then(()=>p):p;let w=[],S=u.keySet,R=l._zod,P=R.def.type;for(let z of Object.keys(h)){if(S.has(z))continue;if(P==="never"){w.push(z);continue}let F=R.run({value:h[z],issues:[]},y);F instanceof Promise?m.push(F.then(W=>Aa(W,p,z))):Aa(F,p,z)}return w.length&&p.issues.push({code:"unrecognized_keys",keys:w,input:h,inst:t}),m.length?Promise.all(m).then(()=>p):p}});Oa=I("$ZodUnion",(t,e)=>{Ae.init(t,e),Ne(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Ne(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Ne(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Ne(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=>Ts(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=>D_(i,r,t,n)):D_(s,r,t,n)}}),Fd=I("$ZodDiscriminatedUnion",(t,e)=>{Oa.init(t,e);let r=t._zod.parse;Ne(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=Ss(()=>{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(!xo(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)}}),Bd=I("$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])=>M_(r,c,l)):M_(r,s,i)}});Zd=I("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!ko(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(...gr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...gr(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=>rr(l,n,Ot())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...gr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...gr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Vd=I("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=ks(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Ju.has(typeof n)).map(n=>typeof n=="string"?Jr(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}}),Hd=I("$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"?Jr(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}}),Kd=I("$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 Or;return r.value=o,r}}),Wd=I("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Ne(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Ne(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ts(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)}),Gd=I("$ZodNullable",(t,e)=>{Ae.init(t,e),Ne(t._zod,"optin",()=>e.innerType._zod.optin),Ne(t._zod,"optout",()=>e.innerType._zod.optout),Ne(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ts(r.source)}|null)$`):void 0}),Ne(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)}),Jd=I("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ne(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=>U_(s,e)):U_(o,e)}});Yd=I("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ne(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))}),Xd=I("$ZodNonOptional",(t,e)=>{Ae.init(t,e),Ne(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=>q_(s,t)):q_(o,t)}});Qd=I("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Ne(t._zod,"optout",()=>e.innerType._zod.optout),Ne(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=>rr(i,n,Ot()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>rr(s,n,Ot()))},input:r.value}),r.issues=[]),r)}}),ep=I("$ZodPipe",(t,e)=>{Ae.init(t,e),Ne(t._zod,"values",()=>e.in._zod.values),Ne(t._zod,"optin",()=>e.in._zod.optin),Ne(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=>F_(s,e,n)):F_(o,e,n)}});tp=I("$ZodReadonly",(t,e)=>{Ae.init(t,e),Ne(t._zod,"propValues",()=>e.innerType._zod.propValues),Ne(t._zod,"values",()=>e.innerType._zod.values),Ne(t._zod,"optin",()=>e.innerType._zod.optin),Ne(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(B_):B_(o)}});rp=I("$ZodCustom",(t,e)=>{it.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=>Z_(s,r,n,t));Z_(o,r,n,t)}})});function Y_(){return{localeError:DC()}}var jC,DC,X_=O(()=>{yr();jC=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},DC=()=>{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 ${jC(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Sa(n.values[0])}`:`Invalid option: expected one of ${xa(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":""}: ${xa(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 Na=O(()=>{});function Q_(){return new Cs}var Cs,Yr,op=O(()=>{Cs=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)}};Yr=Q_()});function sp(t,e){return new t({type:"string",...ie(e)})}function ip(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ie(e)})}function za(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ie(e)})}function ap(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ie(e)})}function cp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ie(e)})}function lp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ie(e)})}function up(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ie(e)})}function dp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ie(e)})}function pp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ie(e)})}function mp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ie(e)})}function hp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ie(e)})}function fp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ie(e)})}function gp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ie(e)})}function yp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ie(e)})}function bp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ie(e)})}function wp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ie(e)})}function _p(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ie(e)})}function vp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ie(e)})}function xp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ie(e)})}function kp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ie(e)})}function Sp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ie(e)})}function $p(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ie(e)})}function Tp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ie(e)})}function ev(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ie(e)})}function tv(t,e){return new t({type:"string",format:"date",check:"string_format",...ie(e)})}function rv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ie(e)})}function nv(t,e){return new t({type:"string",format:"duration",check:"string_format",...ie(e)})}function Rp(t,e){return new t({type:"number",checks:[],...ie(e)})}function Ep(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ie(e)})}function Pp(t,e){return new t({type:"boolean",...ie(e)})}function Ap(t,e){return new t({type:"null",...ie(e)})}function Cp(t){return new t({type:"unknown"})}function Ip(t,e){return new t({type:"never",...ie(e)})}function La(t,e){return new pd({check:"less_than",...ie(e),value:t,inclusive:!1})}function Is(t,e){return new pd({check:"less_than",...ie(e),value:t,inclusive:!0})}function ja(t,e){return new md({check:"greater_than",...ie(e),value:t,inclusive:!1})}function Os(t,e){return new md({check:"greater_than",...ie(e),value:t,inclusive:!0})}function Da(t,e){return new x_({check:"multiple_of",...ie(e),value:t})}function Ma(t,e){return new S_({check:"max_length",...ie(e),maximum:t})}function So(t,e){return new $_({check:"min_length",...ie(e),minimum:t})}function Ua(t,e){return new T_({check:"length_equals",...ie(e),length:t})}function Op(t,e){return new R_({check:"string_format",format:"regex",...ie(e),pattern:t})}function Np(t){return new E_({check:"string_format",format:"lowercase",...ie(t)})}function zp(t){return new P_({check:"string_format",format:"uppercase",...ie(t)})}function Lp(t,e){return new A_({check:"string_format",format:"includes",...ie(e),includes:t})}function jp(t,e){return new C_({check:"string_format",format:"starts_with",...ie(e),prefix:t})}function Dp(t,e){return new I_({check:"string_format",format:"ends_with",...ie(e),suffix:t})}function Mn(t){return new O_({check:"overwrite",tx:t})}function Mp(t){return Mn(e=>e.normalize(t))}function Up(){return Mn(t=>t.trim())}function qp(){return Mn(t=>t.toLowerCase())}function Fp(){return Mn(t=>t.toUpperCase())}function ov(t,e,r){return new t({type:"array",element:e,...ie(r)})}function Bp(t,e,r){let n=ie(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Zp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ie(r)})}var sv=O(()=>{Ea();yr()});var iv=O(()=>{});function Vp(t,e){if(t instanceof Cs){let n=new qa(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 qa(e);return r.process(t),r.emit(t,e)}function Xe(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 Xe(o.element,r);case"object":{for(let s in o.shape)if(Xe(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Xe(s,r))return!0;return!1}case"intersection":return Xe(o.left,r)||Xe(o.right,r);case"tuple":{for(let s of o.items)if(Xe(s,r))return!0;return!!(o.rest&&Xe(o.rest,r))}case"record":return Xe(o.keyType,r)||Xe(o.valueType,r);case"map":return Xe(o.keyType,r)||Xe(o.valueType,r);case"set":return Xe(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Xe(o.innerType,r);case"lazy":return Xe(o.getter(),r);case"default":return Xe(o.innerType,r);case"prefault":return Xe(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Xe(o.in,r)||Xe(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var qa,av=O(()=>{op();yr();qa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Yr,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},y=e._zod.parent;if(y)a.ref=y,this.process(y,p),this.seen.get(y).isParent=!0;else{let h=a.schema;switch(o.type){case"string":{let m=h;m.type="string";let{minimum:w,maximum:S,format:R,patterns:P,contentEncoding:z}=e._zod.bag;if(typeof w=="number"&&(m.minLength=w),typeof S=="number"&&(m.maxLength=S),R&&(m.format=s[R]??R,m.format===""&&delete m.format),z&&(m.contentEncoding=z),P&&P.size>0){let F=[...P];F.length===1?m.pattern=F[0].source:F.length>1&&(a.schema.allOf=[...F.map(W=>({...this.target==="draft-7"?{type:"string"}:{},pattern:W.source}))])}break}case"number":{let m=h,{minimum:w,maximum:S,format:R,multipleOf:P,exclusiveMaximum:z,exclusiveMinimum:F}=e._zod.bag;typeof R=="string"&&R.includes("int")?m.type="integer":m.type="number",typeof F=="number"&&(m.exclusiveMinimum=F),typeof w=="number"&&(m.minimum=w,typeof F=="number"&&(F>=w?delete m.minimum:delete m.exclusiveMinimum)),typeof z=="number"&&(m.exclusiveMaximum=z),typeof S=="number"&&(m.maximum=S,typeof z=="number"&&(z<=S?delete m.maximum:delete m.exclusiveMaximum)),typeof P=="number"&&(m.multipleOf=P);break}case"boolean":{let m=h;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":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=h,{minimum:w,maximum:S}=e._zod.bag;typeof w=="number"&&(m.minItems=w),typeof S=="number"&&(m.maxItems=S),m.type="array",m.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=h;m.type="object",m.properties={};let w=o.shape;for(let P in w)m.properties[P]=this.process(w[P],{...p,path:[...p.path,"properties",P]});let S=new Set(Object.keys(w)),R=new Set([...S].filter(P=>{let z=o.shape[P]._zod;return this.io==="input"?z.optin===void 0:z.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=h;m.anyOf=o.options.map((w,S)=>this.process(w,{...p,path:[...p.path,"anyOf",S]}));break}case"intersection":{let m=h,w=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),S=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),R=z=>"allOf"in z&&Object.keys(z).length===1,P=[...R(w)?w.allOf:[w],...R(S)?S.allOf:[S]];m.allOf=P;break}case"tuple":{let m=h;m.type="array";let w=o.items.map((P,z)=>this.process(P,{...p,path:[...p.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?m.prefixItems=w:m.items=w,o.rest){let P=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=P:m.additionalItems=P}o.rest&&(m.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:S,maximum:R}=e._zod.bag;typeof S=="number"&&(m.minItems=S),typeof R=="number"&&(m.maxItems=R);break}case"record":{let m=h;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=h,w=ks(o.entries);w.every(S=>typeof S=="number")&&(m.type="number"),w.every(S=>typeof S=="string")&&(m.type="string"),m.enum=w;break}case"literal":{let m=h,w=[];for(let S of o.values)if(S===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof S=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(S))}else w.push(S);if(w.length!==0)if(w.length===1){let S=w[0];m.type=S===null?"null":typeof S,m.const=S}else w.every(S=>typeof S=="number")&&(m.type="number"),w.every(S=>typeof S=="string")&&(m.type="string"),w.every(S=>typeof S=="boolean")&&(m.type="string"),w.every(S=>S===null)&&(m.type="null"),m.enum=w;break}case"file":{let m=h,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:S,maximum:R,mime:P}=e._zod.bag;S!==void 0&&(w.minLength=S),R!==void 0&&(w.maxLength=R),P?P.length===1?(w.contentMediaType=P[0],Object.assign(m,w)):m.anyOf=P.map(z=>({...w,contentMediaType:z})):Object.assign(m,w);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);h.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let m=h;m.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,h.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(h._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")}h.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=h,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=w.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,h.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"&&Xe(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 w=n.external.registry.get(u[0])?.id,S=n.external.uri??(P=>P);if(w)return{ref:S(w)};let R=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=R,{defId:R,ref:`${S("__shared")}#/${p}/${R}`}}if(u[1]===o)return{ref:"#"};let h=`#/${p}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:h+m}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:y,defId:h}=s(u);p.def={...p.schema},h&&(p.defId=h);let m=p.schema;for(let w in m)delete m[w];m.$ref=y};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>
2045
+ path: iss.path ? [${Ln(P)}, ...iss.path] : [${Ln(P)}]
2046
+ })));`),b.write(`newResult[${Ln(P)}] = ${z}.value`)}b.write("payload.value = newResult;"),b.write("return payload;");let R=b.compile();return(P,z)=>R(p,P,z)},o,s=ko,i=!ka.jitless,c=i&&Xu.value,l=e.catchall,u;t._zod.parse=(p,b)=>{u??(u=r.value);let m=p.value;if(!s(m))return p.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),p;let h=[];if(i&&c&&b?.async===!1&&b.jitless!==!0)o||(o=n(e.shape)),p=o(p,b);else{p.value={};let z=u.shape;for(let B of u.keys){let K=z[B],Ge=K._zod.run({value:m[B],issues:[]},b),Je=K._zod.optin==="optional"&&K._zod.optout==="optional";Ge instanceof Promise?h.push(Ge.then(Jt=>Je?W_(Jt,p,B,m):Ia(Jt,p,B))):Je?W_(Ge,p,B,m):Ia(Ge,p,B)}}if(!l)return h.length?Promise.all(h).then(()=>p):p;let w=[],S=u.keySet,R=l._zod,P=R.def.type;for(let z of Object.keys(m)){if(S.has(z))continue;if(P==="never"){w.push(z);continue}let B=R.run({value:m[z],issues:[]},b);B instanceof Promise?h.push(B.then(K=>Ia(K,p,z))):Ia(B,p,z)}return w.length&&p.issues.push({code:"unrecognized_keys",keys:w,input:m,inst:t}),h.length?Promise.all(h).then(()=>p):p}});za=I("$ZodUnion",(t,e)=>{Ie.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=>Ps(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=>G_(i,r,t,n)):G_(s,r,t,n)}}),Vd=I("$ZodDiscriminatedUnion",(t,e)=>{za.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=Rs(()=>{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(!ko(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)}}),Hd=I("$ZodIntersection",(t,e)=>{Ie.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])=>J_(r,c,l)):J_(r,s,i)}});Kd=I("$ZodRecord",(t,e)=>{Ie.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!So(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...yr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...yr(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=>nr(l,n,Nt())),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(...yr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...yr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Wd=I("$ZodEnum",(t,e)=>{Ie.init(t,e);let r=Ts(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Qu.has(typeof n)).map(n=>typeof n=="string"?Yr(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}}),Gd=I("$ZodLiteral",(t,e)=>{Ie.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Yr(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}}),Jd=I("$ZodTransform",(t,e)=>{Ie.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 Nr;return r.value=o,r}}),Yd=I("$ZodOptional",(t,e)=>{Ie.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(`^(${Ps(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)}),Xd=I("$ZodNullable",(t,e)=>{Ie.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(`^(${Ps(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)}),Qd=I("$ZodDefault",(t,e)=>{Ie.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=>Y_(s,e)):Y_(o,e)}});ep=I("$ZodPrefault",(t,e)=>{Ie.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))}),tp=I("$ZodNonOptional",(t,e)=>{Ie.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=>X_(s,t)):X_(o,t)}});rp=I("$ZodCatch",(t,e)=>{Ie.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=>nr(i,n,Nt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>nr(s,n,Nt()))},input:r.value}),r.issues=[]),r)}}),np=I("$ZodPipe",(t,e)=>{Ie.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=>Q_(s,e,n)):Q_(o,e,n)}});op=I("$ZodReadonly",(t,e)=>{Ie.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(ev):ev(o)}});sp=I("$ZodCustom",(t,e)=>{ct.init(t,e),Ie.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=>tv(s,r,n,t));tv(o,r,n,t)}})});function cv(){return{localeError:tI()}}var eI,tI,lv=O(()=>{br();eI=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},tI=()=>{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 ${eI(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ta(n.values[0])}`:`Invalid option: expected one of ${Sa(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":""}: ${Sa(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 La=O(()=>{});function uv(){return new Ns}var Ns,Xr,ap=O(()=>{Ns=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)}};Xr=uv()});function cp(t,e){return new t({type:"string",...ie(e)})}function lp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ie(e)})}function ja(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ie(e)})}function up(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ie(e)})}function dp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ie(e)})}function pp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ie(e)})}function hp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ie(e)})}function mp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ie(e)})}function fp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ie(e)})}function gp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ie(e)})}function yp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ie(e)})}function bp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ie(e)})}function wp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ie(e)})}function _p(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ie(e)})}function vp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ie(e)})}function xp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ie(e)})}function kp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ie(e)})}function Sp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ie(e)})}function $p(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ie(e)})}function Tp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ie(e)})}function Rp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ie(e)})}function Ep(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ie(e)})}function Pp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ie(e)})}function dv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ie(e)})}function pv(t,e){return new t({type:"string",format:"date",check:"string_format",...ie(e)})}function hv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ie(e)})}function mv(t,e){return new t({type:"string",format:"duration",check:"string_format",...ie(e)})}function Ap(t,e){return new t({type:"number",checks:[],...ie(e)})}function Cp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ie(e)})}function Ip(t,e){return new t({type:"boolean",...ie(e)})}function Op(t,e){return new t({type:"null",...ie(e)})}function Np(t){return new t({type:"unknown"})}function zp(t,e){return new t({type:"never",...ie(e)})}function Da(t,e){return new fd({check:"less_than",...ie(e),value:t,inclusive:!1})}function zs(t,e){return new fd({check:"less_than",...ie(e),value:t,inclusive:!0})}function Ma(t,e){return new gd({check:"greater_than",...ie(e),value:t,inclusive:!1})}function Ls(t,e){return new gd({check:"greater_than",...ie(e),value:t,inclusive:!0})}function Ua(t,e){return new O_({check:"multiple_of",...ie(e),value:t})}function qa(t,e){return new z_({check:"max_length",...ie(e),maximum:t})}function $o(t,e){return new L_({check:"min_length",...ie(e),minimum:t})}function Ba(t,e){return new j_({check:"length_equals",...ie(e),length:t})}function Lp(t,e){return new D_({check:"string_format",format:"regex",...ie(e),pattern:t})}function jp(t){return new M_({check:"string_format",format:"lowercase",...ie(t)})}function Dp(t){return new U_({check:"string_format",format:"uppercase",...ie(t)})}function Mp(t,e){return new q_({check:"string_format",format:"includes",...ie(e),includes:t})}function Up(t,e){return new B_({check:"string_format",format:"starts_with",...ie(e),prefix:t})}function qp(t,e){return new F_({check:"string_format",format:"ends_with",...ie(e),suffix:t})}function Un(t){return new Z_({check:"overwrite",tx:t})}function Bp(t){return Un(e=>e.normalize(t))}function Fp(){return Un(t=>t.trim())}function Zp(){return Un(t=>t.toLowerCase())}function Vp(){return Un(t=>t.toUpperCase())}function fv(t,e,r){return new t({type:"array",element:e,...ie(r)})}function Hp(t,e,r){let n=ie(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Kp(t,e,r){return new t({type:"custom",check:"custom",fn:e,...ie(r)})}var gv=O(()=>{Aa();br()});var yv=O(()=>{});function Wp(t,e){if(t instanceof Ns){let n=new Fa(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 Fa(e);return r.process(t),r.emit(t,e)}function tt(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 tt(o.element,r);case"object":{for(let s in o.shape)if(tt(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(tt(s,r))return!0;return!1}case"intersection":return tt(o.left,r)||tt(o.right,r);case"tuple":{for(let s of o.items)if(tt(s,r))return!0;return!!(o.rest&&tt(o.rest,r))}case"record":return tt(o.keyType,r)||tt(o.valueType,r);case"map":return tt(o.keyType,r)||tt(o.valueType,r);case"set":return tt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return tt(o.innerType,r);case"lazy":return tt(o.getter(),r);case"default":return tt(o.innerType,r);case"prefault":return tt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return tt(o.in,r)||tt(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Fa,bv=O(()=>{ap();br();Fa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Xr,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},b=e._zod.parent;if(b)a.ref=b,this.process(b,p),this.seen.get(b).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let h=m;h.type="string";let{minimum:w,maximum:S,format:R,patterns:P,contentEncoding:z}=e._zod.bag;if(typeof w=="number"&&(h.minLength=w),typeof S=="number"&&(h.maxLength=S),R&&(h.format=s[R]??R,h.format===""&&delete h.format),z&&(h.contentEncoding=z),P&&P.size>0){let B=[...P];B.length===1?h.pattern=B[0].source:B.length>1&&(a.schema.allOf=[...B.map(K=>({...this.target==="draft-7"?{type:"string"}:{},pattern:K.source}))])}break}case"number":{let h=m,{minimum:w,maximum:S,format:R,multipleOf:P,exclusiveMaximum:z,exclusiveMinimum:B}=e._zod.bag;typeof R=="string"&&R.includes("int")?h.type="integer":h.type="number",typeof B=="number"&&(h.exclusiveMinimum=B),typeof w=="number"&&(h.minimum=w,typeof B=="number"&&(B>=w?delete h.minimum:delete h.exclusiveMinimum)),typeof z=="number"&&(h.exclusiveMaximum=z),typeof S=="number"&&(h.maximum=S,typeof z=="number"&&(z<=S?delete h.maximum:delete h.exclusiveMaximum)),typeof P=="number"&&(h.multipleOf=P);break}case"boolean":{let h=m;h.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let h=m,{minimum:w,maximum:S}=e._zod.bag;typeof w=="number"&&(h.minItems=w),typeof S=="number"&&(h.maxItems=S),h.type="array",h.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let h=m;h.type="object",h.properties={};let w=o.shape;for(let P in w)h.properties[P]=this.process(w[P],{...p,path:[...p.path,"properties",P]});let S=new Set(Object.keys(w)),R=new Set([...S].filter(P=>{let z=o.shape[P]._zod;return this.io==="input"?z.optin===void 0:z.optout===void 0}));R.size>0&&(h.required=Array.from(R)),o.catchall?._zod.def.type==="never"?h.additionalProperties=!1:o.catchall?o.catchall&&(h.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(h.additionalProperties=!1);break}case"union":{let h=m;h.anyOf=o.options.map((w,S)=>this.process(w,{...p,path:[...p.path,"anyOf",S]}));break}case"intersection":{let h=m,w=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),S=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),R=z=>"allOf"in z&&Object.keys(z).length===1,P=[...R(w)?w.allOf:[w],...R(S)?S.allOf:[S]];h.allOf=P;break}case"tuple":{let h=m;h.type="array";let w=o.items.map((P,z)=>this.process(P,{...p,path:[...p.path,"prefixItems",z]}));if(this.target==="draft-2020-12"?h.prefixItems=w:h.items=w,o.rest){let P=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?h.items=P:h.additionalItems=P}o.rest&&(h.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:S,maximum:R}=e._zod.bag;typeof S=="number"&&(h.minItems=S),typeof R=="number"&&(h.maxItems=R);break}case"record":{let h=m;h.type="object",h.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),h.additionalProperties=this.process(o.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let h=m,w=Ts(o.entries);w.every(S=>typeof S=="number")&&(h.type="number"),w.every(S=>typeof S=="string")&&(h.type="string"),h.enum=w;break}case"literal":{let h=m,w=[];for(let S of o.values)if(S===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof S=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");w.push(Number(S))}else w.push(S);if(w.length!==0)if(w.length===1){let S=w[0];h.type=S===null?"null":typeof S,h.const=S}else w.every(S=>typeof S=="number")&&(h.type="number"),w.every(S=>typeof S=="string")&&(h.type="string"),w.every(S=>typeof S=="boolean")&&(h.type="string"),w.every(S=>S===null)&&(h.type="null"),h.enum=w;break}case"file":{let h=m,w={type:"string",format:"binary",contentEncoding:"binary"},{minimum:S,maximum:R,mime:P}=e._zod.bag;S!==void 0&&(w.minLength=S),R!==void 0&&(w.maxLength=R),P?P.length===1?(w.contentMediaType=P[0],Object.assign(h,w)):h.anyOf=P.map(z=>({...w,contentMediaType:z})):Object.assign(h,w);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let h=this.process(o.innerType,p);m.anyOf=[h,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let h=m;h.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let h;try{h=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=h;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let h=m,w=e._zod.pattern;if(!w)throw new Error("Pattern not found in template literal");h.type="string",h.pattern=w.source;break}case"pipe":{let h=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(h,p),a.ref=h;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let h=e._zod.innerType;this.process(h,p),a.ref=h;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&tt(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 w=n.external.registry.get(u[0])?.id,S=n.external.uri??(P=>P);if(w)return{ref:S(w)};let R=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=R,{defId:R,ref:`${S("__shared")}#/${p}/${R}`}}if(u[1]===o)return{ref:"#"};let m=`#/${p}/`,h=u[1].schema.id??`__schema${this.counter++}`;return{defId:h,ref:m+h}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:b,defId:m}=s(u);p.def={...p.schema},m&&(p.defId=m);let h=p.schema;for(let w in h)delete h[w];h.$ref=b};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>
2047
2047
 
2048
- 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 h=n.external.registry.get(u[0])?.id;if(e!==u[0]&&h){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let y=this.seen.get(u),h=y.def??y.schema,m={...h};if(y.ref===null)return;let w=y.ref;if(y.ref=null,w){a(w,p);let S=this.seen.get(w).schema;S.$ref&&p.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(S)):(Object.assign(h,S),Object.assign(h,m))}y.isParent||this.override({zodSchema:u,jsonSchema:h,path:y.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let 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 cv=O(()=>{});var gt=O(()=>{vo();ld();rd();J_();Ea();fd();yr();Ra();Na();op();hd();iv();sv();av();cv()});var Hp=O(()=>{gt()});function Kp(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new _I(r)}var wI,_I,lv=O(()=>{gt();gt();Hp();wI=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>od(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>jn(t,r,n),t.parseAsync=async(r,n)=>id(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Dn(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)=>Nt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),_I=I("ZodMiniObject",(t,e)=>{Ia.init(t,e),wI.init(t,e),we.defineLazy(t,"shape",()=>e.shape)})});var uv=O(()=>{});var dv=O(()=>{});var pv=O(()=>{});var mv=O(()=>{gt();Hp();lv();uv();gt();Na();dv();pv()});var hv=O(()=>{mv()});var Wp=O(()=>{hv()});function br(t){return!!t._zod}function qn(t){let e=Object.values(t);if(e.length===0)return Kp({});let r=e.every(br),n=e.every(o=>!br(o));if(r)return Kp(t);if(n)return Ml(t);throw new Error("Mixed Zod versions detected in object shape.")}function Xr(t,e){return br(t)?jn(t,e):t.safeParse(e)}async function Fa(t,e){return br(t)?await Dn(t,e):await t.safeParseAsync(e)}function Qr(t){if(!t)return;let e;if(br(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $o(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return qn(t)}}if(br(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 kI(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ba(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 ${kI(e.path)}`:e.message).join(`
2049
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function gv(t){return t.description}function yv(t){if(br(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function To(t){if(br(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 Ns=O(()=>{vs();Wp()});var Gp=O(()=>{gt()});var zs={};Xo(zs,{ZodISODate:()=>wv,ZodISODateTime:()=>bv,ZodISODuration:()=>vv,ZodISOTime:()=>_v,date:()=>Yp,datetime:()=>Jp,duration:()=>Qp,time:()=>Xp});function Jp(t){return ev(bv,t)}function Yp(t){return tv(wv,t)}function Xp(t){return rv(_v,t)}function Qp(t){return nv(vv,t)}var bv,wv,_v,vv,em=O(()=>{gt();tm();bv=I("ZodISODateTime",(t,e)=>{V_.init(t,e),qe.init(t,e)});wv=I("ZodISODate",(t,e)=>{H_.init(t,e),qe.init(t,e)});_v=I("ZodISOTime",(t,e)=>{K_.init(t,e),qe.init(t,e)});vv=I("ZodISODuration",(t,e)=>{W_.init(t,e),qe.init(t,e)})});var xv,T4,Ls,rm=O(()=>{gt();gt();xv=(t,e)=>{$a.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>td(t,r)},flatten:{value:r=>ed(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},T4=I("ZodError",xv),Ls=I("ZodError",xv,{Parent:Error})});var kv,Sv,$v,Tv,nm=O(()=>{gt();rm();kv=nd(Ls),Sv=sd(Ls),$v=ad(Ls),Tv=cd(Ls)});function C(t){return sp(CI,t)}function Ee(t){return Rp(Cv,t)}function Ev(t){return Ep(GI,t)}function rt(t){return Pp(JI,t)}function Iv(t){return Ap(YI,t)}function Fe(){return Cp(XI)}function eO(t){return Ip(QI,t)}function ve(t,e){return ov(tO,t,e)}function K(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new Ov(r)}function yt(t,e){return new Ov({type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},catchall:Fe(),...we.normalizeParams(e)})}function je(t,e){return new Nv({type:"union",options:t,...we.normalizeParams(e)})}function im(t,e,r){return new rO({type:"union",options:e,discriminator:t,...we.normalizeParams(r)})}function Va(t,e){return new nO({type:"intersection",left:t,right:e})}function Le(t,e,r){return new oO({type:"record",keyType:t,valueType:e,...we.normalizeParams(r)})}function Rt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new om({type:"enum",entries:r,...we.normalizeParams(e)})}function X(t,e){return new sO({type:"literal",values:Array.isArray(t)?t:[t],...we.normalizeParams(e)})}function zv(t){return new iO({type:"transform",transform:t})}function Be(t){return new Lv({type:"optional",innerType:t})}function Pv(t){return new aO({type:"nullable",innerType:t})}function lO(t,e){return new cO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function dO(t,e){return new uO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function pO(t,e){return new jv({type:"nonoptional",innerType:t,...we.normalizeParams(e)})}function hO(t,e){return new mO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function sm(t,e){return new fO({type:"pipe",in:t,out:e})}function yO(t){return new gO({type:"readonly",innerType:t})}function bO(t){let e=new it({check:"custom"});return e._zod.check=t,e}function Mv(t,e){return Bp(Dv,t??(()=>!0),e)}function wO(t,e={}){return Zp(Dv,t,e)}function _O(t){let e=bO(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(we.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(we.issue(o))}},t(r.value,r)));return e}function am(t,e){return sm(zv(t),e)}var Ve,Av,CI,qe,II,Rv,Za,OI,NI,zI,LI,jI,DI,MI,UI,qI,FI,BI,ZI,VI,HI,KI,WI,Cv,GI,JI,YI,XI,QI,tO,Ov,Nv,rO,nO,oO,om,sO,iO,Lv,aO,cO,uO,jv,mO,fO,gO,Dv,tm=O(()=>{gt();gt();Gp();em();nm();Ve=I("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)=>Nt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>kv(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>$v(t,r,n),t.parseAsync=async(r,n)=>Sv(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Tv(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(wO(r,n)),t.superRefine=r=>t.check(_O(r)),t.overwrite=r=>t.check(Mn(r)),t.optional=()=>Be(t),t.nullable=()=>Pv(t),t.nullish=()=>Be(Pv(t)),t.nonoptional=r=>pO(t,r),t.array=()=>ve(t),t.or=r=>je([t,r]),t.and=r=>Va(t,r),t.transform=r=>sm(t,zv(r)),t.default=r=>lO(t,r),t.prefault=r=>dO(t,r),t.catch=r=>hO(t,r),t.pipe=r=>sm(t,r),t.readonly=()=>yO(t),t.describe=r=>{let n=t.clone();return Yr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Yr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Yr.get(t);let n=t.clone();return Yr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Av=I("_ZodString",(t,e)=>{As.init(t,e),Ve.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(Op(...n)),t.includes=(...n)=>t.check(Lp(...n)),t.startsWith=(...n)=>t.check(jp(...n)),t.endsWith=(...n)=>t.check(Dp(...n)),t.min=(...n)=>t.check(So(...n)),t.max=(...n)=>t.check(Ma(...n)),t.length=(...n)=>t.check(Ua(...n)),t.nonempty=(...n)=>t.check(So(1,...n)),t.lowercase=n=>t.check(Np(n)),t.uppercase=n=>t.check(zp(n)),t.trim=()=>t.check(Up()),t.normalize=(...n)=>t.check(Mp(...n)),t.toLowerCase=()=>t.check(qp()),t.toUpperCase=()=>t.check(Fp())}),CI=I("ZodString",(t,e)=>{As.init(t,e),Av.init(t,e),t.email=r=>t.check(ip(II,r)),t.url=r=>t.check(dp(OI,r)),t.jwt=r=>t.check(Tp(WI,r)),t.emoji=r=>t.check(pp(NI,r)),t.guid=r=>t.check(za(Rv,r)),t.uuid=r=>t.check(ap(Za,r)),t.uuidv4=r=>t.check(cp(Za,r)),t.uuidv6=r=>t.check(lp(Za,r)),t.uuidv7=r=>t.check(up(Za,r)),t.nanoid=r=>t.check(mp(zI,r)),t.guid=r=>t.check(za(Rv,r)),t.cuid=r=>t.check(hp(LI,r)),t.cuid2=r=>t.check(fp(jI,r)),t.ulid=r=>t.check(gp(DI,r)),t.base64=r=>t.check(kp(VI,r)),t.base64url=r=>t.check(Sp(HI,r)),t.xid=r=>t.check(yp(MI,r)),t.ksuid=r=>t.check(bp(UI,r)),t.ipv4=r=>t.check(wp(qI,r)),t.ipv6=r=>t.check(_p(FI,r)),t.cidrv4=r=>t.check(vp(BI,r)),t.cidrv6=r=>t.check(xp(ZI,r)),t.e164=r=>t.check($p(KI,r)),t.datetime=r=>t.check(Jp(r)),t.date=r=>t.check(Yp(r)),t.time=r=>t.check(Xp(r)),t.duration=r=>t.check(Qp(r))});qe=I("ZodStringFormat",(t,e)=>{ze.init(t,e),Av.init(t,e)}),II=I("ZodEmail",(t,e)=>{wd.init(t,e),qe.init(t,e)}),Rv=I("ZodGUID",(t,e)=>{yd.init(t,e),qe.init(t,e)}),Za=I("ZodUUID",(t,e)=>{bd.init(t,e),qe.init(t,e)}),OI=I("ZodURL",(t,e)=>{_d.init(t,e),qe.init(t,e)}),NI=I("ZodEmoji",(t,e)=>{vd.init(t,e),qe.init(t,e)}),zI=I("ZodNanoID",(t,e)=>{xd.init(t,e),qe.init(t,e)}),LI=I("ZodCUID",(t,e)=>{kd.init(t,e),qe.init(t,e)}),jI=I("ZodCUID2",(t,e)=>{Sd.init(t,e),qe.init(t,e)}),DI=I("ZodULID",(t,e)=>{$d.init(t,e),qe.init(t,e)}),MI=I("ZodXID",(t,e)=>{Td.init(t,e),qe.init(t,e)}),UI=I("ZodKSUID",(t,e)=>{Rd.init(t,e),qe.init(t,e)}),qI=I("ZodIPv4",(t,e)=>{Ed.init(t,e),qe.init(t,e)}),FI=I("ZodIPv6",(t,e)=>{Pd.init(t,e),qe.init(t,e)}),BI=I("ZodCIDRv4",(t,e)=>{Ad.init(t,e),qe.init(t,e)}),ZI=I("ZodCIDRv6",(t,e)=>{Cd.init(t,e),qe.init(t,e)}),VI=I("ZodBase64",(t,e)=>{Id.init(t,e),qe.init(t,e)}),HI=I("ZodBase64URL",(t,e)=>{Od.init(t,e),qe.init(t,e)}),KI=I("ZodE164",(t,e)=>{Nd.init(t,e),qe.init(t,e)}),WI=I("ZodJWT",(t,e)=>{zd.init(t,e),qe.init(t,e)}),Cv=I("ZodNumber",(t,e)=>{Ca.init(t,e),Ve.init(t,e),t.gt=(n,o)=>t.check(ja(n,o)),t.gte=(n,o)=>t.check(Os(n,o)),t.min=(n,o)=>t.check(Os(n,o)),t.lt=(n,o)=>t.check(La(n,o)),t.lte=(n,o)=>t.check(Is(n,o)),t.max=(n,o)=>t.check(Is(n,o)),t.int=n=>t.check(Ev(n)),t.safe=n=>t.check(Ev(n)),t.positive=n=>t.check(ja(0,n)),t.nonnegative=n=>t.check(Os(0,n)),t.negative=n=>t.check(La(0,n)),t.nonpositive=n=>t.check(Is(0,n)),t.multipleOf=(n,o)=>t.check(Da(n,o)),t.step=(n,o)=>t.check(Da(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});GI=I("ZodNumberFormat",(t,e)=>{Ld.init(t,e),Cv.init(t,e)});JI=I("ZodBoolean",(t,e)=>{jd.init(t,e),Ve.init(t,e)});YI=I("ZodNull",(t,e)=>{Dd.init(t,e),Ve.init(t,e)});XI=I("ZodUnknown",(t,e)=>{Md.init(t,e),Ve.init(t,e)});QI=I("ZodNever",(t,e)=>{Ud.init(t,e),Ve.init(t,e)});tO=I("ZodArray",(t,e)=>{qd.init(t,e),Ve.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(So(r,n)),t.nonempty=r=>t.check(So(1,r)),t.max=(r,n)=>t.check(Ma(r,n)),t.length=(r,n)=>t.check(Ua(r,n)),t.unwrap=()=>t.element});Ov=I("ZodObject",(t,e)=>{Ia.init(t,e),Ve.init(t,e),we.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Rt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Fe()}),t.loose=()=>t.clone({...t._zod.def,catchall:Fe()}),t.strict=()=>t.clone({...t._zod.def,catchall:eO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>we.extend(t,r),t.merge=r=>we.merge(t,r),t.pick=r=>we.pick(t,r),t.omit=r=>we.omit(t,r),t.partial=(...r)=>we.partial(Lv,t,r[0]),t.required=(...r)=>we.required(jv,t,r[0])});Nv=I("ZodUnion",(t,e)=>{Oa.init(t,e),Ve.init(t,e),t.options=e.options});rO=I("ZodDiscriminatedUnion",(t,e)=>{Nv.init(t,e),Fd.init(t,e)});nO=I("ZodIntersection",(t,e)=>{Bd.init(t,e),Ve.init(t,e)});oO=I("ZodRecord",(t,e)=>{Zd.init(t,e),Ve.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});om=I("ZodEnum",(t,e)=>{Vd.init(t,e),Ve.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 om({...e,checks:[],...we.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 om({...e,checks:[],...we.normalizeParams(o),entries:s})}});sO=I("ZodLiteral",(t,e)=>{Hd.init(t,e),Ve.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]}})});iO=I("ZodTransform",(t,e)=>{Kd.init(t,e),Ve.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(we.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(we.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Lv=I("ZodOptional",(t,e)=>{Wd.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});aO=I("ZodNullable",(t,e)=>{Gd.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});cO=I("ZodDefault",(t,e)=>{Jd.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});uO=I("ZodPrefault",(t,e)=>{Yd.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});jv=I("ZodNonOptional",(t,e)=>{Xd.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType});mO=I("ZodCatch",(t,e)=>{Qd.init(t,e),Ve.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});fO=I("ZodPipe",(t,e)=>{ep.init(t,e),Ve.init(t,e),t.in=e.in,t.out=e.out});gO=I("ZodReadonly",(t,e)=>{tp.init(t,e),Ve.init(t,e)});Dv=I("ZodCustom",(t,e)=>{rp.init(t,e),Ve.init(t,e)})});var Uv=O(()=>{});var qv=O(()=>{});var Fv=O(()=>{gt();tm();Gp();rm();nm();Uv();gt();X_();Na();em();qv();Ot(Y_())});var Bv=O(()=>{Fv()});var Zv=O(()=>{Bv()});function ax(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function cx(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var lm,Vv,en,Ka,Qe,Hv,Kv,F4,kO,SO,um,zt,js,Wv,at,Ft,Bt,ct,Wa,Gv,dm,Jv,Yv,pm,Ds,re,mm,Xv,Qv,B4,Ga,$O,Ja,TO,Ms,Ro,ex,RO,EO,PO,AO,CO,IO,hm,OO,NO,fm,Ya,zO,LO,Xa,jO,Us,qs,DO,Fs,Eo,MO,Bs,Qa,ec,tc,Z4,rc,nc,oc,tx,rx,nx,gm,ox,Zs,Po,sx,UO,sc,qO,ic,FO,ym,BO,ac,ZO,VO,HO,KO,WO,GO,JO,YO,XO,QO,cc,eN,tN,lc,bm,wm,_m,rN,nN,oN,vm,sN,iN,aN,cN,lN,ix,uc,uN,dc,V4,dN,Ao,pN,H4,Vs,mN,xm,hN,fN,gN,yN,bN,wN,_N,Ha,vN,xN,kN,Hs,km,SN,$N,TN,RN,EN,PN,AN,CN,IN,ON,NN,zN,LN,jN,DN,MN,UN,qN,Co,FN,BN,ZN,pc,VN,HN,KN,Sm,WN,K4,W4,G4,J4,Y4,X4,Y,cm,Io=O(()=>{Zv();lm="2025-11-25",Vv=[lm,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],en="io.modelcontextprotocol/related-task",Ka="2.0",Qe=Mv(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Hv=je([C(),Ee().int()]),Kv=C(),F4=yt({ttl:Ee().optional(),pollInterval:Ee().optional()}),kO=K({ttl:Ee().optional()}),SO=K({taskId:C()}),um=yt({progressToken:Hv.optional(),[en]:SO.optional()}),zt=K({_meta:um.optional()}),js=zt.extend({task:kO.optional()}),Wv=t=>js.safeParse(t).success,at=K({method:C(),params:zt.loose().optional()}),Ft=K({_meta:um.optional()}),Bt=K({method:C(),params:Ft.loose().optional()}),ct=yt({_meta:um.optional()}),Wa=je([C(),Ee().int()]),Gv=K({jsonrpc:X(Ka),id:Wa,...at.shape}).strict(),dm=t=>Gv.safeParse(t).success,Jv=K({jsonrpc:X(Ka),...Bt.shape}).strict(),Yv=t=>Jv.safeParse(t).success,pm=K({jsonrpc:X(Ka),id:Wa,result:ct}).strict(),Ds=t=>pm.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"})(re||(re={}));mm=K({jsonrpc:X(Ka),id:Wa.optional(),error:K({code:Ee().int(),message:C(),data:Fe().optional()})}).strict(),Xv=t=>mm.safeParse(t).success,Qv=je([Gv,Jv,pm,mm]),B4=je([pm,mm]),Ga=ct.strict(),$O=Ft.extend({requestId:Wa.optional(),reason:C().optional()}),Ja=Bt.extend({method:X("notifications/cancelled"),params:$O}),TO=K({src:C(),mimeType:C().optional(),sizes:ve(C()).optional(),theme:Rt(["light","dark"]).optional()}),Ms=K({icons:ve(TO).optional()}),Ro=K({name:C(),title:C().optional()}),ex=Ro.extend({...Ro.shape,...Ms.shape,version:C(),websiteUrl:C().optional(),description:C().optional()}),RO=Va(K({applyDefaults:rt().optional()}),Le(C(),Fe())),EO=am(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Va(K({form:RO.optional(),url:Qe.optional()}),Le(C(),Fe()).optional())),PO=yt({list:Qe.optional(),cancel:Qe.optional(),requests:yt({sampling:yt({createMessage:Qe.optional()}).optional(),elicitation:yt({create:Qe.optional()}).optional()}).optional()}),AO=yt({list:Qe.optional(),cancel:Qe.optional(),requests:yt({tools:yt({call:Qe.optional()}).optional()}).optional()}),CO=K({experimental:Le(C(),Qe).optional(),sampling:K({context:Qe.optional(),tools:Qe.optional()}).optional(),elicitation:EO.optional(),roots:K({listChanged:rt().optional()}).optional(),tasks:PO.optional(),extensions:Le(C(),Qe).optional()}),IO=zt.extend({protocolVersion:C(),capabilities:CO,clientInfo:ex}),hm=at.extend({method:X("initialize"),params:IO}),OO=K({experimental:Le(C(),Qe).optional(),logging:Qe.optional(),completions:Qe.optional(),prompts:K({listChanged:rt().optional()}).optional(),resources:K({subscribe:rt().optional(),listChanged:rt().optional()}).optional(),tools:K({listChanged:rt().optional()}).optional(),tasks:AO.optional(),extensions:Le(C(),Qe).optional()}),NO=ct.extend({protocolVersion:C(),capabilities:OO,serverInfo:ex,instructions:C().optional()}),fm=Bt.extend({method:X("notifications/initialized"),params:Ft.optional()}),Ya=at.extend({method:X("ping"),params:zt.optional()}),zO=K({progress:Ee(),total:Be(Ee()),message:Be(C())}),LO=K({...Ft.shape,...zO.shape,progressToken:Hv}),Xa=Bt.extend({method:X("notifications/progress"),params:LO}),jO=zt.extend({cursor:Kv.optional()}),Us=at.extend({params:jO.optional()}),qs=ct.extend({nextCursor:Kv.optional()}),DO=Rt(["working","input_required","completed","failed","cancelled"]),Fs=K({taskId:C(),status:DO,ttl:je([Ee(),Iv()]),createdAt:C(),lastUpdatedAt:C(),pollInterval:Be(Ee()),statusMessage:Be(C())}),Eo=ct.extend({task:Fs}),MO=Ft.merge(Fs),Bs=Bt.extend({method:X("notifications/tasks/status"),params:MO}),Qa=at.extend({method:X("tasks/get"),params:zt.extend({taskId:C()})}),ec=ct.merge(Fs),tc=at.extend({method:X("tasks/result"),params:zt.extend({taskId:C()})}),Z4=ct.loose(),rc=Us.extend({method:X("tasks/list")}),nc=qs.extend({tasks:ve(Fs)}),oc=at.extend({method:X("tasks/cancel"),params:zt.extend({taskId:C()})}),tx=ct.merge(Fs),rx=K({uri:C(),mimeType:Be(C()),_meta:Le(C(),Fe()).optional()}),nx=rx.extend({text:C()}),gm=C().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ox=rx.extend({blob:gm}),Zs=Rt(["user","assistant"]),Po=K({audience:ve(Zs).optional(),priority:Ee().min(0).max(1).optional(),lastModified:zs.datetime({offset:!0}).optional()}),sx=K({...Ro.shape,...Ms.shape,uri:C(),description:Be(C()),mimeType:Be(C()),size:Be(Ee()),annotations:Po.optional(),_meta:Be(yt({}))}),UO=K({...Ro.shape,...Ms.shape,uriTemplate:C(),description:Be(C()),mimeType:Be(C()),annotations:Po.optional(),_meta:Be(yt({}))}),sc=Us.extend({method:X("resources/list")}),qO=qs.extend({resources:ve(sx)}),ic=Us.extend({method:X("resources/templates/list")}),FO=qs.extend({resourceTemplates:ve(UO)}),ym=zt.extend({uri:C()}),BO=ym,ac=at.extend({method:X("resources/read"),params:BO}),ZO=ct.extend({contents:ve(je([nx,ox]))}),VO=Bt.extend({method:X("notifications/resources/list_changed"),params:Ft.optional()}),HO=ym,KO=at.extend({method:X("resources/subscribe"),params:HO}),WO=ym,GO=at.extend({method:X("resources/unsubscribe"),params:WO}),JO=Ft.extend({uri:C()}),YO=Bt.extend({method:X("notifications/resources/updated"),params:JO}),XO=K({name:C(),description:Be(C()),required:Be(rt())}),QO=K({...Ro.shape,...Ms.shape,description:Be(C()),arguments:Be(ve(XO)),_meta:Be(yt({}))}),cc=Us.extend({method:X("prompts/list")}),eN=qs.extend({prompts:ve(QO)}),tN=zt.extend({name:C(),arguments:Le(C(),C()).optional()}),lc=at.extend({method:X("prompts/get"),params:tN}),bm=K({type:X("text"),text:C(),annotations:Po.optional(),_meta:Le(C(),Fe()).optional()}),wm=K({type:X("image"),data:gm,mimeType:C(),annotations:Po.optional(),_meta:Le(C(),Fe()).optional()}),_m=K({type:X("audio"),data:gm,mimeType:C(),annotations:Po.optional(),_meta:Le(C(),Fe()).optional()}),rN=K({type:X("tool_use"),name:C(),id:C(),input:Le(C(),Fe()),_meta:Le(C(),Fe()).optional()}),nN=K({type:X("resource"),resource:je([nx,ox]),annotations:Po.optional(),_meta:Le(C(),Fe()).optional()}),oN=sx.extend({type:X("resource_link")}),vm=je([bm,wm,_m,oN,nN]),sN=K({role:Zs,content:vm}),iN=ct.extend({description:C().optional(),messages:ve(sN)}),aN=Bt.extend({method:X("notifications/prompts/list_changed"),params:Ft.optional()}),cN=K({title:C().optional(),readOnlyHint:rt().optional(),destructiveHint:rt().optional(),idempotentHint:rt().optional(),openWorldHint:rt().optional()}),lN=K({taskSupport:Rt(["required","optional","forbidden"]).optional()}),ix=K({...Ro.shape,...Ms.shape,description:C().optional(),inputSchema:K({type:X("object"),properties:Le(C(),Qe).optional(),required:ve(C()).optional()}).catchall(Fe()),outputSchema:K({type:X("object"),properties:Le(C(),Qe).optional(),required:ve(C()).optional()}).catchall(Fe()).optional(),annotations:cN.optional(),execution:lN.optional(),_meta:Le(C(),Fe()).optional()}),uc=Us.extend({method:X("tools/list")}),uN=qs.extend({tools:ve(ix)}),dc=ct.extend({content:ve(vm).default([]),structuredContent:Le(C(),Fe()).optional(),isError:rt().optional()}),V4=dc.or(ct.extend({toolResult:Fe()})),dN=js.extend({name:C(),arguments:Le(C(),Fe()).optional()}),Ao=at.extend({method:X("tools/call"),params:dN}),pN=Bt.extend({method:X("notifications/tools/list_changed"),params:Ft.optional()}),H4=K({autoRefresh:rt().default(!0),debounceMs:Ee().int().nonnegative().default(300)}),Vs=Rt(["debug","info","notice","warning","error","critical","alert","emergency"]),mN=zt.extend({level:Vs}),xm=at.extend({method:X("logging/setLevel"),params:mN}),hN=Ft.extend({level:Vs,logger:C().optional(),data:Fe()}),fN=Bt.extend({method:X("notifications/message"),params:hN}),gN=K({name:C().optional()}),yN=K({hints:ve(gN).optional(),costPriority:Ee().min(0).max(1).optional(),speedPriority:Ee().min(0).max(1).optional(),intelligencePriority:Ee().min(0).max(1).optional()}),bN=K({mode:Rt(["auto","required","none"]).optional()}),wN=K({type:X("tool_result"),toolUseId:C().describe("The unique identifier for the corresponding tool call."),content:ve(vm).default([]),structuredContent:K({}).loose().optional(),isError:rt().optional(),_meta:Le(C(),Fe()).optional()}),_N=im("type",[bm,wm,_m]),Ha=im("type",[bm,wm,_m,rN,wN]),vN=K({role:Zs,content:je([Ha,ve(Ha)]),_meta:Le(C(),Fe()).optional()}),xN=js.extend({messages:ve(vN),modelPreferences:yN.optional(),systemPrompt:C().optional(),includeContext:Rt(["none","thisServer","allServers"]).optional(),temperature:Ee().optional(),maxTokens:Ee().int(),stopSequences:ve(C()).optional(),metadata:Qe.optional(),tools:ve(ix).optional(),toolChoice:bN.optional()}),kN=at.extend({method:X("sampling/createMessage"),params:xN}),Hs=ct.extend({model:C(),stopReason:Be(Rt(["endTurn","stopSequence","maxTokens"]).or(C())),role:Zs,content:_N}),km=ct.extend({model:C(),stopReason:Be(Rt(["endTurn","stopSequence","maxTokens","toolUse"]).or(C())),role:Zs,content:je([Ha,ve(Ha)])}),SN=K({type:X("boolean"),title:C().optional(),description:C().optional(),default:rt().optional()}),$N=K({type:X("string"),title:C().optional(),description:C().optional(),minLength:Ee().optional(),maxLength:Ee().optional(),format:Rt(["email","uri","date","date-time"]).optional(),default:C().optional()}),TN=K({type:Rt(["number","integer"]),title:C().optional(),description:C().optional(),minimum:Ee().optional(),maximum:Ee().optional(),default:Ee().optional()}),RN=K({type:X("string"),title:C().optional(),description:C().optional(),enum:ve(C()),default:C().optional()}),EN=K({type:X("string"),title:C().optional(),description:C().optional(),oneOf:ve(K({const:C(),title:C()})),default:C().optional()}),PN=K({type:X("string"),title:C().optional(),description:C().optional(),enum:ve(C()),enumNames:ve(C()).optional(),default:C().optional()}),AN=je([RN,EN]),CN=K({type:X("array"),title:C().optional(),description:C().optional(),minItems:Ee().optional(),maxItems:Ee().optional(),items:K({type:X("string"),enum:ve(C())}),default:ve(C()).optional()}),IN=K({type:X("array"),title:C().optional(),description:C().optional(),minItems:Ee().optional(),maxItems:Ee().optional(),items:K({anyOf:ve(K({const:C(),title:C()}))}),default:ve(C()).optional()}),ON=je([CN,IN]),NN=je([PN,AN,ON]),zN=je([NN,SN,$N,TN]),LN=js.extend({mode:X("form").optional(),message:C(),requestedSchema:K({type:X("object"),properties:Le(C(),zN),required:ve(C()).optional()})}),jN=js.extend({mode:X("url"),message:C(),elicitationId:C(),url:C().url()}),DN=je([LN,jN]),MN=at.extend({method:X("elicitation/create"),params:DN}),UN=Ft.extend({elicitationId:C()}),qN=Bt.extend({method:X("notifications/elicitation/complete"),params:UN}),Co=ct.extend({action:Rt(["accept","decline","cancel"]),content:am(t=>t===null?void 0:t,Le(C(),je([C(),Ee(),rt(),ve(C())])).optional())}),FN=K({type:X("ref/resource"),uri:C()}),BN=K({type:X("ref/prompt"),name:C()}),ZN=zt.extend({ref:je([BN,FN]),argument:K({name:C(),value:C()}),context:K({arguments:Le(C(),C()).optional()}).optional()}),pc=at.extend({method:X("completion/complete"),params:ZN});VN=ct.extend({completion:yt({values:ve(C()).max(100),total:Be(Ee().int()),hasMore:Be(rt())})}),HN=K({uri:C().startsWith("file://"),name:C().optional(),_meta:Le(C(),Fe()).optional()}),KN=at.extend({method:X("roots/list"),params:zt.optional()}),Sm=ct.extend({roots:ve(HN)}),WN=Bt.extend({method:X("notifications/roots/list_changed"),params:Ft.optional()}),K4=je([Ya,hm,pc,xm,lc,cc,sc,ic,ac,KO,GO,Ao,uc,Qa,tc,rc,oc]),W4=je([Ja,Xa,fm,WN,Bs]),G4=je([Ga,Hs,km,Co,Sm,ec,nc,Eo]),J4=je([Ya,kN,MN,KN,Qa,tc,rc,oc]),Y4=je([Ja,Xa,fN,YO,VO,pN,aN,Bs,qN]),X4=je([Ga,NO,VN,iN,eN,qO,FO,ZO,dc,uN,ec,nc,Eo]),Y=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===re.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new cm(o.elicitations,r)}return new t(e,r,n)}},cm=class extends Y{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(re.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function tn(t){return t==="completed"||t==="failed"||t==="cancelled"}var lx=O(()=>{});var dx,ux,px,mc=O(()=>{dx=Symbol("Let zodToJsonSchema decide on which parser to use"),ux={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"},px=t=>typeof t=="string"?{...ux,name:t}:{...ux,...t}});var mx,$m=O(()=>{mc();mx=t=>{let e=px(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 Tm(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,Tm(t,e,n,o)}var rn=O(()=>{});var hc,fc=O(()=>{hc=(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 Ze(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?hc(e,t.currentPath):e.join("/")}}var Zt=O(()=>{fc()});function hx(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==U.ZodAny&&(r.items=ae(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 Rm=O(()=>{vs();rn();Je()});function fx(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 Em=O(()=>{rn()});function gx(){return{type:"boolean"}}var Pm=O(()=>{});function gc(t,e){return ae(t.type._def,e)}var yc=O(()=>{Je()});var yx,Am=O(()=>{Je();yx=(t,e)=>ae(t.innerType._def,e)});function Cm(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Cm(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 GN(t,e)}}var GN,Im=O(()=>{rn();GN=(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 bx(t,e){return{...ae(t.innerType._def,e),default:t.defaultValue()}}var Om=O(()=>{Je()});function wx(t,e){return e.effectStrategy==="input"?ae(t.schema._def,e):Ze(e)}var Nm=O(()=>{Je();Zt()});function _x(t){return{type:"string",enum:Array.from(t.values)}}var zm=O(()=>{});function vx(t,e){let r=[ae(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ae(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(JN(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 JN,Lm=O(()=>{Je();JN=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function xx(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 jm=O(()=>{});function bc(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":or(r,"email",n.message,e);break;case"format:idn-email":or(r,"idn-email",n.message,e);break;case"pattern:zod":bt(r,nr.email,n.message,e);break}break;case"url":or(r,"uri",n.message,e);break;case"uuid":or(r,"uuid",n.message,e);break;case"regex":bt(r,n.regex,n.message,e);break;case"cuid":bt(r,nr.cuid,n.message,e);break;case"cuid2":bt(r,nr.cuid2,n.message,e);break;case"startsWith":bt(r,RegExp(`^${Mm(n.value,e)}`),n.message,e);break;case"endsWith":bt(r,RegExp(`${Mm(n.value,e)}$`),n.message,e);break;case"datetime":or(r,"date-time",n.message,e);break;case"date":or(r,"date",n.message,e);break;case"time":or(r,"time",n.message,e);break;case"duration":or(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":{bt(r,RegExp(Mm(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&or(r,"ipv4",n.message,e),n.version!=="v4"&&or(r,"ipv6",n.message,e);break}case"base64url":bt(r,nr.base64url,n.message,e);break;case"jwt":bt(r,nr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&bt(r,nr.ipv4Cidr,n.message,e),n.version!=="v4"&&bt(r,nr.ipv6Cidr,n.message,e);break}case"emoji":bt(r,nr.emoji(),n.message,e);break;case"ulid":{bt(r,nr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{or(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{bt(r,nr.base64,n.message,e);break}}break}case"nanoid":bt(r,nr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Mm(t,e){return e.patternStrategy==="escape"?XN(t):t}function XN(t){let e="";for(let r=0;r<t.length;r++)YN.has(t[r])||(e+="\\"),e+=t[r];return e}function or(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 bt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:kx(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",kx(e,n),r,n)}function kx(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
2048
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let m=n.external.registry.get(u[0])?.id;if(e!==u[0]&&m){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let b=this.seen.get(u),m=b.def??b.schema,h={...m};if(b.ref===null)return;let w=b.ref;if(b.ref=null,w){a(w,p);let S=this.seen.get(w).schema;S.$ref&&p.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(S)):(Object.assign(m,S),Object.assign(m,h))}b.isParent||this.override({zodSchema:u,jsonSchema:m,path:b.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let 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 wv=O(()=>{});var yt=O(()=>{xo();pd();sd();av();Aa();bd();br();Pa();La();ap();yd();yv();gv();bv();wv()});var Gp=O(()=>{yt()});function Jp(t,e){let r={type:"object",get shape(){return ve.assignProp(this,"shape",{...t}),this.shape},...ve.normalizeParams(e)};return new jI(r)}var LI,jI,_v=O(()=>{yt();yt();Gp();LI=I("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ie.init(t,e),t.def=e,t.parse=(r,n)=>ad(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Dn(t,r,n),t.parseAsync=async(r,n)=>ld(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Mn(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)=>zt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),jI=I("ZodMiniObject",(t,e)=>{Na.init(t,e),LI.init(t,e),ve.defineLazy(t,"shape",()=>e.shape)})});var vv=O(()=>{});var xv=O(()=>{});var kv=O(()=>{});var Sv=O(()=>{yt();Gp();_v();vv();yt();La();xv();kv()});var $v=O(()=>{Sv()});var Yp=O(()=>{$v()});function wr(t){return!!t._zod}function Bn(t){let e=Object.values(t);if(e.length===0)return Jp({});let r=e.every(wr),n=e.every(o=>!wr(o));if(r)return Jp(t);if(n)return ql(t);throw new Error("Mixed Zod versions detected in object shape.")}function Qr(t,e){return wr(t)?Dn(t,e):t.safeParse(e)}async function Za(t,e){return wr(t)?await Mn(t,e):await t.safeParseAsync(e)}function en(t){if(!t)return;let e;if(wr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function To(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 Bn(t)}}if(wr(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 UI(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Va(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 ${UI(e.path)}`:e.message).join(`
2049
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Rv(t){return t.description}function Ev(t){if(wr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Ro(t){if(wr(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 js=O(()=>{Ss();Yp()});var Xp=O(()=>{yt()});var Ds={};es(Ds,{ZodISODate:()=>Av,ZodISODateTime:()=>Pv,ZodISODuration:()=>Iv,ZodISOTime:()=>Cv,date:()=>eh,datetime:()=>Qp,duration:()=>rh,time:()=>th});function Qp(t){return dv(Pv,t)}function eh(t){return pv(Av,t)}function th(t){return hv(Cv,t)}function rh(t){return mv(Iv,t)}var Pv,Av,Cv,Iv,nh=O(()=>{yt();oh();Pv=I("ZodISODateTime",(t,e)=>{rv.init(t,e),Fe.init(t,e)});Av=I("ZodISODate",(t,e)=>{nv.init(t,e),Fe.init(t,e)});Cv=I("ZodISOTime",(t,e)=>{ov.init(t,e),Fe.init(t,e)});Iv=I("ZodISODuration",(t,e)=>{sv.init(t,e),Fe.init(t,e)})});var Ov,H4,Ms,sh=O(()=>{yt();yt();Ov=(t,e)=>{Ra.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>od(t,r)},flatten:{value:r=>nd(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},H4=I("ZodError",Ov),Ms=I("ZodError",Ov,{Parent:Error})});var Nv,zv,Lv,jv,ih=O(()=>{yt();sh();Nv=id(Ms),zv=cd(Ms),Lv=ud(Ms),jv=dd(Ms)});function C(t){return cp(WI,t)}function Ae(t){return Ap(Bv,t)}function Mv(t){return Cp(pO,t)}function ot(t){return Ip(hO,t)}function Fv(t){return Op(mO,t)}function Ze(){return Np(fO)}function yO(t){return zp(gO,t)}function xe(t,e){return fv(bO,t,e)}function H(t,e){let r={type:"object",get shape(){return ve.assignProp(this,"shape",{...t}),this.shape},...ve.normalizeParams(e)};return new Zv(r)}function bt(t,e){return new Zv({type:"object",get shape(){return ve.assignProp(this,"shape",{...t}),this.shape},catchall:Ze(),...ve.normalizeParams(e)})}function Me(t,e){return new Vv({type:"union",options:t,...ve.normalizeParams(e)})}function lh(t,e,r){return new wO({type:"union",options:e,discriminator:t,...ve.normalizeParams(r)})}function Ka(t,e){return new _O({type:"intersection",left:t,right:e})}function De(t,e,r){return new vO({type:"record",keyType:t,valueType:e,...ve.normalizeParams(r)})}function Et(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new ah({type:"enum",entries:r,...ve.normalizeParams(e)})}function Y(t,e){return new xO({type:"literal",values:Array.isArray(t)?t:[t],...ve.normalizeParams(e)})}function Hv(t){return new kO({type:"transform",transform:t})}function Ve(t){return new Kv({type:"optional",innerType:t})}function Uv(t){return new SO({type:"nullable",innerType:t})}function TO(t,e){return new $O({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function EO(t,e){return new RO({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function PO(t,e){return new Wv({type:"nonoptional",innerType:t,...ve.normalizeParams(e)})}function CO(t,e){return new AO({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function ch(t,e){return new IO({type:"pipe",in:t,out:e})}function NO(t){return new OO({type:"readonly",innerType:t})}function zO(t){let e=new ct({check:"custom"});return e._zod.check=t,e}function Jv(t,e){return Hp(Gv,t??(()=>!0),e)}function LO(t,e={}){return Kp(Gv,t,e)}function jO(t){let e=zO(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ve.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(ve.issue(o))}},t(r.value,r)));return e}function uh(t,e){return ch(Hv(t),e)}var Ke,qv,WI,Fe,GI,Dv,Ha,JI,YI,XI,QI,eO,tO,rO,nO,oO,sO,iO,aO,cO,lO,uO,dO,Bv,pO,hO,mO,fO,gO,bO,Zv,Vv,wO,_O,vO,ah,xO,kO,Kv,SO,$O,RO,Wv,AO,IO,OO,Gv,oh=O(()=>{yt();yt();Xp();nh();ih();Ke=I("ZodType",(t,e)=>(Ie.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)=>zt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Nv(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Lv(t,r,n),t.parseAsync=async(r,n)=>zv(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>jv(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(LO(r,n)),t.superRefine=r=>t.check(jO(r)),t.overwrite=r=>t.check(Un(r)),t.optional=()=>Ve(t),t.nullable=()=>Uv(t),t.nullish=()=>Ve(Uv(t)),t.nonoptional=r=>PO(t,r),t.array=()=>xe(t),t.or=r=>Me([t,r]),t.and=r=>Ka(t,r),t.transform=r=>ch(t,Hv(r)),t.default=r=>TO(t,r),t.prefault=r=>EO(t,r),t.catch=r=>CO(t,r),t.pipe=r=>ch(t,r),t.readonly=()=>NO(t),t.describe=r=>{let n=t.clone();return Xr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Xr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Xr.get(t);let n=t.clone();return Xr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),qv=I("_ZodString",(t,e)=>{Os.init(t,e),Ke.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(Lp(...n)),t.includes=(...n)=>t.check(Mp(...n)),t.startsWith=(...n)=>t.check(Up(...n)),t.endsWith=(...n)=>t.check(qp(...n)),t.min=(...n)=>t.check($o(...n)),t.max=(...n)=>t.check(qa(...n)),t.length=(...n)=>t.check(Ba(...n)),t.nonempty=(...n)=>t.check($o(1,...n)),t.lowercase=n=>t.check(jp(n)),t.uppercase=n=>t.check(Dp(n)),t.trim=()=>t.check(Fp()),t.normalize=(...n)=>t.check(Bp(...n)),t.toLowerCase=()=>t.check(Zp()),t.toUpperCase=()=>t.check(Vp())}),WI=I("ZodString",(t,e)=>{Os.init(t,e),qv.init(t,e),t.email=r=>t.check(lp(GI,r)),t.url=r=>t.check(mp(JI,r)),t.jwt=r=>t.check(Pp(dO,r)),t.emoji=r=>t.check(fp(YI,r)),t.guid=r=>t.check(ja(Dv,r)),t.uuid=r=>t.check(up(Ha,r)),t.uuidv4=r=>t.check(dp(Ha,r)),t.uuidv6=r=>t.check(pp(Ha,r)),t.uuidv7=r=>t.check(hp(Ha,r)),t.nanoid=r=>t.check(gp(XI,r)),t.guid=r=>t.check(ja(Dv,r)),t.cuid=r=>t.check(yp(QI,r)),t.cuid2=r=>t.check(bp(eO,r)),t.ulid=r=>t.check(wp(tO,r)),t.base64=r=>t.check(Tp(cO,r)),t.base64url=r=>t.check(Rp(lO,r)),t.xid=r=>t.check(_p(rO,r)),t.ksuid=r=>t.check(vp(nO,r)),t.ipv4=r=>t.check(xp(oO,r)),t.ipv6=r=>t.check(kp(sO,r)),t.cidrv4=r=>t.check(Sp(iO,r)),t.cidrv6=r=>t.check($p(aO,r)),t.e164=r=>t.check(Ep(uO,r)),t.datetime=r=>t.check(Qp(r)),t.date=r=>t.check(eh(r)),t.time=r=>t.check(th(r)),t.duration=r=>t.check(rh(r))});Fe=I("ZodStringFormat",(t,e)=>{je.init(t,e),qv.init(t,e)}),GI=I("ZodEmail",(t,e)=>{xd.init(t,e),Fe.init(t,e)}),Dv=I("ZodGUID",(t,e)=>{_d.init(t,e),Fe.init(t,e)}),Ha=I("ZodUUID",(t,e)=>{vd.init(t,e),Fe.init(t,e)}),JI=I("ZodURL",(t,e)=>{kd.init(t,e),Fe.init(t,e)}),YI=I("ZodEmoji",(t,e)=>{Sd.init(t,e),Fe.init(t,e)}),XI=I("ZodNanoID",(t,e)=>{$d.init(t,e),Fe.init(t,e)}),QI=I("ZodCUID",(t,e)=>{Td.init(t,e),Fe.init(t,e)}),eO=I("ZodCUID2",(t,e)=>{Rd.init(t,e),Fe.init(t,e)}),tO=I("ZodULID",(t,e)=>{Ed.init(t,e),Fe.init(t,e)}),rO=I("ZodXID",(t,e)=>{Pd.init(t,e),Fe.init(t,e)}),nO=I("ZodKSUID",(t,e)=>{Ad.init(t,e),Fe.init(t,e)}),oO=I("ZodIPv4",(t,e)=>{Cd.init(t,e),Fe.init(t,e)}),sO=I("ZodIPv6",(t,e)=>{Id.init(t,e),Fe.init(t,e)}),iO=I("ZodCIDRv4",(t,e)=>{Od.init(t,e),Fe.init(t,e)}),aO=I("ZodCIDRv6",(t,e)=>{Nd.init(t,e),Fe.init(t,e)}),cO=I("ZodBase64",(t,e)=>{zd.init(t,e),Fe.init(t,e)}),lO=I("ZodBase64URL",(t,e)=>{Ld.init(t,e),Fe.init(t,e)}),uO=I("ZodE164",(t,e)=>{jd.init(t,e),Fe.init(t,e)}),dO=I("ZodJWT",(t,e)=>{Dd.init(t,e),Fe.init(t,e)}),Bv=I("ZodNumber",(t,e)=>{Oa.init(t,e),Ke.init(t,e),t.gt=(n,o)=>t.check(Ma(n,o)),t.gte=(n,o)=>t.check(Ls(n,o)),t.min=(n,o)=>t.check(Ls(n,o)),t.lt=(n,o)=>t.check(Da(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(Mv(n)),t.safe=n=>t.check(Mv(n)),t.positive=n=>t.check(Ma(0,n)),t.nonnegative=n=>t.check(Ls(0,n)),t.negative=n=>t.check(Da(0,n)),t.nonpositive=n=>t.check(zs(0,n)),t.multipleOf=(n,o)=>t.check(Ua(n,o)),t.step=(n,o)=>t.check(Ua(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});pO=I("ZodNumberFormat",(t,e)=>{Md.init(t,e),Bv.init(t,e)});hO=I("ZodBoolean",(t,e)=>{Ud.init(t,e),Ke.init(t,e)});mO=I("ZodNull",(t,e)=>{qd.init(t,e),Ke.init(t,e)});fO=I("ZodUnknown",(t,e)=>{Bd.init(t,e),Ke.init(t,e)});gO=I("ZodNever",(t,e)=>{Fd.init(t,e),Ke.init(t,e)});bO=I("ZodArray",(t,e)=>{Zd.init(t,e),Ke.init(t,e),t.element=e.element,t.min=(r,n)=>t.check($o(r,n)),t.nonempty=r=>t.check($o(1,r)),t.max=(r,n)=>t.check(qa(r,n)),t.length=(r,n)=>t.check(Ba(r,n)),t.unwrap=()=>t.element});Zv=I("ZodObject",(t,e)=>{Na.init(t,e),Ke.init(t,e),ve.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Et(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ze()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ze()}),t.strict=()=>t.clone({...t._zod.def,catchall:yO()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ve.extend(t,r),t.merge=r=>ve.merge(t,r),t.pick=r=>ve.pick(t,r),t.omit=r=>ve.omit(t,r),t.partial=(...r)=>ve.partial(Kv,t,r[0]),t.required=(...r)=>ve.required(Wv,t,r[0])});Vv=I("ZodUnion",(t,e)=>{za.init(t,e),Ke.init(t,e),t.options=e.options});wO=I("ZodDiscriminatedUnion",(t,e)=>{Vv.init(t,e),Vd.init(t,e)});_O=I("ZodIntersection",(t,e)=>{Hd.init(t,e),Ke.init(t,e)});vO=I("ZodRecord",(t,e)=>{Kd.init(t,e),Ke.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});ah=I("ZodEnum",(t,e)=>{Wd.init(t,e),Ke.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 ah({...e,checks:[],...ve.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 ah({...e,checks:[],...ve.normalizeParams(o),entries:s})}});xO=I("ZodLiteral",(t,e)=>{Gd.init(t,e),Ke.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]}})});kO=I("ZodTransform",(t,e)=>{Jd.init(t,e),Ke.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(ve.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(ve.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});Kv=I("ZodOptional",(t,e)=>{Yd.init(t,e),Ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});SO=I("ZodNullable",(t,e)=>{Xd.init(t,e),Ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});$O=I("ZodDefault",(t,e)=>{Qd.init(t,e),Ke.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});RO=I("ZodPrefault",(t,e)=>{ep.init(t,e),Ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});Wv=I("ZodNonOptional",(t,e)=>{tp.init(t,e),Ke.init(t,e),t.unwrap=()=>t._zod.def.innerType});AO=I("ZodCatch",(t,e)=>{rp.init(t,e),Ke.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});IO=I("ZodPipe",(t,e)=>{np.init(t,e),Ke.init(t,e),t.in=e.in,t.out=e.out});OO=I("ZodReadonly",(t,e)=>{op.init(t,e),Ke.init(t,e)});Gv=I("ZodCustom",(t,e)=>{sp.init(t,e),Ke.init(t,e)})});var Yv=O(()=>{});var Xv=O(()=>{});var Qv=O(()=>{yt();oh();Xp();sh();ih();Yv();yt();lv();La();nh();Xv();Nt(cv())});var ex=O(()=>{Qv()});var tx=O(()=>{ex()});function bx(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function wx(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var ph,rx,tn,Ga,rt,nx,ox,cV,UO,qO,hh,Lt,Us,sx,lt,Ft,Zt,ut,Ja,ix,mh,ax,cx,fh,qs,ee,gh,lx,ux,lV,Ya,BO,Xa,FO,Bs,Eo,dx,ZO,VO,HO,KO,WO,GO,yh,JO,YO,bh,Qa,XO,QO,ec,eN,Fs,Zs,tN,Vs,Po,rN,Hs,tc,rc,nc,uV,oc,sc,ic,px,hx,mx,wh,fx,Ks,Ao,gx,nN,ac,oN,cc,sN,_h,iN,lc,aN,cN,lN,uN,dN,pN,hN,mN,fN,gN,uc,yN,bN,dc,vh,xh,kh,wN,_N,vN,Sh,xN,kN,SN,$N,TN,yx,pc,RN,hc,dV,EN,Co,PN,pV,Ws,AN,$h,CN,IN,ON,NN,zN,LN,jN,Wa,DN,MN,UN,Gs,Th,qN,BN,FN,ZN,VN,HN,KN,WN,GN,JN,YN,XN,QN,ez,tz,rz,nz,oz,Io,sz,iz,az,mc,cz,lz,uz,Rh,dz,hV,mV,fV,gV,yV,bV,J,dh,Oo=O(()=>{tx();ph="2025-11-25",rx=[ph,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],tn="io.modelcontextprotocol/related-task",Ga="2.0",rt=Jv(t=>t!==null&&(typeof t=="object"||typeof t=="function")),nx=Me([C(),Ae().int()]),ox=C(),cV=bt({ttl:Ae().optional(),pollInterval:Ae().optional()}),UO=H({ttl:Ae().optional()}),qO=H({taskId:C()}),hh=bt({progressToken:nx.optional(),[tn]:qO.optional()}),Lt=H({_meta:hh.optional()}),Us=Lt.extend({task:UO.optional()}),sx=t=>Us.safeParse(t).success,lt=H({method:C(),params:Lt.loose().optional()}),Ft=H({_meta:hh.optional()}),Zt=H({method:C(),params:Ft.loose().optional()}),ut=bt({_meta:hh.optional()}),Ja=Me([C(),Ae().int()]),ix=H({jsonrpc:Y(Ga),id:Ja,...lt.shape}).strict(),mh=t=>ix.safeParse(t).success,ax=H({jsonrpc:Y(Ga),...Zt.shape}).strict(),cx=t=>ax.safeParse(t).success,fh=H({jsonrpc:Y(Ga),id:Ja,result:ut}).strict(),qs=t=>fh.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(ee||(ee={}));gh=H({jsonrpc:Y(Ga),id:Ja.optional(),error:H({code:Ae().int(),message:C(),data:Ze().optional()})}).strict(),lx=t=>gh.safeParse(t).success,ux=Me([ix,ax,fh,gh]),lV=Me([fh,gh]),Ya=ut.strict(),BO=Ft.extend({requestId:Ja.optional(),reason:C().optional()}),Xa=Zt.extend({method:Y("notifications/cancelled"),params:BO}),FO=H({src:C(),mimeType:C().optional(),sizes:xe(C()).optional(),theme:Et(["light","dark"]).optional()}),Bs=H({icons:xe(FO).optional()}),Eo=H({name:C(),title:C().optional()}),dx=Eo.extend({...Eo.shape,...Bs.shape,version:C(),websiteUrl:C().optional(),description:C().optional()}),ZO=Ka(H({applyDefaults:ot().optional()}),De(C(),Ze())),VO=uh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ka(H({form:ZO.optional(),url:rt.optional()}),De(C(),Ze()).optional())),HO=bt({list:rt.optional(),cancel:rt.optional(),requests:bt({sampling:bt({createMessage:rt.optional()}).optional(),elicitation:bt({create:rt.optional()}).optional()}).optional()}),KO=bt({list:rt.optional(),cancel:rt.optional(),requests:bt({tools:bt({call:rt.optional()}).optional()}).optional()}),WO=H({experimental:De(C(),rt).optional(),sampling:H({context:rt.optional(),tools:rt.optional()}).optional(),elicitation:VO.optional(),roots:H({listChanged:ot().optional()}).optional(),tasks:HO.optional(),extensions:De(C(),rt).optional()}),GO=Lt.extend({protocolVersion:C(),capabilities:WO,clientInfo:dx}),yh=lt.extend({method:Y("initialize"),params:GO}),JO=H({experimental:De(C(),rt).optional(),logging:rt.optional(),completions:rt.optional(),prompts:H({listChanged:ot().optional()}).optional(),resources:H({subscribe:ot().optional(),listChanged:ot().optional()}).optional(),tools:H({listChanged:ot().optional()}).optional(),tasks:KO.optional(),extensions:De(C(),rt).optional()}),YO=ut.extend({protocolVersion:C(),capabilities:JO,serverInfo:dx,instructions:C().optional()}),bh=Zt.extend({method:Y("notifications/initialized"),params:Ft.optional()}),Qa=lt.extend({method:Y("ping"),params:Lt.optional()}),XO=H({progress:Ae(),total:Ve(Ae()),message:Ve(C())}),QO=H({...Ft.shape,...XO.shape,progressToken:nx}),ec=Zt.extend({method:Y("notifications/progress"),params:QO}),eN=Lt.extend({cursor:ox.optional()}),Fs=lt.extend({params:eN.optional()}),Zs=ut.extend({nextCursor:ox.optional()}),tN=Et(["working","input_required","completed","failed","cancelled"]),Vs=H({taskId:C(),status:tN,ttl:Me([Ae(),Fv()]),createdAt:C(),lastUpdatedAt:C(),pollInterval:Ve(Ae()),statusMessage:Ve(C())}),Po=ut.extend({task:Vs}),rN=Ft.merge(Vs),Hs=Zt.extend({method:Y("notifications/tasks/status"),params:rN}),tc=lt.extend({method:Y("tasks/get"),params:Lt.extend({taskId:C()})}),rc=ut.merge(Vs),nc=lt.extend({method:Y("tasks/result"),params:Lt.extend({taskId:C()})}),uV=ut.loose(),oc=Fs.extend({method:Y("tasks/list")}),sc=Zs.extend({tasks:xe(Vs)}),ic=lt.extend({method:Y("tasks/cancel"),params:Lt.extend({taskId:C()})}),px=ut.merge(Vs),hx=H({uri:C(),mimeType:Ve(C()),_meta:De(C(),Ze()).optional()}),mx=hx.extend({text:C()}),wh=C().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),fx=hx.extend({blob:wh}),Ks=Et(["user","assistant"]),Ao=H({audience:xe(Ks).optional(),priority:Ae().min(0).max(1).optional(),lastModified:Ds.datetime({offset:!0}).optional()}),gx=H({...Eo.shape,...Bs.shape,uri:C(),description:Ve(C()),mimeType:Ve(C()),size:Ve(Ae()),annotations:Ao.optional(),_meta:Ve(bt({}))}),nN=H({...Eo.shape,...Bs.shape,uriTemplate:C(),description:Ve(C()),mimeType:Ve(C()),annotations:Ao.optional(),_meta:Ve(bt({}))}),ac=Fs.extend({method:Y("resources/list")}),oN=Zs.extend({resources:xe(gx)}),cc=Fs.extend({method:Y("resources/templates/list")}),sN=Zs.extend({resourceTemplates:xe(nN)}),_h=Lt.extend({uri:C()}),iN=_h,lc=lt.extend({method:Y("resources/read"),params:iN}),aN=ut.extend({contents:xe(Me([mx,fx]))}),cN=Zt.extend({method:Y("notifications/resources/list_changed"),params:Ft.optional()}),lN=_h,uN=lt.extend({method:Y("resources/subscribe"),params:lN}),dN=_h,pN=lt.extend({method:Y("resources/unsubscribe"),params:dN}),hN=Ft.extend({uri:C()}),mN=Zt.extend({method:Y("notifications/resources/updated"),params:hN}),fN=H({name:C(),description:Ve(C()),required:Ve(ot())}),gN=H({...Eo.shape,...Bs.shape,description:Ve(C()),arguments:Ve(xe(fN)),_meta:Ve(bt({}))}),uc=Fs.extend({method:Y("prompts/list")}),yN=Zs.extend({prompts:xe(gN)}),bN=Lt.extend({name:C(),arguments:De(C(),C()).optional()}),dc=lt.extend({method:Y("prompts/get"),params:bN}),vh=H({type:Y("text"),text:C(),annotations:Ao.optional(),_meta:De(C(),Ze()).optional()}),xh=H({type:Y("image"),data:wh,mimeType:C(),annotations:Ao.optional(),_meta:De(C(),Ze()).optional()}),kh=H({type:Y("audio"),data:wh,mimeType:C(),annotations:Ao.optional(),_meta:De(C(),Ze()).optional()}),wN=H({type:Y("tool_use"),name:C(),id:C(),input:De(C(),Ze()),_meta:De(C(),Ze()).optional()}),_N=H({type:Y("resource"),resource:Me([mx,fx]),annotations:Ao.optional(),_meta:De(C(),Ze()).optional()}),vN=gx.extend({type:Y("resource_link")}),Sh=Me([vh,xh,kh,vN,_N]),xN=H({role:Ks,content:Sh}),kN=ut.extend({description:C().optional(),messages:xe(xN)}),SN=Zt.extend({method:Y("notifications/prompts/list_changed"),params:Ft.optional()}),$N=H({title:C().optional(),readOnlyHint:ot().optional(),destructiveHint:ot().optional(),idempotentHint:ot().optional(),openWorldHint:ot().optional()}),TN=H({taskSupport:Et(["required","optional","forbidden"]).optional()}),yx=H({...Eo.shape,...Bs.shape,description:C().optional(),inputSchema:H({type:Y("object"),properties:De(C(),rt).optional(),required:xe(C()).optional()}).catchall(Ze()),outputSchema:H({type:Y("object"),properties:De(C(),rt).optional(),required:xe(C()).optional()}).catchall(Ze()).optional(),annotations:$N.optional(),execution:TN.optional(),_meta:De(C(),Ze()).optional()}),pc=Fs.extend({method:Y("tools/list")}),RN=Zs.extend({tools:xe(yx)}),hc=ut.extend({content:xe(Sh).default([]),structuredContent:De(C(),Ze()).optional(),isError:ot().optional()}),dV=hc.or(ut.extend({toolResult:Ze()})),EN=Us.extend({name:C(),arguments:De(C(),Ze()).optional()}),Co=lt.extend({method:Y("tools/call"),params:EN}),PN=Zt.extend({method:Y("notifications/tools/list_changed"),params:Ft.optional()}),pV=H({autoRefresh:ot().default(!0),debounceMs:Ae().int().nonnegative().default(300)}),Ws=Et(["debug","info","notice","warning","error","critical","alert","emergency"]),AN=Lt.extend({level:Ws}),$h=lt.extend({method:Y("logging/setLevel"),params:AN}),CN=Ft.extend({level:Ws,logger:C().optional(),data:Ze()}),IN=Zt.extend({method:Y("notifications/message"),params:CN}),ON=H({name:C().optional()}),NN=H({hints:xe(ON).optional(),costPriority:Ae().min(0).max(1).optional(),speedPriority:Ae().min(0).max(1).optional(),intelligencePriority:Ae().min(0).max(1).optional()}),zN=H({mode:Et(["auto","required","none"]).optional()}),LN=H({type:Y("tool_result"),toolUseId:C().describe("The unique identifier for the corresponding tool call."),content:xe(Sh).default([]),structuredContent:H({}).loose().optional(),isError:ot().optional(),_meta:De(C(),Ze()).optional()}),jN=lh("type",[vh,xh,kh]),Wa=lh("type",[vh,xh,kh,wN,LN]),DN=H({role:Ks,content:Me([Wa,xe(Wa)]),_meta:De(C(),Ze()).optional()}),MN=Us.extend({messages:xe(DN),modelPreferences:NN.optional(),systemPrompt:C().optional(),includeContext:Et(["none","thisServer","allServers"]).optional(),temperature:Ae().optional(),maxTokens:Ae().int(),stopSequences:xe(C()).optional(),metadata:rt.optional(),tools:xe(yx).optional(),toolChoice:zN.optional()}),UN=lt.extend({method:Y("sampling/createMessage"),params:MN}),Gs=ut.extend({model:C(),stopReason:Ve(Et(["endTurn","stopSequence","maxTokens"]).or(C())),role:Ks,content:jN}),Th=ut.extend({model:C(),stopReason:Ve(Et(["endTurn","stopSequence","maxTokens","toolUse"]).or(C())),role:Ks,content:Me([Wa,xe(Wa)])}),qN=H({type:Y("boolean"),title:C().optional(),description:C().optional(),default:ot().optional()}),BN=H({type:Y("string"),title:C().optional(),description:C().optional(),minLength:Ae().optional(),maxLength:Ae().optional(),format:Et(["email","uri","date","date-time"]).optional(),default:C().optional()}),FN=H({type:Et(["number","integer"]),title:C().optional(),description:C().optional(),minimum:Ae().optional(),maximum:Ae().optional(),default:Ae().optional()}),ZN=H({type:Y("string"),title:C().optional(),description:C().optional(),enum:xe(C()),default:C().optional()}),VN=H({type:Y("string"),title:C().optional(),description:C().optional(),oneOf:xe(H({const:C(),title:C()})),default:C().optional()}),HN=H({type:Y("string"),title:C().optional(),description:C().optional(),enum:xe(C()),enumNames:xe(C()).optional(),default:C().optional()}),KN=Me([ZN,VN]),WN=H({type:Y("array"),title:C().optional(),description:C().optional(),minItems:Ae().optional(),maxItems:Ae().optional(),items:H({type:Y("string"),enum:xe(C())}),default:xe(C()).optional()}),GN=H({type:Y("array"),title:C().optional(),description:C().optional(),minItems:Ae().optional(),maxItems:Ae().optional(),items:H({anyOf:xe(H({const:C(),title:C()}))}),default:xe(C()).optional()}),JN=Me([WN,GN]),YN=Me([HN,KN,JN]),XN=Me([YN,qN,BN,FN]),QN=Us.extend({mode:Y("form").optional(),message:C(),requestedSchema:H({type:Y("object"),properties:De(C(),XN),required:xe(C()).optional()})}),ez=Us.extend({mode:Y("url"),message:C(),elicitationId:C(),url:C().url()}),tz=Me([QN,ez]),rz=lt.extend({method:Y("elicitation/create"),params:tz}),nz=Ft.extend({elicitationId:C()}),oz=Zt.extend({method:Y("notifications/elicitation/complete"),params:nz}),Io=ut.extend({action:Et(["accept","decline","cancel"]),content:uh(t=>t===null?void 0:t,De(C(),Me([C(),Ae(),ot(),xe(C())])).optional())}),sz=H({type:Y("ref/resource"),uri:C()}),iz=H({type:Y("ref/prompt"),name:C()}),az=Lt.extend({ref:Me([iz,sz]),argument:H({name:C(),value:C()}),context:H({arguments:De(C(),C()).optional()}).optional()}),mc=lt.extend({method:Y("completion/complete"),params:az});cz=ut.extend({completion:bt({values:xe(C()).max(100),total:Ve(Ae().int()),hasMore:Ve(ot())})}),lz=H({uri:C().startsWith("file://"),name:C().optional(),_meta:De(C(),Ze()).optional()}),uz=lt.extend({method:Y("roots/list"),params:Lt.optional()}),Rh=ut.extend({roots:xe(lz)}),dz=Zt.extend({method:Y("notifications/roots/list_changed"),params:Ft.optional()}),hV=Me([Qa,yh,mc,$h,dc,uc,ac,cc,lc,uN,pN,Co,pc,tc,nc,oc,ic]),mV=Me([Xa,ec,bh,dz,Hs]),fV=Me([Ya,Gs,Th,Io,Rh,rc,sc,Po]),gV=Me([Qa,UN,rz,uz,tc,nc,oc,ic]),yV=Me([Xa,ec,IN,mN,cN,PN,SN,Hs,oz]),bV=Me([Ya,YO,cz,kN,yN,oN,sN,aN,hc,RN,rc,sc,Po]),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===ee.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new dh(o.elicitations,r)}return new t(e,r,n)}},dh=class extends J{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(ee.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function rn(t){return t==="completed"||t==="failed"||t==="cancelled"}var _x=O(()=>{});var xx,vx,kx,fc=O(()=>{xx=Symbol("Let zodToJsonSchema decide on which parser to use"),vx={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"},kx=t=>typeof t=="string"?{...vx,name:t}:{...vx,...t}});var Sx,Eh=O(()=>{fc();Sx=t=>{let e=kx(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 Ph(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ke(t,e,r,n,o){t[e]=r,Ph(t,e,n,o)}var nn=O(()=>{});var gc,yc=O(()=>{gc=(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 He(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?gc(e,t.currentPath):e.join("/")}}var Vt=O(()=>{yc()});function $x(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==D.ZodAny&&(r.items=ae(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 Ah=O(()=>{Ss();nn();et()});function Tx(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 Ch=O(()=>{nn()});function Rx(){return{type:"boolean"}}var Ih=O(()=>{});function bc(t,e){return ae(t.type._def,e)}var wc=O(()=>{et()});var Ex,Oh=O(()=>{et();Ex=(t,e)=>ae(t.innerType._def,e)});function Nh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Nh(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 pz(t,e)}}var pz,zh=O(()=>{nn();pz=(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 Px(t,e){return{...ae(t.innerType._def,e),default:t.defaultValue()}}var Lh=O(()=>{et()});function Ax(t,e){return e.effectStrategy==="input"?ae(t.schema._def,e):He(e)}var jh=O(()=>{et();Vt()});function Cx(t){return{type:"string",enum:Array.from(t.values)}}var Dh=O(()=>{});function Ix(t,e){let r=[ae(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ae(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(hz(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 hz,Mh=O(()=>{et();hz=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Ox(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 Uh=O(()=>{});function _c(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":sr(r,"email",n.message,e);break;case"format:idn-email":sr(r,"idn-email",n.message,e);break;case"pattern:zod":wt(r,or.email,n.message,e);break}break;case"url":sr(r,"uri",n.message,e);break;case"uuid":sr(r,"uuid",n.message,e);break;case"regex":wt(r,n.regex,n.message,e);break;case"cuid":wt(r,or.cuid,n.message,e);break;case"cuid2":wt(r,or.cuid2,n.message,e);break;case"startsWith":wt(r,RegExp(`^${Bh(n.value,e)}`),n.message,e);break;case"endsWith":wt(r,RegExp(`${Bh(n.value,e)}$`),n.message,e);break;case"datetime":sr(r,"date-time",n.message,e);break;case"date":sr(r,"date",n.message,e);break;case"time":sr(r,"time",n.message,e);break;case"duration":sr(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":{wt(r,RegExp(Bh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&sr(r,"ipv4",n.message,e),n.version!=="v4"&&sr(r,"ipv6",n.message,e);break}case"base64url":wt(r,or.base64url,n.message,e);break;case"jwt":wt(r,or.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&wt(r,or.ipv4Cidr,n.message,e),n.version!=="v4"&&wt(r,or.ipv6Cidr,n.message,e);break}case"emoji":wt(r,or.emoji(),n.message,e);break;case"ulid":{wt(r,or.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{sr(r,"binary",n.message,e);break}case"contentEncoding:base64":{ke(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{wt(r,or.base64,n.message,e);break}}break}case"nanoid":wt(r,or.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Bh(t,e){return e.patternStrategy==="escape"?fz(t):t}function fz(t){let e="";for(let r=0;r<t.length;r++)mz.has(t[r])||(e+="\\"),e+=t[r];return e}function sr(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 wt(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:Nx(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ke(t,"pattern",Nx(e,n),r,n)}function Nx(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
2050
2050
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
2051
2051
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
2052
2052
  `:`[${n[c]}\r
2053
- ]`;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 Dm,nr,YN,wc=O(()=>{rn();nr={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:()=>(Dm===void 0&&(Dm=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Dm),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-_]*$/};YN=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function _c(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]:ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ze(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ae(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}=bc(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}=gc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var vc=O(()=>{vs();Je();wc();yc();Zt()});function Sx(t,e){if(e.mapStrategy==="record")return _c(t,e);let r=ae(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ze(e),n=ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ze(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Um=O(()=>{Je();vc();Zt()});function $x(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 qm=O(()=>{});function Tx(t){return t.target==="openAi"?void 0:{not:Ze({...t,currentPath:[...t.currentPath,"not"]})}}var Fm=O(()=>{Zt()});function Rx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Bm=O(()=>{});function Px(t,e){if(e.target==="openApi3")return Ex(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ks&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Ks[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 Ex(t,e)}var Ks,Ex,xc=O(()=>{Je();Ks={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Ex=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ae(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 Ax(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:Ks[t.innerType._def.typeName],nullable:!0}:{type:[Ks[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ae(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ae(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Zm=O(()=>{Je();xc()});function Cx(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",Tm(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 Vm=O(()=>{rn()});function Ix(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=ez(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ae(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=QN(t,e);return i!==void 0&&(n.additionalProperties=i),n}function QN(t,e){if(t.catchall._def.typeName!=="ZodNever")return ae(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 ez(t){try{return t.isOptional()}catch{return!0}}var Hm=O(()=>{Je()});var Ox,Km=O(()=>{Je();Zt();Ox=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ae(t.innerType._def,e);let r=ae(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ze(e)},r]}:Ze(e)}});var Nx,Wm=O(()=>{Je();Nx=(t,e)=>{if(e.pipeStrategy==="input")return ae(t.in._def,e);if(e.pipeStrategy==="output")return ae(t.out._def,e);let r=ae(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ae(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function zx(t,e){return ae(t.type._def,e)}var Gm=O(()=>{Je()});function Lx(t,e){let n={type:"array",uniqueItems:!0,items:ae(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 Jm=O(()=>{rn();Je()});function jx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ae(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ae(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ae(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Ym=O(()=>{Je()});function Dx(t){return{not:Ze(t)}}var Xm=O(()=>{Zt()});function Mx(t){return Ze(t)}var Qm=O(()=>{Zt()});var Ux,eh=O(()=>{Je();Ux=(t,e)=>ae(t.innerType._def,e)});var qx,th=O(()=>{vs();Zt();Rm();Em();Pm();yc();Am();Im();Om();Nm();zm();Lm();jm();Um();qm();Fm();Bm();Zm();Vm();Hm();Km();Wm();Gm();vc();Jm();wc();Ym();Xm();xc();Qm();eh();qx=(t,e,r)=>{switch(e){case U.ZodString:return bc(t,r);case U.ZodNumber:return Cx(t,r);case U.ZodObject:return Ix(t,r);case U.ZodBigInt:return fx(t,r);case U.ZodBoolean:return gx();case U.ZodDate:return Cm(t,r);case U.ZodUndefined:return Dx(r);case U.ZodNull:return Rx(r);case U.ZodArray:return hx(t,r);case U.ZodUnion:case U.ZodDiscriminatedUnion:return Px(t,r);case U.ZodIntersection:return vx(t,r);case U.ZodTuple:return jx(t,r);case U.ZodRecord:return _c(t,r);case U.ZodLiteral:return xx(t,r);case U.ZodEnum:return _x(t);case U.ZodNativeEnum:return $x(t);case U.ZodNullable:return Ax(t,r);case U.ZodOptional:return Ox(t,r);case U.ZodMap:return Sx(t,r);case U.ZodSet:return Lx(t,r);case U.ZodLazy:return()=>t.getter()._def;case U.ZodPromise:return zx(t,r);case U.ZodNaN:case U.ZodNever:return Tx(r);case U.ZodEffects:return wx(t,r);case U.ZodAny:return Ze(r);case U.ZodUnknown:return Mx(r);case U.ZodDefault:return bx(t,r);case U.ZodBranded:return gc(t,r);case U.ZodReadonly:return Ux(t,r);case U.ZodCatch:return yx(t,r);case U.ZodPipeline:return Nx(t,r);case U.ZodFunction:case U.ZodVoid:case U.ZodSymbol:return;default:return(n=>{})(e)}}});function ae(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==dx)return a}if(n&&!r){let a=tz(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=qx(t,t.typeName,e),i=typeof s=="function"?ae(s(),e):s;if(i&&rz(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var tz,rz,Je=O(()=>{mc();th();fc();Zt();tz=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:hc(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`),Ze(e)):e.$refStrategy==="seen"?Ze(e):void 0}},rz=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Fx=O(()=>{});var rh,nh=O(()=>{Je();$m();Zt();rh=(t,e)=>{let r=mx(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ae(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Ze(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ae(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ze(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 Bx=O(()=>{mc();$m();rn();fc();Je();Fx();Zt();Rm();Em();Pm();yc();Am();Im();Om();Nm();zm();Lm();jm();Um();qm();Fm();Bm();Zm();Vm();Hm();Km();Wm();Gm();eh();vc();Jm();wc();Ym();Xm();xc();Qm();th();nh();nh()});function nz(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function oh(t,e){return br(t)?Vp(t,{target:nz(e?.target),io:e?.pipeStrategy??"input"}):rh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function sh(t){let r=Qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=To(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ih(t,e){let r=Xr(t,e);if(!r.success)throw r.error;return r.data}var ah=O(()=>{Wp();Ns();Bx()});function Zx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vx(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];Zx(i)&&Zx(s)?r[o]={...i,...s}:r[o]=s}return r}var oz,kc,Hx=O(()=>{Ns();Io();lx();ah();oz=6e4,kc=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(Ja,r=>{this._oncancel(r)}),this.setNotificationHandler(Xa,r=>{this._onprogress(r)}),this.setRequestHandler(Ya,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Qa,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Y(re.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(tc,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,y=new Y(p.error.code,p.error.message,p.error.data);u(y)}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 Y(re.InvalidParams,`Task not found: ${s}`);if(!tn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(tn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[en]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(rc,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 Y(re.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(oc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new Y(re.InvalidParams,`Task not found: ${r.params.taskId}`);if(tn(o.status))throw new Y(re.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new Y(re.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof Y?o:new Y(re.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),Y.fromError(re.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),Ds(s)||Xv(s)?this._onresponse(s):dm(s)?this._onrequest(s,i):Yv(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=Y.fromError(re.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?.[en]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:re.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Wv(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,y)=>{if(i.signal.aborted)throw new Y(re.ConnectionClosed,"Request was cancelled");let h={...y,relatedRequestId:e.id};s&&!h.relatedTask&&(h.relatedTask={taskId:s});let m=h.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,p,h)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:re.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Ds(e))n(e);else{let i=new Y(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(Ds(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),Ds(e))o(e);else{let i=Y.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 Y?i:new Y(re.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Eo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new Y(re.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},tn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new Y(re.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new Y(re.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 Y?i:new Y(re.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=P=>{u(P)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(P){p(P);return}n?.signal?.throwIfAborted();let y=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:y};n?.onprogress&&(this._progressHandlers.set(y,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:y}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[en]:c}});let m=P=>{this._responseHandlers.delete(y),this._progressHandlers.delete(y),this._cleanupTimeout(y),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(P)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(F=>this._onerror(new Error(`Failed to send cancellation: ${F}`)));let z=P instanceof Y?P:new Y(re.RequestTimeout,String(P));u(z)};this._responseHandlers.set(y,P=>{if(!n?.signal?.aborted){if(P instanceof Error)return u(P);try{let z=Xr(r,P.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let w=n?.timeout??oz,S=()=>m(Y.fromError(re.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(y,w,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let R=c?.taskId;if(R){let P=z=>{let F=this._responseHandlers.get(y);F?F(z):this._onerror(new Error(`Response handler missing for side-channeled request ${y}`))};this._requestResolvers.set(y,P),this._enqueueTaskMessage(R,{type:"request",message:h,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(y),u(z)})}else this._transport.send(h,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>{this._cleanupTimeout(y),u(P)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ec,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},nc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},tx,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||{},[en]: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||{},[en]: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||{},[en]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=sh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ih(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=sh(e);this._notificationHandlers.set(n,o=>{let s=ih(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&dm(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new Y(re.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new Y(re.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new Y(re.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 Y(re.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=Bs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),tn(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 Y(re.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(tn(a.status))throw new Y(re.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=Bs.parse({method:"notifications/tasks/status",params:c});await this.notification(l),tn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Js=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 Ws=class{};Re._CodeOrName=Ws;Re.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fn=class extends Ws{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=Fn;var Vt=class extends Ws{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 Fn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Re._Code=Vt;Re.nil=new Vt("");function Kx(t,...e){let r=[t[0]],n=0;for(;n<e.length;)lh(r,e[n]),r.push(t[++n]);return new Vt(r)}Re._=Kx;var ch=new Vt("+");function Wx(t,...e){let r=[Gs(t[0])],n=0;for(;n<e.length;)r.push(ch),lh(r,e[n]),r.push(ch,Gs(t[++n]));return sz(r),new Vt(r)}Re.str=Wx;function lh(t,e){e instanceof Vt?t.push(...e._items):e instanceof Fn?t.push(e):t.push(cz(e))}Re.addCodeArg=lh;function sz(t){let e=1;for(;e<t.length-1;){if(t[e]===ch){let r=iz(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function iz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Fn||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 Fn))return`"${t}${e.slice(1)}`}function az(t,e){return e.emptyStr()?t:t.emptyStr()?e:Wx`${t}${e}`}Re.strConcat=az;function cz(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Gs(Array.isArray(t)?t.join(","):t)}function lz(t){return new Vt(Gs(t))}Re.stringify=lz;function Gs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Re.safeStringify=Gs;function uz(t){return typeof t=="string"&&Re.IDENTIFIER.test(t)?new Vt(`.${t}`):Kx`[${t}]`}Re.getProperty=uz;function dz(t){if(typeof t=="string"&&Re.IDENTIFIER.test(t))return new Vt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Re.getEsmExportName=dz;function pz(t){return new Vt(t.toString())}Re.regexpCode=pz});var ph=B(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.ValueScope=Pt.ValueScopeName=Pt.Scope=Pt.varKinds=Pt.UsedValueState=void 0;var Et=Js(),uh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Sc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Sc||(Pt.UsedValueState=Sc={}));Pt.varKinds={const:new Et.Name("const"),let:new Et.Name("let"),var:new Et.Name("var")};var $c=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Et.Name?e:this.name(e)}name(e){return new Et.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}}};Pt.Scope=$c;var Tc=class extends Et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Et._)`.${new Et.Name(r)}[${n}]`}};Pt.ValueScopeName=Tc;var mz=(0,Et._)`\n`,dh=class extends $c{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?mz:Et.nil}}get(){return this._scope}name(e){return new Tc(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,Et._)`${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=Et.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,Sc.Started);let u=r(l);if(u){let p=this.opts.es5?Pt.varKinds.var:Pt.varKinds.const;s=(0,Et._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Et._)`${s}${u}${this.opts._n}`;else throw new uh(l);c.set(l,Sc.Completed)})}return s}};Pt.ValueScope=dh});var me=B(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.or=he.and=he.not=he.CodeGen=he.operators=he.varKinds=he.ValueScopeName=he.ValueScope=he.Scope=he.Name=he.regexpCode=he.stringify=he.getProperty=he.nil=he.strConcat=he.str=he._=void 0;var ke=Js(),sr=ph(),nn=Js();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return nn._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return nn.str}});Object.defineProperty(he,"strConcat",{enumerable:!0,get:function(){return nn.strConcat}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return nn.nil}});Object.defineProperty(he,"getProperty",{enumerable:!0,get:function(){return nn.getProperty}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return nn.stringify}});Object.defineProperty(he,"regexpCode",{enumerable:!0,get:function(){return nn.regexpCode}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return nn.Name}});var Ac=ph();Object.defineProperty(he,"Scope",{enumerable:!0,get:function(){return Ac.Scope}});Object.defineProperty(he,"ValueScope",{enumerable:!0,get:function(){return Ac.ValueScope}});Object.defineProperty(he,"ValueScopeName",{enumerable:!0,get:function(){return Ac.ValueScopeName}});Object.defineProperty(he,"varKinds",{enumerable:!0,get:function(){return Ac.varKinds}});he.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 Nr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},mh=class extends Nr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?sr.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=No(this.rhs,e,r)),this}get names(){return this.rhs instanceof ke._CodeOrName?this.rhs.names:{}}},Rc=class extends Nr{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=No(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ke.Name?{}:{...this.lhs.names};return Pc(e,this.rhs)}},hh=class extends Rc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},fh=class extends Nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},gh=class extends Nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},yh=class extends Nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},bh=class extends Nr{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=No(this.code,e,r),this}get names(){return this.code instanceof ke._CodeOrName?this.code.names:{}}},Ys=class extends Nr{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)||(hz(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Vn(e,r.names),{})}},zr=class extends Ys{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},wh=class extends Ys{},Oo=class extends zr{};Oo.kind="else";var Bn=class t extends zr{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 Oo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Gx(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=No(this.condition,e,r),this}get names(){let e=super.names;return Pc(e,this.condition),this.else&&Vn(e,this.else.names),e}};Bn.kind="if";var Zn=class extends zr{};Zn.kind="for";var _h=class extends Zn{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=No(this.iteration,e,r),this}get names(){return Vn(super.names,this.iteration.names)}},vh=class extends Zn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?sr.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=Pc(super.names,this.from);return Pc(e,this.to)}},Ec=class extends Zn{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=No(this.iterable,e,r),this}get names(){return Vn(super.names,this.iterable.names)}},Xs=class extends zr{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)}};Xs.kind="func";var Qs=class extends Ys{render(e){return"return "+super.render(e)}};Qs.kind="return";var xh=class extends zr{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&&Vn(e,this.catch.names),this.finally&&Vn(e,this.finally.names),e}},ei=class extends zr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ei.kind="catch";var ti=class extends zr{render(e){return"finally"+super.render(e)}};ti.kind="finally";var kh=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2054
- `:""},this._extScope=e,this._scope=new sr.Scope({parent:e}),this._nodes=[new wh]}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 mh(e,s,n)),s}const(e,r,n){return this._def(sr.varKinds.const,e,r,n)}let(e,r,n){return this._def(sr.varKinds.let,e,r,n)}var(e,r,n){return this._def(sr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Rc(e,r,n))}add(e,r){return this._leafNode(new hh(e,he.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ke.nil&&this._leafNode(new bh(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 Bn(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 Bn(e))}else(){return this._elseNode(new Oo)}endIf(){return this._endBlockNode(Bn,Oo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new _h(e),r)}forRange(e,r,n,o,s=this.opts.es5?sr.varKinds.var:sr.varKinds.let){let i=this._scope.toName(e);return this._for(new vh(s,i,r,n),()=>o(i))}forOf(e,r,n,o=sr.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 Ec("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?sr.varKinds.var:sr.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 Ec("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Zn)}label(e){return this._leafNode(new fh(e))}break(e){return this._leafNode(new gh(e))}return(e){let r=new Qs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Qs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new xh;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ei(s),r(s)}return n&&(this._currNode=o.finally=new ti,this.code(n)),this._endBlockNode(ei,ti)}throw(e){return this._leafNode(new yh(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 Xs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Xs)}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 Bn))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}};he.CodeGen=kh;function Vn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Pc(t,e){return e instanceof ke._CodeOrName?Vn(t,e.names):t}function No(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 hz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Gx(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ke._)`!${Sh(t)}`}he.not=Gx;var fz=Jx(he.operators.AND);function gz(...t){return t.reduce(fz)}he.and=gz;var yz=Jx(he.operators.OR);function bz(...t){return t.reduce(yz)}he.or=bz;function Jx(t){return(e,r)=>e===ke.nil?r:r===ke.nil?e:(0,ke._)`${Sh(e)} ${t} ${Sh(r)}`}function Sh(t){return t instanceof ke.Name?t:(0,ke._)`(${t})`}});var $e=B(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.checkStrictMode=fe.getErrorPath=fe.Type=fe.useFunc=fe.setEvaluated=fe.evaluatedPropsToName=fe.mergeEvaluated=fe.eachItem=fe.unescapeJsonPointer=fe.escapeJsonPointer=fe.escapeFragment=fe.unescapeFragment=fe.schemaRefOrVal=fe.schemaHasRulesButRef=fe.schemaHasRules=fe.checkUnknownRules=fe.alwaysValidSchema=fe.toHash=void 0;var Ie=me(),wz=Js();function _z(t){let e={};for(let r of t)e[r]=!0;return e}fe.toHash=_z;function vz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Qx(t,e),!ek(e,t.self.RULES.all))}fe.alwaysValidSchema=vz;function Qx(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]||nk(t,`unknown keyword: "${s}"`)}fe.checkUnknownRules=Qx;function ek(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}fe.schemaHasRules=ek;function xz(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}fe.schemaHasRulesButRef=xz;function kz({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ie._)`${r}`}return(0,Ie._)`${t}${e}${(0,Ie.getProperty)(n)}`}fe.schemaRefOrVal=kz;function Sz(t){return tk(decodeURIComponent(t))}fe.unescapeFragment=Sz;function $z(t){return encodeURIComponent(Th(t))}fe.escapeFragment=$z;function Th(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}fe.escapeJsonPointer=Th;function tk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}fe.unescapeJsonPointer=tk;function Tz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}fe.eachItem=Tz;function Yx({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ie.Name?(s instanceof Ie.Name?t(o,s,i):e(o,s,i),i):s instanceof Ie.Name?(e(o,i,s),s):r(s,i);return a===Ie.Name&&!(c instanceof Ie.Name)?n(o,c):c}}fe.mergeEvaluated={props:Yx({mergeNames:(t,e,r)=>t.if((0,Ie._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ie._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ie._)`${r} || {}`).code((0,Ie._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ie._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ie._)`${r} || {}`),Rh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:rk}),items:Yx({mergeNames:(t,e,r)=>t.if((0,Ie._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ie._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ie._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ie._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function rk(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ie._)`{}`);return e!==void 0&&Rh(t,r,e),r}fe.evaluatedPropsToName=rk;function Rh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ie._)`${e}${(0,Ie.getProperty)(n)}`,!0))}fe.setEvaluated=Rh;var Xx={};function Rz(t,e){return t.scopeValue("func",{ref:e,code:Xx[e.code]||(Xx[e.code]=new wz._Code(e.code))})}fe.useFunc=Rz;var $h;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})($h||(fe.Type=$h={}));function Ez(t,e,r){if(t instanceof Ie.Name){let n=e===$h.Num;return r?n?(0,Ie._)`"[" + ${t} + "]"`:(0,Ie._)`"['" + ${t} + "']"`:n?(0,Ie._)`"/" + ${t}`:(0,Ie._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ie.getProperty)(t).toString():"/"+Th(t)}fe.getErrorPath=Ez;function nk(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}fe.checkStrictMode=nk});var Lr=B(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var mt=me(),Pz={data:new mt.Name("data"),valCxt:new mt.Name("valCxt"),instancePath:new mt.Name("instancePath"),parentData:new mt.Name("parentData"),parentDataProperty:new mt.Name("parentDataProperty"),rootData:new mt.Name("rootData"),dynamicAnchors:new mt.Name("dynamicAnchors"),vErrors:new mt.Name("vErrors"),errors:new mt.Name("errors"),this:new mt.Name("this"),self:new mt.Name("self"),scope:new mt.Name("scope"),json:new mt.Name("json"),jsonPos:new mt.Name("jsonPos"),jsonLen:new mt.Name("jsonLen"),jsonPart:new mt.Name("jsonPart")};Eh.default=Pz});var ri=B(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.extendErrors=ht.resetErrorsCount=ht.reportExtraError=ht.reportError=ht.keyword$DataError=ht.keywordError=void 0;var Te=me(),Cc=$e(),wt=Lr();ht.keywordError={message:({keyword:t})=>(0,Te.str)`must pass "${t}" keyword validation`};ht.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 Az(t,e=ht.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=ik(t,e,r);n??(i||a)?ok(s,c):sk(o,(0,Te._)`[${c}]`)}ht.reportError=Az;function Cz(t,e=ht.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=ik(t,e,r);ok(o,a),s||i||sk(n,wt.default.vErrors)}ht.reportExtraError=Cz;function Iz(t,e){t.assign(wt.default.errors,e),t.if((0,Te._)`${wt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Te._)`${wt.default.vErrors}.length`,e),()=>t.assign(wt.default.vErrors,null)))}ht.resetErrorsCount=Iz;function Oz({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,wt.default.errors,a=>{t.const(i,(0,Te._)`${wt.default.vErrors}[${a}]`),t.if((0,Te._)`${i}.instancePath === undefined`,()=>t.assign((0,Te._)`${i}.instancePath`,(0,Te.strConcat)(wt.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))})}ht.extendErrors=Oz;function ok(t,e){let r=t.const("err",e);t.if((0,Te._)`${wt.default.vErrors} === null`,()=>t.assign(wt.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${wt.default.vErrors}.push(${r})`),t.code((0,Te._)`${wt.default.errors}++`)}function sk(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 Hn={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 ik(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Te._)`{}`:Nz(t,e,r)}function Nz(t,e,r={}){let{gen:n,it:o}=t,s=[zz(o,r),Lz(t,r)];return jz(t,e,s),n.object(...s)}function zz({errorPath:t},{instancePath:e}){let r=e?(0,Te.str)`${t}${(0,Cc.getErrorPath)(e,Cc.Type.Str)}`:t;return[wt.default.instancePath,(0,Te.strConcat)(wt.default.instancePath,r)]}function Lz({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,Cc.getErrorPath)(r,Cc.Type.Str)}`),[Hn.schemaPath,o]}function jz(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([Hn.keyword,o],[Hn.params,typeof e=="function"?e(t):e||(0,Te._)`{}`]),c.messages&&n.push([Hn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Hn.schema,i],[Hn.parentSchema,(0,Te._)`${u}${p}`],[wt.default.data,s]),l&&n.push([Hn.propertyName,l])}});var ck=B(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.boolOrEmptySchema=zo.topBoolOrEmptySchema=void 0;var Dz=ri(),Mz=me(),Uz=Lr(),qz={message:"boolean schema is false"};function Fz(t){let{gen:e,schema:r,validateName:n}=t;r===!1?ak(t,!1):typeof r=="object"&&r.$async===!0?e.return(Uz.default.data):(e.assign((0,Mz._)`${n}.errors`,null),e.return(!0))}zo.topBoolOrEmptySchema=Fz;function Bz(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),ak(t)):r.var(e,!0)}zo.boolOrEmptySchema=Bz;function ak(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,Dz.reportError)(o,qz,void 0,e)}});var Ph=B(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.getRules=Lo.isJSONType=void 0;var Zz=["string","number","integer","boolean","null","object","array"],Vz=new Set(Zz);function Hz(t){return typeof t=="string"&&Vz.has(t)}Lo.isJSONType=Hz;function Kz(){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:{}}}Lo.getRules=Kz});var Ah=B(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.shouldUseRule=on.shouldUseGroup=on.schemaHasRulesForType=void 0;function Wz({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&lk(t,n)}on.schemaHasRulesForType=Wz;function lk(t,e){return e.rules.some(r=>uk(t,r))}on.shouldUseGroup=lk;function uk(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))}on.shouldUseRule=uk});var ni=B(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.reportTypeError=ft.checkDataTypes=ft.checkDataType=ft.coerceAndCheckDataType=ft.getJSONTypes=ft.getSchemaTypes=ft.DataType=void 0;var Gz=Ph(),Jz=Ah(),Yz=ri(),de=me(),dk=$e(),jo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(jo||(ft.DataType=jo={}));function Xz(t){let e=pk(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}ft.getSchemaTypes=Xz;function pk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Gz.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ft.getJSONTypes=pk;function Qz(t,e){let{gen:r,data:n,opts:o}=t,s=eL(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Jz.schemaHasRulesForType)(t,e[0]));if(i){let a=Ih(e,n,o.strictNumbers,jo.Wrong);r.if(a,()=>{s.length?tL(t,e,s):Oh(t)})}return i}ft.coerceAndCheckDataType=Qz;var mk=new Set(["string","number","integer","boolean","null"]);function eL(t,e){return e?t.filter(r=>mk.has(r)||e==="array"&&r==="array"):[]}function tL(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,de._)`typeof ${o}`),a=n.let("coerced",(0,de._)`undefined`);s.coerceTypes==="array"&&n.if((0,de._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,de._)`${o}[0]`).assign(i,(0,de._)`typeof ${o}`).if(Ih(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,de._)`${a} !== undefined`);for(let l of r)(mk.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Oh(t),n.endIf(),n.if((0,de._)`${a} !== undefined`,()=>{n.assign(o,a),rL(t,a)});function c(l){switch(l){case"string":n.elseIf((0,de._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,de._)`"" + ${o}`).elseIf((0,de._)`${o} === null`).assign(a,(0,de._)`""`);return;case"number":n.elseIf((0,de._)`${i} == "boolean" || ${o} === null
2055
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,de._)`+${o}`);return;case"integer":n.elseIf((0,de._)`${i} === "boolean" || ${o} === null
2056
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,de._)`+${o}`);return;case"boolean":n.elseIf((0,de._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,de._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,de._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,de._)`${i} === "string" || ${i} === "number"
2057
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,de._)`[${o}]`)}}}function rL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,de._)`${e} !== undefined`,()=>t.assign((0,de._)`${e}[${r}]`,n))}function Ch(t,e,r,n=jo.Correct){let o=n===jo.Correct?de.operators.EQ:de.operators.NEQ,s;switch(t){case"null":return(0,de._)`${e} ${o} null`;case"array":s=(0,de._)`Array.isArray(${e})`;break;case"object":s=(0,de._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,de._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,de._)`typeof ${e} ${o} ${t}`}return n===jo.Correct?s:(0,de.not)(s);function i(a=de.nil){return(0,de.and)((0,de._)`typeof ${e} == "number"`,a,r?(0,de._)`isFinite(${e})`:de.nil)}}ft.checkDataType=Ch;function Ih(t,e,r,n){if(t.length===1)return Ch(t[0],e,r,n);let o,s=(0,dk.toHash)(t);if(s.array&&s.object){let i=(0,de._)`typeof ${e} != "object"`;o=s.null?i:(0,de._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=de.nil;s.number&&delete s.integer;for(let i in s)o=(0,de.and)(o,Ch(i,e,r,n));return o}ft.checkDataTypes=Ih;var nL={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,de._)`{type: ${t}}`:(0,de._)`{type: ${e}}`};function Oh(t){let e=oL(t);(0,Yz.reportError)(e,nL)}ft.reportTypeError=Oh;function oL(t){let{gen:e,data:r,schema:n}=t,o=(0,dk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var fk=B(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});Ic.assignDefaults=void 0;var Do=me(),sL=$e();function iL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)hk(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>hk(t,s,o.default))}Ic.assignDefaults=iL;function hk(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Do._)`${s}${(0,Do.getProperty)(e)}`;if(o){(0,sL.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Do._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Do._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Do._)`${a} = ${(0,Do.stringify)(r)}`)}});var Ht=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 De=me(),Nh=$e(),sn=Lr(),aL=$e();function cL(t,e){let{gen:r,data:n,it:o}=t;r.if(Lh(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,De._)`${e}`},!0),t.error()})}Ce.checkReportMissingProp=cL;function lL({gen:t,data:e,it:{opts:r}},n,o){return(0,De.or)(...n.map(s=>(0,De.and)(Lh(t,e,s,r.ownProperties),(0,De._)`${o} = ${s}`)))}Ce.checkMissingProp=lL;function uL(t,e){t.setParams({missingProperty:e},!0),t.error()}Ce.reportMissingProp=uL;function gk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,De._)`Object.prototype.hasOwnProperty`})}Ce.hasPropFunc=gk;function zh(t,e,r){return(0,De._)`${gk(t)}.call(${e}, ${r})`}Ce.isOwnProperty=zh;function dL(t,e,r,n){let o=(0,De._)`${e}${(0,De.getProperty)(r)} !== undefined`;return n?(0,De._)`${o} && ${zh(t,e,r)}`:o}Ce.propertyInData=dL;function Lh(t,e,r,n){let o=(0,De._)`${e}${(0,De.getProperty)(r)} === undefined`;return n?(0,De.or)(o,(0,De.not)(zh(t,e,r))):o}Ce.noPropertyInData=Lh;function yk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ce.allSchemaProperties=yk;function pL(t,e){return yk(e).filter(r=>!(0,Nh.alwaysValidSchema)(t,e[r]))}Ce.schemaProperties=pL;function mL({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,De._)`${t}, ${e}, ${n}${o}`:e,p=[[sn.default.instancePath,(0,De.strConcat)(sn.default.instancePath,s)],[sn.default.parentData,i.parentData],[sn.default.parentDataProperty,i.parentDataProperty],[sn.default.rootData,sn.default.rootData]];i.opts.dynamicRef&&p.push([sn.default.dynamicAnchors,sn.default.dynamicAnchors]);let y=(0,De._)`${u}, ${r.object(...p)}`;return c!==De.nil?(0,De._)`${a}.call(${c}, ${y})`:(0,De._)`${a}(${y})`}Ce.callValidateCode=mL;var hL=(0,De._)`new RegExp`;function fL({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,De._)`${o.code==="new RegExp"?hL:(0,aL.useFunc)(t,o)}(${r}, ${n})`})}Ce.usePattern=fL;function gL(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,De._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:Nh.Type.Num},s),e.if((0,De.not)(s),a)})}}Ce.validateArray=gL;function yL(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,Nh.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,De._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,De.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ce.validateUnion=yL});var _k=B(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.validateKeywordUsage=wr.validSchemaType=wr.funcKeywordCode=wr.macroKeywordCode=void 0;var _t=me(),Kn=Lr(),bL=Ht(),wL=ri();function _L(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=wk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:_t.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}wr.macroKeywordCode=_L;function vL(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;kL(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=wk(n,o,l),p=n.let("valid");t.block$data(p,y),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function y(){if(e.errors===!1)w(),e.modifying&&bk(t),S(()=>t.error());else{let R=e.async?h():m();e.modifying&&bk(t),S(()=>xL(t,R))}}function h(){let R=n.let("ruleErrs",null);return n.try(()=>w((0,_t._)`await `),P=>n.assign(p,!1).if((0,_t._)`${P} instanceof ${c.ValidationError}`,()=>n.assign(R,(0,_t._)`${P}.errors`),()=>n.throw(P))),R}function m(){let R=(0,_t._)`${u}.errors`;return n.assign(R,null),w(_t.nil),R}function w(R=e.async?(0,_t._)`await `:_t.nil){let P=c.opts.passContext?Kn.default.this:Kn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,_t._)`${R}${(0,bL.callValidateCode)(t,u,P,z)}`,e.modifying)}function S(R){var P;n.if((0,_t.not)((P=e.valid)!==null&&P!==void 0?P:p),R)}}wr.funcKeywordCode=vL;function bk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,_t._)`${n.parentData}[${n.parentDataProperty}]`))}function xL(t,e){let{gen:r}=t;r.if((0,_t._)`Array.isArray(${e})`,()=>{r.assign(Kn.default.vErrors,(0,_t._)`${Kn.default.vErrors} === null ? ${e} : ${Kn.default.vErrors}.concat(${e})`).assign(Kn.default.errors,(0,_t._)`${Kn.default.vErrors}.length`),(0,wL.extendErrors)(t)},()=>t.error())}function kL({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function wk(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,_t.stringify)(r)})}function SL(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")}wr.validSchemaType=SL;function $L({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)}}wr.validateKeywordUsage=$L});var xk=B(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.extendSubschemaMode=an.extendSubschemaData=an.getSubschema=void 0;var _r=me(),vk=$e();function TL(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,vk.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')}an.getSubschema=TL;function RL(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,y=a.let("data",(0,_r._)`${e.data}${(0,_r.getProperty)(r)}`,!0);c(y),t.errorPath=(0,_r.str)`${l}${(0,vk.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]}}an.extendSubschemaData=RL;function EL(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}an.extendSubschemaMode=EL});var jh=B((hK,kk)=>{"use strict";kk.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 $k=B((fK,Sk)=>{"use strict";var cn=Sk.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(){};Oc(e,n,o,t,"",t)};cn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};cn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};cn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};cn.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 Oc(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 cn.arrayKeywords)for(var y=0;y<p.length;y++)Oc(t,e,r,p[y],o+"/"+u+"/"+y,s,o,u,n,y)}else if(u in cn.propsKeywords){if(p&&typeof p=="object")for(var h in p)Oc(t,e,r,p[h],o+"/"+u+"/"+PL(h),s,o,u,n,h)}else(u in cn.keywords||t.allKeys&&!(u in cn.skipKeywords))&&Oc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function PL(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var oi=B(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.getSchemaRefs=At.resolveUrl=At.normalizeId=At._getFullPath=At.getFullPath=At.inlineRef=void 0;var AL=$e(),CL=jh(),IL=$k(),OL=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function NL(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Dh(t):e?Tk(t)<=e:!1}At.inlineRef=NL;var zL=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Dh(t){for(let e in t){if(zL.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Dh)||typeof r=="object"&&Dh(r))return!0}return!1}function Tk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!OL.has(r)&&(typeof t[r]=="object"&&(0,AL.eachItem)(t[r],n=>e+=Tk(n)),e===1/0))return 1/0}return e}function Rk(t,e="",r){r!==!1&&(e=Mo(e));let n=t.parse(e);return Ek(t,n)}At.getFullPath=Rk;function Ek(t,e){return t.serialize(e).split("#")[0]+"#"}At._getFullPath=Ek;var LL=/#\/?$/;function Mo(t){return t?t.replace(LL,""):""}At.normalizeId=Mo;function jL(t,e,r){return r=Mo(r),t.resolve(e,r)}At.resolveUrl=jL;var DL=/^[a-z_][-a-z0-9._]*$/i;function ML(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Mo(t[r]||e),s={"":o},i=Rk(n,o,!1),a={},c=new Set;return IL(t,{allKeys:!0},(p,y,h,m)=>{if(m===void 0)return;let w=i+y,S=s[m];typeof p[r]=="string"&&(S=R.call(this,p[r])),P.call(this,p.$anchor),P.call(this,p.$dynamicAnchor),s[y]=S;function R(z){let F=this.opts.uriResolver.resolve;if(z=Mo(S?F(S,z):z),c.has(z))throw u(z);c.add(z);let W=this.refs[z];return typeof W=="string"&&(W=this.refs[W]),typeof W=="object"?l(p,W.schema,z):z!==Mo(w)&&(z[0]==="#"?(l(p,a[z],z),a[z]=p):this.refs[z]=w),z}function P(z){if(typeof z=="string"){if(!DL.test(z))throw new Error(`invalid anchor "${z}"`);R.call(this,`#${z}`)}}}),a;function l(p,y,h){if(y!==void 0&&!CL(p,y))throw u(h)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}At.getSchemaRefs=ML});var ai=B(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.getData=ln.KeywordCxt=ln.validateFunctionCode=void 0;var Ok=ck(),Pk=ni(),Uh=Ah(),Nc=ni(),UL=fk(),ii=_k(),Mh=xk(),Q=me(),le=Lr(),qL=oi(),jr=$e(),si=ri();function FL(t){if(Lk(t)&&(jk(t),zk(t))){VL(t);return}Nk(t,()=>(0,Ok.topBoolOrEmptySchema)(t))}ln.validateFunctionCode=FL;function Nk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Q._)`${le.default.data}, ${le.default.valCxt}`,n.$async,()=>{t.code((0,Q._)`"use strict"; ${Ak(r,o)}`),ZL(t,o),t.code(s)}):t.func(e,(0,Q._)`${le.default.data}, ${BL(o)}`,n.$async,()=>t.code(Ak(r,o)).code(s))}function BL(t){return(0,Q._)`{${le.default.instancePath}="", ${le.default.parentData}, ${le.default.parentDataProperty}, ${le.default.rootData}=${le.default.data}${t.dynamicRef?(0,Q._)`, ${le.default.dynamicAnchors}={}`:Q.nil}}={}`}function ZL(t,e){t.if(le.default.valCxt,()=>{t.var(le.default.instancePath,(0,Q._)`${le.default.valCxt}.${le.default.instancePath}`),t.var(le.default.parentData,(0,Q._)`${le.default.valCxt}.${le.default.parentData}`),t.var(le.default.parentDataProperty,(0,Q._)`${le.default.valCxt}.${le.default.parentDataProperty}`),t.var(le.default.rootData,(0,Q._)`${le.default.valCxt}.${le.default.rootData}`),e.dynamicRef&&t.var(le.default.dynamicAnchors,(0,Q._)`${le.default.valCxt}.${le.default.dynamicAnchors}`)},()=>{t.var(le.default.instancePath,(0,Q._)`""`),t.var(le.default.parentData,(0,Q._)`undefined`),t.var(le.default.parentDataProperty,(0,Q._)`undefined`),t.var(le.default.rootData,le.default.data),e.dynamicRef&&t.var(le.default.dynamicAnchors,(0,Q._)`{}`)})}function VL(t){let{schema:e,opts:r,gen:n}=t;Nk(t,()=>{r.$comment&&e.$comment&&Mk(t),JL(t),n.let(le.default.vErrors,null),n.let(le.default.errors,0),r.unevaluated&&HL(t),Dk(t),QL(t)})}function HL(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Q._)`${r}.evaluated`),e.if((0,Q._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Q._)`${t.evaluated}.props`,(0,Q._)`undefined`)),e.if((0,Q._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Q._)`${t.evaluated}.items`,(0,Q._)`undefined`))}function Ak(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Q._)`/*# sourceURL=${r} */`:Q.nil}function KL(t,e){if(Lk(t)&&(jk(t),zk(t))){WL(t,e);return}(0,Ok.boolOrEmptySchema)(t,e)}function zk({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 Lk(t){return typeof t.schema!="boolean"}function WL(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Mk(t),YL(t),XL(t);let s=n.const("_errs",le.default.errors);Dk(t,s),n.var(e,(0,Q._)`${s} === ${le.default.errors}`)}function jk(t){(0,jr.checkUnknownRules)(t),GL(t)}function Dk(t,e){if(t.opts.jtd)return Ck(t,[],!1,e);let r=(0,Pk.getSchemaTypes)(t.schema),n=(0,Pk.coerceAndCheckDataType)(t,r);Ck(t,r,!n,e)}function GL(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,jr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function JL(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,jr.checkStrictMode)(t,"default is ignored in the schema root")}function YL(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,qL.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function XL(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Mk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Q._)`${le.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Q.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Q._)`${le.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function QL(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Q._)`${le.default.errors} === 0`,()=>e.return(le.default.data),()=>e.throw((0,Q._)`new ${o}(${le.default.vErrors})`)):(e.assign((0,Q._)`${n}.errors`,le.default.vErrors),s.unevaluated&&ej(t),e.return((0,Q._)`${le.default.errors} === 0`))}function ej({gen:t,evaluated:e,props:r,items:n}){r instanceof Q.Name&&t.assign((0,Q._)`${e}.props`,r),n instanceof Q.Name&&t.assign((0,Q._)`${e}.items`,n)}function Ck(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,jr.schemaHasRulesButRef)(s,u))){o.block(()=>qk(t,"$ref",u.all.$ref.definition));return}c.jtd||tj(t,e),o.block(()=>{for(let y of u.rules)p(y);p(u.post)});function p(y){(0,Uh.shouldUseGroup)(s,y)&&(y.type?(o.if((0,Nc.checkDataType)(y.type,i,c.strictNumbers)),Ik(t,y),e.length===1&&e[0]===y.type&&r&&(o.else(),(0,Nc.reportTypeError)(t)),o.endIf()):Ik(t,y),a||o.if((0,Q._)`${le.default.errors} === ${n||0}`))}}function Ik(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,UL.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Uh.shouldUseRule)(n,s)&&qk(t,s.keyword,s.definition,e.type)})}function tj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(rj(t,e),t.opts.allowUnionTypes||nj(t,e),oj(t,t.dataTypes))}function rj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Uk(t.dataTypes,r)||qh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),ij(t,e)}}function nj(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&qh(t,"use allowUnionTypes to allow union type keyword")}function oj(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Uh.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>sj(e,i))&&qh(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function sj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Uk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function ij(t,e){let r=[];for(let n of t.dataTypes)Uk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function qh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,jr.checkStrictMode)(t,e,t.opts.strictTypes)}var zc=class{constructor(e,r,n){if((0,ii.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,jr.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",Fk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ii.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",le.default.errors))}result(e,r,n){this.failResult((0,Q.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,Q.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,Q._)`${r} !== undefined && (${(0,Q.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?si.reportExtraError:si.reportError)(this,this.def.error,r)}$dataError(){(0,si.reportError)(this,this.def.$dataError||si.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,si.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=Q.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Q.nil,r=Q.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Q.or)((0,Q._)`${o} === undefined`,r)),e!==Q.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Q.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Q.or)(i(),a());function i(){if(n.length){if(!(r instanceof Q.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Q._)`${(0,Nc.checkDataTypes)(c,r,s.opts.strictNumbers,Nc.DataType.Wrong)}`}return Q.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Q._)`!${c}(${r})`}return Q.nil}}subschema(e,r){let n=(0,Mh.getSubschema)(this.it,e);(0,Mh.extendSubschemaData)(n,this.it,e),(0,Mh.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return KL(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=jr.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,Q.Name)),!0}};ln.KeywordCxt=zc;function qk(t,e,r,n){let o=new zc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ii.funcKeywordCode)(o,r):"macro"in r?(0,ii.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ii.funcKeywordCode)(o,r)}var aj=/^\/(?:[^~]|~0|~1)*$/,cj=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Fk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return le.default.rootData;if(t[0]==="/"){if(!aj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=le.default.rootData}else{let l=cj.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,Q._)`${s}${(0,Q.getProperty)((0,jr.unescapeJsonPointer)(l))}`,i=(0,Q._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}ln.getData=Fk});var Lc=B(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var Fh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Bh.default=Fh});var ci=B(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var Zh=oi(),Vh=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Zh.resolveUrl)(e,r,n),this.missingSchema=(0,Zh.normalizeId)((0,Zh.getFullPath)(e,this.missingRef))}};Hh.default=Vh});var Dc=B(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.resolveSchema=Kt.getCompilingSchema=Kt.resolveRef=Kt.compileSchema=Kt.SchemaEnv=void 0;var ir=me(),lj=Lc(),Wn=Lr(),ar=oi(),Bk=$e(),uj=ai(),Uo=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,ar.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Kt.SchemaEnv=Uo;function Wh(t){let e=Zk.call(this,t);if(e)return e;let r=(0,ar.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new ir.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:lj.default,code:(0,ir._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Wn.default.data,parentData:Wn.default.parentData,parentDataProperty:Wn.default.parentDataProperty,dataNames:[Wn.default.data],dataPathArr:[ir.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ir.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ir.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ir._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,uj.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Wn.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let h=new Function(`${Wn.default.self}`,`${Wn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:w}=l;h.evaluated={props:m instanceof ir.Name?void 0:m,items:w instanceof ir.Name?void 0:w,dynamicProps:m instanceof ir.Name,dynamicItems:w instanceof ir.Name},h.source&&(h.source.evaluated=(0,ir.stringify)(h.evaluated))}return t.validate=h,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Kt.compileSchema=Wh;function dj(t,e,r){var n;r=(0,ar.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=hj.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 Uo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=pj.call(this,s)}Kt.resolveRef=dj;function pj(t){return(0,ar.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Wh.call(this,t)}function Zk(t){for(let e of this._compilations)if(mj(e,t))return e}Kt.getCompilingSchema=Zk;function mj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function hj(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||jc.call(this,t,e)}function jc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,ar._getFullPath)(this.opts.uriResolver,r),o=(0,ar.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Kh.call(this,r,t);let s=(0,ar.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=jc.call(this,t,i);return typeof a?.schema!="object"?void 0:Kh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Wh.call(this,i),s===(0,ar.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,ar.resolveUrl)(this.opts.uriResolver,o,l)),new Uo({schema:a,schemaId:c,root:t,baseId:o})}return Kh.call(this,r,i)}}Kt.resolveSchema=jc;var fj=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Kh(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,Bk.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!fj.has(a)&&l&&(e=(0,ar.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Bk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,ar.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=jc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Uo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Vk=B((vK,gj)=>{gj.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 Yh=B((xK,Yk)=>{"use strict";var yj=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Kk=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),Gh=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Wk=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),bj=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Jh(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 wj=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Hk(t){return t.length=0,!0}function _j(t,e,r){if(t.length){let n=Jh(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function vj(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=_j;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=Hk}else{o.push(l);continue}}return o.length&&(a===Hk?r.zone=o.join(""):i?n.push(o.join("")):n.push(Jh(o))),r.address=n.join(""),r}function Gk(t){if(xj(t,":")<2)return{host:t,isIPV6:!1};let e=vj(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function xj(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function kj(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var Sj={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},$j=/[@/?#:]/g,Tj=/[@/?#]/g;function Jk(t,e){let r=e?Tj:$j;return r.lastIndex=0,t.replace(r,n=>Sj[n])}function Rj(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(Gh(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Wk(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function Ej(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(Gh(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Wk(s)?e+=s:e+="%"+o,r+=2;continue}}bj(t[r])?e+=t[r]:e+=escape(t[r])}return e}function Pj(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(Gh(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Aj(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Kk(r)){let n=Gk(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Jk(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Yk.exports={nonSimpleDomain:wj,recomposeAuthority:Aj,reescapeHostDelimiters:Jk,normalizePercentEncoding:Rj,normalizePathEncoding:Ej,escapePreservingEscapes:Pj,removeDotSegments:kj,isIPv4:Kk,isUUID:yj,normalizeIPv6:Gk,stringArrayToHexStripped:Jh}});var rS=B((kK,tS)=>{"use strict";var{isUUID:Cj}=Yh(),Ij=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Oj=["http","https","ws","wss","urn","urn:uuid"];function Nj(t){return Oj.indexOf(t)!==-1}function Xh(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 Xk(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Qk(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 zj(t){return t.secure=Xh(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Lj(t){if((t.port===(Xh(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function jj(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Ij);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Qh(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Dj(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=Qh(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 Mj(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Cj(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Uj(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var eS={scheme:"http",domainHost:!0,parse:Xk,serialize:Qk},qj={scheme:"https",domainHost:eS.domainHost,parse:Xk,serialize:Qk},Mc={scheme:"ws",domainHost:!0,parse:zj,serialize:Lj},Fj={scheme:"wss",domainHost:Mc.domainHost,parse:Mc.parse,serialize:Mc.serialize},Bj={scheme:"urn",parse:jj,serialize:Dj,skipNormalize:!0},Zj={scheme:"urn:uuid",parse:Mj,serialize:Uj,skipNormalize:!0},Uc={http:eS,https:qj,ws:Mc,wss:Fj,urn:Bj,"urn:uuid":Zj};Object.setPrototypeOf(Uc,null);function Qh(t){return t&&(Uc[t]||Uc[t.toLowerCase()])||void 0}tS.exports={wsIsSecure:Xh,SCHEMES:Uc,isValidSchemeName:Nj,getSchemeHandler:Qh}});var aS=B((SK,Bc)=>{"use strict";var{normalizeIPv6:Vj,removeDotSegments:li,recomposeAuthority:Hj,normalizePercentEncoding:Kj,normalizePathEncoding:Wj,escapePreservingEscapes:Gj,reescapeHostDelimiters:Jj,isIPv4:Yj,nonSimpleDomain:Xj}=Yh(),{SCHEMES:Qj,getSchemeHandler:oS}=rS();function eD(t,e){return typeof t=="string"?t=aD(t,e):typeof t=="object"&&(t=Fc(Gn(t,e),e)),t}function tD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=qc(t,n),{parsed:i,malformedAuthorityOrPort:a}=qc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=sS(o,i,n,!0);return n.skipEscape=!0,Gn(c,n)}function sS(t,e,r,n){let o={};return n||(t=Fc(Gn(t,r),r),e=Fc(Gn(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=li(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=li(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=li(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=li(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function rD(t,e,r){let n=nS(t,r),o=nS(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Gn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=oS(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Kj(r.path):(r.path=Gj(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=Hj(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=li(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var nD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,oD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,sD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function iD(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 qc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(oD);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(sD);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(nD);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=iD(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(Yj(n.host)===!1){let y=Vj(n.host);n.host=y.host.toLowerCase(),s=y.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=oS(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&Xj(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Jj(unescape(n.host),s))),n.path&&(n.path=Wj(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Fc(t,e){return qc(t,e).parsed}function aD(t,e){return iS(t,e).normalized}function iS(t,e){let{parsed:r,malformedAuthorityOrPort:n}=qc(t,e);return{normalized:n?t:Gn(r,e),malformedAuthorityOrPort:n}}function nS(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=iS(t,e);return n?void 0:r}if(typeof t=="object")return Gn(t,e)}var ef={SCHEMES:Qj,normalize:eD,resolve:tD,resolveComponent:sS,equal:rD,serialize:Gn,parse:Fc};Bc.exports=ef;Bc.exports.default=ef;Bc.exports.fastUri=ef});var lS=B(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var cS=aS();cS.code='require("ajv/dist/runtime/uri").default';tf.default=cS});var yS=B(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.CodeGen=lt.Name=lt.nil=lt.stringify=lt.str=lt._=lt.KeywordCxt=void 0;var cD=ai();Object.defineProperty(lt,"KeywordCxt",{enumerable:!0,get:function(){return cD.KeywordCxt}});var qo=me();Object.defineProperty(lt,"_",{enumerable:!0,get:function(){return qo._}});Object.defineProperty(lt,"str",{enumerable:!0,get:function(){return qo.str}});Object.defineProperty(lt,"stringify",{enumerable:!0,get:function(){return qo.stringify}});Object.defineProperty(lt,"nil",{enumerable:!0,get:function(){return qo.nil}});Object.defineProperty(lt,"Name",{enumerable:!0,get:function(){return qo.Name}});Object.defineProperty(lt,"CodeGen",{enumerable:!0,get:function(){return qo.CodeGen}});var lD=Lc(),hS=ci(),uD=Ph(),ui=Dc(),dD=me(),di=oi(),Zc=ni(),nf=$e(),uS=Vk(),pD=lS(),fS=(t,e)=>new RegExp(t,e);fS.code="new RegExp";var mD=["removeAdditional","useDefaults","coerceTypes"],hD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),fD={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."},gD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},dS=200;function yD(t){var e,r,n,o,s,i,a,c,l,u,p,y,h,m,w,S,R,P,z,F,W,Ke,Ye,Gt,Mr;let mn=t.strict,Ur=(e=t.code)===null||e===void 0?void 0:e.optimize,ur=Ur===!0||Ur===void 0?1:Ur||0,$i=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:fS,gl=(o=t.uriResolver)!==null&&o!==void 0?o:pD.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:mn)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:mn)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:mn)!==null&&u!==void 0?u:"log",strictTuples:(y=(p=t.strictTuples)!==null&&p!==void 0?p:mn)!==null&&y!==void 0?y:"log",strictRequired:(m=(h=t.strictRequired)!==null&&h!==void 0?h:mn)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:ur,regExp:$i}:{optimize:ur,regExp:$i},loopRequired:(w=t.loopRequired)!==null&&w!==void 0?w:dS,loopEnum:(S=t.loopEnum)!==null&&S!==void 0?S:dS,meta:(R=t.meta)!==null&&R!==void 0?R:!0,messages:(P=t.messages)!==null&&P!==void 0?P:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(F=t.schemaId)!==null&&F!==void 0?F:"$id",addUsedSchema:(W=t.addUsedSchema)!==null&&W!==void 0?W:!0,validateSchema:(Ke=t.validateSchema)!==null&&Ke!==void 0?Ke:!0,validateFormats:(Ye=t.validateFormats)!==null&&Ye!==void 0?Ye:!0,unicodeRegExp:(Gt=t.unicodeRegExp)!==null&&Gt!==void 0?Gt:!0,int32range:(Mr=t.int32range)!==null&&Mr!==void 0?Mr:!0,uriResolver:gl}}var pi=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,...yD(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new dD.ValueScope({scope:{},prefixes:hD,es5:r,lines:n}),this.logger=kD(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,uD.getRules)(),pS.call(this,fD,e,"NOT SUPPORTED"),pS.call(this,gD,e,"DEPRECATED","warn"),this._metaOpts=vD.call(this),e.formats&&wD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&_D.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),bD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=uS;n==="id"&&(o={...uS},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 y=this._addSchema(u,p);return y.validate||i.call(this,y)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof hS.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,di.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=mS.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ui.SchemaEnv({schema:{},schemaId:n});if(r=ui.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=mS.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,di.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($D.call(this,n,r),!r)return(0,nf.eachItem)(n,s=>rf.call(this,s)),this;RD.call(this,r);let o={...r,type:(0,Zc.getJSONTypes)(r.type),schemaType:(0,Zc.getJSONTypes)(r.schemaType)};return(0,nf.eachItem)(n,o.type.length===0?s=>rf.call(this,s,o):s=>o.type.forEach(i=>rf.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]=gS(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,di.normalizeId)(i||n);let l=di.getSchemaRefs.call(this,e,n);return c=new ui.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):ui.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{ui.compileSchema.call(this,e)}finally{this.opts=r}}};pi.ValidationError=lD.default;pi.MissingRefError=hS.default;lt.default=pi;function pS(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 mS(t){return t=(0,di.normalizeId)(t),this.schemas[t]||this.refs[t]}function bD(){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 wD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function _D(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 vD(){let t={...this.opts};for(let e of mD)delete t[e];return t}var xD={log(){},warn(){},error(){}};function kD(t){if(t===!1)return xD;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 SD=/^[a-z_$][a-z0-9_$:-]*$/i;function $D(t,e){let{RULES:r}=this;if((0,nf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!SD.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 rf(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,Zc.getJSONTypes)(e.type),schemaType:(0,Zc.getJSONTypes)(e.schemaType)}};e.before?TD.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 TD(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 RD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=gS(e)),t.validateSchema=this.compile(e,!0))}var ED={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function gS(t){return{anyOf:[t,ED]}}});var bS=B(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var PD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};of.default=PD});var xS=B(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.callRef=Jn.getValidate=void 0;var AD=ci(),wS=Ht(),Ct=me(),Fo=Lr(),_S=Dc(),Vc=$e(),CD={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=_S.resolveRef.call(c,l,o,r);if(u===void 0)throw new AD.default(n.opts.uriResolver,o,r);if(u instanceof _S.SchemaEnv)return y(u);return h(u);function p(){if(s===l)return Hc(t,i,s,s.$async);let m=e.scopeValue("root",{ref:l});return Hc(t,(0,Ct._)`${m}.validate`,l,l.$async)}function y(m){let w=vS(t,m);Hc(t,w,m,m.$async)}function h(m){let w=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Ct.stringify)(m)}:{ref:m}),S=e.name("valid"),R=t.subschema({schema:m,dataTypes:[],schemaPath:Ct.nil,topSchemaRef:w,errSchemaPath:r},S);t.mergeEvaluated(R),t.ok(S)}}};function vS(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ct._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Jn.getValidate=vS;function Hc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Fo.default.this:Ct.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,Ct._)`await ${(0,wS.callValidateCode)(t,e,l)}`),h(e),i||o.assign(m,!0)},w=>{o.if((0,Ct._)`!(${w} instanceof ${s.ValidationError})`,()=>o.throw(w)),y(w),i||o.assign(m,!1)}),t.ok(m)}function p(){t.result((0,wS.callValidateCode)(t,e,l),()=>h(e),()=>y(e))}function y(m){let w=(0,Ct._)`${m}.errors`;o.assign(Fo.default.vErrors,(0,Ct._)`${Fo.default.vErrors} === null ? ${w} : ${Fo.default.vErrors}.concat(${w})`),o.assign(Fo.default.errors,(0,Ct._)`${Fo.default.vErrors}.length`)}function h(m){var w;if(!s.opts.unevaluated)return;let S=(w=r?.validate)===null||w===void 0?void 0:w.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=Vc.mergeEvaluated.props(o,S.props,s.props));else{let R=o.var("props",(0,Ct._)`${m}.evaluated.props`);s.props=Vc.mergeEvaluated.props(o,R,s.props,Ct.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=Vc.mergeEvaluated.items(o,S.items,s.items));else{let R=o.var("items",(0,Ct._)`${m}.evaluated.items`);s.items=Vc.mergeEvaluated.items(o,R,s.items,Ct.Name)}}}Jn.callRef=Hc;Jn.default=CD});var kS=B(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var ID=bS(),OD=xS(),ND=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",ID.default,OD.default];sf.default=ND});var SS=B(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var Kc=me(),un=Kc.operators,Wc={maximum:{okStr:"<=",ok:un.LTE,fail:un.GT},minimum:{okStr:">=",ok:un.GTE,fail:un.LT},exclusiveMaximum:{okStr:"<",ok:un.LT,fail:un.GTE},exclusiveMinimum:{okStr:">",ok:un.GT,fail:un.LTE}},zD={message:({keyword:t,schemaCode:e})=>(0,Kc.str)`must be ${Wc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Kc._)`{comparison: ${Wc[t].okStr}, limit: ${e}}`},LD={keyword:Object.keys(Wc),type:"number",schemaType:"number",$data:!0,error:zD,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Kc._)`${r} ${Wc[e].fail} ${n} || isNaN(${r})`)}};af.default=LD});var $S=B(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var mi=me(),jD={message:({schemaCode:t})=>(0,mi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,mi._)`{multipleOf: ${t}}`},DD={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:jD,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,mi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,mi._)`${i} !== parseInt(${i})`;t.fail$data((0,mi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};cf.default=DD});var RS=B(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});function TS(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=TS;TS.code='require("ajv/dist/runtime/ucs2length").default'});var ES=B(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var Yn=me(),MD=$e(),UD=RS(),qD={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Yn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Yn._)`{limit: ${t}}`},FD={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:qD,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Yn.operators.GT:Yn.operators.LT,i=o.opts.unicode===!1?(0,Yn._)`${r}.length`:(0,Yn._)`${(0,MD.useFunc)(t.gen,UD.default)}(${r})`;t.fail$data((0,Yn._)`${i} ${s} ${n}`)}};uf.default=FD});var PS=B(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var BD=Ht(),ZD=$e(),Bo=me(),VD={message:({schemaCode:t})=>(0,Bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Bo._)`{pattern: ${t}}`},HD={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:VD,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,Bo._)`new RegExp`:(0,ZD.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Bo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Bo._)`!${u}`)}else{let c=(0,BD.usePattern)(t,o);t.fail$data((0,Bo._)`!${c}.test(${r})`)}}};df.default=HD});var AS=B(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var hi=me(),KD={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,hi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,hi._)`{limit: ${t}}`},WD={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:KD,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?hi.operators.GT:hi.operators.LT;t.fail$data((0,hi._)`Object.keys(${r}).length ${o} ${n}`)}};pf.default=WD});var CS=B(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var fi=Ht(),gi=me(),GD=$e(),JD={message:({params:{missingProperty:t}})=>(0,gi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,gi._)`{missingProperty: ${t}}`},YD={keyword:"required",type:"object",schemaType:"array",$data:!0,error:JD,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let h=t.parentSchema.properties,{definedProperties:m}=t.it;for(let w of r)if(h?.[w]===void 0&&!m.has(w)){let S=i.schemaEnv.baseId+i.errSchemaPath,R=`required property "${w}" is not defined at "${S}" (strictRequired)`;(0,GD.checkStrictMode)(i,R,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(gi.nil,p);else for(let h of r)(0,fi.checkReportMissingProp)(t,h)}function u(){let h=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>y(h,m)),t.ok(m)}else e.if((0,fi.checkMissingProp)(t,r,h)),(0,fi.reportMissingProp)(t,h),e.else()}function p(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,fi.noPropertyInData)(e,o,h,a.ownProperties),()=>t.error())})}function y(h,m){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(m,(0,fi.propertyInData)(e,o,h,a.ownProperties)),e.if((0,gi.not)(m),()=>{t.error(),e.break()})},gi.nil)}}};mf.default=YD});var IS=B(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var yi=me(),XD={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,yi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,yi._)`{limit: ${t}}`},QD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:XD,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?yi.operators.GT:yi.operators.LT;t.fail$data((0,yi._)`${r}.length ${o} ${n}`)}};hf.default=QD});var Gc=B(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var OS=jh();OS.code='require("ajv/dist/runtime/equal").default';ff.default=OS});var NS=B(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var gf=ni(),ut=me(),e1=$e(),t1=Gc(),r1={message:({params:{i:t,j:e}})=>(0,ut.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,ut._)`{i: ${t}, j: ${e}}`},n1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:r1,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,gf.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,ut._)`${i} === false`),t.ok(c);function u(){let m=e.let("i",(0,ut._)`${r}.length`),w=e.let("j");t.setParams({i:m,j:w}),e.assign(c,!0),e.if((0,ut._)`${m} > 1`,()=>(p()?y:h)(m,w))}function p(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function y(m,w){let S=e.name("item"),R=(0,gf.checkDataTypes)(l,S,a.opts.strictNumbers,gf.DataType.Wrong),P=e.const("indices",(0,ut._)`{}`);e.for((0,ut._)`;${m}--;`,()=>{e.let(S,(0,ut._)`${r}[${m}]`),e.if(R,(0,ut._)`continue`),l.length>1&&e.if((0,ut._)`typeof ${S} == "string"`,(0,ut._)`${S} += "_"`),e.if((0,ut._)`typeof ${P}[${S}] == "number"`,()=>{e.assign(w,(0,ut._)`${P}[${S}]`),t.error(),e.assign(c,!1).break()}).code((0,ut._)`${P}[${S}] = ${m}`)})}function h(m,w){let S=(0,e1.useFunc)(e,t1.default),R=e.name("outer");e.label(R).for((0,ut._)`;${m}--;`,()=>e.for((0,ut._)`${w} = ${m}; ${w}--;`,()=>e.if((0,ut._)`${S}(${r}[${m}], ${r}[${w}])`,()=>{t.error(),e.assign(c,!1).break(R)})))}}};yf.default=n1});var zS=B(wf=>{"use strict";Object.defineProperty(wf,"__esModule",{value:!0});var bf=me(),o1=$e(),s1=Gc(),i1={message:"must be equal to constant",params:({schemaCode:t})=>(0,bf._)`{allowedValue: ${t}}`},a1={keyword:"const",$data:!0,error:i1,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,bf._)`!${(0,o1.useFunc)(e,s1.default)}(${r}, ${o})`):t.fail((0,bf._)`${s} !== ${r}`)}};wf.default=a1});var LS=B(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var bi=me(),c1=$e(),l1=Gc(),u1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,bi._)`{allowedValues: ${t}}`},d1={keyword:"enum",schemaType:"array",$data:!0,error:u1,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,c1.useFunc)(e,l1.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 h=e.const("vSchema",s);u=(0,bi.or)(...o.map((m,w)=>y(h,w)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,h=>e.if((0,bi._)`${l()}(${r}, ${h})`,()=>e.assign(u,!0).break()))}function y(h,m){let w=o[m];return typeof w=="object"&&w!==null?(0,bi._)`${l()}(${r}, ${h}[${m}])`:(0,bi._)`${r} === ${w}`}}};_f.default=d1});var jS=B(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var p1=SS(),m1=$S(),h1=ES(),f1=PS(),g1=AS(),y1=CS(),b1=IS(),w1=NS(),_1=zS(),v1=LS(),x1=[p1.default,m1.default,h1.default,f1.default,g1.default,y1.default,b1.default,w1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},_1.default,v1.default];vf.default=x1});var kf=B(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.validateAdditionalItems=void 0;var Xn=me(),xf=$e(),k1={message:({params:{len:t}})=>(0,Xn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xn._)`{limit: ${t}}`},S1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:k1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,xf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}DS(t,n)}};function DS(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Xn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Xn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,xf.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Xn._)`${a} <= ${e.length}`);r.if((0,Xn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:xf.Type.Num},l),i.allErrors||r.if((0,Xn.not)(l),()=>r.break())})}}wi.validateAdditionalItems=DS;wi.default=S1});var Sf=B(_i=>{"use strict";Object.defineProperty(_i,"__esModule",{value:!0});_i.validateTuple=void 0;var MS=me(),Jc=$e(),$1=Ht(),T1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return US(t,"additionalItems",e);r.items=!0,!(0,Jc.alwaysValidSchema)(r,e)&&t.ok((0,$1.validateArray)(t))}};function US(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=Jc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,MS._)`${s}.length`);r.forEach((p,y)=>{(0,Jc.alwaysValidSchema)(a,p)||(n.if((0,MS._)`${l} > ${y}`,()=>t.subschema({keyword:i,schemaProp:y,dataProp:y},c)),t.ok(c))});function u(p){let{opts:y,errSchemaPath:h}=a,m=r.length,w=m===p.minItems&&(m===p.maxItems||p[e]===!1);if(y.strictTuples&&!w){let S=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Jc.checkStrictMode)(a,S,y.strictTuples)}}}_i.validateTuple=US;_i.default=T1});var qS=B($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var R1=Sf(),E1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,R1.validateTuple)(t,"items")};$f.default=E1});var BS=B(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var FS=me(),P1=$e(),A1=Ht(),C1=kf(),I1={message:({params:{len:t}})=>(0,FS.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,FS._)`{limit: ${t}}`},O1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:I1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,P1.alwaysValidSchema)(n,e)&&(o?(0,C1.validateAdditionalItems)(t,o):t.ok((0,A1.validateArray)(t)))}};Tf.default=O1});var ZS=B(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var Wt=me(),Yc=$e(),N1={message:({params:{min:t,max:e}})=>e===void 0?(0,Wt.str)`must contain at least ${t} valid item(s)`:(0,Wt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Wt._)`{minContains: ${t}}`:(0,Wt._)`{minContains: ${t}, maxContains: ${e}}`},z1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:N1,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,Wt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Yc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Yc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Yc.alwaysValidSchema)(s,r)){let w=(0,Wt._)`${u} >= ${i}`;a!==void 0&&(w=(0,Wt._)`${w} && ${u} <= ${a}`),t.pass(w);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?h(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Wt._)`${o}.length > 0`,y)):(e.let(p,!1),y()),t.result(p,()=>t.reset());function y(){let w=e.name("_valid"),S=e.let("count",0);h(w,()=>e.if(w,()=>m(S)))}function h(w,S){e.forRange("i",0,u,R=>{t.subschema({keyword:"contains",dataProp:R,dataPropType:Yc.Type.Num,compositeRule:!0},w),S()})}function m(w){e.code((0,Wt._)`${w}++`),a===void 0?e.if((0,Wt._)`${w} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Wt._)`${w} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Wt._)`${w} >= ${i}`,()=>e.assign(p,!0)))}}};Rf.default=z1});var KS=B(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.validateSchemaDeps=vr.validatePropertyDeps=vr.error=void 0;var Ef=me(),L1=$e(),vi=Ht();vr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Ef.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Ef._)`{property: ${t},
2053
+ ]`;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 qh,or,mz,vc=O(()=>{nn();or={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:()=>(qh===void 0&&(qh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qh),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-_]*$/};mz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function xc(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===D.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??He(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===D.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=_c(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===D.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===D.ZodBranded&&t.keyType._def.type._def.typeName===D.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=bc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var kc=O(()=>{Ss();et();vc();wc();Vt()});function zx(t,e){if(e.mapStrategy==="record")return xc(t,e);let r=ae(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||He(e),n=ae(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||He(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Fh=O(()=>{et();kc();Vt()});function Lx(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 Zh=O(()=>{});function jx(t){return t.target==="openAi"?void 0:{not:He({...t,currentPath:[...t.currentPath,"not"]})}}var Vh=O(()=>{Vt()});function Dx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Hh=O(()=>{});function Ux(t,e){if(e.target==="openApi3")return Mx(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Js&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Js[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 Mx(t,e)}var Js,Mx,Sc=O(()=>{et();Js={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Mx=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>ae(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 qx(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:Js[t.innerType._def.typeName],nullable:!0}:{type:[Js[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=ae(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=ae(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Kh=O(()=>{et();Sc()});function Bx(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",Ph(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 Wh=O(()=>{nn()});function Fx(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=yz(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=ae(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=gz(t,e);return i!==void 0&&(n.additionalProperties=i),n}function gz(t,e){if(t.catchall._def.typeName!=="ZodNever")return ae(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 yz(t){try{return t.isOptional()}catch{return!0}}var Gh=O(()=>{et()});var Zx,Jh=O(()=>{et();Vt();Zx=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return ae(t.innerType._def,e);let r=ae(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:He(e)},r]}:He(e)}});var Vx,Yh=O(()=>{et();Vx=(t,e)=>{if(e.pipeStrategy==="input")return ae(t.in._def,e);if(e.pipeStrategy==="output")return ae(t.out._def,e);let r=ae(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=ae(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Hx(t,e){return ae(t.type._def,e)}var Xh=O(()=>{et()});function Kx(t,e){let n={type:"array",uniqueItems:!0,items:ae(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 Qh=O(()=>{nn();et()});function Wx(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>ae(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:ae(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>ae(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var em=O(()=>{et()});function Gx(t){return{not:He(t)}}var tm=O(()=>{Vt()});function Jx(t){return He(t)}var rm=O(()=>{Vt()});var Yx,nm=O(()=>{et();Yx=(t,e)=>ae(t.innerType._def,e)});var Xx,om=O(()=>{Ss();Vt();Ah();Ch();Ih();wc();Oh();zh();Lh();jh();Dh();Mh();Uh();Fh();Zh();Vh();Hh();Kh();Wh();Gh();Jh();Yh();Xh();kc();Qh();vc();em();tm();Sc();rm();nm();Xx=(t,e,r)=>{switch(e){case D.ZodString:return _c(t,r);case D.ZodNumber:return Bx(t,r);case D.ZodObject:return Fx(t,r);case D.ZodBigInt:return Tx(t,r);case D.ZodBoolean:return Rx();case D.ZodDate:return Nh(t,r);case D.ZodUndefined:return Gx(r);case D.ZodNull:return Dx(r);case D.ZodArray:return $x(t,r);case D.ZodUnion:case D.ZodDiscriminatedUnion:return Ux(t,r);case D.ZodIntersection:return Ix(t,r);case D.ZodTuple:return Wx(t,r);case D.ZodRecord:return xc(t,r);case D.ZodLiteral:return Ox(t,r);case D.ZodEnum:return Cx(t);case D.ZodNativeEnum:return Lx(t);case D.ZodNullable:return qx(t,r);case D.ZodOptional:return Zx(t,r);case D.ZodMap:return zx(t,r);case D.ZodSet:return Kx(t,r);case D.ZodLazy:return()=>t.getter()._def;case D.ZodPromise:return Hx(t,r);case D.ZodNaN:case D.ZodNever:return jx(r);case D.ZodEffects:return Ax(t,r);case D.ZodAny:return He(r);case D.ZodUnknown:return Jx(r);case D.ZodDefault:return Px(t,r);case D.ZodBranded:return bc(t,r);case D.ZodReadonly:return Yx(t,r);case D.ZodCatch:return Ex(t,r);case D.ZodPipeline:return Vx(t,r);case D.ZodFunction:case D.ZodVoid:case D.ZodSymbol:return;default:return(n=>{})(e)}}});function ae(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==xx)return a}if(n&&!r){let a=bz(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=Xx(t,t.typeName,e),i=typeof s=="function"?ae(s(),e):s;if(i&&wz(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var bz,wz,et=O(()=>{fc();om();yc();Vt();bz=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:gc(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`),He(e)):e.$refStrategy==="seen"?He(e):void 0}},wz=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Qx=O(()=>{});var sm,im=O(()=>{et();Eh();Vt();sm=(t,e)=>{let r=Sx(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:ae(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??He(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=ae(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??He(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 ek=O(()=>{fc();Eh();nn();yc();et();Qx();Vt();Ah();Ch();Ih();wc();Oh();zh();Lh();jh();Dh();Mh();Uh();Fh();Zh();Vh();Hh();Kh();Wh();Gh();Jh();Yh();Xh();nm();kc();Qh();vc();em();tm();Sc();rm();om();im();im()});function _z(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function am(t,e){return wr(t)?Wp(t,{target:_z(e?.target),io:e?.pipeStrategy??"input"}):sm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function cm(t){let r=en(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ro(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function lm(t,e){let r=Qr(t,e);if(!r.success)throw r.error;return r.data}var um=O(()=>{Yp();js();ek()});function tk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rk(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];tk(i)&&tk(s)?r[o]={...i,...s}:r[o]=s}return r}var vz,$c,nk=O(()=>{js();Oo();_x();um();vz=6e4,$c=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(Xa,r=>{this._oncancel(r)}),this.setNotificationHandler(ec,r=>{this._onprogress(r)}),this.setRequestHandler(Qa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(tc,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(ee.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(nc,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,b=new J(p.error.code,p.error.message,p.error.data);u(b)}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(ee.InvalidParams,`Task not found: ${s}`);if(!rn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(rn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[tn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(oc,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(ee.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ic,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new J(ee.InvalidParams,`Task not found: ${r.params.taskId}`);if(rn(o.status))throw new J(ee.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new J(ee.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof J?o:new J(ee.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),J.fromError(ee.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),qs(s)||lx(s)?this._onresponse(s):mh(s)?this._onrequest(s,i):cx(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(ee.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[tn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:ee.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=sx(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,b)=>{if(i.signal.aborted)throw new J(ee.ConnectionClosed,"Request was cancelled");let m={...b,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let h=m.relatedTask?.taskId??s;return h&&c&&await c.updateTaskStatus(h,"input_required"),await this.request(u,p,m)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:ee.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),qs(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(qs(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),qs(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(ee.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Po,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new J(ee.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},rn(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(ee.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new J(ee.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof J?i:new J(ee.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=P=>{u(P)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(P){p(P);return}n?.signal?.throwIfAborted();let b=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:b};n?.onprogress&&(this._progressHandlers.set(b,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:b}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[tn]:c}});let h=P=>{this._responseHandlers.delete(b),this._progressHandlers.delete(b),this._cleanupTimeout(b),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:b,reason:String(P)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(B=>this._onerror(new Error(`Failed to send cancellation: ${B}`)));let z=P instanceof J?P:new J(ee.RequestTimeout,String(P));u(z)};this._responseHandlers.set(b,P=>{if(!n?.signal?.aborted){if(P instanceof Error)return u(P);try{let z=Qr(r,P.result);z.success?l(z.data):u(z.error)}catch(z){u(z)}}}),n?.signal?.addEventListener("abort",()=>{h(n?.signal?.reason)});let w=n?.timeout??vz,S=()=>h(J.fromError(ee.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(b,w,n?.maxTotalTimeout,S,n?.resetTimeoutOnProgress??!1);let R=c?.taskId;if(R){let P=z=>{let B=this._responseHandlers.get(b);B?B(z):this._onerror(new Error(`Response handler missing for side-channeled request ${b}`))};this._requestResolvers.set(b,P),this._enqueueTaskMessage(R,{type:"request",message:m,timestamp:Date.now()}).catch(z=>{this._cleanupTimeout(b),u(z)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(P=>{this._cleanupTimeout(b),u(P)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},rc,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},sc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},px,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||{},[tn]: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||{},[tn]: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||{},[tn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=cm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=lm(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=cm(e);this._notificationHandlers.set(n,o=>{let s=lm(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&mh(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new J(ee.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new J(ee.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new J(ee.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new J(ee.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Hs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),rn(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(ee.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(rn(a.status))throw new J(ee.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=Hs.parse({method:"notifications/tasks/status",params:c});await this.notification(l),rn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Qs=F(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 Ys=class{};Re._CodeOrName=Ys;Re.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Fn=class extends Ys{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=Fn;var Ht=class extends Ys{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 Fn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Re._Code=Ht;Re.nil=new Ht("");function ok(t,...e){let r=[t[0]],n=0;for(;n<e.length;)pm(r,e[n]),r.push(t[++n]);return new Ht(r)}Re._=ok;var dm=new Ht("+");function sk(t,...e){let r=[Xs(t[0])],n=0;for(;n<e.length;)r.push(dm),pm(r,e[n]),r.push(dm,Xs(t[++n]));return xz(r),new Ht(r)}Re.str=sk;function pm(t,e){e instanceof Ht?t.push(...e._items):e instanceof Fn?t.push(e):t.push($z(e))}Re.addCodeArg=pm;function xz(t){let e=1;for(;e<t.length-1;){if(t[e]===dm){let r=kz(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function kz(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Fn||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 Fn))return`"${t}${e.slice(1)}`}function Sz(t,e){return e.emptyStr()?t:t.emptyStr()?e:sk`${t}${e}`}Re.strConcat=Sz;function $z(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xs(Array.isArray(t)?t.join(","):t)}function Tz(t){return new Ht(Xs(t))}Re.stringify=Tz;function Xs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Re.safeStringify=Xs;function Rz(t){return typeof t=="string"&&Re.IDENTIFIER.test(t)?new Ht(`.${t}`):ok`[${t}]`}Re.getProperty=Rz;function Ez(t){if(typeof t=="string"&&Re.IDENTIFIER.test(t))return new Ht(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Re.getEsmExportName=Ez;function Pz(t){return new Ht(t.toString())}Re.regexpCode=Pz});var fm=F(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.ValueScope=At.ValueScopeName=At.Scope=At.varKinds=At.UsedValueState=void 0;var Pt=Qs(),hm=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Tc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Tc||(At.UsedValueState=Tc={}));At.varKinds={const:new Pt.Name("const"),let:new Pt.Name("let"),var:new Pt.Name("var")};var Rc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Pt.Name?e:this.name(e)}name(e){return new Pt.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}}};At.Scope=Rc;var Ec=class extends Pt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Pt._)`.${new Pt.Name(r)}[${n}]`}};At.ValueScopeName=Ec;var Az=(0,Pt._)`\n`,mm=class extends Rc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Az:Pt.nil}}get(){return this._scope}name(e){return new Ec(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,Pt._)`${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=Pt.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,Tc.Started);let u=r(l);if(u){let p=this.opts.es5?At.varKinds.var:At.varKinds.const;s=(0,Pt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Pt._)`${s}${u}${this.opts._n}`;else throw new hm(l);c.set(l,Tc.Completed)})}return s}};At.ValueScope=mm});var me=F(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var Se=Qs(),ir=fm(),on=Qs();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return on._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return on.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return on.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return on.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return on.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return on.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return on.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return on.Name}});var Ic=fm();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return Ic.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return Ic.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return Ic.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return Ic.varKinds}});fe.operators={GT:new Se._Code(">"),GTE:new Se._Code(">="),LT:new Se._Code("<"),LTE:new Se._Code("<="),EQ:new Se._Code("==="),NEQ:new Se._Code("!=="),NOT:new Se._Code("!"),OR:new Se._Code("||"),AND:new Se._Code("&&"),ADD:new Se._Code("+")};var zr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},gm=class extends zr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ir.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 Se._CodeOrName?this.rhs.names:{}}},Pc=class extends zr{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 Se.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=zo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Se.Name?{}:{...this.lhs.names};return Cc(e,this.rhs)}},ym=class extends Pc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},bm=class extends zr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},wm=class extends zr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},_m=class extends zr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},vm=class extends zr{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 Se._CodeOrName?this.code.names:{}}},ei=class extends zr{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)||(Cz(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Hn(e,r.names),{})}},Lr=class extends ei{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},xm=class extends ei{},No=class extends Lr{};No.kind="else";var Zn=class t extends Lr{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 No(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(ik(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 Cc(e,this.condition),this.else&&Hn(e,this.else.names),e}};Zn.kind="if";var Vn=class extends Lr{};Vn.kind="for";var km=class extends Vn{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 Hn(super.names,this.iteration.names)}},Sm=class extends Vn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?ir.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=Cc(super.names,this.from);return Cc(e,this.to)}},Ac=class extends Vn{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 Hn(super.names,this.iterable.names)}},ti=class extends Lr{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)}};ti.kind="func";var ri=class extends ei{render(e){return"return "+super.render(e)}};ri.kind="return";var $m=class extends Lr{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&&Hn(e,this.catch.names),this.finally&&Hn(e,this.finally.names),e}},ni=class extends Lr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ni.kind="catch";var oi=class extends Lr{render(e){return"finally"+super.render(e)}};oi.kind="finally";var Tm=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2054
+ `:""},this._extScope=e,this._scope=new ir.Scope({parent:e}),this._nodes=[new xm]}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 gm(e,s,n)),s}const(e,r,n){return this._def(ir.varKinds.const,e,r,n)}let(e,r,n){return this._def(ir.varKinds.let,e,r,n)}var(e,r,n){return this._def(ir.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Pc(e,r,n))}add(e,r){return this._leafNode(new ym(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Se.nil&&this._leafNode(new vm(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,Se.addCodeArg)(r,o));return r.push("}"),new Se._Code(r)}if(e,r,n){if(this._blockNode(new Zn(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 Zn(e))}else(){return this._elseNode(new No)}endIf(){return this._endBlockNode(Zn,No)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new km(e),r)}forRange(e,r,n,o,s=this.opts.es5?ir.varKinds.var:ir.varKinds.let){let i=this._scope.toName(e);return this._for(new Sm(s,i,r,n),()=>o(i))}forOf(e,r,n,o=ir.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof Se.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Se._)`${i}.length`,a=>{this.var(s,(0,Se._)`${i}[${a}]`),n(s)})}return this._for(new Ac("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?ir.varKinds.var:ir.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Se._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ac("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Vn)}label(e){return this._leafNode(new bm(e))}break(e){return this._leafNode(new wm(e))}return(e){let r=new ri;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ri)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new $m;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ni(s),r(s)}return n&&(this._currNode=o.finally=new oi,this.code(n)),this._endBlockNode(ni,oi)}throw(e){return this._leafNode(new _m(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=Se.nil,n,o){return this._blockNode(new ti(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ti)}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 Zn))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};fe.CodeGen=Tm;function Hn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Cc(t,e){return e instanceof Se._CodeOrName?Hn(t,e.names):t}function zo(t,e,r){if(t instanceof Se.Name)return n(t);if(!o(t))return t;return new Se._Code(t._items.reduce((s,i)=>(i instanceof Se.Name&&(i=n(i)),i instanceof Se._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 Se._Code&&s._items.some(i=>i instanceof Se.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Cz(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function ik(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Se._)`!${Rm(t)}`}fe.not=ik;var Iz=ak(fe.operators.AND);function Oz(...t){return t.reduce(Iz)}fe.and=Oz;var Nz=ak(fe.operators.OR);function zz(...t){return t.reduce(Nz)}fe.or=zz;function ak(t){return(e,r)=>e===Se.nil?r:r===Se.nil?e:(0,Se._)`${Rm(e)} ${t} ${Rm(r)}`}function Rm(t){return t instanceof Se.Name?t:(0,Se._)`(${t})`}});var $e=F(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.checkStrictMode=ge.getErrorPath=ge.Type=ge.useFunc=ge.setEvaluated=ge.evaluatedPropsToName=ge.mergeEvaluated=ge.eachItem=ge.unescapeJsonPointer=ge.escapeJsonPointer=ge.escapeFragment=ge.unescapeFragment=ge.schemaRefOrVal=ge.schemaHasRulesButRef=ge.schemaHasRules=ge.checkUnknownRules=ge.alwaysValidSchema=ge.toHash=void 0;var Ne=me(),Lz=Qs();function jz(t){let e={};for(let r of t)e[r]=!0;return e}ge.toHash=jz;function Dz(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(uk(t,e),!dk(e,t.self.RULES.all))}ge.alwaysValidSchema=Dz;function uk(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]||mk(t,`unknown keyword: "${s}"`)}ge.checkUnknownRules=uk;function dk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ge.schemaHasRules=dk;function Mz(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ge.schemaHasRulesButRef=Mz;function Uz({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Ne._)`${r}`}return(0,Ne._)`${t}${e}${(0,Ne.getProperty)(n)}`}ge.schemaRefOrVal=Uz;function qz(t){return pk(decodeURIComponent(t))}ge.unescapeFragment=qz;function Bz(t){return encodeURIComponent(Pm(t))}ge.escapeFragment=Bz;function Pm(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ge.escapeJsonPointer=Pm;function pk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ge.unescapeJsonPointer=pk;function Fz(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ge.eachItem=Fz;function ck({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Ne.Name?(s instanceof Ne.Name?t(o,s,i):e(o,s,i),i):s instanceof Ne.Name?(e(o,i,s),s):r(s,i);return a===Ne.Name&&!(c instanceof Ne.Name)?n(o,c):c}}ge.mergeEvaluated={props:ck({mergeNames:(t,e,r)=>t.if((0,Ne._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Ne._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Ne._)`${r} || {}`).code((0,Ne._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Ne._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Ne._)`${r} || {}`),Am(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:hk}),items:ck({mergeNames:(t,e,r)=>t.if((0,Ne._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Ne._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Ne._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Ne._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function hk(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Ne._)`{}`);return e!==void 0&&Am(t,r,e),r}ge.evaluatedPropsToName=hk;function Am(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Ne._)`${e}${(0,Ne.getProperty)(n)}`,!0))}ge.setEvaluated=Am;var lk={};function Zz(t,e){return t.scopeValue("func",{ref:e,code:lk[e.code]||(lk[e.code]=new Lz._Code(e.code))})}ge.useFunc=Zz;var Em;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Em||(ge.Type=Em={}));function Vz(t,e,r){if(t instanceof Ne.Name){let n=e===Em.Num;return r?n?(0,Ne._)`"[" + ${t} + "]"`:(0,Ne._)`"['" + ${t} + "']"`:n?(0,Ne._)`"/" + ${t}`:(0,Ne._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Ne.getProperty)(t).toString():"/"+Pm(t)}ge.getErrorPath=Vz;function mk(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ge.checkStrictMode=mk});var jr=F(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});var mt=me(),Hz={data:new mt.Name("data"),valCxt:new mt.Name("valCxt"),instancePath:new mt.Name("instancePath"),parentData:new mt.Name("parentData"),parentDataProperty:new mt.Name("parentDataProperty"),rootData:new mt.Name("rootData"),dynamicAnchors:new mt.Name("dynamicAnchors"),vErrors:new mt.Name("vErrors"),errors:new mt.Name("errors"),this:new mt.Name("this"),self:new mt.Name("self"),scope:new mt.Name("scope"),json:new mt.Name("json"),jsonPos:new mt.Name("jsonPos"),jsonLen:new mt.Name("jsonLen"),jsonPart:new mt.Name("jsonPart")};Cm.default=Hz});var si=F(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.extendErrors=ft.resetErrorsCount=ft.reportExtraError=ft.reportError=ft.keyword$DataError=ft.keywordError=void 0;var Te=me(),Oc=$e(),_t=jr();ft.keywordError={message:({keyword:t})=>(0,Te.str)`must pass "${t}" keyword validation`};ft.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 Kz(t,e=ft.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=yk(t,e,r);n??(i||a)?fk(s,c):gk(o,(0,Te._)`[${c}]`)}ft.reportError=Kz;function Wz(t,e=ft.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=yk(t,e,r);fk(o,a),s||i||gk(n,_t.default.vErrors)}ft.reportExtraError=Wz;function Gz(t,e){t.assign(_t.default.errors,e),t.if((0,Te._)`${_t.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,Te._)`${_t.default.vErrors}.length`,e),()=>t.assign(_t.default.vErrors,null)))}ft.resetErrorsCount=Gz;function Jz({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,_t.default.errors,a=>{t.const(i,(0,Te._)`${_t.default.vErrors}[${a}]`),t.if((0,Te._)`${i}.instancePath === undefined`,()=>t.assign((0,Te._)`${i}.instancePath`,(0,Te.strConcat)(_t.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))})}ft.extendErrors=Jz;function fk(t,e){let r=t.const("err",e);t.if((0,Te._)`${_t.default.vErrors} === null`,()=>t.assign(_t.default.vErrors,(0,Te._)`[${r}]`),(0,Te._)`${_t.default.vErrors}.push(${r})`),t.code((0,Te._)`${_t.default.errors}++`)}function gk(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 Kn={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 yk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,Te._)`{}`:Yz(t,e,r)}function Yz(t,e,r={}){let{gen:n,it:o}=t,s=[Xz(o,r),Qz(t,r)];return eL(t,e,s),n.object(...s)}function Xz({errorPath:t},{instancePath:e}){let r=e?(0,Te.str)`${t}${(0,Oc.getErrorPath)(e,Oc.Type.Str)}`:t;return[_t.default.instancePath,(0,Te.strConcat)(_t.default.instancePath,r)]}function Qz({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,Oc.getErrorPath)(r,Oc.Type.Str)}`),[Kn.schemaPath,o]}function eL(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([Kn.keyword,o],[Kn.params,typeof e=="function"?e(t):e||(0,Te._)`{}`]),c.messages&&n.push([Kn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Kn.schema,i],[Kn.parentSchema,(0,Te._)`${u}${p}`],[_t.default.data,s]),l&&n.push([Kn.propertyName,l])}});var wk=F(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.boolOrEmptySchema=Lo.topBoolOrEmptySchema=void 0;var tL=si(),rL=me(),nL=jr(),oL={message:"boolean schema is false"};function sL(t){let{gen:e,schema:r,validateName:n}=t;r===!1?bk(t,!1):typeof r=="object"&&r.$async===!0?e.return(nL.default.data):(e.assign((0,rL._)`${n}.errors`,null),e.return(!0))}Lo.topBoolOrEmptySchema=sL;function iL(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),bk(t)):r.var(e,!0)}Lo.boolOrEmptySchema=iL;function bk(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,tL.reportError)(o,oL,void 0,e)}});var Im=F(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.getRules=jo.isJSONType=void 0;var aL=["string","number","integer","boolean","null","object","array"],cL=new Set(aL);function lL(t){return typeof t=="string"&&cL.has(t)}jo.isJSONType=lL;function uL(){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:{}}}jo.getRules=uL});var Om=F(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.shouldUseRule=sn.shouldUseGroup=sn.schemaHasRulesForType=void 0;function dL({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&_k(t,n)}sn.schemaHasRulesForType=dL;function _k(t,e){return e.rules.some(r=>vk(t,r))}sn.shouldUseGroup=_k;function vk(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))}sn.shouldUseRule=vk});var ii=F(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.reportTypeError=gt.checkDataTypes=gt.checkDataType=gt.coerceAndCheckDataType=gt.getJSONTypes=gt.getSchemaTypes=gt.DataType=void 0;var pL=Im(),hL=Om(),mL=si(),pe=me(),xk=$e(),Do;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Do||(gt.DataType=Do={}));function fL(t){let e=kk(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}gt.getSchemaTypes=fL;function kk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(pL.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}gt.getJSONTypes=kk;function gL(t,e){let{gen:r,data:n,opts:o}=t,s=yL(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,hL.schemaHasRulesForType)(t,e[0]));if(i){let a=zm(e,n,o.strictNumbers,Do.Wrong);r.if(a,()=>{s.length?bL(t,e,s):Lm(t)})}return i}gt.coerceAndCheckDataType=gL;var Sk=new Set(["string","number","integer","boolean","null"]);function yL(t,e){return e?t.filter(r=>Sk.has(r)||e==="array"&&r==="array"):[]}function bL(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(zm(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,pe._)`${a} !== undefined`);for(let l of r)(Sk.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Lm(t),n.endIf(),n.if((0,pe._)`${a} !== undefined`,()=>{n.assign(o,a),wL(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
2055
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,pe._)`+${o}`);return;case"integer":n.elseIf((0,pe._)`${i} === "boolean" || ${o} === null
2056
+ || (${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"
2057
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,pe._)`[${o}]`)}}}function wL({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,pe._)`${e} !== undefined`,()=>t.assign((0,pe._)`${e}[${r}]`,n))}function Nm(t,e,r,n=Do.Correct){let o=n===Do.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===Do.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)}}gt.checkDataType=Nm;function zm(t,e,r,n){if(t.length===1)return Nm(t[0],e,r,n);let o,s=(0,xk.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,Nm(i,e,r,n));return o}gt.checkDataTypes=zm;var _L={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,pe._)`{type: ${t}}`:(0,pe._)`{type: ${e}}`};function Lm(t){let e=vL(t);(0,mL.reportError)(e,_L)}gt.reportTypeError=Lm;function vL(t){let{gen:e,data:r,schema:n}=t,o=(0,xk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Tk=F(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.assignDefaults=void 0;var Mo=me(),xL=$e();function kL(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)$k(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>$k(t,s,o.default))}Nc.assignDefaults=kL;function $k(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Mo._)`${s}${(0,Mo.getProperty)(e)}`;if(o){(0,xL.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Mo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Mo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Mo._)`${a} = ${(0,Mo.stringify)(r)}`)}});var Kt=F(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.validateUnion=Oe.validateArray=Oe.usePattern=Oe.callValidateCode=Oe.schemaProperties=Oe.allSchemaProperties=Oe.noPropertyInData=Oe.propertyInData=Oe.isOwnProperty=Oe.hasPropFunc=Oe.reportMissingProp=Oe.checkMissingProp=Oe.checkReportMissingProp=void 0;var Ue=me(),jm=$e(),an=jr(),SL=$e();function $L(t,e){let{gen:r,data:n,it:o}=t;r.if(Mm(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ue._)`${e}`},!0),t.error()})}Oe.checkReportMissingProp=$L;function TL({gen:t,data:e,it:{opts:r}},n,o){return(0,Ue.or)(...n.map(s=>(0,Ue.and)(Mm(t,e,s,r.ownProperties),(0,Ue._)`${o} = ${s}`)))}Oe.checkMissingProp=TL;function RL(t,e){t.setParams({missingProperty:e},!0),t.error()}Oe.reportMissingProp=RL;function Rk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ue._)`Object.prototype.hasOwnProperty`})}Oe.hasPropFunc=Rk;function Dm(t,e,r){return(0,Ue._)`${Rk(t)}.call(${e}, ${r})`}Oe.isOwnProperty=Dm;function EL(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} !== undefined`;return n?(0,Ue._)`${o} && ${Dm(t,e,r)}`:o}Oe.propertyInData=EL;function Mm(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} === undefined`;return n?(0,Ue.or)(o,(0,Ue.not)(Dm(t,e,r))):o}Oe.noPropertyInData=Mm;function Ek(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Oe.allSchemaProperties=Ek;function PL(t,e){return Ek(e).filter(r=>!(0,jm.alwaysValidSchema)(t,e[r]))}Oe.schemaProperties=PL;function AL({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=[[an.default.instancePath,(0,Ue.strConcat)(an.default.instancePath,s)],[an.default.parentData,i.parentData],[an.default.parentDataProperty,i.parentDataProperty],[an.default.rootData,an.default.rootData]];i.opts.dynamicRef&&p.push([an.default.dynamicAnchors,an.default.dynamicAnchors]);let b=(0,Ue._)`${u}, ${r.object(...p)}`;return c!==Ue.nil?(0,Ue._)`${a}.call(${c}, ${b})`:(0,Ue._)`${a}(${b})`}Oe.callValidateCode=AL;var CL=(0,Ue._)`new RegExp`;function IL({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"?CL:(0,SL.useFunc)(t,o)}(${r}, ${n})`})}Oe.usePattern=IL;function OL(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:jm.Type.Num},s),e.if((0,Ue.not)(s),a)})}}Oe.validateArray=OL;function NL(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,jm.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))}Oe.validateUnion=NL});var Ck=F(_r=>{"use strict";Object.defineProperty(_r,"__esModule",{value:!0});_r.validateKeywordUsage=_r.validSchemaType=_r.funcKeywordCode=_r.macroKeywordCode=void 0;var vt=me(),Wn=jr(),zL=Kt(),LL=si();function jL(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Ak(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:vt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}_r.macroKeywordCode=jL;function DL(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;UL(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Ak(n,o,l),p=n.let("valid");t.block$data(p,b),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function b(){if(e.errors===!1)w(),e.modifying&&Pk(t),S(()=>t.error());else{let R=e.async?m():h();e.modifying&&Pk(t),S(()=>ML(t,R))}}function m(){let R=n.let("ruleErrs",null);return n.try(()=>w((0,vt._)`await `),P=>n.assign(p,!1).if((0,vt._)`${P} instanceof ${c.ValidationError}`,()=>n.assign(R,(0,vt._)`${P}.errors`),()=>n.throw(P))),R}function h(){let R=(0,vt._)`${u}.errors`;return n.assign(R,null),w(vt.nil),R}function w(R=e.async?(0,vt._)`await `:vt.nil){let P=c.opts.passContext?Wn.default.this:Wn.default.self,z=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,vt._)`${R}${(0,zL.callValidateCode)(t,u,P,z)}`,e.modifying)}function S(R){var P;n.if((0,vt.not)((P=e.valid)!==null&&P!==void 0?P:p),R)}}_r.funcKeywordCode=DL;function Pk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,vt._)`${n.parentData}[${n.parentDataProperty}]`))}function ML(t,e){let{gen:r}=t;r.if((0,vt._)`Array.isArray(${e})`,()=>{r.assign(Wn.default.vErrors,(0,vt._)`${Wn.default.vErrors} === null ? ${e} : ${Wn.default.vErrors}.concat(${e})`).assign(Wn.default.errors,(0,vt._)`${Wn.default.vErrors}.length`),(0,LL.extendErrors)(t)},()=>t.error())}function UL({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Ak(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,vt.stringify)(r)})}function qL(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")}_r.validSchemaType=qL;function BL({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)}}_r.validateKeywordUsage=BL});var Ok=F(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.extendSubschemaMode=cn.extendSubschemaData=cn.getSubschema=void 0;var vr=me(),Ik=$e();function FL(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,vr._)`${t.schemaPath}${(0,vr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,vr._)`${t.schemaPath}${(0,vr.getProperty)(e)}${(0,vr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Ik.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')}cn.getSubschema=FL;function ZL(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,b=a.let("data",(0,vr._)`${e.data}${(0,vr.getProperty)(r)}`,!0);c(b),t.errorPath=(0,vr.str)`${l}${(0,Ik.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,vr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof vr.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]}}cn.extendSubschemaData=ZL;function VL(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}cn.extendSubschemaMode=VL});var Um=F((NK,Nk)=>{"use strict";Nk.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 Lk=F((zK,zk)=>{"use strict";var ln=zk.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(){};zc(e,n,o,t,"",t)};ln.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ln.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ln.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ln.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 zc(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 ln.arrayKeywords)for(var b=0;b<p.length;b++)zc(t,e,r,p[b],o+"/"+u+"/"+b,s,o,u,n,b)}else if(u in ln.propsKeywords){if(p&&typeof p=="object")for(var m in p)zc(t,e,r,p[m],o+"/"+u+"/"+HL(m),s,o,u,n,m)}else(u in ln.keywords||t.allKeys&&!(u in ln.skipKeywords))&&zc(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function HL(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ai=F(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.getSchemaRefs=Ct.resolveUrl=Ct.normalizeId=Ct._getFullPath=Ct.getFullPath=Ct.inlineRef=void 0;var KL=$e(),WL=Um(),GL=Lk(),JL=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function YL(t,e=!0){return typeof t=="boolean"?!0:e===!0?!qm(t):e?jk(t)<=e:!1}Ct.inlineRef=YL;var XL=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function qm(t){for(let e in t){if(XL.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(qm)||typeof r=="object"&&qm(r))return!0}return!1}function jk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!JL.has(r)&&(typeof t[r]=="object"&&(0,KL.eachItem)(t[r],n=>e+=jk(n)),e===1/0))return 1/0}return e}function Dk(t,e="",r){r!==!1&&(e=Uo(e));let n=t.parse(e);return Mk(t,n)}Ct.getFullPath=Dk;function Mk(t,e){return t.serialize(e).split("#")[0]+"#"}Ct._getFullPath=Mk;var QL=/#\/?$/;function Uo(t){return t?t.replace(QL,""):""}Ct.normalizeId=Uo;function ej(t,e,r){return r=Uo(r),t.resolve(e,r)}Ct.resolveUrl=ej;var tj=/^[a-z_][-a-z0-9._]*$/i;function rj(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Uo(t[r]||e),s={"":o},i=Dk(n,o,!1),a={},c=new Set;return GL(t,{allKeys:!0},(p,b,m,h)=>{if(h===void 0)return;let w=i+b,S=s[h];typeof p[r]=="string"&&(S=R.call(this,p[r])),P.call(this,p.$anchor),P.call(this,p.$dynamicAnchor),s[b]=S;function R(z){let B=this.opts.uriResolver.resolve;if(z=Uo(S?B(S,z):z),c.has(z))throw u(z);c.add(z);let K=this.refs[z];return typeof K=="string"&&(K=this.refs[K]),typeof K=="object"?l(p,K.schema,z):z!==Uo(w)&&(z[0]==="#"?(l(p,a[z],z),a[z]=p):this.refs[z]=w),z}function P(z){if(typeof z=="string"){if(!tj.test(z))throw new Error(`invalid anchor "${z}"`);R.call(this,`#${z}`)}}}),a;function l(p,b,m){if(b!==void 0&&!WL(p,b))throw u(m)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Ct.getSchemaRefs=rj});var ui=F(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.getData=un.KeywordCxt=un.validateFunctionCode=void 0;var Zk=wk(),Uk=ii(),Fm=Om(),Lc=ii(),nj=Tk(),li=Ck(),Bm=Ok(),X=me(),ue=jr(),oj=ai(),Dr=$e(),ci=si();function sj(t){if(Kk(t)&&(Wk(t),Hk(t))){cj(t);return}Vk(t,()=>(0,Zk.topBoolOrEmptySchema)(t))}un.validateFunctionCode=sj;function Vk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,X._)`${ue.default.data}, ${ue.default.valCxt}`,n.$async,()=>{t.code((0,X._)`"use strict"; ${qk(r,o)}`),aj(t,o),t.code(s)}):t.func(e,(0,X._)`${ue.default.data}, ${ij(o)}`,n.$async,()=>t.code(qk(r,o)).code(s))}function ij(t){return(0,X._)`{${ue.default.instancePath}="", ${ue.default.parentData}, ${ue.default.parentDataProperty}, ${ue.default.rootData}=${ue.default.data}${t.dynamicRef?(0,X._)`, ${ue.default.dynamicAnchors}={}`:X.nil}}={}`}function aj(t,e){t.if(ue.default.valCxt,()=>{t.var(ue.default.instancePath,(0,X._)`${ue.default.valCxt}.${ue.default.instancePath}`),t.var(ue.default.parentData,(0,X._)`${ue.default.valCxt}.${ue.default.parentData}`),t.var(ue.default.parentDataProperty,(0,X._)`${ue.default.valCxt}.${ue.default.parentDataProperty}`),t.var(ue.default.rootData,(0,X._)`${ue.default.valCxt}.${ue.default.rootData}`),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,X._)`${ue.default.valCxt}.${ue.default.dynamicAnchors}`)},()=>{t.var(ue.default.instancePath,(0,X._)`""`),t.var(ue.default.parentData,(0,X._)`undefined`),t.var(ue.default.parentDataProperty,(0,X._)`undefined`),t.var(ue.default.rootData,ue.default.data),e.dynamicRef&&t.var(ue.default.dynamicAnchors,(0,X._)`{}`)})}function cj(t){let{schema:e,opts:r,gen:n}=t;Vk(t,()=>{r.$comment&&e.$comment&&Jk(t),hj(t),n.let(ue.default.vErrors,null),n.let(ue.default.errors,0),r.unevaluated&&lj(t),Gk(t),gj(t)})}function lj(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,X._)`${r}.evaluated`),e.if((0,X._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,X._)`${t.evaluated}.props`,(0,X._)`undefined`)),e.if((0,X._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,X._)`${t.evaluated}.items`,(0,X._)`undefined`))}function qk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,X._)`/*# sourceURL=${r} */`:X.nil}function uj(t,e){if(Kk(t)&&(Wk(t),Hk(t))){dj(t,e);return}(0,Zk.boolOrEmptySchema)(t,e)}function Hk({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 Kk(t){return typeof t.schema!="boolean"}function dj(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Jk(t),mj(t),fj(t);let s=n.const("_errs",ue.default.errors);Gk(t,s),n.var(e,(0,X._)`${s} === ${ue.default.errors}`)}function Wk(t){(0,Dr.checkUnknownRules)(t),pj(t)}function Gk(t,e){if(t.opts.jtd)return Bk(t,[],!1,e);let r=(0,Uk.getSchemaTypes)(t.schema),n=(0,Uk.coerceAndCheckDataType)(t,r);Bk(t,r,!n,e)}function pj(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Dr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function hj(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Dr.checkStrictMode)(t,"default is ignored in the schema root")}function mj(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,oj.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function fj(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Jk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,X._)`${ue.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,X.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,X._)`${ue.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function gj(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,X._)`${ue.default.errors} === 0`,()=>e.return(ue.default.data),()=>e.throw((0,X._)`new ${o}(${ue.default.vErrors})`)):(e.assign((0,X._)`${n}.errors`,ue.default.vErrors),s.unevaluated&&yj(t),e.return((0,X._)`${ue.default.errors} === 0`))}function yj({gen:t,evaluated:e,props:r,items:n}){r instanceof X.Name&&t.assign((0,X._)`${e}.props`,r),n instanceof X.Name&&t.assign((0,X._)`${e}.items`,n)}function Bk(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,Dr.schemaHasRulesButRef)(s,u))){o.block(()=>Xk(t,"$ref",u.all.$ref.definition));return}c.jtd||bj(t,e),o.block(()=>{for(let b of u.rules)p(b);p(u.post)});function p(b){(0,Fm.shouldUseGroup)(s,b)&&(b.type?(o.if((0,Lc.checkDataType)(b.type,i,c.strictNumbers)),Fk(t,b),e.length===1&&e[0]===b.type&&r&&(o.else(),(0,Lc.reportTypeError)(t)),o.endIf()):Fk(t,b),a||o.if((0,X._)`${ue.default.errors} === ${n||0}`))}}function Fk(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,nj.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Fm.shouldUseRule)(n,s)&&Xk(t,s.keyword,s.definition,e.type)})}function bj(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(wj(t,e),t.opts.allowUnionTypes||_j(t,e),vj(t,t.dataTypes))}function wj(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Yk(t.dataTypes,r)||Zm(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),kj(t,e)}}function _j(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Zm(t,"use allowUnionTypes to allow union type keyword")}function vj(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Fm.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>xj(e,i))&&Zm(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function xj(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Yk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function kj(t,e){let r=[];for(let n of t.dataTypes)Yk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Zm(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Dr.checkStrictMode)(t,e,t.opts.strictTypes)}var jc=class{constructor(e,r,n){if((0,li.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,Dr.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",Qk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,li.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,X.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,X.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,X._)`${r} !== undefined && (${(0,X.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?ci.reportExtraError:ci.reportError)(this,this.def.error,r)}$dataError(){(0,ci.reportError)(this,this.def.$dataError||ci.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ci.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=X.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=X.nil,r=X.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,X.or)((0,X._)`${o} === undefined`,r)),e!==X.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==X.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,X.or)(i(),a());function i(){if(n.length){if(!(r instanceof X.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,X._)`${(0,Lc.checkDataTypes)(c,r,s.opts.strictNumbers,Lc.DataType.Wrong)}`}return X.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,X._)`!${c}(${r})`}return X.nil}}subschema(e,r){let n=(0,Bm.getSubschema)(this.it,e);(0,Bm.extendSubschemaData)(n,this.it,e),(0,Bm.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return uj(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Dr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Dr.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,X.Name)),!0}};un.KeywordCxt=jc;function Xk(t,e,r,n){let o=new jc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,li.funcKeywordCode)(o,r):"macro"in r?(0,li.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,li.funcKeywordCode)(o,r)}var Sj=/^\/(?:[^~]|~0|~1)*$/,$j=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Qk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ue.default.rootData;if(t[0]==="/"){if(!Sj.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ue.default.rootData}else{let l=$j.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,X._)`${s}${(0,X.getProperty)((0,Dr.unescapeJsonPointer)(l))}`,i=(0,X._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}un.getData=Qk});var Dc=F(Hm=>{"use strict";Object.defineProperty(Hm,"__esModule",{value:!0});var Vm=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Hm.default=Vm});var di=F(Gm=>{"use strict";Object.defineProperty(Gm,"__esModule",{value:!0});var Km=ai(),Wm=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Km.resolveUrl)(e,r,n),this.missingSchema=(0,Km.normalizeId)((0,Km.getFullPath)(e,this.missingRef))}};Gm.default=Wm});var Uc=F(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.resolveSchema=Wt.getCompilingSchema=Wt.resolveRef=Wt.compileSchema=Wt.SchemaEnv=void 0;var ar=me(),Tj=Dc(),Gn=jr(),cr=ai(),eS=$e(),Rj=ui(),qo=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,cr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Wt.SchemaEnv=qo;function Ym(t){let e=tS.call(this,t);if(e)return e;let r=(0,cr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new ar.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:Tj.default,code:(0,ar._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Gn.default.data,parentData:Gn.default.parentData,parentDataProperty:Gn.default.parentDataProperty,dataNames:[Gn.default.data],dataPathArr:[ar.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ar.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ar.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ar._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,Rj.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Gn.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let m=new Function(`${Gn.default.self}`,`${Gn.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:h,items:w}=l;m.evaluated={props:h instanceof ar.Name?void 0:h,items:w instanceof ar.Name?void 0:w,dynamicProps:h instanceof ar.Name,dynamicItems:w instanceof ar.Name},m.source&&(m.source.evaluated=(0,ar.stringify)(m.evaluated))}return t.validate=m,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}Wt.compileSchema=Ym;function Ej(t,e,r){var n;r=(0,cr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=Cj.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 qo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=Pj.call(this,s)}Wt.resolveRef=Ej;function Pj(t){return(0,cr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ym.call(this,t)}function tS(t){for(let e of this._compilations)if(Aj(e,t))return e}Wt.getCompilingSchema=tS;function Aj(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Cj(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Mc.call(this,t,e)}function Mc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,cr._getFullPath)(this.opts.uriResolver,r),o=(0,cr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Jm.call(this,r,t);let s=(0,cr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Mc.call(this,t,i);return typeof a?.schema!="object"?void 0:Jm.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ym.call(this,i),s===(0,cr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,cr.resolveUrl)(this.opts.uriResolver,o,l)),new qo({schema:a,schemaId:c,root:t,baseId:o})}return Jm.call(this,r,i)}}Wt.resolveSchema=Mc;var Ij=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Jm(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,eS.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!Ij.has(a)&&l&&(e=(0,cr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,eS.schemaHasRulesButRef)(r,this.RULES)){let a=(0,cr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Mc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new qo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var rS=F((qK,Oj)=>{Oj.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 ef=F((BK,cS)=>{"use strict";var Nj=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),oS=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),Xm=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),sS=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),zj=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Qm(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 Lj=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function nS(t){return t.length=0,!0}function jj(t,e,r){if(t.length){let n=Qm(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function Dj(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=jj;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=nS}else{o.push(l);continue}}return o.length&&(a===nS?r.zone=o.join(""):i?n.push(o.join("")):n.push(Qm(o))),r.address=n.join(""),r}function iS(t){if(Mj(t,":")<2)return{host:t,isIPV6:!1};let e=Dj(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function Mj(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function Uj(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var qj={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Bj=/[@/?#:]/g,Fj=/[@/?#]/g;function aS(t,e){let r=e?Fj:Bj;return r.lastIndex=0,t.replace(r,n=>qj[n])}function Zj(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(Xm(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&sS(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function Vj(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(Xm(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&sS(s)?e+=s:e+="%"+o,r+=2;continue}}zj(t[r])?e+=t[r]:e+=escape(t[r])}return e}function Hj(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(Xm(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function Kj(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!oS(r)){let n=iS(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=aS(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}cS.exports={nonSimpleDomain:Lj,recomposeAuthority:Kj,reescapeHostDelimiters:aS,normalizePercentEncoding:Zj,normalizePathEncoding:Vj,escapePreservingEscapes:Hj,removeDotSegments:Uj,isIPv4:oS,isUUID:Nj,normalizeIPv6:iS,stringArrayToHexStripped:Qm}});var hS=F((FK,pS)=>{"use strict";var{isUUID:Wj}=ef(),Gj=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Jj=["http","https","ws","wss","urn","urn:uuid"];function Yj(t){return Jj.indexOf(t)!==-1}function tf(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 lS(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function uS(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 Xj(t){return t.secure=tf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Qj(t){if((t.port===(tf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function eD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(Gj);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=rf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function tD(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=rf(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 rD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!Wj(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function nD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var dS={scheme:"http",domainHost:!0,parse:lS,serialize:uS},oD={scheme:"https",domainHost:dS.domainHost,parse:lS,serialize:uS},qc={scheme:"ws",domainHost:!0,parse:Xj,serialize:Qj},sD={scheme:"wss",domainHost:qc.domainHost,parse:qc.parse,serialize:qc.serialize},iD={scheme:"urn",parse:eD,serialize:tD,skipNormalize:!0},aD={scheme:"urn:uuid",parse:rD,serialize:nD,skipNormalize:!0},Bc={http:dS,https:oD,ws:qc,wss:sD,urn:iD,"urn:uuid":aD};Object.setPrototypeOf(Bc,null);function rf(t){return t&&(Bc[t]||Bc[t.toLowerCase()])||void 0}pS.exports={wsIsSecure:tf,SCHEMES:Bc,isValidSchemeName:Yj,getSchemeHandler:rf}});var bS=F((ZK,Vc)=>{"use strict";var{normalizeIPv6:cD,removeDotSegments:pi,recomposeAuthority:lD,normalizePercentEncoding:uD,normalizePathEncoding:dD,escapePreservingEscapes:pD,reescapeHostDelimiters:hD,isIPv4:mD,nonSimpleDomain:fD}=ef(),{SCHEMES:gD,getSchemeHandler:fS}=hS();function yD(t,e){return typeof t=="string"?t=SD(t,e):typeof t=="object"&&(t=Zc(Jn(t,e),e)),t}function bD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=Fc(t,n),{parsed:i,malformedAuthorityOrPort:a}=Fc(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let c=gS(o,i,n,!0);return n.skipEscape=!0,Jn(c,n)}function gS(t,e,r,n){let o={};return n||(t=Zc(Jn(t,r),r),e=Zc(Jn(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=pi(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=pi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=pi(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=pi(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function wD(t,e,r){let n=mS(t,r),o=mS(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Jn(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=fS(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=uD(r.path):(r.path=pD(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=lD(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=pi(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var _D=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,vD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,xD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function kD(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 Fc(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(vD);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(xD);if(a!==null){let l=a[1],u=l.replace(/[\t\n\r]/g,"");u.length>=2&&(u.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):l.length!==u.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let c=t.match(_D);if(c){n.scheme=c[1],n.userinfo=c[3],n.host=c[4],n.port=parseInt(c[5],10),n.path=c[6]||"",n.query=c[7],n.fragment=c[8],isNaN(n.port)&&(n.port=c[5]);let l=kD(n,c);if(l!==void 0&&(n.error=n.error||l,o=!0),n.host)if(mD(n.host)===!1){let b=cD(n.host);n.host=b.host.toLowerCase(),s=b.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let u=fS(r.scheme||n.scheme);if(!r.unicodeSupport&&(!u||!u.unicodeSupport)&&n.host&&(r.domainHost||u&&u.domainHost)&&s===!1&&fD(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(p){n.error=n.error||"Host's domain name can not be converted to ASCII: "+p}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=hD(unescape(n.host),s))),n.path&&(n.path=dD(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}u&&u.parse&&u.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function Zc(t,e){return Fc(t,e).parsed}function SD(t,e){return yS(t,e).normalized}function yS(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Fc(t,e);return{normalized:n?t:Jn(r,e),malformedAuthorityOrPort:n}}function mS(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=yS(t,e);return n?void 0:r}if(typeof t=="object")return Jn(t,e)}var nf={SCHEMES:gD,normalize:yD,resolve:bD,resolveComponent:gS,equal:wD,serialize:Jn,parse:Zc};Vc.exports=nf;Vc.exports.default=nf;Vc.exports.fastUri=nf});var _S=F(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var wS=bS();wS.code='require("ajv/dist/runtime/uri").default';of.default=wS});var ES=F(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.CodeGen=dt.Name=dt.nil=dt.stringify=dt.str=dt._=dt.KeywordCxt=void 0;var $D=ui();Object.defineProperty(dt,"KeywordCxt",{enumerable:!0,get:function(){return $D.KeywordCxt}});var Bo=me();Object.defineProperty(dt,"_",{enumerable:!0,get:function(){return Bo._}});Object.defineProperty(dt,"str",{enumerable:!0,get:function(){return Bo.str}});Object.defineProperty(dt,"stringify",{enumerable:!0,get:function(){return Bo.stringify}});Object.defineProperty(dt,"nil",{enumerable:!0,get:function(){return Bo.nil}});Object.defineProperty(dt,"Name",{enumerable:!0,get:function(){return Bo.Name}});Object.defineProperty(dt,"CodeGen",{enumerable:!0,get:function(){return Bo.CodeGen}});var TD=Dc(),$S=di(),RD=Im(),hi=Uc(),ED=me(),mi=ai(),Hc=ii(),af=$e(),vS=rS(),PD=_S(),TS=(t,e)=>new RegExp(t,e);TS.code="new RegExp";var AD=["removeAdditional","useDefaults","coerceTypes"],CD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),ID={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."},OD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},xS=200;function ND(t){var e,r,n,o,s,i,a,c,l,u,p,b,m,h,w,S,R,P,z,B,K,Ge,Je,Jt,Ur;let qr=t.strict,Yo=(e=t.code)===null||e===void 0?void 0:e.optimize,mn=Yo===!0||Yo===void 0?1:Yo||0,dr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:TS,bl=(o=t.uriResolver)!==null&&o!==void 0?o:PD.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:qr)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:qr)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:qr)!==null&&u!==void 0?u:"log",strictTuples:(b=(p=t.strictTuples)!==null&&p!==void 0?p:qr)!==null&&b!==void 0?b:"log",strictRequired:(h=(m=t.strictRequired)!==null&&m!==void 0?m:qr)!==null&&h!==void 0?h:!1,code:t.code?{...t.code,optimize:mn,regExp:dr}:{optimize:mn,regExp:dr},loopRequired:(w=t.loopRequired)!==null&&w!==void 0?w:xS,loopEnum:(S=t.loopEnum)!==null&&S!==void 0?S:xS,meta:(R=t.meta)!==null&&R!==void 0?R:!0,messages:(P=t.messages)!==null&&P!==void 0?P:!0,inlineRefs:(z=t.inlineRefs)!==null&&z!==void 0?z:!0,schemaId:(B=t.schemaId)!==null&&B!==void 0?B:"$id",addUsedSchema:(K=t.addUsedSchema)!==null&&K!==void 0?K:!0,validateSchema:(Ge=t.validateSchema)!==null&&Ge!==void 0?Ge:!0,validateFormats:(Je=t.validateFormats)!==null&&Je!==void 0?Je:!0,unicodeRegExp:(Jt=t.unicodeRegExp)!==null&&Jt!==void 0?Jt:!0,int32range:(Ur=t.int32range)!==null&&Ur!==void 0?Ur:!0,uriResolver:bl}}var fi=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,...ND(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new ED.ValueScope({scope:{},prefixes:CD,es5:r,lines:n}),this.logger=UD(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,RD.getRules)(),kS.call(this,ID,e,"NOT SUPPORTED"),kS.call(this,OD,e,"DEPRECATED","warn"),this._metaOpts=DD.call(this),e.formats&&LD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&jD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),zD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=vS;n==="id"&&(o={...vS},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 b=this._addSchema(u,p);return b.validate||i.call(this,b)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof $S.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,mi.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=SS.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new hi.SchemaEnv({schema:{},schemaId:n});if(r=hi.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=SS.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,mi.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(BD.call(this,n,r),!r)return(0,af.eachItem)(n,s=>sf.call(this,s)),this;ZD.call(this,r);let o={...r,type:(0,Hc.getJSONTypes)(r.type),schemaType:(0,Hc.getJSONTypes)(r.schemaType)};return(0,af.eachItem)(n,o.type.length===0?s=>sf.call(this,s,o):s=>o.type.forEach(i=>sf.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]=RS(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,mi.normalizeId)(i||n);let l=mi.getSchemaRefs.call(this,e,n);return c=new hi.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):hi.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{hi.compileSchema.call(this,e)}finally{this.opts=r}}};fi.ValidationError=TD.default;fi.MissingRefError=$S.default;dt.default=fi;function kS(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 SS(t){return t=(0,mi.normalizeId)(t),this.schemas[t]||this.refs[t]}function zD(){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 LD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function jD(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 DD(){let t={...this.opts};for(let e of AD)delete t[e];return t}var MD={log(){},warn(){},error(){}};function UD(t){if(t===!1)return MD;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 qD=/^[a-z_$][a-z0-9_$:-]*$/i;function BD(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(!qD.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 sf(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,Hc.getJSONTypes)(e.type),schemaType:(0,Hc.getJSONTypes)(e.schemaType)}};e.before?FD.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 FD(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 ZD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=RS(e)),t.validateSchema=this.compile(e,!0))}var VD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function RS(t){return{anyOf:[t,VD]}}});var PS=F(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var HD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};cf.default=HD});var OS=F(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.callRef=Yn.getValidate=void 0;var KD=di(),AS=Kt(),It=me(),Fo=jr(),CS=Uc(),Kc=$e(),WD={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=CS.resolveRef.call(c,l,o,r);if(u===void 0)throw new KD.default(n.opts.uriResolver,o,r);if(u instanceof CS.SchemaEnv)return b(u);return m(u);function p(){if(s===l)return Wc(t,i,s,s.$async);let h=e.scopeValue("root",{ref:l});return Wc(t,(0,It._)`${h}.validate`,l,l.$async)}function b(h){let w=IS(t,h);Wc(t,w,h,h.$async)}function m(h){let w=e.scopeValue("schema",a.code.source===!0?{ref:h,code:(0,It.stringify)(h)}:{ref:h}),S=e.name("valid"),R=t.subschema({schema:h,dataTypes:[],schemaPath:It.nil,topSchemaRef:w,errSchemaPath:r},S);t.mergeEvaluated(R),t.ok(S)}}};function IS(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,It._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Yn.getValidate=IS;function Wc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Fo.default.this:It.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let h=o.let("valid");o.try(()=>{o.code((0,It._)`await ${(0,AS.callValidateCode)(t,e,l)}`),m(e),i||o.assign(h,!0)},w=>{o.if((0,It._)`!(${w} instanceof ${s.ValidationError})`,()=>o.throw(w)),b(w),i||o.assign(h,!1)}),t.ok(h)}function p(){t.result((0,AS.callValidateCode)(t,e,l),()=>m(e),()=>b(e))}function b(h){let w=(0,It._)`${h}.errors`;o.assign(Fo.default.vErrors,(0,It._)`${Fo.default.vErrors} === null ? ${w} : ${Fo.default.vErrors}.concat(${w})`),o.assign(Fo.default.errors,(0,It._)`${Fo.default.vErrors}.length`)}function m(h){var w;if(!s.opts.unevaluated)return;let S=(w=r?.validate)===null||w===void 0?void 0:w.evaluated;if(s.props!==!0)if(S&&!S.dynamicProps)S.props!==void 0&&(s.props=Kc.mergeEvaluated.props(o,S.props,s.props));else{let R=o.var("props",(0,It._)`${h}.evaluated.props`);s.props=Kc.mergeEvaluated.props(o,R,s.props,It.Name)}if(s.items!==!0)if(S&&!S.dynamicItems)S.items!==void 0&&(s.items=Kc.mergeEvaluated.items(o,S.items,s.items));else{let R=o.var("items",(0,It._)`${h}.evaluated.items`);s.items=Kc.mergeEvaluated.items(o,R,s.items,It.Name)}}}Yn.callRef=Wc;Yn.default=WD});var NS=F(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var GD=PS(),JD=OS(),YD=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",GD.default,JD.default];lf.default=YD});var zS=F(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var Gc=me(),dn=Gc.operators,Jc={maximum:{okStr:"<=",ok:dn.LTE,fail:dn.GT},minimum:{okStr:">=",ok:dn.GTE,fail:dn.LT},exclusiveMaximum:{okStr:"<",ok:dn.LT,fail:dn.GTE},exclusiveMinimum:{okStr:">",ok:dn.GT,fail:dn.LTE}},XD={message:({keyword:t,schemaCode:e})=>(0,Gc.str)`must be ${Jc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Gc._)`{comparison: ${Jc[t].okStr}, limit: ${e}}`},QD={keyword:Object.keys(Jc),type:"number",schemaType:"number",$data:!0,error:XD,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Gc._)`${r} ${Jc[e].fail} ${n} || isNaN(${r})`)}};uf.default=QD});var LS=F(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var gi=me(),e1={message:({schemaCode:t})=>(0,gi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,gi._)`{multipleOf: ${t}}`},t1={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:e1,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,gi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,gi._)`${i} !== parseInt(${i})`;t.fail$data((0,gi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};df.default=t1});var DS=F(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});function jS(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}pf.default=jS;jS.code='require("ajv/dist/runtime/ucs2length").default'});var MS=F(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var Xn=me(),r1=$e(),n1=DS(),o1={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Xn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Xn._)`{limit: ${t}}`},s1={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:o1,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Xn.operators.GT:Xn.operators.LT,i=o.opts.unicode===!1?(0,Xn._)`${r}.length`:(0,Xn._)`${(0,r1.useFunc)(t.gen,n1.default)}(${r})`;t.fail$data((0,Xn._)`${i} ${s} ${n}`)}};hf.default=s1});var US=F(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var i1=Kt(),a1=$e(),Zo=me(),c1={message:({schemaCode:t})=>(0,Zo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Zo._)`{pattern: ${t}}`},l1={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:c1,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,Zo._)`new RegExp`:(0,a1.useFunc)(e,c),u=e.let("valid");e.try(()=>e.assign(u,(0,Zo._)`${l}(${s}, ${a}).test(${r})`),()=>e.assign(u,!1)),t.fail$data((0,Zo._)`!${u}`)}else{let c=(0,i1.usePattern)(t,o);t.fail$data((0,Zo._)`!${c}.test(${r})`)}}};mf.default=l1});var qS=F(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var yi=me(),u1={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,yi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,yi._)`{limit: ${t}}`},d1={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:u1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?yi.operators.GT:yi.operators.LT;t.fail$data((0,yi._)`Object.keys(${r}).length ${o} ${n}`)}};ff.default=d1});var BS=F(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var bi=Kt(),wi=me(),p1=$e(),h1={message:({params:{missingProperty:t}})=>(0,wi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,wi._)`{missingProperty: ${t}}`},m1={keyword:"required",type:"object",schemaType:"array",$data:!0,error:h1,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:h}=t.it;for(let w of r)if(m?.[w]===void 0&&!h.has(w)){let S=i.schemaEnv.baseId+i.errSchemaPath,R=`required property "${w}" is not defined at "${S}" (strictRequired)`;(0,p1.checkStrictMode)(i,R,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(wi.nil,p);else for(let m of r)(0,bi.checkReportMissingProp)(t,m)}function u(){let m=e.let("missing");if(c||s){let h=e.let("valid",!0);t.block$data(h,()=>b(m,h)),t.ok(h)}else e.if((0,bi.checkMissingProp)(t,r,m)),(0,bi.reportMissingProp)(t,m),e.else()}function p(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,bi.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function b(m,h){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(h,(0,bi.propertyInData)(e,o,m,a.ownProperties)),e.if((0,wi.not)(h),()=>{t.error(),e.break()})},wi.nil)}}};gf.default=m1});var FS=F(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var _i=me(),f1={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,_i.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,_i._)`{limit: ${t}}`},g1={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:f1,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?_i.operators.GT:_i.operators.LT;t.fail$data((0,_i._)`${r}.length ${o} ${n}`)}};yf.default=g1});var Yc=F(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var ZS=Um();ZS.code='require("ajv/dist/runtime/equal").default';bf.default=ZS});var VS=F(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var wf=ii(),pt=me(),y1=$e(),b1=Yc(),w1={message:({params:{i:t,j:e}})=>(0,pt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,pt._)`{i: ${t}, j: ${e}}`},_1={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:w1,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,wf.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,pt._)`${i} === false`),t.ok(c);function u(){let h=e.let("i",(0,pt._)`${r}.length`),w=e.let("j");t.setParams({i:h,j:w}),e.assign(c,!0),e.if((0,pt._)`${h} > 1`,()=>(p()?b:m)(h,w))}function p(){return l.length>0&&!l.some(h=>h==="object"||h==="array")}function b(h,w){let S=e.name("item"),R=(0,wf.checkDataTypes)(l,S,a.opts.strictNumbers,wf.DataType.Wrong),P=e.const("indices",(0,pt._)`{}`);e.for((0,pt._)`;${h}--;`,()=>{e.let(S,(0,pt._)`${r}[${h}]`),e.if(R,(0,pt._)`continue`),l.length>1&&e.if((0,pt._)`typeof ${S} == "string"`,(0,pt._)`${S} += "_"`),e.if((0,pt._)`typeof ${P}[${S}] == "number"`,()=>{e.assign(w,(0,pt._)`${P}[${S}]`),t.error(),e.assign(c,!1).break()}).code((0,pt._)`${P}[${S}] = ${h}`)})}function m(h,w){let S=(0,y1.useFunc)(e,b1.default),R=e.name("outer");e.label(R).for((0,pt._)`;${h}--;`,()=>e.for((0,pt._)`${w} = ${h}; ${w}--;`,()=>e.if((0,pt._)`${S}(${r}[${h}], ${r}[${w}])`,()=>{t.error(),e.assign(c,!1).break(R)})))}}};_f.default=_1});var HS=F(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var vf=me(),v1=$e(),x1=Yc(),k1={message:"must be equal to constant",params:({schemaCode:t})=>(0,vf._)`{allowedValue: ${t}}`},S1={keyword:"const",$data:!0,error:k1,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,v1.useFunc)(e,x1.default)}(${r}, ${o})`):t.fail((0,vf._)`${s} !== ${r}`)}};xf.default=S1});var KS=F(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var vi=me(),$1=$e(),T1=Yc(),R1={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,vi._)`{allowedValues: ${t}}`},E1={keyword:"enum",schemaType:"array",$data:!0,error:R1,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,$1.useFunc)(e,T1.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let m=e.const("vSchema",s);u=(0,vi.or)(...o.map((h,w)=>b(m,w)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,m=>e.if((0,vi._)`${l()}(${r}, ${m})`,()=>e.assign(u,!0).break()))}function b(m,h){let w=o[h];return typeof w=="object"&&w!==null?(0,vi._)`${l()}(${r}, ${m}[${h}])`:(0,vi._)`${r} === ${w}`}}};kf.default=E1});var WS=F(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var P1=zS(),A1=LS(),C1=MS(),I1=US(),O1=qS(),N1=BS(),z1=FS(),L1=VS(),j1=HS(),D1=KS(),M1=[P1.default,A1.default,C1.default,I1.default,O1.default,N1.default,z1.default,L1.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},j1.default,D1.default];Sf.default=M1});var Tf=F(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.validateAdditionalItems=void 0;var Qn=me(),$f=$e(),U1={message:({params:{len:t}})=>(0,Qn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Qn._)`{limit: ${t}}`},q1={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:U1,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,$f.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}GS(t,n)}};function GS(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Qn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Qn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,$f.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Qn._)`${a} <= ${e.length}`);r.if((0,Qn.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:$f.Type.Num},l),i.allErrors||r.if((0,Qn.not)(l),()=>r.break())})}}xi.validateAdditionalItems=GS;xi.default=q1});var Rf=F(ki=>{"use strict";Object.defineProperty(ki,"__esModule",{value:!0});ki.validateTuple=void 0;var JS=me(),Xc=$e(),B1=Kt(),F1={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return YS(t,"additionalItems",e);r.items=!0,!(0,Xc.alwaysValidSchema)(r,e)&&t.ok((0,B1.validateArray)(t))}};function YS(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=Xc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,JS._)`${s}.length`);r.forEach((p,b)=>{(0,Xc.alwaysValidSchema)(a,p)||(n.if((0,JS._)`${l} > ${b}`,()=>t.subschema({keyword:i,schemaProp:b,dataProp:b},c)),t.ok(c))});function u(p){let{opts:b,errSchemaPath:m}=a,h=r.length,w=h===p.minItems&&(h===p.maxItems||p[e]===!1);if(b.strictTuples&&!w){let S=`"${i}" is ${h}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,Xc.checkStrictMode)(a,S,b.strictTuples)}}}ki.validateTuple=YS;ki.default=F1});var XS=F(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var Z1=Rf(),V1={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Z1.validateTuple)(t,"items")};Ef.default=V1});var e$=F(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var QS=me(),H1=$e(),K1=Kt(),W1=Tf(),G1={message:({params:{len:t}})=>(0,QS.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,QS._)`{limit: ${t}}`},J1={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:G1,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,H1.alwaysValidSchema)(n,e)&&(o?(0,W1.validateAdditionalItems)(t,o):t.ok((0,K1.validateArray)(t)))}};Pf.default=J1});var t$=F(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var Gt=me(),Qc=$e(),Y1={message:({params:{min:t,max:e}})=>e===void 0?(0,Gt.str)`must contain at least ${t} valid item(s)`:(0,Gt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Gt._)`{minContains: ${t}}`:(0,Gt._)`{minContains: ${t}, maxContains: ${e}}`},X1={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Y1,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,Gt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Qc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Qc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Qc.alwaysValidSchema)(s,r)){let w=(0,Gt._)`${u} >= ${i}`;a!==void 0&&(w=(0,Gt._)`${w} && ${u} <= ${a}`),t.pass(w);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?m(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,Gt._)`${o}.length > 0`,b)):(e.let(p,!1),b()),t.result(p,()=>t.reset());function b(){let w=e.name("_valid"),S=e.let("count",0);m(w,()=>e.if(w,()=>h(S)))}function m(w,S){e.forRange("i",0,u,R=>{t.subschema({keyword:"contains",dataProp:R,dataPropType:Qc.Type.Num,compositeRule:!0},w),S()})}function h(w){e.code((0,Gt._)`${w}++`),a===void 0?e.if((0,Gt._)`${w} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,Gt._)`${w} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,Gt._)`${w} >= ${i}`,()=>e.assign(p,!0)))}}};Af.default=X1});var o$=F(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.validateSchemaDeps=xr.validatePropertyDeps=xr.error=void 0;var Cf=me(),Q1=$e(),Si=Kt();xr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Cf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Cf._)`{property: ${t},
2058
2058
  missingProperty: ${n},
2059
2059
  depsCount: ${e},
2060
- deps: ${r}}`};var j1={keyword:"dependencies",type:"object",schemaType:"object",error:vr.error,code(t){let[e,r]=D1(t);VS(t,e),HS(t,r)}};function D1({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 VS(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,vi.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,vi.checkReportMissingProp)(t,l)}):(r.if((0,Ef._)`${c} && (${(0,vi.checkMissingProp)(t,a,s)})`),(0,vi.reportMissingProp)(t,s),r.else())}}vr.validatePropertyDeps=VS;function HS(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,L1.alwaysValidSchema)(s,e[a])||(r.if((0,vi.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))}vr.validateSchemaDeps=HS;vr.default=j1});var GS=B(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var WS=me(),M1=$e(),U1={message:"property name must be valid",params:({params:t})=>(0,WS._)`{propertyName: ${t.propertyName}}`},q1={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:U1,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,M1.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,WS.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Pf.default=q1});var Cf=B(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var Xc=Ht(),cr=me(),F1=Lr(),Qc=$e(),B1={message:"must NOT have additional properties",params:({params:t})=>(0,cr._)`{additionalProperty: ${t.additionalProperty}}`},Z1={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:B1,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,Qc.alwaysValidSchema)(i,r))return;let l=(0,Xc.allSchemaProperties)(n.properties),u=(0,Xc.allSchemaProperties)(n.patternProperties);p(),t.ok((0,cr._)`${s} === ${F1.default.errors}`);function p(){e.forIn("key",o,S=>{!l.length&&!u.length?m(S):e.if(y(S),()=>m(S))})}function y(S){let R;if(l.length>8){let P=(0,Qc.schemaRefOrVal)(i,n.properties,"properties");R=(0,Xc.isOwnProperty)(e,P,S)}else l.length?R=(0,cr.or)(...l.map(P=>(0,cr._)`${S} === ${P}`)):R=cr.nil;return u.length&&(R=(0,cr.or)(R,...u.map(P=>(0,cr._)`${(0,Xc.usePattern)(t,P)}.test(${S})`))),(0,cr.not)(R)}function h(S){e.code((0,cr._)`delete ${o}[${S}]`)}function m(S){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(S);return}if(r===!1){t.setParams({additionalProperty:S}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Qc.alwaysValidSchema)(i,r)){let R=e.name("valid");c.removeAdditional==="failing"?(w(S,R,!1),e.if((0,cr.not)(R),()=>{t.reset(),h(S)})):(w(S,R),a||e.if((0,cr.not)(R),()=>e.break()))}}function w(S,R,P){let z={keyword:"additionalProperties",dataProp:S,dataPropType:Qc.Type.Str};P===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,R)}}};Af.default=Z1});var XS=B(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var V1=ai(),JS=Ht(),If=$e(),YS=Cf(),H1={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&&YS.default.code(new V1.KeywordCxt(s,YS.default,"additionalProperties"));let i=(0,JS.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=If.mergeEvaluated.props(e,(0,If.toHash)(i),s.props));let a=i.filter(p=>!(0,If.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,JS.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)}}};Of.default=H1});var r$=B(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var QS=Ht(),el=me(),e$=$e(),t$=$e(),K1={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,QS.allSchemaProperties)(r),c=a.filter(w=>(0,e$.alwaysValidSchema)(s,r[w]));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 el.Name)&&(s.props=(0,t$.evaluatedPropsToName)(e,s.props));let{props:p}=s;y();function y(){for(let w of a)l&&h(w),s.allErrors?m(w):(e.var(u,!0),m(w),e.if(u))}function h(w){for(let S in l)new RegExp(w).test(S)&&(0,e$.checkStrictMode)(s,`property ${S} matches pattern ${w} (use allowMatchingProperties)`)}function m(w){e.forIn("key",n,S=>{e.if((0,el._)`${(0,QS.usePattern)(t,w)}.test(${S})`,()=>{let R=c.includes(w);R||t.subschema({keyword:"patternProperties",schemaProp:w,dataProp:S,dataPropType:t$.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,el._)`${p}[${S}]`,!0):!R&&!s.allErrors&&e.if((0,el.not)(u),()=>e.break())})})}}};Nf.default=K1});var n$=B(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var W1=$e(),G1={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,W1.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"}};zf.default=G1});var o$=B(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var J1=Ht(),Y1={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:J1.validateUnion,error:{message:"must match a schema in anyOf"}};Lf.default=Y1});var s$=B(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var tl=me(),X1=$e(),Q1={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,tl._)`{passingSchemas: ${t.passing}}`},eM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Q1,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 y;(0,X1.alwaysValidSchema)(o,u)?e.var(c,!0):y=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,tl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,tl._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),y&&t.mergeEvaluated(y,tl.Name)})})}}};jf.default=eM});var i$=B(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var tM=$e(),rM={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,tM.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Df.default=rM});var l$=B(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var rl=me(),c$=$e(),nM={message:({params:t})=>(0,rl.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,rl._)`{failingKeyword: ${t.ifClause}}`},oM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:nM,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,c$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=a$(n,"then"),s=a$(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,rl.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 y=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(y,i),p?e.assign(p,(0,rl._)`${u}`):t.setParams({ifClause:u})}}}};function a$(t,e){let r=t.schema[e];return r!==void 0&&!(0,c$.alwaysValidSchema)(t,r)}Mf.default=oM});var u$=B(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var sM=$e(),iM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,sM.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Uf.default=iM});var d$=B(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var aM=kf(),cM=qS(),lM=Sf(),uM=BS(),dM=ZS(),pM=KS(),mM=GS(),hM=Cf(),fM=XS(),gM=r$(),yM=n$(),bM=o$(),wM=s$(),_M=i$(),vM=l$(),xM=u$();function kM(t=!1){let e=[yM.default,bM.default,wM.default,_M.default,vM.default,xM.default,mM.default,hM.default,pM.default,fM.default,gM.default];return t?e.push(cM.default,uM.default):e.push(aM.default,lM.default),e.push(dM.default),e}qf.default=kM});var p$=B(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var We=me(),SM={message:({schemaCode:t})=>(0,We.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,We._)`{format: ${t}}`},$M={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:SM,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?y():h();function y(){let m=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),w=r.const("fDef",(0,We._)`${m}[${i}]`),S=r.let("fType"),R=r.let("format");r.if((0,We._)`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>r.assign(S,(0,We._)`${w}.type || "string"`).assign(R,(0,We._)`${w}.validate`),()=>r.assign(S,(0,We._)`"string"`).assign(R,w)),t.fail$data((0,We.or)(P(),z()));function P(){return c.strictSchema===!1?We.nil:(0,We._)`${i} && !${R}`}function z(){let F=u.$async?(0,We._)`(${w}.async ? await ${R}(${n}) : ${R}(${n}))`:(0,We._)`${R}(${n})`,W=(0,We._)`(typeof ${R} == "function" ? ${F} : ${R}.test(${n}))`;return(0,We._)`${R} && ${R} !== true && ${S} === ${e} && !${W}`}}function h(){let m=p.formats[s];if(!m){P();return}if(m===!0)return;let[w,S,R]=z(m);w===e&&t.pass(F());function P(){if(c.strictSchema===!1){p.logger.warn(W());return}throw new Error(W());function W(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(W){let Ke=W instanceof RegExp?(0,We.regexpCode)(W):c.code.formats?(0,We._)`${c.code.formats}${(0,We.getProperty)(s)}`:void 0,Ye=r.scopeValue("formats",{key:s,ref:W,code:Ke});return typeof W=="object"&&!(W instanceof RegExp)?[W.type||"string",W.validate,(0,We._)`${Ye}.validate`]:["string",W,Ye]}function F(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,We._)`await ${R}(${n})`}return typeof S=="function"?(0,We._)`${R}(${n})`:(0,We._)`${R}.test(${n})`}}}};Ff.default=$M});var m$=B(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var TM=p$(),RM=[TM.default];Bf.default=RM});var h$=B(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.contentVocabulary=Zo.metadataVocabulary=void 0;Zo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Zo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var g$=B(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var EM=kS(),PM=jS(),AM=d$(),CM=m$(),f$=h$(),IM=[EM.default,PM.default,(0,AM.default)(),CM.default,f$.metadataVocabulary,f$.contentVocabulary];Zf.default=IM});var b$=B(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.DiscrError=void 0;var y$;(function(t){t.Tag="tag",t.Mapping="mapping"})(y$||(nl.DiscrError=y$={}))});var _$=B(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var Vo=me(),Vf=b$(),w$=Dc(),OM=ci(),NM=$e(),zM={message:({params:{discrError:t,tagName:e}})=>t===Vf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Vo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},LM={keyword:"discriminator",type:"object",schemaType:"object",error:zM,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,Vo._)`${r}${(0,Vo.getProperty)(a)}`);e.if((0,Vo._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Vf.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let h=y();e.if(!1);for(let m in h)e.elseIf((0,Vo._)`${l} === ${m}`),e.assign(c,p(h[m]));e.else(),t.error(!1,{discrError:Vf.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(h){let m=e.name("valid"),w=t.subschema({keyword:"oneOf",schemaProp:h},m);return t.mergeEvaluated(w,Vo.Name),m}function y(){var h;let m={},w=R(o),S=!0;for(let F=0;F<i.length;F++){let W=i[F];if(W?.$ref&&!(0,NM.schemaHasRulesButRef)(W,s.self.RULES)){let Ye=W.$ref;if(W=w$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ye),W instanceof w$.SchemaEnv&&(W=W.schema),W===void 0)throw new OM.default(s.opts.uriResolver,s.baseId,Ye)}let Ke=(h=W?.properties)===null||h===void 0?void 0:h[a];if(typeof Ke!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);S=S&&(w||R(W)),P(Ke,F)}if(!S)throw new Error(`discriminator: "${a}" must be required`);return m;function R({required:F}){return Array.isArray(F)&&F.includes(a)}function P(F,W){if(F.const)z(F.const,W);else if(F.enum)for(let Ke of F.enum)z(Ke,W);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(F,W){if(typeof F!="string"||F in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[F]=W}}}};Hf.default=LM});var v$=B((pW,jM)=>{jM.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 Wf=B((Me,Kf)=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.MissingRefError=Me.ValidationError=Me.CodeGen=Me.Name=Me.nil=Me.stringify=Me.str=Me._=Me.KeywordCxt=Me.Ajv=void 0;var DM=yS(),MM=g$(),UM=_$(),x$=v$(),qM=["/properties"],ol="http://json-schema.org/draft-07/schema",Ho=class extends DM.default{_addVocabularies(){super._addVocabularies(),MM.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(UM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(x$,qM):x$;this.addMetaSchema(e,ol,!1),this.refs["http://json-schema.org/schema"]=ol}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ol)?ol:void 0)}};Me.Ajv=Ho;Kf.exports=Me=Ho;Kf.exports.Ajv=Ho;Object.defineProperty(Me,"__esModule",{value:!0});Me.default=Ho;var FM=ai();Object.defineProperty(Me,"KeywordCxt",{enumerable:!0,get:function(){return FM.KeywordCxt}});var Ko=me();Object.defineProperty(Me,"_",{enumerable:!0,get:function(){return Ko._}});Object.defineProperty(Me,"str",{enumerable:!0,get:function(){return Ko.str}});Object.defineProperty(Me,"stringify",{enumerable:!0,get:function(){return Ko.stringify}});Object.defineProperty(Me,"nil",{enumerable:!0,get:function(){return Ko.nil}});Object.defineProperty(Me,"Name",{enumerable:!0,get:function(){return Ko.Name}});Object.defineProperty(Me,"CodeGen",{enumerable:!0,get:function(){return Ko.CodeGen}});var BM=Lc();Object.defineProperty(Me,"ValidationError",{enumerable:!0,get:function(){return BM.default}});var ZM=ci();Object.defineProperty(Me,"MissingRefError",{enumerable:!0,get:function(){return ZM.default}})});var A$=B(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.formatNames=kr.fastFormats=kr.fullFormats=void 0;function xr(t,e){return{validate:t,compare:e}}kr.fullFormats={date:xr(T$,Xf),time:xr(Jf(!0),Qf),"date-time":xr(k$(!0),E$),"iso-time":xr(Jf(),R$),"iso-date-time":xr(k$(),P$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:JM,"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:nU,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:YM,int32:{type:"number",validate:eU},int64:{type:"number",validate:tU},float:{type:"number",validate:$$},double:{type:"number",validate:$$},password:!0,binary:!0};kr.fastFormats={...kr.fullFormats,date:xr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Xf),time:xr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Qf),"date-time":xr(/^\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,E$),"iso-time":xr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,R$),"iso-date-time":xr(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,P$),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};kr.formatNames=Object.keys(kr.fullFormats);function VM(t){return t%4===0&&(t%100!==0||t%400===0)}var HM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,KM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function T$(t){let e=HM.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&&VM(r)?29:KM[n])}function Xf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Gf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Jf(t){return function(r){let n=Gf.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,y=o-l*c-(p<0?1:0);return(y===23||y===-1)&&(p===59||p===-1)&&i<61}}function Qf(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 R$(t,e){if(!(t&&e))return;let r=Gf.exec(t),n=Gf.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 Yf=/t|\s/i;function k$(t){let e=Jf(t);return function(n){let o=n.split(Yf);return o.length===2&&T$(o[0])&&e(o[1])}}function E$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function P$(t,e){if(!(t&&e))return;let[r,n]=t.split(Yf),[o,s]=e.split(Yf),i=Xf(r,o);if(i!==void 0)return i||Qf(n,s)}var WM=/\/|:/,GM=/^(?:[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 JM(t){return WM.test(t)&&GM.test(t)}var S$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function YM(t){return S$.lastIndex=0,S$.test(t)}var XM=-(2**31),QM=2**31-1;function eU(t){return Number.isInteger(t)&&t<=QM&&t>=XM}function tU(t){return Number.isInteger(t)}function $$(){return!0}var rU=/[^\\]\\Z/;function nU(t){if(rU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var C$=B(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.formatLimitDefinition=void 0;var oU=Wf(),lr=me(),dn=lr.operators,sl={formatMaximum:{okStr:"<=",ok:dn.LTE,fail:dn.GT},formatMinimum:{okStr:">=",ok:dn.GTE,fail:dn.LT},formatExclusiveMaximum:{okStr:"<",ok:dn.LT,fail:dn.GTE},formatExclusiveMinimum:{okStr:">",ok:dn.GT,fail:dn.LTE}},sU={message:({keyword:t,schemaCode:e})=>(0,lr.str)`should be ${sl[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,lr._)`{comparison: ${sl[t].okStr}, limit: ${e}}`};Wo.formatLimitDefinition={keyword:Object.keys(sl),type:"string",schemaType:"string",$data:!0,error:sU,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 oU.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let y=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,lr._)`${y}[${c.schemaCode}]`);t.fail$data((0,lr.or)((0,lr._)`typeof ${h} != "object"`,(0,lr._)`${h} instanceof RegExp`,(0,lr._)`typeof ${h}.compare != "function"`,p(h)))}function u(){let y=c.schema,h=a.formats[y];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${o}": format "${y}" does not define "compare" function`);let m=e.scopeValue("formats",{key:y,ref:h,code:i.code.formats?(0,lr._)`${i.code.formats}${(0,lr.getProperty)(y)}`:void 0});t.fail$data(p(m))}function p(y){return(0,lr._)`${y}.compare(${r}, ${n}) ${sl[o].fail} 0`}},dependencies:["format"]};var iU=t=>(t.addKeyword(Wo.formatLimitDefinition),t);Wo.default=iU});var z$=B((xi,N$)=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});var Go=A$(),aU=C$(),eg=me(),I$=new eg.Name("fullFormats"),cU=new eg.Name("fastFormats"),tg=(t,e={keywords:!0})=>{if(Array.isArray(e))return O$(t,e,Go.fullFormats,I$),t;let[r,n]=e.mode==="fast"?[Go.fastFormats,cU]:[Go.fullFormats,I$],o=e.formats||Go.formatNames;return O$(t,o,r,n),e.keywords&&(0,aU.default)(t),t};tg.get=(t,e="full")=>{let n=(e==="fast"?Go.fastFormats:Go.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function O$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,eg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}N$.exports=xi=tg;Object.defineProperty(xi,"__esModule",{value:!0});xi.default=tg});function lU(){let t=new L$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,j$.default)(t),t}var L$,j$,il,D$=O(()=>{L$=_l(Wf(),1),j$=_l(z$(),1);il=class{constructor(e){this._ajv=e??lU()}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 al,M$=O(()=>{Io();al=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(y=>y.type==="tool_use").map(y=>y.id)),p=new Set(s.filter(y=>y.type==="tool_result").map(y=>y.toolUseId));if(u.size!==p.size||![...u].every(y=>p.has(y)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Hs,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},Co,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 U$(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 q$(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 F$=O(()=>{});var cl,B$=O(()=>{Hx();Io();D$();Ns();M$();F$();cl=class extends kc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Vs.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 il,this.setRequestHandler(hm,n=>this._oninitialize(n)),this.setNotificationHandler(fm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(xm,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Vs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new al(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Vx(this._capabilities,e)}setRequestHandler(e,r){let o=Qr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=To(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=Xr(Ao,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new Y(re.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,y=await Promise.resolve(r(c,l));if(p.task){let m=Xr(Eo,y);if(!m.success){let w=m.error instanceof Error?m.error.message:String(m.error);throw new Y(re.InvalidParams,`Invalid task creation result: ${w}`)}return m.data}let h=Xr(dc,y);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new Y(re.InvalidParams,`Invalid tools/call result: ${m}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){q$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&U$(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:Vv.includes(r)?r:lm,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"},Ga)}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},km,r):this.request({method:"sampling/createMessage",params:e},Hs,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},Co,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},Co,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new Y(re.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof Y?i:new Y(re.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},Sm,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 rg(t){return!!t&&typeof t=="object"&&V$ in t}function H$(t){return t[V$]?.complete}var V$,Z$,K$=O(()=>{V$=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Z$||(Z$={}))});var W$=O(()=>{});function dU(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"),!uU.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 pU(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 ng(t){let e=dU(t);return pU(t,e.warnings),e.isValid}var uU,G$=O(()=>{uU=/^[A-Za-z0-9._-]{1,128}$/});var ll,J$=O(()=>{ll=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 Q$(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function eT(t){return"_def"in t||"_zod"in t||Q$(t)}function og(t){return typeof t!="object"||t===null||eT(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Q$)}function Y$(t){if(t){if(og(t))return qn(t);if(!eT(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function hU(t){let e=Qr(t);return e?Object.entries(e).map(([r,n])=>{let o=gv(n),s=yv(n);return{name:r,description:o,required:!s}}):[]}function pn(t){let r=Qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=To(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function X$(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ul,mU,ki,tT=O(()=>{B$();Ns();ah();Io();K$();W$();G$();J$();Cn();ul=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 cl(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ll(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(pn(uc)),this.server.assertCanSetRequestHandler(pn(Ao)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(uc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=$o(r.inputSchema);return o?oh(o,{strictUnions:!0,pipeStrategy:"input"}):mU})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=$o(r.outputSchema);o&&(n.outputSchema=oh(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ao,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new Y(re.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new Y(re.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 Y(re.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new Y(re.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 Y&&n.code===re.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=$o(e.inputSchema)??e.inputSchema,i=await Fa(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ba(a);throw new Y(re.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 Y(re.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=$o(e.outputSchema),s=await Fa(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ba(i);throw new Y(re.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(y=>setTimeout(y,u));let p=await n.taskStore.getTask(c);if(!p)throw new Y(re.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(pn(pc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(pc,async e=>{switch(e.params.ref.type){case"ref/prompt":return ax(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return cx(e),this.handleResourceCompletion(e,e.params.ref);default:throw new Y(re.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new Y(re.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new Y(re.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ki;let s=Qr(n.argsSchema)?.[e.params.argument.name];if(!rg(s))return ki;let i=H$(s);if(!i)return ki;let a=await i(e.params.argument.value,e.params.context);return X$(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 ki;throw new Y(re.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return ki;let s=await o(e.params.argument.value,e.params.context);return X$(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(pn(sc)),this.server.assertCanSetRequestHandler(pn(ic)),this.server.assertCanSetRequestHandler(pn(ac)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(sc,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(ic,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ac,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new Y(re.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 Y(re.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(pn(cc)),this.server.assertCanSetRequestHandler(pn(lc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(cc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?hU(r.argsSchema):void 0}))})),this.server.setRequestHandler(lc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new Y(re.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new Y(re.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=$o(n.argsSchema),s=await Fa(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Ba(c);throw new Y(re.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:qn(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=qn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof xt?c._def?.innerType:c;return rg(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){ng(e);let u={title:r,description:n,inputSchema:Y$(o),outputSchema:Y$(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"&&ng(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=qn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=qn(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(og(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!og(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()}},mU={type:"object",properties:{}};ki={completion:{values:[],hasMore:!1}}});function gU(t){return Qv.parse(JSON.parse(t))}function rT(t){return JSON.stringify(t)+`
2061
- `}var fU,dl,nT=O(()=>{Io();fU=10*1024*1024,dl=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??fU}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(`
2062
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),gU(r)}clear(){this._buffer=void 0}}});import oT from"node:process";var pl,sT=O(()=>{nT();pl=class{constructor(e=oT.stdin,r=oT.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 dl({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=rT(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var iT,aT=O(()=>{iT=[]});var gT={};Xo(gT,{AUTHORING_MCP_SERVER_NAME:()=>dT,AUTHORING_MCP_SERVER_VERSION:()=>pT,AUTHORING_RESOURCES:()=>kU,AUTHORING_TOOLS:()=>xU,AUTHORING_TOOLS_PUBLIC:()=>fT,buildAuthoringMcpServer:()=>hT,resolveSamplesDir:()=>mT,runAuthoringMcpServer:()=>SU});import{promises as yU}from"node:fs";import{isAbsolute as bU,resolve as ml,sep as wU}from"node:path";function uT(){return lT??=import("../mcp/grounding.js").then(e=>e,()=>null),lT}function mT(t,e){if(e===void 0)return ml(process.cwd(),t??"samples");let r=ml(e);if(t===void 0)return r;if(bU(t))return null;let n=ml(r,t);return n===r||n.startsWith(r+wU)?n:null}function He(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function vU(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 hT(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let h=await Xt(t.baseUrl);if(!h)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:h.baseUrl,token:h.token}}let r=t.grounding??{},n=await uT(),o=null;if(n)try{let h=await e();o={surface:"mcp-authoring",baseUrl:h.baseUrl,token:h.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],c=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{c=(await n.listRecipesForSurface(o,i)).map(h=>({id:h.id,record_type:h.record_type,intent:h.intent}))}catch{c=[]}}let l=o?await vU(o,r):null,u=new ul({name:dT,version:pT},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(h=>h.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let h=o;for(let m of a)u.registerPrompt(m.id,{title:m.name,description:m.description},async()=>{let w=await n.getMcpPromptSkill(h,m.id,r);if(!w)throw new Error(`unknown prompt: ${m.id}`);return{description:w.description,messages:[{role:"user",content:{type:"text",text:(w.prompts??[]).join(`
2060
+ deps: ${r}}`};var eM={keyword:"dependencies",type:"object",schemaType:"object",error:xr.error,code(t){let[e,r]=tM(t);r$(t,e),n$(t,r)}};function tM({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 r$(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,Si.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,Si.checkReportMissingProp)(t,l)}):(r.if((0,Cf._)`${c} && (${(0,Si.checkMissingProp)(t,a,s)})`),(0,Si.reportMissingProp)(t,s),r.else())}}xr.validatePropertyDeps=r$;function n$(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,Q1.alwaysValidSchema)(s,e[a])||(r.if((0,Si.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))}xr.validateSchemaDeps=n$;xr.default=eM});var i$=F(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var s$=me(),rM=$e(),nM={message:"property name must be valid",params:({params:t})=>(0,s$._)`{propertyName: ${t.propertyName}}`},oM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:nM,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,rM.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,s$.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};If.default=oM});var Nf=F(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var el=Kt(),lr=me(),sM=jr(),tl=$e(),iM={message:"must NOT have additional properties",params:({params:t})=>(0,lr._)`{additionalProperty: ${t.additionalProperty}}`},aM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:iM,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,tl.alwaysValidSchema)(i,r))return;let l=(0,el.allSchemaProperties)(n.properties),u=(0,el.allSchemaProperties)(n.patternProperties);p(),t.ok((0,lr._)`${s} === ${sM.default.errors}`);function p(){e.forIn("key",o,S=>{!l.length&&!u.length?h(S):e.if(b(S),()=>h(S))})}function b(S){let R;if(l.length>8){let P=(0,tl.schemaRefOrVal)(i,n.properties,"properties");R=(0,el.isOwnProperty)(e,P,S)}else l.length?R=(0,lr.or)(...l.map(P=>(0,lr._)`${S} === ${P}`)):R=lr.nil;return u.length&&(R=(0,lr.or)(R,...u.map(P=>(0,lr._)`${(0,el.usePattern)(t,P)}.test(${S})`))),(0,lr.not)(R)}function m(S){e.code((0,lr._)`delete ${o}[${S}]`)}function h(S){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(S);return}if(r===!1){t.setParams({additionalProperty:S}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,tl.alwaysValidSchema)(i,r)){let R=e.name("valid");c.removeAdditional==="failing"?(w(S,R,!1),e.if((0,lr.not)(R),()=>{t.reset(),m(S)})):(w(S,R),a||e.if((0,lr.not)(R),()=>e.break()))}}function w(S,R,P){let z={keyword:"additionalProperties",dataProp:S,dataPropType:tl.Type.Str};P===!1&&Object.assign(z,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(z,R)}}};Of.default=aM});var l$=F(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var cM=ui(),a$=Kt(),zf=$e(),c$=Nf(),lM={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&&c$.default.code(new cM.KeywordCxt(s,c$.default,"additionalProperties"));let i=(0,a$.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=zf.mergeEvaluated.props(e,(0,zf.toHash)(i),s.props));let a=i.filter(p=>!(0,zf.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,a$.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)}}};Lf.default=lM});var h$=F(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var u$=Kt(),rl=me(),d$=$e(),p$=$e(),uM={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,u$.allSchemaProperties)(r),c=a.filter(w=>(0,d$.alwaysValidSchema)(s,r[w]));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 rl.Name)&&(s.props=(0,p$.evaluatedPropsToName)(e,s.props));let{props:p}=s;b();function b(){for(let w of a)l&&m(w),s.allErrors?h(w):(e.var(u,!0),h(w),e.if(u))}function m(w){for(let S in l)new RegExp(w).test(S)&&(0,d$.checkStrictMode)(s,`property ${S} matches pattern ${w} (use allowMatchingProperties)`)}function h(w){e.forIn("key",n,S=>{e.if((0,rl._)`${(0,u$.usePattern)(t,w)}.test(${S})`,()=>{let R=c.includes(w);R||t.subschema({keyword:"patternProperties",schemaProp:w,dataProp:S,dataPropType:p$.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,rl._)`${p}[${S}]`,!0):!R&&!s.allErrors&&e.if((0,rl.not)(u),()=>e.break())})})}}};jf.default=uM});var m$=F(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var dM=$e(),pM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,dM.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"}};Df.default=pM});var f$=F(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var hM=Kt(),mM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:hM.validateUnion,error:{message:"must match a schema in anyOf"}};Mf.default=mM});var g$=F(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var nl=me(),fM=$e(),gM={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,nl._)`{passingSchemas: ${t.passing}}`},yM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:gM,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 b;(0,fM.alwaysValidSchema)(o,u)?e.var(c,!0):b=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,nl._)`${c} && ${i}`).assign(i,!1).assign(a,(0,nl._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),b&&t.mergeEvaluated(b,nl.Name)})})}}};Uf.default=yM});var y$=F(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var bM=$e(),wM={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,bM.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};qf.default=wM});var _$=F(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var ol=me(),w$=$e(),_M={message:({params:t})=>(0,ol.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ol._)`{failingKeyword: ${t.ifClause}}`},vM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:_M,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,w$.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=b$(n,"then"),s=b$(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,ol.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 b=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(b,i),p?e.assign(p,(0,ol._)`${u}`):t.setParams({ifClause:u})}}}};function b$(t,e){let r=t.schema[e];return r!==void 0&&!(0,w$.alwaysValidSchema)(t,r)}Bf.default=vM});var v$=F(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var xM=$e(),kM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,xM.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Ff.default=kM});var x$=F(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var SM=Tf(),$M=XS(),TM=Rf(),RM=e$(),EM=t$(),PM=o$(),AM=i$(),CM=Nf(),IM=l$(),OM=h$(),NM=m$(),zM=f$(),LM=g$(),jM=y$(),DM=_$(),MM=v$();function UM(t=!1){let e=[NM.default,zM.default,LM.default,jM.default,DM.default,MM.default,AM.default,CM.default,PM.default,IM.default,OM.default];return t?e.push($M.default,RM.default):e.push(SM.default,TM.default),e.push(EM.default),e}Zf.default=UM});var k$=F(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var Ye=me(),qM={message:({schemaCode:t})=>(0,Ye.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ye._)`{format: ${t}}`},BM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:qM,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?b():m();function b(){let h=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),w=r.const("fDef",(0,Ye._)`${h}[${i}]`),S=r.let("fType"),R=r.let("format");r.if((0,Ye._)`typeof ${w} == "object" && !(${w} instanceof RegExp)`,()=>r.assign(S,(0,Ye._)`${w}.type || "string"`).assign(R,(0,Ye._)`${w}.validate`),()=>r.assign(S,(0,Ye._)`"string"`).assign(R,w)),t.fail$data((0,Ye.or)(P(),z()));function P(){return c.strictSchema===!1?Ye.nil:(0,Ye._)`${i} && !${R}`}function z(){let B=u.$async?(0,Ye._)`(${w}.async ? await ${R}(${n}) : ${R}(${n}))`:(0,Ye._)`${R}(${n})`,K=(0,Ye._)`(typeof ${R} == "function" ? ${B} : ${R}.test(${n}))`;return(0,Ye._)`${R} && ${R} !== true && ${S} === ${e} && !${K}`}}function m(){let h=p.formats[s];if(!h){P();return}if(h===!0)return;let[w,S,R]=z(h);w===e&&t.pass(B());function P(){if(c.strictSchema===!1){p.logger.warn(K());return}throw new Error(K());function K(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function z(K){let Ge=K instanceof RegExp?(0,Ye.regexpCode)(K):c.code.formats?(0,Ye._)`${c.code.formats}${(0,Ye.getProperty)(s)}`:void 0,Je=r.scopeValue("formats",{key:s,ref:K,code:Ge});return typeof K=="object"&&!(K instanceof RegExp)?[K.type||"string",K.validate,(0,Ye._)`${Je}.validate`]:["string",K,Je]}function B(){if(typeof h=="object"&&!(h instanceof RegExp)&&h.async){if(!u.$async)throw new Error("async format in sync schema");return(0,Ye._)`await ${R}(${n})`}return typeof S=="function"?(0,Ye._)`${R}(${n})`:(0,Ye._)`${R}.test(${n})`}}}};Vf.default=BM});var S$=F(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var FM=k$(),ZM=[FM.default];Hf.default=ZM});var $$=F(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.contentVocabulary=Vo.metadataVocabulary=void 0;Vo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Vo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var R$=F(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var VM=NS(),HM=WS(),KM=x$(),WM=S$(),T$=$$(),GM=[VM.default,HM.default,(0,KM.default)(),WM.default,T$.metadataVocabulary,T$.contentVocabulary];Kf.default=GM});var P$=F(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});sl.DiscrError=void 0;var E$;(function(t){t.Tag="tag",t.Mapping="mapping"})(E$||(sl.DiscrError=E$={}))});var C$=F(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var Ho=me(),Wf=P$(),A$=Uc(),JM=di(),YM=$e(),XM={message:({params:{discrError:t,tagName:e}})=>t===Wf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Ho._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},QM={keyword:"discriminator",type:"object",schemaType:"object",error:XM,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,Ho._)`${r}${(0,Ho.getProperty)(a)}`);e.if((0,Ho._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Wf.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let m=b();e.if(!1);for(let h in m)e.elseIf((0,Ho._)`${l} === ${h}`),e.assign(c,p(m[h]));e.else(),t.error(!1,{discrError:Wf.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(m){let h=e.name("valid"),w=t.subschema({keyword:"oneOf",schemaProp:m},h);return t.mergeEvaluated(w,Ho.Name),h}function b(){var m;let h={},w=R(o),S=!0;for(let B=0;B<i.length;B++){let K=i[B];if(K?.$ref&&!(0,YM.schemaHasRulesButRef)(K,s.self.RULES)){let Je=K.$ref;if(K=A$.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Je),K instanceof A$.SchemaEnv&&(K=K.schema),K===void 0)throw new JM.default(s.opts.uriResolver,s.baseId,Je)}let Ge=(m=K?.properties)===null||m===void 0?void 0:m[a];if(typeof Ge!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);S=S&&(w||R(K)),P(Ge,B)}if(!S)throw new Error(`discriminator: "${a}" must be required`);return h;function R({required:B}){return Array.isArray(B)&&B.includes(a)}function P(B,K){if(B.const)z(B.const,K);else if(B.enum)for(let Ge of B.enum)z(Ge,K);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function z(B,K){if(typeof B!="string"||B in h)throw new Error(`discriminator: "${a}" values must be unique strings`);h[B]=K}}}};Gf.default=QM});var I$=F((IW,eU)=>{eU.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 Yf=F((qe,Jf)=>{"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 tU=ES(),rU=R$(),nU=C$(),O$=I$(),oU=["/properties"],il="http://json-schema.org/draft-07/schema",Ko=class extends tU.default{_addVocabularies(){super._addVocabularies(),rU.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(nU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(O$,oU):O$;this.addMetaSchema(e,il,!1),this.refs["http://json-schema.org/schema"]=il}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(il)?il:void 0)}};qe.Ajv=Ko;Jf.exports=qe=Ko;Jf.exports.Ajv=Ko;Object.defineProperty(qe,"__esModule",{value:!0});qe.default=Ko;var sU=ui();Object.defineProperty(qe,"KeywordCxt",{enumerable:!0,get:function(){return sU.KeywordCxt}});var Wo=me();Object.defineProperty(qe,"_",{enumerable:!0,get:function(){return Wo._}});Object.defineProperty(qe,"str",{enumerable:!0,get:function(){return Wo.str}});Object.defineProperty(qe,"stringify",{enumerable:!0,get:function(){return Wo.stringify}});Object.defineProperty(qe,"nil",{enumerable:!0,get:function(){return Wo.nil}});Object.defineProperty(qe,"Name",{enumerable:!0,get:function(){return Wo.Name}});Object.defineProperty(qe,"CodeGen",{enumerable:!0,get:function(){return Wo.CodeGen}});var iU=Dc();Object.defineProperty(qe,"ValidationError",{enumerable:!0,get:function(){return iU.default}});var aU=di();Object.defineProperty(qe,"MissingRefError",{enumerable:!0,get:function(){return aU.default}})});var q$=F(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.formatNames=Sr.fastFormats=Sr.fullFormats=void 0;function kr(t,e){return{validate:t,compare:e}}Sr.fullFormats={date:kr(j$,tg),time:kr(Qf(!0),rg),"date-time":kr(N$(!0),M$),"iso-time":kr(Qf(),D$),"iso-date-time":kr(N$(),U$),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:hU,"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:_U,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:mU,int32:{type:"number",validate:yU},int64:{type:"number",validate:bU},float:{type:"number",validate:L$},double:{type:"number",validate:L$},password:!0,binary:!0};Sr.fastFormats={...Sr.fullFormats,date:kr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,tg),time:kr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,rg),"date-time":kr(/^\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,M$),"iso-time":kr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,D$),"iso-date-time":kr(/^\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,U$),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};Sr.formatNames=Object.keys(Sr.fullFormats);function cU(t){return t%4===0&&(t%100!==0||t%400===0)}var lU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function j$(t){let e=lU.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&&cU(r)?29:uU[n])}function tg(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Xf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Qf(t){return function(r){let n=Xf.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,b=o-l*c-(p<0?1:0);return(b===23||b===-1)&&(p===59||p===-1)&&i<61}}function rg(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 D$(t,e){if(!(t&&e))return;let r=Xf.exec(t),n=Xf.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 eg=/t|\s/i;function N$(t){let e=Qf(t);return function(n){let o=n.split(eg);return o.length===2&&j$(o[0])&&e(o[1])}}function M$(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function U$(t,e){if(!(t&&e))return;let[r,n]=t.split(eg),[o,s]=e.split(eg),i=tg(r,o);if(i!==void 0)return i||rg(n,s)}var dU=/\/|:/,pU=/^(?:[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 hU(t){return dU.test(t)&&pU.test(t)}var z$=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function mU(t){return z$.lastIndex=0,z$.test(t)}var fU=-(2**31),gU=2**31-1;function yU(t){return Number.isInteger(t)&&t<=gU&&t>=fU}function bU(t){return Number.isInteger(t)}function L$(){return!0}var wU=/[^\\]\\Z/;function _U(t){if(wU.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var B$=F(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.formatLimitDefinition=void 0;var vU=Yf(),ur=me(),pn=ur.operators,al={formatMaximum:{okStr:"<=",ok:pn.LTE,fail:pn.GT},formatMinimum:{okStr:">=",ok:pn.GTE,fail:pn.LT},formatExclusiveMaximum:{okStr:"<",ok:pn.LT,fail:pn.GTE},formatExclusiveMinimum:{okStr:">",ok:pn.GT,fail:pn.LTE}},xU={message:({keyword:t,schemaCode:e})=>(0,ur.str)`should be ${al[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ur._)`{comparison: ${al[t].okStr}, limit: ${e}}`};Go.formatLimitDefinition={keyword:Object.keys(al),type:"string",schemaType:"string",$data:!0,error:xU,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 vU.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let b=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,ur._)`${b}[${c.schemaCode}]`);t.fail$data((0,ur.or)((0,ur._)`typeof ${m} != "object"`,(0,ur._)`${m} instanceof RegExp`,(0,ur._)`typeof ${m}.compare != "function"`,p(m)))}function u(){let b=c.schema,m=a.formats[b];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${b}" does not define "compare" function`);let h=e.scopeValue("formats",{key:b,ref:m,code:i.code.formats?(0,ur._)`${i.code.formats}${(0,ur.getProperty)(b)}`:void 0});t.fail$data(p(h))}function p(b){return(0,ur._)`${b}.compare(${r}, ${n}) ${al[o].fail} 0`}},dependencies:["format"]};var kU=t=>(t.addKeyword(Go.formatLimitDefinition),t);Go.default=kU});var H$=F(($i,V$)=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});var Jo=q$(),SU=B$(),ng=me(),F$=new ng.Name("fullFormats"),$U=new ng.Name("fastFormats"),og=(t,e={keywords:!0})=>{if(Array.isArray(e))return Z$(t,e,Jo.fullFormats,F$),t;let[r,n]=e.mode==="fast"?[Jo.fastFormats,$U]:[Jo.fullFormats,F$],o=e.formats||Jo.formatNames;return Z$(t,o,r,n),e.keywords&&(0,SU.default)(t),t};og.get=(t,e="full")=>{let n=(e==="fast"?Jo.fastFormats:Jo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Z$(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,ng._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}V$.exports=$i=og;Object.defineProperty($i,"__esModule",{value:!0});$i.default=og});function TU(){let t=new K$.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,W$.default)(t),t}var K$,W$,cl,G$=O(()=>{K$=xl(Yf(),1),W$=xl(H$(),1);cl=class{constructor(e){this._ajv=e??TU()}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 ll,J$=O(()=>{Oo();ll=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(u=>u.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],l=c.some(u=>u.type==="tool_use");if(i){if(s.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(c.filter(b=>b.type==="tool_use").map(b=>b.id)),p=new Set(s.filter(b=>b.type==="tool_result").map(b=>b.toolUseId));if(u.size!==p.size||![...u].every(b=>p.has(b)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Gs,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},Io,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 Y$(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 X$(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 Q$=O(()=>{});var ul,eT=O(()=>{nk();Oo();G$();js();J$();Q$();ul=class extends $c{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ws.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 cl,this.setRequestHandler(yh,n=>this._oninitialize(n)),this.setNotificationHandler(bh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler($h,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ws.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ll(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rk(this._capabilities,e)}setRequestHandler(e,r){let o=en(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Ro(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=Qr(Co,c);if(!u.success){let h=u.error instanceof Error?u.error.message:String(u.error);throw new J(ee.InvalidParams,`Invalid tools/call request: ${h}`)}let{params:p}=u.data,b=await Promise.resolve(r(c,l));if(p.task){let h=Qr(Po,b);if(!h.success){let w=h.error instanceof Error?h.error.message:String(h.error);throw new J(ee.InvalidParams,`Invalid task creation result: ${w}`)}return h.data}let m=Qr(hc,b);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new J(ee.InvalidParams,`Invalid tools/call result: ${h}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){X$(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Y$(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:rx.includes(r)?r:ph,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"},Ya)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Th,r):this.request({method:"sampling/createMessage",params:e},Gs,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},Io,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},Io,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(ee.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof J?i:new J(ee.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Rh,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function sg(t){return!!t&&typeof t=="object"&&rT in t}function nT(t){return t[rT]?.complete}var rT,tT,oT=O(()=>{rT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(tT||(tT={}))});var sT=O(()=>{});function EU(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"),!RU.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 PU(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 ig(t){let e=EU(t);return PU(t,e.warnings),e.isValid}var RU,iT=O(()=>{RU=/^[A-Za-z0-9._-]{1,128}$/});var dl,aT=O(()=>{dl=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 uT(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function dT(t){return"_def"in t||"_zod"in t||uT(t)}function ag(t){return typeof t!="object"||t===null||dT(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(uT)}function cT(t){if(t){if(ag(t))return Bn(t);if(!dT(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function CU(t){let e=en(t);return e?Object.entries(e).map(([r,n])=>{let o=Rv(n),s=Ev(n);return{name:r,description:o,required:!s}}):[]}function hn(t){let r=en(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ro(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function lT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var pl,AU,Ti,pT=O(()=>{eT();js();um();Oo();oT();sT();iT();aT();In();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 ul(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new dl(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(pc)),this.server.assertCanSetRequestHandler(hn(Co)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(pc,()=>({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=To(r.inputSchema);return o?am(o,{strictUnions:!0,pipeStrategy:"input"}):AU})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=To(r.outputSchema);o&&(n.outputSchema=am(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Co,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new J(ee.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new J(ee.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new J(ee.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new J(ee.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof J&&n.code===ee.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=To(e.inputSchema)??e.inputSchema,i=await Za(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Va(a);throw new J(ee.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new J(ee.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=To(e.outputSchema),s=await Za(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Va(i);throw new J(ee.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(b=>setTimeout(b,u));let p=await n.taskStore.getTask(c);if(!p)throw new J(ee.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(hn(mc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(mc,async e=>{switch(e.params.ref.type){case"ref/prompt":return bx(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return wx(e),this.handleResourceCompletion(e,e.params.ref);default:throw new J(ee.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new J(ee.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new J(ee.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ti;let s=en(n.argsSchema)?.[e.params.argument.name];if(!sg(s))return Ti;let i=nT(s);if(!i)return Ti;let a=await i(e.params.argument.value,e.params.context);return lT(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 Ti;throw new J(ee.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ti;let s=await o(e.params.argument.value,e.params.context);return lT(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(ac)),this.server.assertCanSetRequestHandler(hn(cc)),this.server.assertCanSetRequestHandler(hn(lc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(ac,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(cc,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(lc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new J(ee.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new J(ee.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(hn(uc)),this.server.assertCanSetRequestHandler(hn(dc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(uc,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?CU(r.argsSchema):void 0}))})),this.server.setRequestHandler(dc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new J(ee.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new J(ee.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=To(n.argsSchema),s=await Za(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Va(c);throw new J(ee.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Bn(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=Bn(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 kt?c._def?.innerType:c;return sg(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){ig(e);let u={title:r,description:n,inputSchema:cT(o),outputSchema:cT(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"&&ig(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=Bn(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Bn(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()}},AU={type:"object",properties:{}};Ti={completion:{values:[],hasMore:!1}}});function OU(t){return ux.parse(JSON.parse(t))}function hT(t){return JSON.stringify(t)+`
2061
+ `}var IU,hl,mT=O(()=>{Oo();IU=10*1024*1024,hl=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??IU}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(`
2062
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),OU(r)}clear(){this._buffer=void 0}}});import fT from"node:process";var ml,gT=O(()=>{mT();ml=class{constructor(e=fT.stdin,r=fT.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 hl({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=hT(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var yT,bT=O(()=>{yT=[]});var RT={};es(RT,{AUTHORING_MCP_SERVER_NAME:()=>xT,AUTHORING_MCP_SERVER_VERSION:()=>kT,AUTHORING_RESOURCES:()=>UU,AUTHORING_TOOLS:()=>MU,AUTHORING_TOOLS_PUBLIC:()=>TT,buildAuthoringMcpServer:()=>$T,resolveSamplesDir:()=>ST,runAuthoringMcpServer:()=>qU});import{promises as NU}from"node:fs";import{isAbsolute as zU,resolve as fl,sep as LU}from"node:path";function vT(){return _T??=import("../mcp/grounding.js").then(e=>e,()=>null),_T}function ST(t,e){if(e===void 0)return fl(process.cwd(),t??"samples");let r=fl(e);if(t===void 0)return r;if(zU(t))return null;let n=fl(r,t);return n===r||n.startsWith(r+LU)?n:null}function We(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function DU(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 $T(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let m=await Qt(t.baseUrl);if(!m)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:m.baseUrl,token:m.token}}let r=t.grounding??{},n=await vT(),o=null;if(n)try{let m=await e();o={surface:"mcp-authoring",baseUrl:m.baseUrl,token:m.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],c=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{c=(await n.listRecipesForSurface(o,i)).map(m=>({id:m.id,record_type:m.record_type,intent:m.intent}))}catch{c=[]}}let l=o?await DU(o,r):null,u=new pl({name:xT,version:kT},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:c,promptNames:a.map(m=>m.id),deployedExtensions:l,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let m=o;for(let h of a)u.registerPrompt(h.id,{title:h.name,description:h.description},async()=>{let w=await n.getMcpPromptSkill(m,h.id,r);if(!w)throw new Error(`unknown prompt: ${h.id}`);return{description:w.description,messages:[{role:"user",content:{type:"text",text:(w.prompts??[]).join(`
2063
2063
 
2064
- `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:h,token:m}=await e(),w=await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!w.ok)throw new Error(`catalog fetch failed: ${w.status}`);return He(await w.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:A.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:A.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:h,source:m})=>{let{baseUrl:w,token:S}=await e(),R=m?`?source=${encodeURIComponent(m)}`:"",P=await fetch(`${w}/v1/catalog/records/${encodeURIComponent(h)}${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${h}" \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`record anatomy fetch failed: ${P.status}`);return He(await P.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:A.array(A.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:A.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:h,source:m})=>{let{baseUrl:w,token:S}=await e(),R=new URLSearchParams({types:h.join(",")});m&&R.set("source",m);let P=await fetch(`${w}/v1/catalog/columns?${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${h.join(", ")} \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`common columns fetch failed: ${P.status}`);return He(await P.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:h,token:m}=await e(),w=await fetch(`${h}/v1/catalog/census`,{headers:{Authorization:`Bearer ${m}`,Accept:"application/json"}});if(!w.ok)throw new Error(`catalog census failed: ${w.status}`);return He(await w.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:A.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:A.enum(cT).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:A.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:h,kind:m,limit:w})=>{let{baseUrl:S,token:R}=await e(),P=new URLSearchParams({q:h});m&&P.set("kind",m),w!==void 0&&P.set("limit",String(w));let z=await fetch(`${S}/v1/catalog/objects?${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return He(await z.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:A.enum(cT),externalId:A.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:h,externalId:m})=>{let{baseUrl:w,token:S}=await e(),R=await fetch(`${w}/v1/catalog/objects/${encodeURIComponent(h)}/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown object ${h}:${m} \u2014 find it with search_catalog.`);if(!R.ok)throw new Error(`catalog object fetch failed: ${R.status}`);return He(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:A.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:A.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:h,limit:m})=>{let{baseUrl:w,token:S}=await e(),R=new URLSearchParams({q:h});m!==void 0&&R.set("limit",String(m));let P=await fetch(`${w}/v1/kb/search?${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!P.ok)throw new Error(`kb search failed: ${P.status}`);return He(await P.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:A.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:h})=>{let{baseUrl:m,token:w}=await e(),S=await fetch(`${m}/v1/kb/document/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!S.ok&&S.status!==404)throw new Error(`kb document fetch failed: ${S.status}`);return He(await S.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:A.boolean().optional()}},async({recordsOnly:h})=>{let{baseUrl:m,token:w}=await e();return{content:[{type:"text",text:await In({baseUrl:m,token:w,recordsOnly:h})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:A.string(),event:A.string().optional(),template:A.enum(["require-field","enforce-format","blank"]).optional(),field:A.string().optional(),regex:A.string().optional(),source:A.string().optional(),id:A.string().optional()}},async h=>{let m=fr("hook",{recordType:h.recordType,event:h.event,template:h.template,field:h.field,regex:h.regex,source:h.source,id:h.id});return He({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:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:A.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:A.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:A.string().optional().describe("Target record type (defaults to the trigger record type)."),event:A.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:A.string().optional()}},async h=>{let m=fr("conduit",{recordType:h.recordType,source:h.source,to:h.to,toRecordType:h.toRecordType,event:h.event,id:h.id});return He({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:A.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:A.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:A.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:A.string().optional()}},async h=>{let m=fr("process",{recordType:h.recordType,then:h.then,onFailure:h.onFailure,id:h.id});return He({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:A.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:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:A.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:A.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:A.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:A.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:A.array(A.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async h=>{let{baseUrl:m,token:w}=await e(),S=new J({baseUrl:m,token:w});return He(await S.authorConduit({intent:h.intent,from:{source:h.fromSource,recordType:h.fromRecordType},to:{source:h.toSource,recordType:h.toRecordType},...h.intentId?{intentId:h.intentId}:{},...h.columns?.length?{columns:h.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:A.string().describe("The extension TS source."),samplesDir:A.string().optional().describe('Samples directory (default "samples").')}},async({source:h,samplesDir:m})=>{let w=mT(m,t.samplesRoot);if(w===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:_U})}],isError:!0};let S;try{S=await ls(w)}catch(z){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 z}let R=await ra(h,S.map(z=>z.fixture)),P=R.filter(z=>!z.pass).length;return He({total:R.length,passed:R.length-P,results:R})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:A.string(),recordType:A.string(),event:A.string(),source:A.string().describe('Adapter id or "standalone".'),sourceCode:A.string().describe("The verbatim extension TS."),extensionKind:A.string().optional()}},async h=>{let{baseUrl:m,token:w}=await e(),R=await new J({baseUrl:m,token:w}).deploy({id:h.id,recordType:h.recordType,event:h.event,source:h.source,sourceCode:h.sourceCode,extensionKind:h.extensionKind});return He(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:A.string(),limit:A.number().int().positive().optional()}},async({id:h,limit:m})=>{let{baseUrl:w,token:S}=await e(),R=new J({baseUrl:w,token:S});return He({id:h,logs:await R.logs(h,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:h,token:m}=await e(),w=new J({baseUrl:h,token:m});return He(await w.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:A.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:A.string().optional().describe("Display name (defaults to the slug)."),description:A.string().optional().describe("Short description.")}},async({slug:h,name:m,description:w})=>{let{baseUrl:S,token:R}=await e(),P=new J({baseUrl:S,token:R});return He(await P.appsCreate({slug:h,name:m,description:w}))}),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:A.string().describe("App slug or id.")}},async({app:h})=>{let{baseUrl:m,token:w}=await e(),S=new J({baseUrl:m,token:w});return He(await S.appsPull(h))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:A.string().describe("App slug or id."),files:A.record(A.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:A.string().optional().describe("Short note stored with the revision.")}},async({app:h,files:m,note:w})=>{let{baseUrl:S,token:R}=await e(),P=new J({baseUrl:S,token:R});return He(await P.appsPush(h,m,{note:w}))});let p=A.object({name:A.string().describe("Field name (lowercase identifier)."),type:A.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:A.boolean().optional()}),y=A.object({slug:A.string().describe("Table slug; the physical table is cr_<slug>."),displayName:A.string().optional(),fields:A.array(p).describe("At least one field."),rowLevelOwner:A.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:h,token:m}=await e(),w=new J({baseUrl:h,token:m});return He(await w.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:A.array(y),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:h,claimedBy:m})=>{let{baseUrl:w,token:S}=await e(),R=new J({baseUrl:w,token:S});return He(await R.tablesPlan({tables:h,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:A.array(y),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:h,claimedBy:m})=>{let{baseUrl:w,token:S}=await e(),R=new J({baseUrl:w,token:S});return He(await R.tablesApply({tables:h,claimedBy:m}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async h=>{let{baseUrl:m,token:w}=await e(),R=await(await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}})).text();return{contents:[{uri:h.href,mimeType:"application/json",text:R}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async h=>{let{baseUrl:m,token:w}=await e(),S=await In({baseUrl:m,token:w});return{contents:[{uri:h.href,mimeType:"text/plain",text:S}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async h=>{let m=ml(process.cwd(),"samples"),w=[];try{w=(await yU.readdir(m)).filter(R=>R.endsWith(".json"))}catch{w=[]}let S=await ls(m);return{contents:[{uri:h.href,mimeType:"application/json",text:JSON.stringify({files:w,samples:S.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 h=>{let m=await uT(),w=[];if(m){let{baseUrl:S,token:R}=await e();w=await m.listRecipesForSurface({surface:"mcp-authoring",baseUrl:S,token:R},r)}return{contents:[{uri:h.href,mimeType:"application/json",text:JSON.stringify({recipes:w})}]}}),u}async function SU(t={}){let e=await hT(t),r=new pl;await e.connect(r)}var cT,lT,dT,pT,_U,fT,xU,kU,yT=O(()=>{tT();sT();Cn();Ql();is();Qt();uu();aa();aT();cT=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];dT="turbobase-authoring",pT="0.1.0";_U="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.";fT=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","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"],xU=[...fT,...iT],kU=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as ug}from"node:child_process";import{promises as be}from"node:fs";import{homedir as $U}from"node:os";import{basename as _T,dirname as Dr,join as It,relative as fl,resolve as ge,sep as lg}from"node:path";var Pg=_l(Eg(),1),{program:WU,createCommand:GU,createArgument:JU,createOption:YU,CommanderError:XU,InvalidArgumentError:QU,InvalidOptionArgumentError:eq,Command:Ag,Argument:tq,Option:rq,Help:nq}=Pg.default;Ql();is();Qt();uu();ta();import{promises as Ay}from"node:fs";var WE=/^[a-z][a-z0-9_]+$/;function $y(t,e){if(typeof t!="string"||!WE.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 GE="customrecord",JE="customlist";function YE(t){return t.startsWith("customrecord_")?t.slice(13):t}function XE(t){return t.startsWith("customlist_")?t.slice(11):t}function QE(t){return $y(t,"custom_record scriptId"),`cr_${YE(t)}`}function e0(t){return $y(t,"custom_list scriptId"),`cl_${XE(t)}`}function Ty(t){return t.startsWith(GE)?QE(t):t.startsWith(JE)?e0(t):null}var t0={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:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},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"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function Ry(t,e){let r=e?n0[`${e}:${t}`]:void 0;if(r)return r;let n=t0[t];if(n)return n;let o=Ty(t);return o?{table:o}:void 0}var r0={accountingPeriod:"accounting_period"};var n0={...Object.fromEntries(Object.entries(r0).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: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"},"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"}};function Ey(t,e){let r=Ry(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function Py(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=Ey(t,n),i=Ey(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Cy=4;function du(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=po(t,"id"),r=po(t,"on"),n=po(t,"source"),o=po(t,"recordType"),s=[];for(let c of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let l=po(c[1]??"","source"),u=po(c[1]??"","recordType");l&&u&&s.push({source:l,recordType:u})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(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]):Cy}}function po(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function o0(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function Iy(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=du(t)}catch(l){return{fixtureName:o,conduit:i0(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}let a=o0(e),c=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await ea(t,{resolveDir:n.resolveDir}),p=!!(await cs(l,a,{member:"when",timeoutMs:Qi})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let y=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${y} 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)"}),!p)return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[]};let h=[],m=[],w=[];for(let R=0;R<i.targets.length;R+=1){let P=i.targets[R],z=await cs(l,{...a,materialized:w.map(Mr=>({...Mr}))},{member:"transform",stepIndex:R,timeoutMs:Qi});h.push(...z.effects.logs);let F=z.effects.result;if(!F||typeof F!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${R+1})`:""} returned no result (expected { patch, createdFrom? })`);let W=F,Ke=Py(i.fromRecordType,P.recordType,{fromSource:i.fromSource,toSource:P.source}),{wouldWriteBindings:Ye,masterAction:Gt}=s0(i,P,Ke,e);m.push({to:P,transformResult:W,applyBranch:Ke,wouldWriteBindings:Ye,masterAction:Gt}),w.push({source:P.source,recordType:P.recordType,masterTable:`<${P.recordType} master, dry-run>`,masterRowId:`<dry-run target ${R+1}>`,externalId:null})}let S=m[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,transformResult:S.transformResult,applyBranch:S.applyBranch,wouldWriteBindings:S.wouldWriteBindings,masterAction:S.masterAction,targets:m,logs:h}}catch(l){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function s0(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 i0(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Cy}}async function Oy(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 Ny(t){let e=await Ay.readFile(t,"utf8");return JSON.parse(e)}function zy(t){return Ay.readFile(t,"utf8")}function Ly(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((c,l)=>c+l.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let c=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${c} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
2065
- `);let i=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(i.forEach((a,c)=>{let l=n?` (target ${c+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${l} \u2192 patch:`),o.push(a0(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&o.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),o.push(""),o.push(`apply-branch${l}: ${a.applyBranch}`),o.push(` ${a.masterAction}`),o.push(""),o.push(`bindings that WOULD be written (txn_source_link)${l}:`);for(let u of a.wouldWriteBindings)o.push(` ${u.source} role=${u.role} external_id=${u.externalId??"null"} \u2014 ${u.why}`)}),t.logs.length>0){o.push(""),o.push("conduit logs:");for(let a of t.logs)o.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return o.join(`
2066
- `)}function a0(t,e){return t.split(`
2064
+ `)}}]}})}u.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),w=await fetch(`${m}/v1/catalog/records`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!w.ok)throw new Error(`catalog fetch failed: ${w.status}`);return We(await w.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:A.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:A.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:m,source:h})=>{let{baseUrl:w,token:S}=await e(),R=h?`?source=${encodeURIComponent(h)}`:"",P=await fetch(`${w}/v1/catalog/records/${encodeURIComponent(m)}${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown record type "${m}" \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`record anatomy fetch failed: ${P.status}`);return We(await P.json())}),u.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:A.array(A.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:A.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:m,source:h})=>{let{baseUrl:w,token:S}=await e(),R=new URLSearchParams({types:m.join(",")});h&&R.set("source",h);let P=await fetch(`${w}/v1/catalog/columns?${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(P.status===404)throw new Error(`none of those record types resolved: ${m.join(", ")} \u2014 list them with catalog_get.`);if(!P.ok)throw new Error(`common columns fetch failed: ${P.status}`);return We(await P.json())}),u.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),w=await fetch(`${m}/v1/catalog/census`,{headers:{Authorization:`Bearer ${h}`,Accept:"application/json"}});if(!w.ok)throw new Error(`catalog census failed: ${w.status}`);return We(await w.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:A.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:A.enum(wT).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:A.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:m,kind:h,limit:w})=>{let{baseUrl:S,token:R}=await e(),P=new URLSearchParams({q:m});h&&P.set("kind",h),w!==void 0&&P.set("limit",String(w));let z=await fetch(`${S}/v1/catalog/objects?${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!z.ok)throw new Error(`catalog object search failed: ${z.status}`);return We(await z.json())}),u.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:A.enum(wT),externalId:A.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:m,externalId:h})=>{let{baseUrl:w,token:S}=await e(),R=await fetch(`${w}/v1/catalog/objects/${encodeURIComponent(m)}/${encodeURIComponent(h)}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(R.status===404)throw new Error(`unknown object ${m}:${h} \u2014 find it with search_catalog.`);if(!R.ok)throw new Error(`catalog object fetch failed: ${R.status}`);return We(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:A.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:A.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:m,limit:h})=>{let{baseUrl:w,token:S}=await e(),R=new URLSearchParams({q:m});h!==void 0&&R.set("limit",String(h));let P=await fetch(`${w}/v1/kb/search?${R}`,{headers:{Authorization:`Bearer ${S}`,Accept:"application/json"}});if(!P.ok)throw new Error(`kb search failed: ${P.status}`);return We(await P.json())}),u.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:A.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:m})=>{let{baseUrl:h,token:w}=await e(),S=await fetch(`${h}/v1/kb/document/${encodeURIComponent(m)}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});if(!S.ok&&S.status!==404)throw new Error(`kb document fetch failed: ${S.status}`);return We(await S.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:A.boolean().optional()}},async({recordsOnly:m})=>{let{baseUrl:h,token:w}=await e();return{content:[{type:"text",text:await On({baseUrl:h,token:w,recordsOnly:m})}]}}),u.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:A.string(),event:A.string().optional(),template:A.enum(["require-field","enforce-format","blank"]).optional(),field:A.string().optional(),regex:A.string().optional(),source:A.string().optional(),id:A.string().optional()}},async m=>{let h=gr("hook",{recordType:m.recordType,event:m.event,template:m.template,field:m.field,regex:m.regex,source:m.source,id:m.id});return We({path:h.relativePath,content:h.content})}),u.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:A.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:A.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:A.string().optional().describe("Target record type (defaults to the trigger record type)."),event:A.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:A.string().optional()}},async m=>{let h=gr("conduit",{recordType:m.recordType,source:m.source,to:m.to,toRecordType:m.toRecordType,event:m.event,id:m.id});return We({path:h.relativePath,content:h.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:A.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:A.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:A.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:A.string().optional()}},async m=>{let h=gr("process",{recordType:m.recordType,then:m.then,onFailure:m.onFailure,id:m.id});return We({path:h.relativePath,content:h.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:A.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:A.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:A.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:A.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:A.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:A.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:A.array(A.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async m=>{let{baseUrl:h,token:w}=await e(),S=new G({baseUrl:h,token:w});return We(await S.authorConduit({intent:m.intent,from:{source:m.fromSource,recordType:m.fromRecordType},to:{source:m.toSource,recordType:m.toRecordType},...m.intentId?{intentId:m.intentId}:{},...m.columns?.length?{columns:m.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:A.string().describe("The extension TS source."),samplesDir:A.string().optional().describe('Samples directory (default "samples").')}},async({source:m,samplesDir:h})=>{let w=ST(h,t.samplesRoot);if(w===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:jU})}],isError:!0};let S;try{S=await ds(w)}catch(z){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 z}let R=await oa(m,S.map(z=>z.fixture)),P=R.filter(z=>!z.pass).length;return We({total:R.length,passed:R.length-P,results:R})}),u.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:A.string(),recordType:A.string(),event:A.string(),source:A.string().describe('Adapter id or "standalone".'),sourceCode:A.string().describe("The verbatim extension TS."),extensionKind:A.string().optional()}},async m=>{let{baseUrl:h,token:w}=await e(),R=await new G({baseUrl:h,token:w}).deploy({id:m.id,recordType:m.recordType,event:m.event,source:m.source,sourceCode:m.sourceCode,extensionKind:m.extensionKind});return We(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:A.string(),limit:A.number().int().positive().optional()}},async({id:m,limit:h})=>{let{baseUrl:w,token:S}=await e(),R=new G({baseUrl:w,token:S});return We({id:m,logs:await R.logs(m,h)})}),u.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),w=new G({baseUrl:m,token:h});return We(await w.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:A.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:A.string().optional().describe("Display name (defaults to the slug)."),description:A.string().optional().describe("Short description.")}},async({slug:m,name:h,description:w})=>{let{baseUrl:S,token:R}=await e(),P=new G({baseUrl:S,token:R});return We(await P.appsCreate({slug:m,name:h,description:w}))}),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:A.string().describe("App slug or id.")}},async({app:m})=>{let{baseUrl:h,token:w}=await e(),S=new G({baseUrl:h,token:w});return We(await S.appsPull(m))}),u.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:A.string().describe("App slug or id."),files:A.record(A.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:A.string().optional().describe("Short note stored with the revision.")}},async({app:m,files:h,note:w})=>{let{baseUrl:S,token:R}=await e(),P=new G({baseUrl:S,token:R});return We(await P.appsPush(m,h,{note:w}))});let p=A.object({name:A.string().describe("Field name (lowercase identifier)."),type:A.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:A.boolean().optional()}),b=A.object({slug:A.string().describe("Table slug; the physical table is cr_<slug>."),displayName:A.string().optional(),fields:A.array(p).describe("At least one field."),rowLevelOwner:A.boolean().optional().describe("Restrict non-admins to rows they created.")});return u.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:m,token:h}=await e(),w=new G({baseUrl:m,token:h});return We(await w.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:A.array(b),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:w,token:S}=await e(),R=new G({baseUrl:w,token:S});return We(await R.tablesPlan({tables:m,claimedBy:h}))}),u.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:A.array(b),claimedBy:A.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:m,claimedBy:h})=>{let{baseUrl:w,token:S}=await e(),R=new G({baseUrl:w,token:S});return We(await R.tablesApply({tables:m,claimedBy:h}))}),u.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async m=>{let{baseUrl:h,token:w}=await e(),R=await(await fetch(`${h}/v1/catalog/records`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}})).text();return{contents:[{uri:m.href,mimeType:"application/json",text:R}]}}),u.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async m=>{let{baseUrl:h,token:w}=await e(),S=await On({baseUrl:h,token:w});return{contents:[{uri:m.href,mimeType:"text/plain",text:S}]}}),u.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async m=>{let h=fl(process.cwd(),"samples"),w=[];try{w=(await NU.readdir(h)).filter(R=>R.endsWith(".json"))}catch{w=[]}let S=await ds(h);return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({files:w,samples:S.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 m=>{let h=await vT(),w=[];if(h){let{baseUrl:S,token:R}=await e();w=await h.listRecipesForSurface({surface:"mcp-authoring",baseUrl:S,token:R},r)}return{contents:[{uri:m.href,mimeType:"application/json",text:JSON.stringify({recipes:w})}]}}),u}async function qU(t={}){let e=await $T(t),r=new ml;await e.connect(r)}var wT,_T,xT,kT,jU,TT,MU,UU,ET=O(()=>{pT();gT();In();tu();cs();er();pu();la();bT();wT=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];xT="turbobase-authoring",kT="0.1.0";jU="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.";TT=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","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"],MU=[...TT,...yT],UU=["catalog:///","types://all","samples:///","recipes:///"]});import{spawn as hg}from"node:child_process";import{promises as _e}from"node:fs";import{homedir as BU}from"node:os";import{basename as CT,dirname as Mr,join as Ot,relative as yl,resolve as ye,sep as pg}from"node:path";var Ig=xl(Cg(),1),{program:dq,createCommand:pq,createArgument:hq,createOption:mq,CommanderError:fq,InvalidArgumentError:gq,InvalidOptionArgumentError:yq,Command:Og,Argument:bq,Option:wq,Help:_q}=Ig.default;tu();cs();er();pu();na();import{promises as Oy}from"node:fs";var i0=/^[a-z][a-z0-9_]+$/;function Ey(t,e){if(typeof t!="string"||!i0.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 a0="customrecord",c0="customlist";function l0(t){return t.startsWith("customrecord_")?t.slice(13):t}function u0(t){return t.startsWith("customlist_")?t.slice(11):t}function d0(t){return Ey(t,"custom_record scriptId"),`cr_${l0(t)}`}function p0(t){return Ey(t,"custom_list scriptId"),`cl_${u0(t)}`}function Py(t){return t.startsWith(a0)?d0(t):t.startsWith(c0)?p0(t):null}var h0={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:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},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"},request:{table:"request"}};function Ay(t,e){let r=e?f0[`${e}:${t}`]:void 0;if(r)return r;let n=h0[t];if(n)return n;let o=Py(t);return o?{table:o}:void 0}var m0={accountingPeriod:"accounting_period"};var f0={...Object.fromEntries(Object.entries(m0).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: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"},"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"},"azure_blob:file":{table:"source_file"}};function Cy(t,e){let r=Ay(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function Iy(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=Cy(t,n),i=Cy(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Ny=4;function hu(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=po(t,"id"),r=po(t,"on"),n=po(t,"source"),o=po(t,"recordType"),s=[];for(let c of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let l=po(c[1]??"","source"),u=po(c[1]??"","recordType");l&&u&&s.push({source:l,recordType:u})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(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]):Ny}}function po(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function g0(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}async function zy(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=hu(t)}catch(l){return{fixtureName:o,conduit:b0(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}let a=g0(e),c=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await ra(t,{resolveDir:n.resolveDir}),p=!!(await us(l,a,{member:"when",timeoutMs:ta})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let b=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${b} 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)"}),!p)return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[]};let m=[],h=[],w=[];for(let R=0;R<i.targets.length;R+=1){let P=i.targets[R],z=await us(l,{...a,materialized:w.map(Ur=>({...Ur}))},{member:"transform",stepIndex:R,timeoutMs:ta});m.push(...z.effects.logs);let B=z.effects.result;if(!B||typeof B!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${R+1})`:""} returned no result (expected { patch, createdFrom? })`);let K=B,Ge=Iy(i.fromRecordType,P.recordType,{fromSource:i.fromSource,toSource:P.source}),{wouldWriteBindings:Je,masterAction:Jt}=y0(i,P,Ge,e);h.push({to:P,transformResult:K,applyBranch:Ge,wouldWriteBindings:Je,masterAction:Jt}),w.push({source:P.source,recordType:P.recordType,masterTable:`<${P.recordType} master, dry-run>`,masterRowId:`<dry-run target ${R+1}>`,externalId:null})}let S=h[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:p,atlasResolutions:c,transformResult:S.transformResult,applyBranch:S.applyBranch,wouldWriteBindings:S.wouldWriteBindings,masterAction:S.masterAction,targets:h,logs:m}}catch(l){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:c,wouldWriteBindings:[],targets:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function y0(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 b0(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Ny}}async function Ly(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 jy(t){let e=await Oy.readFile(t,"utf8");return JSON.parse(e)}function Dy(t){return Oy.readFile(t,"utf8")}function My(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let n=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(n){let a=t.targets.reduce((c,l)=>c+l.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let o=[];o.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),o.push(`conduit: ${r.id}`);let s=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");o.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${s}${r.on?` on=${r.on}`:""}`),o.push(""),o.push("guards (dispatch order):");for(let a of t.guards){let c=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${c} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(o.push(""),o.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)o.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)o.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return o.push(""),o.push("transform: SKIPPED (from.when gate did not fire)."),o.join(`
2065
+ `);let i=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(i.forEach((a,c)=>{let l=n?` (target ${c+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${l} \u2192 patch:`),o.push(w0(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&o.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),o.push(""),o.push(`apply-branch${l}: ${a.applyBranch}`),o.push(` ${a.masterAction}`),o.push(""),o.push(`bindings that WOULD be written (txn_source_link)${l}:`);for(let u of a.wouldWriteBindings)o.push(` ${u.source} role=${u.role} external_id=${u.externalId??"null"} \u2014 ${u.why}`)}),t.logs.length>0){o.push(""),o.push("conduit logs:");for(let a of t.logs)o.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return o.join(`
2066
+ `)}function w0(t,e){return t.split(`
2067
2067
  `).map(r=>e+r).join(`
2068
- `)}var c0="2026-01-01",jy="2026-01-01T00:00:00.000Z";function l0(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?c0:r.startsWith("timestamp")?jy: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:jy}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function u0(t){let e={};for(let r of t.columns)e[r.name]=l0(r.pgType,r.name);return e}function d0(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:u0(t)},expect:e.expect??"pass"}}function Dy(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:d0(r,e)}))}import{promises as My}from"node:fs";import{join as Uy,relative as p0,sep as m0}from"node:path";var h0=67324752,f0=33639248,g0=101010256,y0=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function b0(t){let e=4294967295;for(let r=0;r<t.length;r++)e=y0[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function w0(t){let e=[];async function r(n){let o=await My.readdir(n,{withFileTypes:!0});for(let s of o){let i=Uy(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(p0(t,i).split(m0).join("/"))}}return await r(t),e.sort(),e}async function qy(t){let e=await w0(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await My.readFile(Uy(t,a)),u=b0(l),p=Buffer.alloc(30+c.length);p.writeUInt32LE(h0,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 y=Buffer.alloc(46+c.length);y.writeUInt32LE(f0,0),y.writeUInt16LE(20,4),y.writeUInt16LE(20,6),y.writeUInt16LE(0,10),y.writeUInt32LE(u,16),y.writeUInt32LE(l.length,20),y.writeUInt32LE(l.length,24),y.writeUInt16LE(c.length,28),y.writeUInt32LE(o,42),c.copy(y,46),n.push(y),o+=p.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(g0,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}su();function _0(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function na(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function v0(t){let e=x0(t,"from"),n=Fy(t,"to").map(o=>({source:na(o,"source"),recordType:na(o,"recordType")}));return{fromSource:e?na(e,"source"):void 0,fromRecordType:e?na(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function x0(t,e){return Fy(t,e)[0]??null}function Fy(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 k0(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 S0(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function $0(t){return/\bcreatedFrom\b/.test(t)}function By(t){let e=_0(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,fromRecordType:o,toRecordType:s,targets:i}=v0(t);for(let u of i)if(n&&u.source&&n===u.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=k0(t);if(a!==null){let u=/\bexternalId\b/.test(a),p=/\bfromSource\b/.test(a);!u&&!p&&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}``."})}let c=i.find(u=>u.recordType&&o&&u.recordType!==o)?.recordType??(o!==s?s:void 0);o&&c&&!$0(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${c}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${c} 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 l=S0(t,"cycleBudget");return l!==void 0&&(l<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${l} 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)."}):l>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${l} 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 Zy(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(`
2068
+ `)}var _0="2026-01-01",Uy="2026-01-01T00:00:00.000Z";function v0(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"?_0:r.startsWith("timestamp")?Uy: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:Uy}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function x0(t){let e={};for(let r of t.columns)e[r.name]=v0(r.pgType,r.name);return e}function k0(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:x0(t)},expect:e.expect??"pass"}}function qy(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:k0(r,e)}))}import{promises as By}from"node:fs";import{join as Fy,relative as S0,sep as $0}from"node:path";var T0=67324752,R0=33639248,E0=101010256,P0=(()=>{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 A0(t){let e=4294967295;for(let r=0;r<t.length;r++)e=P0[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function C0(t){let e=[];async function r(n){let o=await By.readdir(n,{withFileTypes:!0});for(let s of o){let i=Fy(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(S0(t,i).split($0).join("/"))}}return await r(t),e.sort(),e}async function Zy(t){let e=await C0(t),r=[],n=[],o=0;for(let a of e){let c=Buffer.from(a,"utf8"),l=await By.readFile(Fy(t,a)),u=A0(l),p=Buffer.alloc(30+c.length);p.writeUInt32LE(T0,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 b=Buffer.alloc(46+c.length);b.writeUInt32LE(R0,0),b.writeUInt16LE(20,4),b.writeUInt16LE(20,6),b.writeUInt16LE(0,10),b.writeUInt32LE(u,16),b.writeUInt32LE(l.length,20),b.writeUInt32LE(l.length,24),b.writeUInt16LE(c.length,28),b.writeUInt32LE(o,42),c.copy(b,46),n.push(b),o+=p.length+l.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(E0,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}}au();function I0(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function sa(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function O0(t){let e=N0(t,"from"),n=Vy(t,"to").map(o=>({source:sa(o,"source"),recordType:sa(o,"recordType")}));return{fromSource:e?sa(e,"source"):void 0,fromRecordType:e?sa(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function N0(t,e){return Vy(t,e)[0]??null}function Vy(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 z0(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 L0(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function j0(t){return/\bcreatedFrom\b/.test(t)}function Hy(t){let e=I0(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,fromRecordType:o,toRecordType:s,targets:i}=O0(t);for(let u of i)if(n&&u.source&&n===u.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=z0(t);if(a!==null){let u=/\bexternalId\b/.test(a),p=/\bfromSource\b/.test(a);!u&&!p&&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}``."})}let c=i.find(u=>u.recordType&&o&&u.recordType!==o)?.recordType??(o!==s?s:void 0);o&&c&&!j0(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${c}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${c} 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 l=L0(t,"cycleBudget");return l!==void 0&&(l<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${l} 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)."}):l>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${l} 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 Ky(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(`
2069
2069
  `);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(`
2070
2070
  lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
2071
- `)}function Vy(t){return t.cases.filter(e=>e.status==="failed").length}function ds(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function T0(t){let e=Vy(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${ds(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${ds(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${ds(n.type)}"`:"";r.push(` <failure${i} message="${ds(s)}">${ds(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2071
+ `)}function Wy(t){return t.cases.filter(e=>e.status==="failed").length}function hs(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function D0(t){let e=Wy(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${hs(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${hs(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${hs(n.type)}"`:"";r.push(` <failure${i} message="${hs(s)}">${hs(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2072
2072
  `)}
2073
- `}function R0(t){let e={suite:t.name,tests:t.cases.length,failures:Vy(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2074
- `}function oa(t,e){return e==="junit"?T0(t):R0(t)}var St={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"},Ge={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},mo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Mt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Hy=/\x1b\[[0-9;]*m/g;function Ar(t){return t.replace(Hy,"").length}function pu(t,e){return e<=0?1:Math.max(1,Math.ceil(Ar(t)/e))}function E0(){return process.env.NO_COLOR!=null&&process.env.NO_COLOR!==""?!1:process.env.FORCE_COLOR&&process.env.FORCE_COLOR!=="0"?!0:process.env.TERM==="dumb"?!1:process.stdout.isTTY===!0}var mu=E0();function tt(){return mu}function hu(t){mu=t}function ot(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function Ut(t,e){return mu?`${t}${e}${St.reset}`:e}var g={bold:t=>Ut(St.bold,t),dim:t=>Ut(St.dim,t),red:t=>Ut(St.red,t),green:t=>Ut(St.green,t),yellow:t=>Ut(St.yellow,t),blue:t=>Ut(St.blue,t),magenta:t=>Ut(St.magenta,t),cyan:t=>Ut(St.cyan,t),grey:t=>Ut(St.grey,t)};var Oe={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}`},Hr={add:t=>g.green(`+ ${t}`),change:t=>g.yellow(`~ ${t}`),destroy:t=>g.red(`- ${t}`)},P0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),A0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),C0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function ho(t){let e=t.toLowerCase();return P0.has(e)?g.green(t):A0.has(e)?g.red(t):C0.has(e)?g.yellow(t):t}function Kr(t,e=[]){let r=Math.max(Ar(t),...e.map(Ar),0),n=r+2,o=g.cyan(Mt.v),s=a=>` ${a}${" ".repeat(r-Ar(a))} `,i=[g.cyan(`${Mt.tl}${Mt.h.repeat(n)}${Mt.tr}`),`${o}${g.bold(s(t))}${o}`];if(e.length){i.push(`${g.cyan(Mt.ml)}${g.dim(Mt.h.repeat(n))}${g.cyan(Mt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(g.cyan(`${Mt.bl}${Mt.h.repeat(n)}${Mt.br}`)),i.join(`
2075
- `)}function er(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=>Ar(u[l]??"")));let a=l=>{let u=l.map((p,y)=>{let h=p??"";return y===l.length-1?h:h+" ".repeat(Math.max(0,i[y]-Ar(h)))});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]??Ar(l)))))));for(let l of t)c.push(a(l));return c.join(`
2076
- `)}function fu(t="the CLI for your Turbobase instance"){let e=[" \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u2550\u2588\u2588\u2554\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D"," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2557 "," \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551\u255A\u2550\u2550\u2550\u2550\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D "," \u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557"," \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"];return`${tt()?e.map(n=>Ut(St.cyan,n)).join(`
2073
+ `}function M0(t){let e={suite:t.name,tests:t.cases.length,failures:Wy(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2074
+ `}function ia(t,e){return e==="junit"?D0(t):M0(t)}var $t={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",invert:"\x1B[7m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",grey:"\x1B[90m"},Qe={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},ho=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Ut={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Gy=/\x1b\[[0-9;]*m/g;function Cr(t){return t.replace(Gy,"").length}function mu(t,e){return e<=0?1:Math.max(1,Math.ceil(Cr(t)/e))}function U0(){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 fu=U0();function nt(){return fu}function gu(t){fu=t}function it(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function qt(t,e){return fu?`${t}${e}${$t.reset}`:e}var f={bold:t=>qt($t.bold,t),dim:t=>qt($t.dim,t),red:t=>qt($t.red,t),green:t=>qt($t.green,t),yellow:t=>qt($t.yellow,t),blue:t=>qt($t.blue,t),magenta:t=>qt($t.magenta,t),cyan:t=>qt($t.cyan,t),grey:t=>qt($t.grey,t)};var ze={success:t=>`${f.green("\u2713")} ${t}`,error:t=>`${f.red("\u2716")} ${t}`,warn:t=>`${f.yellow("\u26A0")} ${t}`,info:t=>`${f.dim("\xB7")} ${t}`,step:t=>`${f.cyan("\u25B8")} ${t}`},Kr={add:t=>f.green(`+ ${t}`),change:t=>f.yellow(`~ ${t}`),destroy:t=>f.red(`- ${t}`)},q0=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),B0=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),F0=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function mo(t){let e=t.toLowerCase();return q0.has(e)?f.green(t):B0.has(e)?f.red(t):F0.has(e)?f.yellow(t):t}function Wr(t,e=[]){let r=Math.max(Cr(t),...e.map(Cr),0),n=r+2,o=f.cyan(Ut.v),s=a=>` ${a}${" ".repeat(r-Cr(a))} `,i=[f.cyan(`${Ut.tl}${Ut.h.repeat(n)}${Ut.tr}`),`${o}${f.bold(s(t))}${o}`];if(e.length){i.push(`${f.cyan(Ut.ml)}${f.dim(Ut.h.repeat(n))}${f.cyan(Ut.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(f.cyan(`${Ut.bl}${Ut.h.repeat(n)}${Ut.br}`)),i.join(`
2075
+ `)}function tr(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=>Cr(u[l]??"")));let a=l=>{let u=l.map((p,b)=>{let m=p??"";return b===l.length-1?m:m+" ".repeat(Math.max(0,i[b]-Cr(m)))});return r+u.join(n)},c=[];e.head&&(c.push(a(e.head.map(l=>f.bold(l)))),c.push(a(e.head.map((l,u)=>f.dim("\u2500".repeat(i[u]??Cr(l)))))));for(let l of t)c.push(a(l));return c.join(`
2076
+ `)}function yu(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`${nt()?e.map(n=>qt($t.cyan,n)).join(`
2077
2077
  `):e.join(`
2078
2078
  `)}
2079
- ${g.dim(` ${t}`)}`}var qt=t=>{process.stderr.write(t)};function sa(){return tt()&&process.stderr.isTTY===!0}function Ky(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 se(t,e){let r=sa(),n=0,o;r&&(qt(Ge.hideCursor),o=setInterval(()=>{qt(`${Ge.col0}${Ge.clearLine}${g.magenta(mo[n++%mo.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&qt(`${Ge.col0}${Ge.clearLine}${Ge.showCursor}`)};try{let i=await e();return s(),r&&qt(`${Oe.success(t)}
2080
- `),i}catch(i){throw s(),r&&qt(`${Oe.error(t)}
2081
- `),i}}function gu(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=g.magenta(mo[e%mo.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} ${Ky(r.percent)} ${p}`},s=()=>{qt(`${Ge.col0}${Ge.clearLine}${o()}`),n=!0},i=()=>{n&&qt(`${Ge.col0}${Ge.clearLine}`),n=!1};qt(Ge.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),qt(`${c}
2082
- `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),qt(Ge.showCursor);let l=c.stage!=="failed",u=`${t} ${g.dim("\u25B8")} ${I0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;qt(`${l?Oe.success(u):Oe.error(u)}
2083
- `)},stop(){clearInterval(a),i(),qt(Ge.showCursor)}}}function I0(t){return t==="completed"?g.green(t):t==="failed"?g.red(t):g.cyan(t)}function st(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(w=>!w.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=w=>{process.stderr.write(w)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${g.bold(g.cyan("?"))} ${g.bold(t)}
2084
- `),a(`${g.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2085
- `),a(Ge.hideCursor);let u=0,p=()=>{let w=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Ge.cursorUp(u)),a(Ge.clearToEnd));let S=0;for(let R=0;R<e.length;R+=1){let P=e[R],z=R===i,F=z?g.cyan("\u25B6"):" ",W=P.disabled?g.grey(P.label):z?g.bold(g.cyan(P.label)):P.label,Ke=P.description?` ${g.dim(P.description)}`:"",Ye=` ${F} ${W}${Ke}`;a(`\r${Ye}
2086
- `),S+=pu(Ye,w)}u=S},y=()=>{c.removeListener("data",m),c.setRawMode?.(l??!1),c.pause(),a(Ge.showCursor)},h=w=>{let S=i;for(let R=0;R<e.length;R+=1)if(S=(S+w+e.length)%e.length,!e[S].disabled){i=S;return}},m=w=>{let S=w.toString("utf8");if(S===""||S==="q"){y(),a(`
2079
+ ${f.dim(` ${t}`)}`}var Bt=t=>{process.stderr.write(t)};function aa(){return nt()&&process.stderr.isTTY===!0}function Jy(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${f.dim("\u2591".repeat(e-n))}`}async function se(t,e){let r=aa(),n=0,o;r&&(Bt(Qe.hideCursor),o=setInterval(()=>{Bt(`${Qe.col0}${Qe.clearLine}${f.magenta(ho[n++%ho.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&Bt(`${Qe.col0}${Qe.clearLine}${Qe.showCursor}`)};try{let i=await e();return s(),r&&Bt(`${ze.success(t)}
2080
+ `),i}catch(i){throw s(),r&&Bt(`${ze.error(t)}
2081
+ `),i}}function bu(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let c=f.magenta(ho[e%ho.length]),l=f.cyan(r.stage),u=r.runStatus?` ${f.dim(`(${r.runStatus})`)}`:"",p=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${c} ${t} ${f.dim("\u25B8")} ${l}${u} ${Jy(r.percent)} ${p}`},s=()=>{Bt(`${Qe.col0}${Qe.clearLine}${o()}`),n=!0},i=()=>{n&&Bt(`${Qe.col0}${Qe.clearLine}`),n=!1};Bt(Qe.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(c){i(),Bt(`${c}
2082
+ `),s()},status(c){r=c,s()},done(c){clearInterval(a),i(),Bt(Qe.showCursor);let l=c.stage!=="failed",u=`${t} ${f.dim("\u25B8")} ${Z0(c.stage)}${c.runStatus?` (${c.runStatus})`:""}`;Bt(`${l?ze.success(u):ze.error(u)}
2083
+ `)},stop(){clearInterval(a),i(),Bt(Qe.showCursor)}}}function Z0(t){return t==="completed"?f.green(t):t==="failed"?f.red(t):f.cyan(t)}function at(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(w=>!w.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=w=>{process.stderr.write(w)},c=process.stdin,l=c.isRaw;c.setRawMode?.(!0),c.resume(),a(`${f.bold(f.cyan("?"))} ${f.bold(t)}
2084
+ `),a(`${f.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2085
+ `),a(Qe.hideCursor);let u=0,p=()=>{let w=process.stderr.columns??process.stdout.columns??80;u>0&&(a(Qe.cursorUp(u)),a(Qe.clearToEnd));let S=0;for(let R=0;R<e.length;R+=1){let P=e[R],z=R===i,B=z?f.cyan("\u25B6"):" ",K=P.disabled?f.grey(P.label):z?f.bold(f.cyan(P.label)):P.label,Ge=P.description?` ${f.dim(P.description)}`:"",Je=` ${B} ${K}${Ge}`;a(`\r${Je}
2086
+ `),S+=mu(Je,w)}u=S},b=()=>{c.removeListener("data",h),c.setRawMode?.(l??!1),c.pause(),a(Qe.showCursor)},m=w=>{let S=i;for(let R=0;R<e.length;R+=1)if(S=(S+w+e.length)%e.length,!e[S].disabled){i=S;return}},h=w=>{let S=w.toString("utf8");if(S===""||S==="q"){b(),a(`
2087
2087
  `),o(new Error("aborted"));return}if(S==="\r"||S===`
2088
- `){let P=e[i];if(P.disabled)return;y(),n(P.value);return}if(S==="\x1B[A"||S==="k"){h(-1),p();return}if(S==="\x1B[B"||S==="j"){h(1),p();return}let R=Number(S);Number.isFinite(R)&&R>=1&&R<=e.length&&!e[R-1].disabled&&(i=R-1,p())};c.on("data",m),p()})}function ia(t,e){return`${ho(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Gy=t=>new Promise(e=>setTimeout(e,t));function Wy(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${ia(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Jy(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
2089
- `)}),o=r.sleep??Gy,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(Wy(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 y of[...p].reverse())n(Wy(y)),a+=1,y.updatedAt>c&&(c=y.updatedAt)}return a}function O0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${ia(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function Yy(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2090
- `)});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(O0(o));return r(`
2091
- binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function N0(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}] ${ia(t.severity,5)} ${ia(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function Xy(t,e={}){let r=e.sink??(R=>{process.stdout.write(`${R}
2092
- `)}),n=e.sleep??Gy,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:c,sleep:l,intervalMs:u,...p}=e,y=R=>{r(a?JSON.stringify(R):N0(R))},h=await t.platformEvents({...p,limit:p.limit??100});if(h.length===0&&!s)return r("logs: no events matched."),0;let m=0,w="";for(let R of[...h].reverse())y(R),m+=1,R.ts>w&&(w=R.ts);if(!s)return m;let S=i??Number.POSITIVE_INFINITY;for(let R=0;R<S;R+=1){await n(o);let P=await t.platformEvents({...p,...w?{after:w,since:void 0}:{},limit:200});for(let z of[...P].reverse())y(z),m+=1,z.ts>w&&(w=z.ts)}return m}aa();ta();function eb(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var yu=".github/workflows/turbobase-release-deploy.yml",M0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2088
+ `){let P=e[i];if(P.disabled)return;b(),n(P.value);return}if(S==="\x1B[A"||S==="k"){m(-1),p();return}if(S==="\x1B[B"||S==="j"){m(1),p();return}let R=Number(S);Number.isFinite(R)&&R>=1&&R<=e.length&&!e[R-1].disabled&&(i=R-1,p())};c.on("data",h),p()})}function ca(t,e){return`${mo(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Xy=t=>new Promise(e=>setTimeout(e,t));function Yy(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${ca(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Qy(t,e,r={}){let n=r.sink??(u=>{process.stdout.write(`${u}
2089
+ `)}),o=r.sleep??Xy,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(Yy(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 b of[...p].reverse())n(Yy(b)),a+=1,b.updatedAt>c&&(c=b.updatedAt)}return a}function V0(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${ca(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function eb(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2090
+ `)});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(V0(o));return r(`
2091
+ binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function H0(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}] ${ca(t.severity,5)} ${ca(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function tb(t,e={}){let r=e.sink??(R=>{process.stdout.write(`${R}
2092
+ `)}),n=e.sleep??Xy,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:c,sleep:l,intervalMs:u,...p}=e,b=R=>{r(a?JSON.stringify(R):H0(R))},m=await t.platformEvents({...p,limit:p.limit??100});if(m.length===0&&!s)return r("logs: no events matched."),0;let h=0,w="";for(let R of[...m].reverse())b(R),h+=1,R.ts>w&&(w=R.ts);if(!s)return h;let S=i??Number.POSITIVE_INFINITY;for(let R=0;R<S;R+=1){await n(o);let P=await t.platformEvents({...p,...w?{after:w,since:void 0}:{},limit:200});for(let z of[...P].reverse())b(z),h+=1,z.ts>w&&(w=z.ts)}return h}la();na();function nb(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var ib=9,ms=" ".repeat(2+ib);function fo(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,ib-t.length))}function Y0(t,e,r){return t===1?e:r}function ab(t){return t?f.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function cb(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function X0(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 ${cb(o[s]??[])}`);return e}function ob(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:f.dim(`${ms}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:f.dim(`${ms}adopted ${s} ${cb(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:f.dim(`${ms}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:f.dim(`${ms}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:f.yellow(`${ms}! ${s}`)});return e}function lb(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 sb(t){return lb(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function Q0(t,e,r){let n=r==="applied",o=X0(t.scopeChanges),s=n?ab(t.holdersRestamped):"",i=c=>{let l=[...c,...o];return l.length>0?` ${f.dim(l.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${fo("ERROR",f.bold)}${e} \u2014 ${t.message??"cannot be created"}`},...ob(t)];let a;if(t.action==="create"){let c=t.addCapabilities?.length??0;a=` ${fo(n?"created":"create")}${e}${i([`${c} ${Y0(c,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let c=(t.addCapabilities??[]).map(l=>`+${l}`).join(", ");a=` ${fo(n?"updated":"add")}${e}${i([c])}${s}`}else t.action==="update_scopes"?a=` ${fo(n?"updated":"update")}${e}${o.length>0?i([]):` ${f.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${fo("ok",f.dim)}${e} ${f.dim("already up to date")}`:a=` ${fo(n?"changed":"change")}${e}${i([])} ${f.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...ob(t)]}function eP(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}: ${f.dim(o)}${e==="applied"?ab(n.holdersRestamped):""}`})}return r}function ub(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(l=>l.action!=="noop"||sb(l)),o=eP(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:f.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(...Q0(l,l.name.padEnd(i),e));s.push(...o);let a=n.some(l=>tP.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:f.dim(l)})}else if(o.length===0&&c&&n.some(l=>sb(l))){let l=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",u=n.some(p=>lb(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:f.dim(` ${l} \u2014 ${u}`)})}return s}var tP=new Set(["create","add_capabilities","update_scopes"]);function wu(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:f.yellow(`! ${o}`)},{stream:"out",text:f.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:f.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 db(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 _u=".github/workflows/turbobase-release-deploy.yml",rP=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2093
2093
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
2094
2094
  #
2095
2095
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -2191,7 +2191,7 @@ jobs:
2191
2191
  --ref "\${{ github.sha }}" \\
2192
2192
  --project . \\
2193
2193
  --follow
2194
- `,U0=".github/workflows/turbobase-app-deploy.yml",q0=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2194
+ `,nP=".github/workflows/turbobase-app-deploy.yml",oP=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2195
2195
  # Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
2196
2196
  #
2197
2197
  # What ships from this repo, and when:
@@ -2277,9 +2277,11 @@ jobs:
2277
2277
  # Refuse early on anything the deploy would refuse anyway: a table field
2278
2278
  # another app claims at a different type, or a declared write a guardrail
2279
2279
  # denies. \`apps deploy\` re-runs both checks \u2014 this only moves the failure
2280
- # to before the build.
2280
+ # to before the build. \`--app\` names the app the way the deploy does, so
2281
+ # the role check reads this app's own earlier declarations as its own:
2282
+ # without it a scope any app declared on a role is left unplanned.
2281
2283
  - name: Preflight the manifest
2282
- run: turbobase apps plan .
2284
+ run: turbobase apps plan . --app "\${{ vars.TURBOBASE_APP_SLUG }}"
2283
2285
 
2284
2286
  # Config FIRST. hooks/, conduits/, turbobase/sync.json and
2285
2287
  # turbobase/schedules.json are the desired state; this adds and updates
@@ -2323,7 +2325,7 @@ jobs:
2323
2325
  --token "$TURBOBASE_PAT"
2324
2326
 
2325
2327
  - name: Preflight the manifest
2326
- run: turbobase apps plan .
2328
+ run: turbobase apps plan . --app "\${{ vars.TURBOBASE_APP_SLUG }}"
2327
2329
 
2328
2330
  # DIFF ONLY \u2014 writes nothing. This is what a reviewer reads to see whether
2329
2331
  # merging would change a hook, a schedule, or remove one.
@@ -2409,14 +2411,14 @@ jobs:
2409
2411
  else
2410
2412
  echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
2411
2413
  fi
2412
- `;function tb(){return[{path:yu,content:M0}]}function rb(){return[{path:U0,content:q0}]}aa();var F0=[".mcp.json"];function sb(t,e=F0){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2414
+ `;function pb(){return[{path:_u,content:rP}]}function hb(){return[{path:nP,content:oP}]}la();var sP=[".mcp.json"];function gb(t,e=sP){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2413
2415
  `).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(`
2414
2416
  `)?t:`${t}
2415
2417
  `}
2416
2418
  # Added by the Turbobase scaffold.
2417
2419
  ${o.join(`
2418
2420
  `)}
2419
- `}var B0=`# Turbobase Extensions \u2014 extension project
2421
+ `}var iP=`# Turbobase Extensions \u2014 extension project
2420
2422
 
2421
2423
  This directory authors **Turbobase extensions** (hooks today; conduits later)
2422
2424
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -2485,8 +2487,8 @@ order is the signal, and it is the part the product team reads first.
2485
2487
 
2486
2488
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
2487
2489
  updating a test. It is checked into the repo so the whole team sees it.
2488
- `,Z0=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)+`
2489
- `;function V0(t){return`---
2490
+ `,aP=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)+`
2491
+ `;function cP(t){return`---
2490
2492
  name: generate-types
2491
2493
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
2492
2494
  ---
@@ -2497,7 +2499,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
2497
2499
 
2498
2500
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
2499
2501
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
2500
- `}var H0=`---
2502
+ `}var lP=`---
2501
2503
  name: mock-test
2502
2504
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
2503
2505
  ---
@@ -2506,7 +2508,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
2506
2508
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
2507
2509
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
2508
2510
  fixture for each branch (a passing record and a rejecting record).
2509
- `,K0=`---
2511
+ `,uP=`---
2510
2512
  name: deploy
2511
2513
  description: Deploy a hook to your instance. Use only after mock-test is green.
2512
2514
  ---
@@ -2514,7 +2516,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
2514
2516
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
2515
2517
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
2516
2518
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
2517
- `;function W0(t){return`# ${t} \u2014 Turbobase app
2519
+ `;function dP(t){return`# ${t} \u2014 Turbobase app
2518
2520
 
2519
2521
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
2520
2522
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -2652,10 +2654,17 @@ Deploying creates it as an ordinary role \u2014 the same one an admin manages in
2652
2654
  Admin \u2192 Roles. Same asymmetry as guardrails, one step further: **a declared role
2653
2655
  has no holders until an admin assigns it in Admin \u2192 Users.** Deploying grants
2654
2656
  nobody anything, including you. You cannot declare \`appRole\` (admin is assigned,
2655
- never authored) or \`scopes\` (row-level narrowing is the admin's).
2657
+ never authored).
2658
+
2659
+ A role may also carry \`scopes\`: row restrictions (\`"location":
2660
+ ["{{user.location}}"]\`) and \`content\` \u2014 the exact Slack channels whose history
2661
+ the role reads in \`memory_document\` (\`"content": ["slack:<channel id>"]\`, paired
2662
+ with \`read:memory\`). See the \`roles-and-permissions\` skill before declaring
2663
+ either.
2656
2664
 
2657
2665
  Redeploying ADDS missing capabilities to an existing role and never removes any \u2014
2658
2666
  a role can have live holders, so a deploy must not be able to revoke access.
2667
+ Scopes are the exception, and only your app's own: see the skill.
2659
2668
 
2660
2669
  Gate your screens on the same capability strings with \`hasCapability()\` from
2661
2670
  \`src/lib/turbobase.ts\`, and catch \`TurbobasePermissionError\` on writes \u2014 that
@@ -2856,7 +2865,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
2856
2865
  review, so what you write reaches the knowledge base and the product team instead
2857
2866
  of evaporating at the end of the session. Keep the section headings exactly as
2858
2867
  they are \u2014 the ingest finds entries by heading, not by filename.
2859
- `}var fo="customer",On="email",G0="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",J0=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2868
+ `}var go="customer",Nn="email",pP="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",hP=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2860
2869
  //
2861
2870
  // It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
2862
2871
  // the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
@@ -2875,8 +2884,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
2875
2884
  // Pure and credentials-free: no secrets, no network, no Node builtins, one
2876
2885
  // concern per file, nothing factored into a shared module (the sandbox fences
2877
2886
  // every import except the SDK).
2878
- `;function Y0(){let t=fr("hook",{recordType:fo,event:"before_save",template:"enforce-format",field:On,regex:G0,id:`app:${fo}:${On}-format`,description:`Reject a ${fo} write whose ${On} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:fo,event:"before_save",payload:r},expect:n},null,2)+`
2879
- `;return[{path:t.relativePath,content:`${J0}${t.content}`},{path:`samples/${fo}.${On}-ok.json`,content:e({company_name:"Acme Supply",[On]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${fo}.${On}-malformed.json`,content:e({company_name:"Acme Supply",[On]:"ada-at-example"},"reject","a malformed address is rejected")}]}var X0="---\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",Q0=`---
2887
+ `;function mP(){let t=gr("hook",{recordType:go,event:"before_save",template:"enforce-format",field:Nn,regex:pP,id:`app:${go}:${Nn}-format`,description:`Reject a ${go} write whose ${Nn} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:go,event:"before_save",payload:r},expect:n},null,2)+`
2888
+ `;return[{path:t.relativePath,content:`${hP}${t.content}`},{path:`samples/${go}.${Nn}-ok.json`,content:e({company_name:"Acme Supply",[Nn]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${go}.${Nn}-malformed.json`,content:e({company_name:"Acme Supply",[Nn]:"ada-at-example"},"reject","a malformed address is rejected")}]}var fP="---\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",gP=`---
2880
2889
  name: ship-app
2881
2890
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
2882
2891
  ---
@@ -2919,7 +2928,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
2919
2928
  non-text, so images and fonts belong in the build pipeline or object storage, not
2920
2929
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
2921
2930
  project root and DO travel \u2014 deploy reads them.
2922
- `,eP=`---
2931
+ `,yP=`---
2923
2932
  name: business-rule-to-hook
2924
2933
  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.
2925
2934
  ---
@@ -2987,7 +2996,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
2987
2996
  standing rules for every agent on the instance \u2014 see the record-learning skill.
2988
2997
  A rule enforced in code and nowhere written down gets re-litigated by the next
2989
2998
  person.
2990
- `;function tP(t){return`---
2999
+ `;function bP(t){return`---
2991
3000
  name: record-learning
2992
3001
  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.
2993
3002
  ---
@@ -3042,7 +3051,7 @@ earlier claim" and still publish.
3042
3051
 
3043
3052
  Do not reword the three headings. The deploy-side ingest recognises entries by
3044
3053
  heading, not by filename, so a renamed section is a finding nobody receives.
3045
- `}function rP(t){return`# What this instance's source system actually does
3054
+ `}function wP(t){return`# What this instance's source system actually does
3046
3055
 
3047
3056
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
3048
3057
  Written for the knowledge base, and **everything here is verified against real
@@ -3173,7 +3182,7 @@ finding has not been handed to the knowledge base yet.
3173
3182
  and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
3174
3183
  already live, which is worth reading before adding another rule. -->
3175
3184
 
3176
- `}function nP(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3185
+ `}function _P(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3177
3186
 
3178
3187
  Everything below cost time or produced a wrong result. Not speculation, and not
3179
3188
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -3253,7 +3262,7 @@ Expected / happened / cost / fix.
3253
3262
  and what it would replace. These are the highest-signal entries in the file:
3254
3263
  each one is a page downloading rows to fold that it could have asked for
3255
3264
  folded. -->
3256
- `}function oP(t,e){let r=e?`
3265
+ `}function vP(t,e){let r=e?`
3257
3266
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
3258
3267
  # --records focus a previous run stamped into the file, so a refresh never
3259
3268
  # narrows what an agent deliberately widened.
@@ -3284,8 +3293,8 @@ ${r}
3284
3293
  # surface unticked items at the start of a session.
3285
3294
  turbobase project adopt -o ADOPT.md >/dev/null \\
3286
3295
  || echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
3287
- `}var ib="Turbobase consultant",sP="turbobase-consultant",iP=`---
3288
- name: ${ib}
3296
+ `}var yb="Turbobase consultant",xP="turbobase-consultant",kP=`---
3297
+ name: ${yb}
3289
3298
  description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
3290
3299
  keep-coding-instructions: true
3291
3300
  ---
@@ -3358,8 +3367,8 @@ exists on purpose.
3358
3367
  - Do not show a stack trace. Say what broke and what you are doing about it.
3359
3368
  - Do not apologise repeatedly or pad with "great question".
3360
3369
  - Do not use a table when a sentence works.
3361
- `,aP=JSON.stringify({outputStyle:ib,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
3362
- `,cP=`#!/usr/bin/env bash
3370
+ `,SP=JSON.stringify({outputStyle:yb,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
3371
+ `,$P=`#!/usr/bin/env bash
3363
3372
  # PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
3364
3373
  #
3365
3374
  # Advisory only: exits 0 always, and adds a note for the agent when the edited
@@ -3376,7 +3385,7 @@ set -uo pipefail
3376
3385
  command -v node >/dev/null 2>&1 || exit 0
3377
3386
 
3378
3387
  exec node "$(dirname "$0")/check-rule-placement.mjs"
3379
- `,lP=String.raw`/**
3388
+ `,TP=String.raw`/**
3380
3389
  * Is the file that was just edited enforcing a business rule inside the SPA?
3381
3390
  *
3382
3391
  * Reads the PostToolUse payload on stdin, and when BOTH signals are present —
@@ -3445,9 +3454,9 @@ process.stdout.write(
3445
3454
  },
3446
3455
  }),
3447
3456
  );
3448
- `,uP=`---
3457
+ `,RP=`---
3449
3458
  name: roles-and-permissions
3450
- description: Decide who can open a screen and who can change a record \u2014 declare roles in public/turbobase.json, gate the UI on capabilities, and turn a denial into a message that names the role to ask for. Use when adding a screen, a nav item, a write button, a role, or answering "who can see/do X".
3459
+ 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".
3451
3460
  ---
3452
3461
 
3453
3462
  Two things are true at once on this platform, and holding both is the whole
@@ -3499,19 +3508,101 @@ permission system decorative.
3499
3508
  - **\`appRole\`** \u2014 a manifest role is always a standard role. Admin bypasses
3500
3509
  every capability check, so it is assigned, never authored. Declaring it is a
3501
3510
  deploy error, not a silently ignored key.
3502
- - **\`scopes\`** \u2014 row-level narrowing ("only this subsidiary", "only my own
3503
- records") is authored by an administrator. If a user needs to see fewer ROWS
3504
- of a table rather than fewer tables, that is a scope, and it is their job.
3511
+
3512
+ ## Scopes \u2014 restrict a role's rows, or grant it a Slack channel
3513
+
3514
+ A declared role may carry \`scopes\`, the same field an administrator edits in
3515
+ **Admin \u2192 Roles**. It holds two different kinds of dimension, with OPPOSITE
3516
+ defaults \u2014 keep them apart in your head:
3517
+
3518
+ \`\`\`json
3519
+ {
3520
+ "name": "Receiver",
3521
+ "capabilities": ["read:item_receipt", "read:memory"],
3522
+ "scopes": {
3523
+ "location": ["{{user.location}}"],
3524
+ "content": ["slack:C0PUBLIC"]
3525
+ }
3526
+ }
3527
+ \`\`\`
3528
+
3529
+ - **A RESTRICTION** (\`subsidiary\`, \`location\`, \`department\`, \`class\`, or any
3530
+ name matching \`^[a-z0-9_]{1,63}$\`) takes rows AWAY. Absent or empty means
3531
+ unrestricted. A whole-value \`{{user.<field>}}\` token narrows each holder to
3532
+ their own value. A dimension no table on this instance maps restricts nothing \u2014
3533
+ \`turbobase apps plan\` warns about it rather than letting you ship a role you
3534
+ believe is narrower than it is.
3535
+ - **\`content\` is a GRANT** \u2014 the exact containers of \`memory_document\` the role
3536
+ may read, written \`slack:<channel id>\`. Absent or empty means NOTHING. Slack is
3537
+ the only grantable source; at most 16 values; no \`*\`, no \`{{user.\u2026}}\` token.
3538
+ Direct messages can never be granted.
3539
+
3540
+ ### Reading Slack history: \`read:memory\` AND \`content\`, or nothing
3541
+
3542
+ A non-admin reads a \`memory_document\` row only when the role they are ACTING AS
3543
+ holds \`read:memory\` and lists that row's channel in \`content\`. Either half on
3544
+ its own reads nothing, and the deploy warns about a role that has one without
3545
+ the other. A granted channel's history is readable whether or not the holder is
3546
+ in that channel, or has a Slack account at all \u2014 private channels included.
3547
+ Posting to Slack and Pilot are unchanged by a grant.
3548
+
3549
+ Someone who holds several roles reads a granted channel only while acting as the
3550
+ role that grants it. A query against a channel the acting role is not granted
3551
+ returns an empty list, exactly like any other denied read \u2014 so gate the screen
3552
+ on \`hasCapability('read:memory')\` and say which role to ask for.
3553
+
3554
+ **Never write a customer's channel id into an app other accounts deploy.** Ship
3555
+ the role with \`read:memory\` and no \`content\`, and have each account's own deploy
3556
+ add its channel to \`roles[].scopes.content\`. Only an app built for exactly one
3557
+ account names that account's channels in source.
3505
3558
 
3506
3559
  ### Changing a role later
3507
3560
 
3508
3561
  Adding a capability to a declared role and redeploying adds it. **Removing one
3509
3562
  from the manifest does NOT remove it from the role** \u2014 a role can have live
3510
- holders, and a deploy must never be able to revoke someone's access. Ask an
3511
- administrator to narrow it in the role editor.
3512
-
3513
- Run \`turbobase apps plan\` to see exactly what a deploy would create or widen
3514
- before you ship it. It writes nothing.
3563
+ holders, and a deploy must never be able to take whole screens away from them.
3564
+ Ask an administrator to narrow it in the role editor.
3565
+
3566
+ **Scopes are different, and only your app's own can move.** Omitting \`scopes\`, or
3567
+ one dimension of it, changes nothing on the role \u2014 so an older manifest or a
3568
+ deploy that skipped the account's channel cannot retract anything.
3569
+
3570
+ - **\`content\`:** a redeploy adds what is new since your last deploy and removes
3571
+ what you stopped declaring \u2014 only values your app ADDED, and not while
3572
+ another app on the same role still declares them. \`"content": []\` retires
3573
+ everything your app added. A value an administrator ADDED (one your app did
3574
+ not put there) is never touched, even if your manifest later declares the
3575
+ same value: the deploy ADOPTS a value the role already holds, and adopting is
3576
+ not owning. A value an administrator REMOVED is not re-added for as long as
3577
+ your app keeps declaring it. Dropping the role from \`roles\`, or deleting the
3578
+ app, retires the \`content\` values your app added on it too.
3579
+ - **Restrictions:** a restriction is your app's only when your deploy WROTE it \u2014
3580
+ on a role it created, or on one that was unrestricted on that dimension
3581
+ (which narrows what its current holders see). Your app may narrow, widen or
3582
+ clear (\`[]\`) a restriction it wrote, until an administrator changes it \u2014 then
3583
+ the administrator's value stays and the deploy says so, and if that value is
3584
+ WIDER than yours, a deploy that adds capabilities to the role is refused
3585
+ (they would reach rows your declaration keeps them from). Declaring the value
3586
+ a role already holds ADOPTS it: nothing changes, and your app can never clear
3587
+ it (\`[]\` leaves it) or change it (a different value is a conflict).
3588
+ Declaring a restriction your app never wrote on a role that already carries a
3589
+ DIFFERENT one, or one another app declares differently on the same role, is
3590
+ a conflict that **refuses the whole deploy**, capabilities included: the
3591
+ capabilities without their restriction would widen the role. A role your app
3592
+ stops declaring keeps its restrictions exactly as they are.
3593
+
3594
+ A removed \`content\` value stops applying on the holder's next query; anything a
3595
+ role GAINS reaches its holders when they next sign in.
3596
+
3597
+ Run \`turbobase apps plan . --app <your app's slug>\` to see what a deploy would
3598
+ create, widen, narrow or retire before you ship it. It writes nothing, prints
3599
+ every warning, and exits non-zero on a conflict. **The slug is not optional in
3600
+ practice:** it is how the plan tells your app's earlier declarations from
3601
+ another app's, as the deploy does. Without it, every scope an app has already
3602
+ declared on a role is left out of the plan with a notice \u2014 the deploy decides
3603
+ it, and may refuse \u2014 and nothing a deploy would retire is listed. With it the
3604
+ plan lists what \`"roles": []\` retires too. The one thing it never lists is
3605
+ what deleting the app retires.
3515
3606
 
3516
3607
  ## Capabilities
3517
3608
 
@@ -3594,9 +3685,9 @@ a denial look like emptiness.
3594
3685
  - Does the nav entry check \`hasCapability\`?
3595
3686
  - Does the screen check BEFORE rendering, with a message naming the role?
3596
3687
  - Does every write catch \`TurbobasePermissionError\`?
3597
- - Did you run \`turbobase apps plan\`?
3688
+ - Did you run \`turbobase apps plan . --app <slug>\`?
3598
3689
  - Did you tell the user their administrator still has to ASSIGN the role?
3599
- `,dP=`---
3690
+ `,EP=`---
3600
3691
  name: app-design
3601
3692
  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.
3602
3693
  ---
@@ -3691,7 +3782,7 @@ The design system covers the look. Two rules it does not:
3691
3782
  Load it in the browser and check: does it render with ZERO rows, with ONE row,
3692
3783
  and with several hundred? Does it survive the query failing? Does tab reach every
3693
3784
  control, with a visible focus ring? A green \`npm run build\` proves none of these.
3694
- `,ca="",nb=String.raw`{
3785
+ `,ua="",mb=String.raw`{
3695
3786
  "_comment": [
3696
3787
  "Declarative sync config — part of this repo's desired state.",
3697
3788
  " turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
@@ -3713,7 +3804,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3713
3804
  "fields": [],
3714
3805
  "tables": []
3715
3806
  }
3716
- `,ob=String.raw`{
3807
+ `,fb=String.raw`{
3717
3808
  "_comment": [
3718
3809
  "Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
3719
3810
  "Removing an entry does NOT remove the schedule unless you pass --prune.",
@@ -3729,93 +3820,93 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3729
3820
  ],
3730
3821
  "schedules": []
3731
3822
  }
3732
- `,pP=t=>`node_modules/
3823
+ `,PP=t=>`node_modules/
3733
3824
 
3734
3825
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
3735
3826
  .mcp.json
3736
3827
 
3737
3828
  .DS_Store
3738
- `;function bu(t={}){let e=Z0.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:pP(r)},{path:"INSTANCE-LEARNINGS.md",content:rP(o)},{path:"TURBOBASE-FEEDBACK.md",content:nP(o)},{path:".claude/settings.json",content:aP},{path:`.claude/output-styles/${sP}.md`,content:iP},{path:".claude/skills/generate-types/SKILL.md",content:V0(n)},{path:".claude/skills/record-learning/SKILL.md",content:tP(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:eP},{path:".claude/hooks/session-start-refresh-types.sh",content:oP(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:cP,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:lP}];return r?[{path:"CLAUDE.md",content:W0(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:X0},{path:".claude/skills/ship-app/SKILL.md",content:Q0},{path:".claude/skills/app-design/SKILL.md",content:dP},{path:".claude/skills/roles-and-permissions/SKILL.md",content:uP},...Y0(),{path:"conduits/.gitkeep",content:ca},{path:"turbobase/sync.json",content:nb},{path:"turbobase/schedules.json",content:ob},...rb()]:[{path:"CLAUDE.md",content:B0},...s,{path:".claude/skills/mock-test/SKILL.md",content:H0},{path:".claude/skills/deploy/SKILL.md",content:K0},{path:"hooks/.gitkeep",content:ca},{path:"conduits/.gitkeep",content:ca},{path:"samples/.gitkeep",content:ca},{path:"turbobase/sync.json",content:nb},{path:"turbobase/schedules.json",content:ob}]}import{promises as _u}from"node:fs";import{dirname as mP,join as tr,resolve as db}from"node:path";function cb(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var ps="bundle.json",la="turbobase";function lb(t){let e;try{e=JSON.parse(t)}catch(c){throw new Error(`bundle.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=c=>Array.isArray(c)?c:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return wu(a)}function wu(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(ab)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(ab)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function ab(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function ub(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 da="hooks",pa="conduits",pb="processes",Wr="turbobase/sync.json",Gr="turbobase/schedules.json";function vu(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 xu(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 ms(t){let e;try{e=await _u.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 ms(tr(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 ua(t,e){let r;try{r=await _u.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function hP(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function fP(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function gP(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 mb(t=process.cwd()){let e=db(t),[r,n,o]=await Promise.all([ms(tr(e,da)),ms(tr(e,pa)),ms(tr(e,pb))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([ua(tr(e,Wr),Wr).catch(()=>{}),ua(tr(e,Gr),Gr).catch(()=>{})]);return s!==void 0||i!==void 0}async function hb(t=process.cwd(),e={}){let r=db(t),n=cb(e.tenant),o=[],s=[];for(let c of[da,pa,pb])for(let l of await ms(tr(r,c))){let u=`${c}/${l}`,p=await _u.readFile(tr(r,c,l),"utf8"),y=e.inline?await e.inline(p,mP(tr(r,c,l))):p,h=vu(y);if(!h){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(y)&&s.push({file:u,reason:xu(y)});continue}let m={id:h.id,kind:h.extensionKind,recordType:h.recordType,event:h.event,source:h.source,sourceCode:y};h.extensionKind==="conduit"?n.conduits.push(m):n.hooks.push(m),o.push(u)}let i=await ua(tr(r,Wr),Wr);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Wr} 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(hP(l));for(let l of Array.isArray(c.tables)?c.tables:[])n.sync.tables.push(fP(l));o.push(Wr)}let a=await ua(tr(r,Gr),Gr);if(a!==void 0){let c=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(c===null)throw new Error(`${Gr} must be a JSON array, or an object with a "schedules" array.`);for(let l of c)n.schedules.push(gP(l));o.push(Gr)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(c=>c.event==="before_save").map(c=>c.id).sort(),{manifest:wu(n),contributed:o,unparsed:s}}import{promises as $u}from"node:fs";import{resolve as xP}from"node:path";var yP="For app developers \u2014 adopt these";function fb(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 gb(t,e){let r=fb(t),n=fb(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 bP(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var NB=bP(yP);is();Qt();var wP=t=>new Promise(e=>setTimeout(e,t));function yb(t){return t.stage==="completed"||t.stage==="failed"}function _P(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function vP(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(`
3739
- `))r(i)}return n}async function ku(t,e={}){let r=e.sink??(y=>{process.stdout.write(`${y}
3740
- `)}),n=e.sleep??wP,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(y=>r(_P(y))),a=e.onPoll,c="",l="",u=y=>{a?.(y),y.stage!==l&&i(y),c=vP(y,c,r),l=y.stage},p=await t();if(u(p),yb(p))return p;for(let y=0;y<s;y+=1)if(await n(o),p=await t(),u(p),yb(p))return p;return p}var _=t=>{process.stdout.write(`${t}
3829
+ `;function vu(t={}){let e=aP.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:PP(r)},{path:"INSTANCE-LEARNINGS.md",content:wP(o)},{path:"TURBOBASE-FEEDBACK.md",content:_P(o)},{path:".claude/settings.json",content:SP},{path:`.claude/output-styles/${xP}.md`,content:kP},{path:".claude/skills/generate-types/SKILL.md",content:cP(n)},{path:".claude/skills/record-learning/SKILL.md",content:bP(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:yP},{path:".claude/hooks/session-start-refresh-types.sh",content:vP(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:$P,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:TP}];return r?[{path:"CLAUDE.md",content:dP(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:fP},{path:".claude/skills/ship-app/SKILL.md",content:gP},{path:".claude/skills/app-design/SKILL.md",content:EP},{path:".claude/skills/roles-and-permissions/SKILL.md",content:RP},...mP(),{path:"conduits/.gitkeep",content:ua},{path:"turbobase/sync.json",content:mb},{path:"turbobase/schedules.json",content:fb},...hb()]:[{path:"CLAUDE.md",content:iP},...s,{path:".claude/skills/mock-test/SKILL.md",content:lP},{path:".claude/skills/deploy/SKILL.md",content:uP},{path:"hooks/.gitkeep",content:ua},{path:"conduits/.gitkeep",content:ua},{path:"samples/.gitkeep",content:ua},{path:"turbobase/sync.json",content:mb},{path:"turbobase/schedules.json",content:fb}]}import{promises as ku}from"node:fs";import{dirname as AP,join as rr,resolve as xb}from"node:path";function wb(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var fs="bundle.json",da="turbobase";function _b(t){let e;try{e=JSON.parse(t)}catch(c){throw new Error(`bundle.json is not valid JSON: ${c instanceof Error?c.message:String(c)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=c=>Array.isArray(c)?c:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return xu(a)}function xu(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(bb)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(bb)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function bb(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function vb(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 ha="hooks",ma="conduits",kb="processes",Gr="turbobase/sync.json",Jr="turbobase/schedules.json";function Su(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 $u(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 gs(t){let e;try{e=await ku.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 gs(rr(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 pa(t,e){let r;try{r=await ku.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function CP(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function IP(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function OP(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 Sb(t=process.cwd()){let e=xb(t),[r,n,o]=await Promise.all([gs(rr(e,ha)),gs(rr(e,ma)),gs(rr(e,kb))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([pa(rr(e,Gr),Gr).catch(()=>{}),pa(rr(e,Jr),Jr).catch(()=>{})]);return s!==void 0||i!==void 0}async function $b(t=process.cwd(),e={}){let r=xb(t),n=wb(e.tenant),o=[],s=[];for(let c of[ha,ma,kb])for(let l of await gs(rr(r,c))){let u=`${c}/${l}`,p=await ku.readFile(rr(r,c,l),"utf8"),b=e.inline?await e.inline(p,AP(rr(r,c,l))):p,m=Su(b);if(!m){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(b)&&s.push({file:u,reason:$u(b)});continue}let h={id:m.id,kind:m.extensionKind,recordType:m.recordType,event:m.event,source:m.source,sourceCode:b};m.extensionKind==="conduit"?n.conduits.push(h):n.hooks.push(h),o.push(u)}let i=await pa(rr(r,Gr),Gr);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Gr} 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(CP(l));for(let l of Array.isArray(c.tables)?c.tables:[])n.sync.tables.push(IP(l));o.push(Gr)}let a=await pa(rr(r,Jr),Jr);if(a!==void 0){let c=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(c===null)throw new Error(`${Jr} must be a JSON array, or an object with a "schedules" array.`);for(let l of c)n.schedules.push(OP(l));o.push(Jr)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(c=>c.event==="before_save").map(c=>c.id).sort(),{manifest:xu(n),contributed:o,unparsed:s}}import{promises as Eu}from"node:fs";import{resolve as MP}from"node:path";var NP="For app developers \u2014 adopt these";function Tb(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 Rb(t,e){let r=Tb(t),n=Tb(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 zP(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var QF=zP(NP);cs();er();var LP=t=>new Promise(e=>setTimeout(e,t));function Eb(t){return t.stage==="completed"||t.stage==="failed"}function jP(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function DP(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(`
3830
+ `))r(i)}return n}async function Tu(t,e={}){let r=e.sink??(b=>{process.stdout.write(`${b}
3831
+ `)}),n=e.sleep??LP,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(b=>r(jP(b))),a=e.onPoll,c="",l="",u=b=>{a?.(b),b.stage!==l&&i(b),c=DP(b,c,r),l=b.stage},p=await t();if(u(p),Eb(p))return p;for(let b=0;b<s;b+=1)if(await n(o),p=await t(),u(p),Eb(p))return p;return p}var _=t=>{process.stdout.write(`${t}
3741
3832
  `)},q=t=>{process.stderr.write(`${t}
3742
- `)};function x(t){q(g.red(`turbobase: ${t}`)),process.exit(1)}var hs=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function bb(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&hu(!1)}async function te(t){let e=await Xt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Pr();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";x(`not signed in to ${Dt(t)}.${n} Run \`turbobase auth login --base-url ${Dt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&x("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ot())try{let n=await st("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Wi(n);let o=await Xt();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 ne(t,e,r){if(!(t instanceof ce)||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 Su(t,e,r){let n=r?Number(r):void 0;if(sa()){let s=gu(e),i;try{i=await ku(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 ku(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 kP=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function SP(t){try{let e=await $u.readFile(t,"utf8");return kP.exec(e)?.[1]??null}catch{return null}}var $P=/GENERATED by `turbobase project adopt`/,_b=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,TP=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function wb(t){let e=[],r=null;for(let n of t.split(`
3743
- `)){let o=_b.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=TP.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 RP(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
3833
+ `)};function v(t){q(f.red(`turbobase: ${t}`)),process.exit(1)}var ys=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Pb(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&gu(!1)}async function Q(t){let e=await Qt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Ar();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";v(`not signed in to ${Mt(t)}.${n} Run \`turbobase auth login --base-url ${Mt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it())try{let n=await at("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Ji(n);let o=await Qt();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}v(`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 te(t,e,r){if(!(t instanceof le)||t.status!==403)return;t.body?.error==="approval_required"&&v(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),v(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Ru(t,e,r){let n=r?Number(r):void 0;if(aa()){let s=bu(e),i;try{i=await Tu(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(),v(`${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 Tu(t,{sink:_,intervalMs:n})}catch(s){v(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&v(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),_(`${e} ${o.stage}.`)}var UP=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function qP(t){try{let e=await Eu.readFile(t,"utf8");return UP.exec(e)?.[1]??null}catch{return null}}var BP=/GENERATED by `turbobase project adopt`/,Cb=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,FP=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Ab(t){let e=[],r=null;for(let n of t.split(`
3834
+ `)){let o=Cb.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=FP.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 ZP(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
3744
3835
  `)).join(`
3745
3836
  `);return`## v${t.version}
3746
3837
 
3747
- ${e}`}function EP(t,e){let r=wb(t);if(r.length===0&&!$P.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of wb(e)){let p=n.get(u.version);n.delete(u.version);let y=new Set(u.items.map(m=>m.key)),h=u.items.map(m=>{let w=p?.items.find(S=>S.key===m.key);return w?{...m,done:w.done,extra:w.extra}:m});for(let m of p?.items??[])y.has(m.key)||m.done||(h.push(m),s+=1);o.push({version:u.version,items:h})}for(let u of n.values()){let p=u.items.filter(y=>!y.done);p.length!==0&&(s+=p.length,o.push({version:u.version,items:p}))}o.sort((u,p)=>gb(p.version,u.version));let i=e.split(`
3748
- `),a=i.findIndex(u=>_b.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
3838
+ ${e}`}function VP(t,e){let r=Ab(t);if(r.length===0&&!BP.test(t))return null;let n=new Map(r.map(u=>[u.version,u])),o=[],s=0;for(let u of Ab(e)){let p=n.get(u.version);n.delete(u.version);let b=new Set(u.items.map(h=>h.key)),m=u.items.map(h=>{let w=p?.items.find(S=>S.key===h.key);return w?{...h,done:w.done,extra:w.extra}:h});for(let h of p?.items??[])b.has(h.key)||h.done||(m.push(h),s+=1);o.push({version:u.version,items:m})}for(let u of n.values()){let p=u.items.filter(b=>!b.done);p.length!==0&&(s+=p.length,o.push({version:u.version,items:p}))}o.sort((u,p)=>Rb(p.version,u.version));let i=e.split(`
3839
+ `),a=i.findIndex(u=>Cb.test(u)),c=(a===-1?i:i.slice(0,a)).join(`
3749
3840
  `).replace(/\s+$/,"");return{markdown:o.length===0?`${c}
3750
3841
  `:`${c}
3751
3842
 
3752
- ${o.map(RP).join(`
3843
+ ${o.map(ZP).join(`
3753
3844
 
3754
3845
  `)}
3755
- `,carried:s}}function vb(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 te(e.baseUrl),o=xP(process.cwd(),e.out),s=e.since?.trim()||await SP(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((S,R)=>S+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??"",y=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${p}. Re-run to refresh; delete this file once every line is done. -->
3756
-
3757
- `,h=await $u.readFile(o,"utf8").catch(()=>null),m=l.markdown,w=0;if(h!==null&&h.trim()!==""){let S=EP(h,l.markdown);S||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=S.markdown,w=S.carried}await $u.writeFile(o,y+m,"utf8"),_(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${w>0?`, keeping ${w} unticked item(s) already in the file`:""}.`)})}Qt();var fs=["suggested_kb_edit","kb_correction"];var PP=[{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 AP(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var KB=new Map(PP.map(t=>[AP(t.heading),t]));var WB=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 CP(t){return t.diff??!!t.dryRun}var IP={update_page:"append to the existing page",new_page:"create a NEW page"},Cr=(t,e)=>` ${g.dim(t.padEnd(11))}${e}`,Sb=t=>t.ownerEmail??t.ownerId;function go(t){return!t.needsPageRef&&!t.blockedBy}var ma=t=>g.green(t?` + ${t}`:" +"),OP=t=>g.red(t?` - ${t}`:" -"),Nn=t=>g.dim(` ${t}`),NP=` ${g.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Tu=80;function zP(t){let e=[NP];t.target?(e.push(Nn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(OP(`visibility: ${t.target.visibility}`)),e.push(ma("visibility: admin"))):e.push(Nn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(Nn("title, slug, evidence: untouched")),e.push(Nn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(Nn("turbobase.document \xB7 new")),e.push(ma(`title: ${t.pageTitle}`)),e.push(ma("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(Nn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(Nn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3758
- `);for(let n of r.slice(0,Tu))e.push(ma(n?` ${n}`:""));return r.length>Tu&&e.push(g.yellow(` \u2026 ${r.length-Tu} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function LP(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(Cr("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:g.dim("new \u2014 no existing page matches"))),r.push(Cr("action",go(n)?IP[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(Cr("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(Cr("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(Cr("confidence",n.withdraws?g.red("WITHDRAWN from readers (text untouched)"):g.dim("untouched"))),n.supersedes&&r.push(Cr("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(Cr("blocked",g.red(`unpublished work on this page belongs to ${Sb(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Cr("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(Cr("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&&go(n)&&r.push(...zP(n)),r.push("")}),r}function jP(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(go)} page(s)`,`${e(l=>l.action==="update_page"&&go(l))} appended`,`${e(l=>l.action==="new_page"&&go(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 DP(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?Sb(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 xb(t){if(t instanceof ce){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.")}ne(t,"extensions:deploy","learnings push-kb")}async function gs(t,e){let r;try{r=await se("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof ce&&o.status===404?q(g.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):by(o)?q(g.yellow(kb(o))):q(g.yellow(`could not re-read the pushed markdown: ${kb(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return q(g.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),r;let n=[`${r.filesScanned} file(s) scanned`];return r.docsIngested>0&&n.push(`${r.docsIngested} changed`),r.docsUnchanged>0&&n.push(`${r.docsUnchanged} unchanged`),n.push(`${r.entriesAdded} new finding(s)`),r.entriesDuplicate>0&&n.push(`${r.entriesDuplicate} already known`),r.parseSkipped>0&&n.push(g.yellow(`${r.parseSkipped} unparseable`)),q(g.dim(n.join(" \xB7 "))),r}function kb(t){return t instanceof Error?t.message:String(t)}async function $b(t,e=r=>new J(r)){t.section&&!fs.includes(t.section.trim())&&x(`unknown --section "${t.section}" \u2014 expected one of ${fs.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&x("--limit must be a positive integer.");let r=await te(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 gs(n,t.app),i;try{i=await se("reading the pending queue",()=>n.learningsPending(o))}catch(l){xb(l),x(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){q(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}q(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(_(LP(i.items,{diff:CP(t)}).join(`
3759
- `)),_(jP(i.items)),t.dryRun){q(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(go);if(a.length===0){q(g.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let c=a.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!ot()){q(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await st(`Push ${c} finding(s) into the knowledge base as ${a.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await se("writing pages",()=>n.learningsPushKb(i.planToken,o));_(DP(l.applied,i.items).join(`
3760
- `))}catch(l){if(l instanceof ce&&l.status===409){q(g.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),q(`re-run \`${hs} kb push\` to review the current plan.`),process.exitCode=2;return}xb(l),q(g.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}Qt();var yo=t=>new J(t);async function bo(t,e){let r=await te(t.baseUrl);return e(r)}async function ha(t,e,r,n){return n.yes?!0:ot()?await st(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function MP(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function Tb(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function UP(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(`${Tb(g.bold(s.slug),e)} ${Tb(MP(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 Rb(t,e=yo){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 bo(t,e),o;try{o=await se("reading the knowledge base",()=>n.docsList(r))}catch(s){ne(s,"docs:publish","read the knowledge base"),x(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}_(UP(o).join(`
3761
- `))}async function Eb(t,e,r=yo){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 bo(e,r);if(!await ha(`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 se("publishing",()=>o.docsPublish(n))}catch(c){ne(c,"docs:publish","publish a page"),x(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);_(g.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),q(g.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Pb(t,e,r=yo){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 bo(e,r);if(!await ha(`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 se("unpublishing",()=>o.docsUnpublish(n))}catch(c){ne(c,"docs:publish","unpublish a page"),x(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);_(g.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),q(g.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(q(g.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Ab(t,e=yo){let r=await bo(t,e),n;try{n=await se("reading the releases",()=>r.docsVersions())}catch(o){ne(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 Cb(t,e,r=yo){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 bo(e,r);if(await ha(`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 se("rolling back",()=>o.docsRollback(n));_(g.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){ne(i,"docs:publish","roll the knowledge base back"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Ib(t,e,r=yo){let n=(t??"").trim();n||x("name the page slug to delete. `turbobase kb list` shows them.");let o=await bo(e,r);if(await ha(`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 se("deleting",()=>o.docsDelete(n));_(g.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){ne(i,"docs:publish","delete a page"),x(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Qt();function qP(t){return t.diff??!!t.dryRun}function FP(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(`
3762
- `))r.push(` ${g.dim("|")} ${a}`)}r.push("")}),r}function BP(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 Ob(t,e=r=>new J(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&x("--limit must be a positive integer.");let r=await te(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 gs(n,t.app),i;try{i=await se("reading the pending rules",()=>n.rulesPending(o))}catch(c){ne(c,"extensions:deploy","read the pending rules"),x(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){q(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}q(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(_(FP(i.items,{diff:qP(t)}).join(`
3763
- `)),_(BP(i.items)),t.dryRun){q(g.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!ot()){q(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await st(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await se("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof ce&&c.status===409&&x("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),x(`push failed: ${c instanceof Error?c.message:String(c)}`)}_(g.green(`wrote ${i.items.length} draft rule(s).`)),q(g.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as GP,readFile as JP,stat as YP}from"node:fs/promises";import{join as Lb,resolve as XP}from"node:path";var Ir=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},ZP=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Nb(t){let e=t.replace(/^/,""),r=ZP.exec(e);if(!r)throw new Ir("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=VP(n??""),i=s.name,a=s.description;if(!i)throw new Ir("SKILL.md frontmatter is missing required `name`");if(!a)throw new Ir("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 VP(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 Ir(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Ir(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=KP(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(`
3764
- `)).trim();continue}e[i]=HP(a),n+=1}return e}function HP(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function KP(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 WP=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function zb(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)";WP.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}Qt();async function QP(t){let e=XP(t),r;try{r=(await GP(e)).sort()}catch{x(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=Lb(e,o,"SKILL.md");if(await YP(s).then(a=>a.isFile()).catch(()=>!1))try{let a=Nb(await JP(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Ir&&x(`${Lb(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var fa={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},eA={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 tA(t){let e=[];for(let r of t.items){let n=r.action==="refused"?g.red(fa.refused):r.action==="unchanged"?g.dim(fa.unchanged):r.action==="new"?g.green(fa.new):g.yellow(fa.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(eA[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 jb(t,e=r=>new J(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 QP(t.from),n=zb(r);n.length>0&&x(`nothing was sent:
3846
+ `,carried:s}}function Ib(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 Q(e.baseUrl),o=MP(process.cwd(),e.out),s=e.since?.trim()||await qP(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||v(`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((S,R)=>S+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??"",b=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${p}. Re-run to refresh; delete this file once every line is done. -->
3847
+
3848
+ `,m=await Eu.readFile(o,"utf8").catch(()=>null),h=l.markdown,w=0;if(m!==null&&m.trim()!==""){let S=VP(m,l.markdown);S||v(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),h=S.markdown,w=S.carried}await Eu.writeFile(o,b+h,"utf8"),_(`wrote ${o} \u2014 ${u} item(s) across ${l.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${w>0?`, keeping ${w} unticked item(s) already in the file`:""}.`)})}er();var bs=["suggested_kb_edit","kb_correction"];var HP=[{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 KP(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var pZ=new Map(HP.map(t=>[KP(t.heading),t]));var hZ=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 WP(t){return t.diff??!!t.dryRun}var GP={update_page:"append to the existing page",new_page:"create a NEW page"},Ir=(t,e)=>` ${f.dim(t.padEnd(11))}${e}`,zb=t=>t.ownerEmail??t.ownerId;function yo(t){return!t.needsPageRef&&!t.blockedBy}var fa=t=>f.green(t?` + ${t}`:" +"),JP=t=>f.red(t?` - ${t}`:" -"),zn=t=>f.dim(` ${t}`),YP=` ${f.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Pu=80;function XP(t){let e=[YP];t.target?(e.push(zn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(JP(`visibility: ${t.target.visibility}`)),e.push(fa("visibility: admin"))):e.push(zn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(zn("title, slug, evidence: untouched")),e.push(zn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(zn("turbobase.document \xB7 new")),e.push(fa(`title: ${t.pageTitle}`)),e.push(fa("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(zn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(zn('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3849
+ `);for(let n of r.slice(0,Pu))e.push(fa(n?` ${n}`:""));return r.length>Pu&&e.push(f.yellow(` \u2026 ${r.length-Pu} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function QP(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${f.bold(n.pageTitle)}`),r.push(Ir("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:f.dim("new \u2014 no existing page matches"))),r.push(Ir("action",yo(n)?GP[n.action]:f.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(Ir("unresolved",f.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(Ir("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?` ${f.dim(`\xB7 ${a.verdict}`)}`:"",l=a.kb_page_ref?` ${f.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${f.dim("\xB7")} ${a.title.trim()}${l}${c}`)}),r.push(Ir("confidence",n.withdraws?f.red("WITHDRAWN from readers (text untouched)"):f.dim("untouched"))),n.supersedes&&r.push(Ir("supersedes",f.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(Ir("blocked",f.red(`unpublished work on this page belongs to ${zb(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Ir("ambiguous",f.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(Ir("similar",f.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&&yo(n)&&r.push(...XP(n)),r.push("")}),r}function eA(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(yo)} page(s)`,`${e(l=>l.action==="update_page"&&yo(l))} appended`,`${e(l=>l.action==="new_page"&&yo(l))} created (unpublished)`,...s>0?[f.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?f.red(`${n} page(s) WITHDRAWN from readers`):f.dim("no page withdrawn"),c=o>0?` \xB7 ${f.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${c}`}function tA(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(`${f.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?zb(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(`${f.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(`${f.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?f.green("created "):f.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${f.bold(o.documentId??"?")}`+(o.created?f.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${f.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${f.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${f.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Ob(t){if(t instanceof le){let e=t.body;t.status===403&&e?.reason==="admin_required"&&v("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&&v("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}te(t,"extensions:deploy","learnings push-kb")}async function ws(t,e){let r;try{r=await se("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof le&&o.status===404?q(f.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`.")):vy(o)?q(f.yellow(Nb(o))):q(f.yellow(`could not re-read the pushed markdown: ${Nb(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return q(f.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(f.yellow(`${r.parseSkipped} unparseable`)),q(f.dim(n.join(" \xB7 "))),r}function Nb(t){return t instanceof Error?t.message:String(t)}async function Lb(t,e=r=>new G(r)){t.section&&!bs.includes(t.section.trim())&&v(`unknown --section "${t.section}" \u2014 expected one of ${bs.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await Q(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 ws(n,t.app),i;try{i=await se("reading the pending queue",()=>n.learningsPending(o))}catch(l){Ob(l),v(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){q(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}q(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(_(QP(i.items,{diff:WP(t)}).join(`
3850
+ `)),_(eA(i.items)),t.dryRun){q(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(yo);if(a.length===0){q(f.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(!it()){q(f.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 at(`Push ${c} finding(s) into the knowledge base as ${a.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let l=await se("writing pages",()=>n.learningsPushKb(i.planToken,o));_(tA(l.applied,i.items).join(`
3851
+ `))}catch(l){if(l instanceof le&&l.status===409){q(f.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),q(`re-run \`${ys} kb push\` to review the current plan.`),process.exitCode=2;return}Ob(l),q(f.red(`turbobase: ${l instanceof Error?l.message:String(l)}`)),process.exitCode=2}}er();var bo=t=>new G(t);async function wo(t,e){let r=await Q(t.baseUrl);return e(r)}async function ga(t,e,r,n){return n.yes?!0:it()?await at(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function rA(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function jb(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function nA(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(`${jb(f.bold(s.slug),e)} ${jb(rA(s),10)} ${f.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 Db(t,e=bo){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await wo(t,e),o;try{o=await se("reading the knowledge base",()=>n.docsList(r))}catch(s){te(s,"docs:publish","read the knowledge base"),v(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}_(nA(o).join(`
3852
+ `))}async function Mb(t,e,r=bo){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await wo(e,r);if(!await ga(`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 se("publishing",()=>o.docsPublish(n))}catch(c){te(c,"docs:publish","publish a page"),v(`publish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.published.map(c=>c.slug);_(f.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(q(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),q(f.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Ub(t,e,r=bo){let n=[...new Set(t.map(c=>c.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await wo(e,r);if(!await ga(`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 se("unpublishing",()=>o.docsUnpublish(n))}catch(c){te(c,"docs:publish","unpublish a page"),v(`unpublish failed: ${c instanceof Error?c.message:String(c)}`)}let a=i.unpublished.map(c=>c.slug);_(f.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),q(f.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(q(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function qb(t,e=bo){let r=await wo(t,e),n;try{n=await se("reading the releases",()=>r.docsVersions())}catch(o){te(o,"docs:publish","read the knowledge-base releases"),v(`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?f.green("current"):f.dim(" ");_(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${f.dim(o.published_by)}`:""}`),o.release_note&&_(` ${f.dim(o.release_note)}`)}}async function Bb(t,e,r=bo){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await wo(e,r);if(await ga(`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 se("rolling back",()=>o.docsRollback(n));_(f.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){te(i,"docs:publish","roll the knowledge base back"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Fb(t,e,r=bo){let n=(t??"").trim();n||v("name the page slug to delete. `turbobase kb list` shows them.");let o=await wo(e,r);if(await ga(`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 se("deleting",()=>o.docsDelete(n));_(f.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){te(i,"docs:publish","delete a page"),v(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}er();function oA(t){return t.diff??!!t.dryRun}function sA(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?f.green("new rule"):f.yellow("amend rule"),i=n.targetPublished?` ${f.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${f.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${f.dim(n.description)}`);for(let a of n.entries)r.push(` ${f.dim("\xB7")} ${f.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
3853
+ `))r.push(` ${f.dim("|")} ${a}`)}r.push("")}),r}function iA(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(f.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Zb(t,e=r=>new G(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await Q(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 ws(n,t.app),i;try{i=await se("reading the pending rules",()=>n.rulesPending(o))}catch(c){te(c,"extensions:deploy","read the pending rules"),v(`could not read the pending queue: ${c instanceof Error?c.message:String(c)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){q(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}q(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(_(sA(i.items,{diff:oA(t)}).join(`
3854
+ `)),_(iA(i.items)),t.dryRun){q(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((c,l)=>c+l.entries.length,0);if(!t.yes){if(!it()){q(f.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 at(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await se("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(c){c instanceof le&&c.status===409&&v("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),v(`push failed: ${c instanceof Error?c.message:String(c)}`)}_(f.green(`wrote ${i.items.length} draft rule(s).`)),q(f.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as pA,readFile as hA,stat as mA}from"node:fs/promises";import{join as Kb,resolve as fA}from"node:path";var Or=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},aA=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Vb(t){let e=t.replace(/^/,""),r=aA.exec(e);if(!r)throw new Or("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=cA(n??""),i=s.name,a=s.description;if(!i)throw new Or("SKILL.md frontmatter is missing required `name`");if(!a)throw new Or("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 cA(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 Or(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Or(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=uA(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(`
3855
+ `)).trim();continue}e[i]=lA(a),n+=1}return e}function lA(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function uA(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 dA=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function Hb(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)";dA.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}er();async function gA(t){let e=fA(t),r;try{r=(await pA(e)).sort()}catch{v(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=Kb(e,o,"SKILL.md");if(await mA(s).then(a=>a.isFile()).catch(()=>!1))try{let a=Vb(await hA(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Or&&v(`${Kb(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var ya={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},yA={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 bA(t){let e=[];for(let r of t.items){let n=r.action==="refused"?f.red(ya.refused):r.action==="unchanged"?f.dim(ya.unchanged):r.action==="new"?f.green(ya.new):f.yellow(ya.update),o=r.targetPublished?` ${f.yellow("[currently live]")}`:"";e.push(`${n} ${f.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${f.red(yA[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${f.yellow("orphan")} ${f.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 Wb(t,e=r=>new G(r)){t.app||v("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await gA(t.from),n=Hb(r);n.length>0&&v(`nothing was sent:
3765
3856
  ${n.join(`
3766
- `)}`);let o=await te(t.baseUrl),s=e(o),i=async y=>{try{return await se(y?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,y))}catch(h){if(ne(h,"extensions:deploy","push skill files"),h instanceof ce&&h.status===404){let m=h.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: ${h instanceof Error?h.message:String(h)}`)}},a=await i(!0);_(tA(a).join(`
3767
- `));let c=a.items.filter(y=>y.action==="new"||y.action==="update").length,l=a.items.filter(y=>y.action==="refused").length;if(t.dryRun){q(g.dim("dry run \u2014 nothing was written.")),l>0&&(process.exitCode=1);return}let u=a;if(c>0){if(!t.yes){if(!ot()){q(g.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await st(`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"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}u=await i(!1)}let p=u.items.filter(y=>y.action==="new"||y.action==="update").map(y=>y.slug);if(_(`${p.length} written, ${u.items.filter(y=>y.action==="unchanged").length} unchanged, ${u.items.filter(y=>y.action==="refused").length} refused.`),t.publish&&p.length>0){let y;try{y=await se("publishing",()=>s.skillsPublish(p))}catch(h){ne(h,"skills:publish","publish the pushed skills"),x(`the skills were written as drafts but publishing failed: ${h instanceof Error?h.message:String(h)}`)}_(g.green(`published ${y.published.join(", ")} \u2014 live as of release ${y.version.version_no}.`))}else t.publish?_(g.dim("nothing changed \u2014 nothing to publish.")):p.length>0&&q(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(y=>y.action==="refused")&&(q(g.red("one or more skill files were refused and not written.")),process.exitCode=1)}Qt();var rA=["proposed","active","rejected"],nA=["mechanic","operator","learning","code-baseline"],ga=t=>new J(t);async function ya(t,e){let r=await te(t.baseUrl);return e(r)}function Db(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 oA(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 qb(t){let e=Db(t.status,rA,"--status"),r=Db(t.provenance,nA,"--provenance"),n=oA(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Mb(t){return!!(t.provenance?.length||t.recordType||t.source)}var Fb=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function sA(t){return t.status==="active"?g.green("active"):t.status==="rejected"?g.dim("rejected"):g.yellow("proposed")}function iA(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 Bb(t){return[t.hookId,sA(t),t.provenance==="learning"?g.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),iA(t)]}async function Zb(t={},e=ga){let r=await ya(t,e),n=qb(t),o;try{o=await r.proposals(n)}catch(i){ne(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.
3768
- `+g.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}_(er(o.map(Bb),{head:Fb})),_(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 aA(t,e,r){return r.yes?!0:ot()?await st(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function cA(t){return!(t instanceof ce)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Ru(t,e){cA(t)&&ne(t,"extensions:deploy",e)}function Eu(t,e){let r=e instanceof ce?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);q(Oe.error(`${g.bold(t)} \u2014 ${s}`))}async function Ub(t,e){try{let r=await t.proposalPromote(e);return _(Oe.success(`${g.bold(e)} ${g.dim(`${r.previousStatus} \u2192`)} ${g.green(r.status)}`)),!0}catch(r){return Ru(r,"promote a hook proposal"),Eu(e,r),!1}}async function Vb(t,e={},r=ga){!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 ya(e,r);if(!e.auto){let u=0;for(let p of t)await Ub(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=qb({...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){ne(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${Mb(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):`),_(er(a.map(Bb),{head:Fb})),i.length>0&&_(g.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){_(""),_(Oe.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Mb(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 aA(`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 Ub(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 Hb(t,e={},r=ga){t.length===0&&x("retract: name at least one proposal id.");let n=await ya(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);_(Oe.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.yellow(i.status)}`)),o+=1}catch(i){Ru(i,"retract a hook proposal"),Eu(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 Kb(t,e={},r=ga){t.length===0&&x("reject: name at least one proposal id.");let n=await ya(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);_(Oe.success(`${g.bold(s)} ${g.dim(`${i.previousStatus} \u2192`)} ${g.dim(i.status)}`)),o+=1}catch(i){Ru(i,"reject a hook proposal"),Eu(s,i)}o<t.length&&(process.exitCode=1)}Qt();var Pu=t=>new J(t);async function lA(t,e){let r=await te(t.baseUrl);return e(r)}function uA(t){return!(t instanceof ce)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function dA(t,e){let r=e instanceof ce?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);q(Oe.error(`${g.bold(t)} \u2014 ${s}`))}async function Au(t,e,r,n,o,s,i){e.length===0&&x(`${t}: name at least one extension id.`);let a=await lA(r,n),c=[];for(let l of e)try{let u=await o(a,l);c.push(u),r.json||_(s(u))}catch(u){uA(u)&&ne(u,"extensions:deploy",`${t} an extension`),dA(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 Wb(t,e={},r=Pu){await Au("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>Oe.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 Gb(t,e={},r=Pu){await Au("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>Oe.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 Jb(t,e={},r=Pu){await Au("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>Oe.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)}Qt();var wo=t=>new J(t);async function _o(t,e){let r=await te(t.baseUrl);return e(r)}async function ba(t,e,r,n){return n.yes?!0:ot()?await st(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(g.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function pA(t){return t.visibility!=="published"?g.dim("draft"):t.in_current_release?g.green("live"):g.yellow("unreleased")}function Yb(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function mA(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(`${Yb(g.bold(s.slug),e)} ${Yb(pA(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 Xb(t,e=wo){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 _o(t,e),o;try{o=await se("reading the skills",()=>n.skillsList(r))}catch(s){ne(s,"skills:publish","read the instance skills"),x(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}_(mA(o).join(`
3769
- `))}async function Qb(t,e,r=wo){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 _o(e,r);if(!await ba(`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 se("publishing",()=>o.skillsPublish(n))}catch(a){ne(a,"skills:publish","publish a skill"),x(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(g.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function ew(t,e,r=wo){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 _o(e,r);if(!await ba(`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 se("unpublishing",()=>o.skillsUnpublish(n))}catch(a){ne(a,"skills:publish","unpublish a skill"),x(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(g.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(g.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(g.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function tw(t,e,r=wo){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 _o(e,r);if(await ba(`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 se("rolling back",()=>o.skillsRollback(n));_(g.green(`rolled back to v${i.version.version_no}.`))}catch(i){ne(i,"skills:publish","roll back a skills release"),x(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function rw(t,e=wo){let r=await _o(t,e),n;try{n=await se("reading the releases",()=>r.skillsReleases())}catch(o){ne(o,"skills:publish","read the skills releases"),x(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("no releases yet.");return}for(let o of n.items){let s=o.is_current?g.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";_(`${s} v${o.version_no} ${o.skill_count} skill(s) ${g.dim(o.published_at)}${o.published_by?g.dim(` by ${o.published_by}`):""}${g.dim(i)}`)}}async function nw(t,e,r=wo){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 _o(e,r);if(!await ba(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3857
+ `)}`);let o=await Q(t.baseUrl),s=e(o),i=async b=>{try{return await se(b?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,b))}catch(m){if(te(m,"extensions:deploy","push skill files"),m instanceof le&&m.status===404){let h=m.body;v(h?.error==="app_not_found"?String(h.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}v(`push failed: ${m instanceof Error?m.message:String(m)}`)}},a=await i(!0);_(bA(a).join(`
3858
+ `));let c=a.items.filter(b=>b.action==="new"||b.action==="update").length,l=a.items.filter(b=>b.action==="refused").length;if(t.dryRun){q(f.dim("dry run \u2014 nothing was written.")),l>0&&(process.exitCode=1);return}let u=a;if(c>0){if(!t.yes){if(!it()){q(f.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await at(`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"){q("aborted \u2014 nothing was written."),process.exitCode=1;return}}u=await i(!1)}let p=u.items.filter(b=>b.action==="new"||b.action==="update").map(b=>b.slug);if(_(`${p.length} written, ${u.items.filter(b=>b.action==="unchanged").length} unchanged, ${u.items.filter(b=>b.action==="refused").length} refused.`),t.publish&&p.length>0){let b;try{b=await se("publishing",()=>s.skillsPublish(p))}catch(m){te(m,"skills:publish","publish the pushed skills"),v(`the skills were written as drafts but publishing failed: ${m instanceof Error?m.message:String(m)}`)}_(f.green(`published ${b.published.join(", ")} \u2014 live as of release ${b.version.version_no}.`))}else t.publish?_(f.dim("nothing changed \u2014 nothing to publish.")):p.length>0&&q(f.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(b=>b.action==="refused")&&(q(f.red("one or more skill files were refused and not written.")),process.exitCode=1)}er();var wA=["proposed","active","rejected"],_A=["mechanic","operator","learning","code-baseline"],ba=t=>new G(t);async function wa(t,e){let r=await Q(t.baseUrl);return e(r)}function Gb(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)||v(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function vA(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&v("--limit must be a positive number."),Math.floor(e)}function Xb(t){let e=Gb(t.status,wA,"--status"),r=Gb(t.provenance,_A,"--provenance"),n=vA(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Jb(t){return!!(t.provenance?.length||t.recordType||t.source)}var Qb=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function xA(t){return t.status==="active"?f.green("active"):t.status==="rejected"?f.dim("rejected"):f.yellow("proposed")}function kA(t){return t.message?t.message:t.kind&&t.field?f.dim(`${t.kind} ${t.field}`):t.kind?f.dim(t.kind):f.dim("(no description)")}function ew(t){return[t.hookId,xA(t),t.provenance==="learning"?f.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),kA(t)]}async function tw(t={},e=ba){let r=await wa(t,e),n=Xb(t),o;try{o=await r.proposals(n)}catch(i){te(i,"extensions:deploy","list hook proposals"),v(`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.
3859
+ `+f.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}_(tr(o.map(ew),{head:Qb})),_(f.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&&_(f.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function SA(t,e,r){return r.yes?!0:it()?await at(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function $A(t){return!(t instanceof le)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Au(t,e){$A(t)&&te(t,"extensions:deploy",e)}function Cu(t,e){let r=e instanceof le?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);q(ze.error(`${f.bold(t)} \u2014 ${s}`))}async function Yb(t,e){try{let r=await t.proposalPromote(e);return _(ze.success(`${f.bold(e)} ${f.dim(`${r.previousStatus} \u2192`)} ${f.green(r.status)}`)),!0}catch(r){return Au(r,"promote a hook proposal"),Cu(e,r),!1}}async function rw(t,e={},r=ba){!e.auto&&t.length===0&&v("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&v("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&v("promote: --apply / --all only mean something with --auto.");let n=await wa(e,r);if(!e.auto){let u=0;for(let p of t)await Yb(n,p)&&(u+=1);u>0&&_(f.dim(` ${u} hook(s) armed \u2014 the loader compiles them on its next reload.`)),u<t.length&&(process.exitCode=1);return}let o=Xb({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&v("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")&&v("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(u){te(u,"extensions:deploy","list hook proposals"),v(`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${Jb(o)?" for that filter":""}.`),i.length>0&&_(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(_(e.apply?`promoting ${f.bold(String(a.length))} hook proposal(s):`:`${f.bold("dry run")} \u2014 would promote ${f.bold(String(a.length))} hook proposal(s):`),_(tr(a.map(ew),{head:Qb})),i.length>0&&_(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){_(""),_(ze.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Jb(o)&&!e.all&&v(`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 SA(`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 Yb(n,u.hookId)&&(l+=1);_(f.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 nw(t,e={},r=ba){t.length===0&&v("retract: name at least one proposal id.");let n=await wa(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);_(ze.success(`${f.bold(s)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.yellow(i.status)}`)),o+=1}catch(i){Au(i,"retract a hook proposal"),Cu(s,i)}o>0&&_(f.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function ow(t,e={},r=ba){t.length===0&&v("reject: name at least one proposal id.");let n=await wa(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);_(ze.success(`${f.bold(s)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.dim(i.status)}`)),o+=1}catch(i){Au(i,"reject a hook proposal"),Cu(s,i)}o<t.length&&(process.exitCode=1)}er();var Iu=t=>new G(t);async function TA(t,e){let r=await Q(t.baseUrl);return e(r)}function RA(t){return!(t instanceof le)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function EA(t,e){let r=e instanceof le?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);q(ze.error(`${f.bold(t)} \u2014 ${s}`))}async function Ou(t,e,r,n,o,s,i){e.length===0&&v(`${t}: name at least one extension id.`);let a=await TA(r,n),c=[];for(let l of e)try{let u=await o(a,l);c.push(u),r.json||_(s(u))}catch(u){RA(u)&&te(u,"extensions:deploy",`${t} an extension`),EA(l,u)}if(r.json)_(JSON.stringify(c,null,2));else{let l=i(c.length);l&&_(f.dim(l))}c.length<e.length&&(process.exitCode=1)}async function sw(t,e={},r=Iu){await Ou("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>ze.success(`${f.bold(n.id)} ${f.dim(`${n.previousStatus} \u2192`)} ${f.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 iw(t,e={},r=Iu){await Ou("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>ze.success(`${f.bold(n.id)} ${f.dim(`${n.previousStatus} \u2192`)} ${f.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function aw(t,e={},r=Iu){await Ou("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>ze.success(`${f.bold(n.id)} ${f.dim(`${n.previousStatus} \u2192`)} ${f.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}er();var _o=t=>new G(t);async function vo(t,e){let r=await Q(t.baseUrl);return e(r)}async function _a(t,e,r,n){return n.yes?!0:it()?await at(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(q("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(q(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function PA(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function cw(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function AA(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(`${cw(f.bold(s.slug),e)} ${cw(PA(s),10)} ${s.surfaces.join(",")||f.dim("none")}`),s.description&&r.push(` ${f.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 lw(t,e=_o){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await vo(t,e),o;try{o=await se("reading the skills",()=>n.skillsList(r))}catch(s){te(s,"skills:publish","read the instance skills"),v(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}_(AA(o).join(`
3860
+ `))}async function uw(t,e,r=_o){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await vo(e,r);if(!await _a(`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 se("publishing",()=>o.skillsPublish(n))}catch(a){te(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}_(f.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(q(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),q(f.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function dw(t,e,r=_o){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await vo(e,r);if(!await _a(`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 se("unpublishing",()=>o.skillsUnpublish(n))}catch(a){te(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}_(f.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),q(f.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(q(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function pw(t,e,r=_o){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await vo(e,r);if(await _a(`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 se("rolling back",()=>o.skillsRollback(n));_(f.green(`rolled back to v${i.version.version_no}.`))}catch(i){te(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function hw(t,e=_o){let r=await vo(t,e),n;try{n=await se("reading the releases",()=>r.skillsReleases())}catch(o){te(o,"skills:publish","read the skills releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){q("no releases yet.");return}for(let o of n.items){let s=o.is_current?f.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";_(`${s} v${o.version_no} ${o.skill_count} skill(s) ${f.dim(o.published_at)}${o.published_by?f.dim(` by ${o.published_by}`):""}${f.dim(i)}`)}}async function mw(t,e,r=_o){let n=[...new Set((t??[]).map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await vo(e,r);if(!await _a(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3770
3861
  ${n.join(`
3771
- `)}`,"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 se(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof ce&&u.status===404){a.push(l);continue}i.length>0&&q(g.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),ne(u,"skills:publish","delete a skill"),x(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&_(g.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(g.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(g.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as ow}from"node:fs";import{join as hA,relative as fA,resolve as gA,sep as yA}from"node:path";var bA=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),wA=new Set([".mcp.json",".env"]);function _A(t){return wA.has(t)||t.startsWith(".env.")&&t!==".env.example"}function vA(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function xA(t){return t.includes(0)}async function sw(t){let e=gA(t),r={},n=[],o=[],s=[];async function i(a){let c=await ow.readdir(a,{withFileTypes:!0});for(let l of c){let u=hA(a,l.name);if(bA.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=fA(e,u).split(yA).join("/");if(_A(l.name)){o.push(p);continue}let y=await ow.readFile(u);if(!vA(y)){n.push(p);continue}xA(y)&&s.push(p),r[p]=y.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as kA}from"node:crypto";var SA="/_tb/app-assets",$A=16,TA=/^[0-9a-f]{32}$/;function iw(){return kA($A).toString("hex")}function RA(t){return TA.test(t)}function aw(t){if(!RA(t))throw new Error(`not a build id: ${t}`);return`${SA}/${t}/`}var cw=7;Iu();var Ou=50*1024*1024;import wa from"node:fs/promises";import ys from"node:path";var Nu={esbuild:"0.28.1","isolated-vm":"6.1.2"},zu="@turbobase/isolated-vm-prebuilds";function Lu(t,e){return`${t}-${e}`}function ju(t=process.versions){return`abi${t.modules}`}var lw=["darwin-x64","win32-arm64"];async function uw(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Lu(e,r),o=ys.join(t.home,"node_modules"),s=ys.join(o,...zu.split("/"),"prebuilds",n),i=ys.join(o,"isolated-vm","prebuilds",n),a;try{a=await wa.readdir(s)}catch{return[]}let c=[];await wa.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=ys.join(i,l);try{await wa.copyFile(ys.join(s,l),u,wa.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as EA}from"node:os";import{join as dw}from"node:path";import{promises as Du}from"node:fs";function mw(){let t=process.env.TURBOBASE_HOME??dw(EA(),".turbobase");return{dir:t,file:dw(t,"sandboxes.json")}}var PA={s:1e3,m:6e4,h:36e5,d:864e5};function AA(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*PA[e[2]]}function CA(t,e=Date.now()){return new Date(e+AA(t)).toISOString()}function IA(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function OA(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 NA(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 zA="[REDACTED]",bs=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Mu=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 LA(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Mu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:zA:n[o]=s}return n}function jA(t,e,r){return e.map(n=>LA(t,n,r))}var pw=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),DA=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function MA(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 Uu(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 DA)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=MA(t);if(!pw.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...pw].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function UA(t,e=qA){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function qA(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function FA(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function BA(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function qu(){let{file:t}=mw();try{let e=await Du.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function hw(t){let{dir:e,file:r}=mw();await Du.mkdir(e,{recursive:!0}),await Du.writeFile(r,`${JSON.stringify(t,null,2)}
3772
- `,{mode:384})}async function ZA(t){let e=await qu();e.push(t),await hw(e)}async function fw(t){let e=await qu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await hw(e),n??null}async function _a(){return qu()}function Fu(t,e=Date.now()){let r=[],n=[];for(let o of t)IA(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function gw(t,e){Uu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new bs(r);let n=OA(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>UA(l)))(e.fromTenant),i=FA(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=NA(l.rows,n),p=jA(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:CA(e.ttl,o),sampleFraction:n,url:BA(s,e.baseUrl)};return await ZA(c),c}async function yw(t,e){Uu(t.target());let n=(await _a()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await fw(e),n):null}async function Bu(t,e=Date.now()){Uu(t.target());let r=await _a(),{expired:n}=Fu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await fw(s.name),o.push(s)}return o}var ws={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"],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"}},n2=Object.keys(ws).filter(t=>ws[t].mintable);var i2=ws.pat.prefix,VA=Object.entries(ws).map(([t,e])=>[e.prefix,t]),HA=/^[A-Za-z0-9_-]{20,}$/;function KA(t){if(typeof t!="string")return null;for(let[e,r]of VA)if(t.startsWith(e)&&HA.test(t.slice(e.length)))return r;return null}function bw(t){return KA(t)==="pat"}is();var WA=8e3,GA={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 JA(t){return GA[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function YA(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(WA)})}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 ww(t){return t.state==="accepted"?tt()?g.green("accepted"):"accepted":t.state==="rejected"?tt()?g.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:tt()?g.yellow("unreachable"):"unreachable"}async function _w(t={},e=fetch){let r=await Pr(),{file:n}=Ki();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(g.dim(`no sign-ins stored in ${n}.`));return}let o=await Xt(),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 YA(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(tt())_(er(s.map(i=>[i.active?g.green("*"):" ",g.bold(i.baseUrl),ww(i.check),g.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${ww(i.check)} (updated ${i.updatedAt})`);q(g.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(g.red(`${i.baseUrl}: ${JA(i.check.reason)}.`)),q(g.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(g.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function TU(t){let e=await Pr();e.length===0&&x("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),ot()||x("this command needs an explicit <base-url> in a non-interactive shell.");try{return await st(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{x("cancelled.")}}async function RU(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 EU(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function PU(t,e,r){let n=await my({baseUrl:t,token:e}),o=(await Pr()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),EU(n.baseUrl),!r)return;let s=await RU(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function AU(t){let e=await cu(await us(t),Dr(t)),r=vu(e);return r||x(`${t}: ${xu(e)}`),{...r,sourceCode:e}}async function Qn(t,e,r,n){try{return await be.access(t),"skipped"}catch{}return await be.mkdir(Dr(t),{recursive:!0}),await be.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await be.chmod(t,n),"wrote"}async function bT(t,e){if(_T(t)!==".gitignore")return Qn(t,e.content,e.executable,e.mode);let r=await be.readFile(t,"utf8").catch(()=>null);if(r===null)return Qn(t,e.content,e.executable,e.mode);let n=sb(r);return n===null?"skipped":(await be.writeFile(t,n,"utf8"),"merged")}function sg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;x(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function hl(t){process.exit(t)}function CU(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 IU(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 OU(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 wT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function dg({includeInternal:t=!0}={}){let e=new Ag;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.33.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${fu()}
3773
- `),e.hook("preAction",(d,f)=>{bb(e.opts(),f.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let f=Dt(d.baseUrl);d.token||x(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3774
- ${hs} auth login --base-url ${f} --token tb_pat_\u2026`),bw(d.token)||x("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await PU(f,d.token,d.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>_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 f=d??await TU("Pick the active instance:"),v=await Wi(f);if(!v){let T=await Pr();x(`no stored sign-in for ${Dt(f)}.`+(T.length?` Stored: ${T.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Dt(f)} --token tb_pat_\u2026\`.`)}_(`active instance \u2192 ${v.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let T=await Pr();for(let k of T)await ru(k.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let f=await ru(d.baseUrl);f||x(d.baseUrl?`no stored sign-in for ${Dt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let v=await Xt();_(`signed out of ${f}.`+(v?` Active instance \u2192 ${v.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T;try{T=await In({baseUrl:f,token:v,recordsOnly:d.recordsOnly})}catch(b){let $=b instanceof Error?b.message:String(b);if(!d.recordsOnly&&/openapi\.json failed \(401/.test($)){q("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await In({baseUrl:f,token:v,recordsOnly:!0})}catch(E){x(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else x(`types generation failed: ${$}`)}let k=ge(process.cwd(),d.out);await be.writeFile(k,T,"utf8"),_(`wrote ${k} (${T.split(`
3775
- `).length} lines).`)}),vb(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let k=T.toString(),b=await fetch(`${f}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${v}`,Accept:"application/json"}});b.ok||x(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${b.status}`);let E=((await b.json()).markdown??"").trim(),N=ge(process.cwd(),d.out),j=d.records?` records=${d.records}`:"",D=`<!-- GENERATED by \`turbobase project grounding\` against ${f}${j} \u2014 do not edit; re-run to refresh. -->
3862
+ `)}`,"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 se(`deleting ${l}`,()=>o.skillsDelete(l)))}catch(u){if(u instanceof le&&u.status===404){a.push(l);continue}i.length>0&&q(f.dim(`deleted before the error: ${i.map(p=>p.slug).join(", ")}`)),te(u,"skills:publish","delete a skill"),v(`delete failed on '${l}': ${u instanceof Error?u.message:String(u)}`)}i.length>0&&_(f.green(`deleted ${i.length} skill(s).`));let c=i.filter(l=>l.wasPublished).map(l=>l.slug);c.length>0&&q(f.yellow(`Published until now, so no longer injected: ${c.join(", ")}`)),a.length>0&&(q(f.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as fw}from"node:fs";import{join as CA,relative as IA,resolve as OA,sep as NA}from"node:path";var zA=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),LA=new Set([".mcp.json",".env"]);function jA(t){return LA.has(t)||t.startsWith(".env.")&&t!==".env.example"}function DA(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function MA(t){return t.includes(0)}async function gw(t){let e=OA(t),r={},n=[],o=[],s=[];async function i(a){let c=await fw.readdir(a,{withFileTypes:!0});for(let l of c){let u=CA(a,l.name);if(zA.has(l.name))continue;if(l.isDirectory()){await i(u);continue}if(!l.isFile())continue;let p=IA(e,u).split(NA).join("/");if(jA(l.name)){o.push(p);continue}let b=await fw.readFile(u);if(!DA(b)){n.push(p);continue}MA(b)&&s.push(p),r[p]=b.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as UA}from"node:crypto";var qA="/_tb/app-assets",BA=16,FA=/^[0-9a-f]{32}$/;function yw(){return UA(BA).toString("hex")}function ZA(t){return FA.test(t)}function bw(t){if(!ZA(t))throw new Error(`not a build id: ${t}`);return`${qA}/${t}/`}var ww=7;zu();var Lu=50*1024*1024;import va from"node:fs/promises";import _s from"node:path";var ju={esbuild:"0.28.1","isolated-vm":"6.1.2"},Du="@turbobase/isolated-vm-prebuilds";function Mu(t,e){return`${t}-${e}`}function Uu(t=process.versions){return`abi${t.modules}`}var _w=["darwin-x64","win32-arm64"];async function vw(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Mu(e,r),o=_s.join(t.home,"node_modules"),s=_s.join(o,...Du.split("/"),"prebuilds",n),i=_s.join(o,"isolated-vm","prebuilds",n),a;try{a=await va.readdir(s)}catch{return[]}let c=[];await va.mkdir(i,{recursive:!0});for(let l of a){if(!l.endsWith(".node"))continue;let u=_s.join(i,l);try{await va.copyFile(_s.join(s,l),u,va.constants?.COPYFILE_EXCL??1),c.push(l)}catch{}}return c}import{homedir as VA}from"node:os";import{join as xw}from"node:path";import{promises as qu}from"node:fs";function Sw(){let t=process.env.TURBOBASE_HOME??xw(VA(),".turbobase");return{dir:t,file:xw(t,"sandboxes.json")}}var HA={s:1e3,m:6e4,h:36e5,d:864e5};function KA(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*HA[e[2]]}function WA(t,e=Date.now()){return new Date(e+KA(t)).toISOString()}function GA(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function JA(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 YA(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 XA="[REDACTED]",vs=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Bu=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function QA(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Bu(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:XA:n[o]=s}return n}function eC(t,e,r){return e.map(n=>QA(t,n,r))}var kw=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),tC=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function rC(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 Fu(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 tC)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=rC(t);if(!kw.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...kw].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function nC(t,e=oC){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function oC(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function sC(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function iC(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Zu(){let{file:t}=Sw();try{let e=await qu.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function $w(t){let{dir:e,file:r}=Sw();await qu.mkdir(e,{recursive:!0}),await qu.writeFile(r,`${JSON.stringify(t,null,2)}
3863
+ `,{mode:384})}async function aC(t){let e=await Zu();e.push(t),await $w(e)}async function Tw(t){let e=await Zu(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await $w(e),n??null}async function xa(){return Zu()}function Vu(t,e=Date.now()){let r=[],n=[];for(let o of t)GA(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Rw(t,e){Fu(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new vs(r);let n=JA(e.sample),o=e.now??Date.now(),s=(e.nameGen??(l=>nC(l)))(e.fromTenant),i=sC(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let l of a){let u=YA(l.rows,n),p=eC(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:WA(e.ttl,o),sampleFraction:n,url:iC(s,e.baseUrl)};return await aC(c),c}async function Ew(t,e){Fu(t.target());let n=(await xa()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Tw(e),n):null}async function Hu(t,e=Date.now()){Fu(t.target());let r=await xa(),{expired:n}=Vu(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Tw(s.name),o.push(s)}return o}var xs={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"],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"}},k2=Object.keys(xs).filter(t=>xs[t].mintable);var T2=xs.pat.prefix,cC=Object.entries(xs).map(([t,e])=>[e.prefix,t]),lC=/^[A-Za-z0-9_-]{20,}$/;function uC(t){if(typeof t!="string")return null;for(let[e,r]of cC)if(t.startsWith(e)&&lC.test(t.slice(e.length)))return r;return null}function Pw(t){return uC(t)==="pat"}cs();var dC=8e3,pC={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 hC(t){return pC[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function mC(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(dC)})}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 Aw(t){return t.state==="accepted"?nt()?f.green("accepted"):"accepted":t.state==="rejected"?nt()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:nt()?f.yellow("unreachable"):"unreachable"}async function Cw(t={},e=fetch){let r=await Ar(),{file:n}=Gi();if(r.length===0){_("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),q(f.dim(`no sign-ins stored in ${n}.`));return}let o=await Qt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await mC(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(nt())_(tr(s.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),Aw(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)_(`${i.active?"* ":" "}${i.baseUrl} ${Aw(i.check)} (updated ${i.updatedAt})`);q(f.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(q(f.red(`${i.baseUrl}: ${hC(i.check.reason)}.`)),q(f.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&q(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||q("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function FU(t){let e=await Ar();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),it()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await at(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function ZU(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 VU(t){q(""),q("Sharing is ON. Two things reach the Turbobase product team from this instance:"),q(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),q(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),q(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),q(" about OUR platform, with instance name, user names and ids masked before they leave."),q(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),q("")}async function HU(t,e,r){let n=await gy({baseUrl:t,token:e}),o=(await Ar()).length-1;if(_(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),VU(n.baseUrl),!r)return;let s=await ZU(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(q(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),q(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),q(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?q(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):q(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function KU(t){let e=await uu(await ps(t),Mr(t)),r=Su(e);return r||v(`${t}: ${$u(e)}`),{...r,sourceCode:e}}async function eo(t,e,r,n){try{return await _e.access(t),"skipped"}catch{}return await _e.mkdir(Mr(t),{recursive:!0}),await _e.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await _e.chmod(t,n),"wrote"}async function PT(t,e){if(CT(t)!==".gitignore")return eo(t,e.content,e.executable,e.mode);let r=await _e.readFile(t,"utf8").catch(()=>null);if(r===null)return eo(t,e.content,e.executable,e.mode);let n=gb(r);return n===null?"skipped":(await _e.writeFile(t,n,"utf8"),"merged")}function cg(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function gl(t){process.exit(t)}function WU(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 GU(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 JU(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 AT(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function mg({includeInternal:t=!0}={}){let e=new Og;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.34.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${yu()}
3864
+ `),e.hook("preAction",(d,g)=>{Pb(e.opts(),g.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 g=Mt(d.baseUrl);d.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3865
+ ${ys} auth login --base-url ${g} --token tb_pat_\u2026`),Pw(d.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await HU(g,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=>Cw({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 g=d??await FU("Pick the active instance:"),x=await Ji(g);if(!x){let T=await Ar();v(`no stored sign-in for ${Mt(g)}.`+(T.length?` Stored: ${T.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Mt(g)} --token tb_pat_\u2026\`.`)}_(`active instance \u2192 ${x.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 Ar();for(let k of T)await ou(k.baseUrl);_(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let g=await ou(d.baseUrl);g||v(d.baseUrl?`no stored sign-in for ${Mt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let x=await Qt();_(`signed out of ${g}.`+(x?` Active instance \u2192 ${x.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:g,token:x}=await Q(d.baseUrl),T;try{T=await On({baseUrl:g,token:x,recordsOnly:d.recordsOnly})}catch(y){let $=y instanceof Error?y.message:String(y);if(!d.recordsOnly&&/openapi\.json failed \(401/.test($)){q("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await On({baseUrl:g,token:x,recordsOnly:!0})}catch(E){v(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else v(`types generation failed: ${$}`)}let k=ye(process.cwd(),d.out);await _e.writeFile(k,T,"utf8"),_(`wrote ${k} (${T.split(`
3866
+ `).length} lines).`)}),Ib(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:g,token:x}=await Q(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(`${g}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"}});y.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${y.status}`);let E=((await y.json()).markdown??"").trim(),N=ye(process.cwd(),d.out),L=d.records?` records=${d.records}`:"",M=`<!-- GENERATED by \`turbobase project grounding\` against ${g}${L} \u2014 do not edit; re-run to refresh. -->
3776
3867
 
3777
- `;await be.writeFile(N,D+(E?`${E}
3868
+ `;await _e.writeFile(N,M+(E?`${E}
3778
3869
  `:`(no grounding available yet)
3779
- `),"utf8"),_(`wrote ${N}${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 (${fs.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=>$b(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=>Rb(d)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Eb(d,f)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Pb(d,f)),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=>Ab(d)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Cb(d,f)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Ib(d,f)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--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?jb({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):Ob(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=>Xb(d)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>Qb(d,f)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>ew(d,f)),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=>rw(d)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>tw(d,f)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,f)=>nw(d,f));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async d=>{let f;try{f=fr("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=ge(process.cwd(),f.relativePath);await Qn(v,f.content)==="skipped"&&x(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let f;try{f=fr("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=ge(process.cwd(),f.relativePath);await Qn(v,f.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 f;try{f=fr("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=ge(process.cwd(),f.relativePath);await Qn(v,f.content)==="skipped"&&x(`refusing to overwrite existing file: ${v}`),_(`wrote ${v}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(d,f)=>{let v=sg(f.reporter),T=await us(ge(process.cwd(),d)),k=ge(process.cwd(),f.samples),b=await ls(k);b.length===0&&!v&&_(`no samples found under ${k} \u2014 add JSON fixtures to dry-run against.`);let $;try{$=await ra(T,b.map(j=>j.fixture),{resolveDir:Dr(ge(process.cwd(),d))})}catch(j){x(`bundle failed: ${j instanceof Error?j.message:String(j)}`)}if(v){let j=CU($);_(oa(j,v)),hl(j.cases.some(D=>D.status==="failed")?1:0)}let E=0;for(let j of $){let D=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"})`:"";_(` ${D} ${j.name}${V}`)}let N=`${$.length-E}/${$.length} sample(s) passed.`;_(`
3780
- ${E===0?g.green(N):g.yellow(N)}`),hl(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,f)=>{if(f.to){let $=await ig(),{baseUrl:E,token:N}=await te(f.baseUrl),j=new J({baseUrl:E,token:N});try{let D=await se(`applying bundle to ${f.to}`,()=>j.configApply($,{prune:f.prune}));_(`applied bundle to ${f.to}: +${D.applied.add} ~${D.applied.change} -${D.applied.destroy}`+(D.backfillsQueued.length?` (${D.backfillsQueued.length} backfill(s) queued)`:""));let V=D.skippedDestroys??[];if(V.length>0){q(`${V.length} resource(s) exist on ${f.to} but are not declared by this project \u2014 NOT removed:`);for(let L of V)q(` ${L.kind} ${L.id}`);q("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(D){D instanceof ce&&D.status===403&&x("apply forbidden (403) \u2014 the stored PAT is not for an admin."),x(`bundle apply failed: ${D instanceof Error?D.message:String(D)}`)}return}d||x("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:v,token:T}=await te(f.baseUrl),k=await AU(ge(process.cwd(),d)),b=new J({baseUrl:v,token:T});try{let $=await se(`deploying ${_T(d)}`,()=>b.deploy(k));tt()?_(Kr("Deployed",[`${g.bold($.id)} ${ho($.status)} ${g.dim($.outcome)}`])):_(`deployed ${$.id} \u2192 status=${$.status} (${$.outcome}).`)}catch($){$ instanceof ce&&$.status===403&&x("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),x(`deploy failed: ${$ instanceof Error?$.message:String($)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,f,v)=>{let T=!!(v.preview||v.replace||v.replaceLabel);v.replace&&v.replaceLabel&&x("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let k=ge(process.cwd(),f??".");await be.mkdir(k,{recursive:!0});let b=v.proposal??await S(k),{baseUrl:$,token:E}=await te(v.baseUrl),N=new J({baseUrl:$,token:E}),j=!1;try{j=(await N.appsList()).some(Se=>Se.slug===d||Se.id===d)}catch(Se){ne(Se,"extensions:deploy","deploy"),x(`could not reach ${$}: ${Se instanceof Error?Se.message:String(Se)}`)}if(!j){v.create||x(`no app "${d}" on ${$} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let Se=await se(`creating app ${d}`,()=>p($,E,{slug:d},{tolerateExisting:!0}));Se.existed||_(`created ${Se.slug??d}.`)}let D;if(v.replace)if(typeof v.replace=="string")D=v.replace;else{let{previews:Se}=await W($,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 et of Se)_(` ${et.previewId} v${et.version}${et.label?` ${et.label}`:""} ${et.url}`);x(`${d} has ${Se.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${Se[0].previewId}\`.`)}D=Se[0].previewId}let V;if(v.replaceLabel){let Se=v.replaceLabel,{previews:et}=await W($,E,d),dr=et.filter(bl=>bl.label===Se);dr.length>0?(D=dr[0].previewId,dr.length>1&&q(`${dr.length} open previews carry the label "${Se}"; replacing the newest (${D}). Close the others with \`turbobase apps preview discard\`.`)):_(`no open preview labelled "${Se}" \u2014 opening one.`),V=Se}let L=Se=>be.stat(It(k,Se)).then(()=>!0).catch(()=>!1),ee=d,_e=k,Pe=v.build!==!1;if(Pe&&!await L("package.json"))if(await L("index.html"))_("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Pe=!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 se(`pulling ${d}`,()=>y($,E,d));ee=Se.slug??d,await h(k,Se.files,!0),_(`pulled generated source (rev ${Se.rev}).`)}let to;if(Pe){let Se=iw();if(to={buildId:Se,assetBase:aw(Se)},v.install!==!1&&!await L("node_modules")){_("installing dependencies\u2026");try{await P(["install"],k)}catch(et){x(`npm install failed: ${et instanceof Error?et.message:String(et)}`)}}_("building\u2026");try{await P(["run","build"],k,{TURBOBASE_ASSET_BASE:to.assetBase})}catch(et){x(`build failed: ${et instanceof Error?et.message:String(et)}`)}await L("dist")||x(`no dist/ after build in ${k} \u2014 check the app's build script.`),_e=It(k,"dist")}T&&!to&&x(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${ee}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let dt=await Ke($,E,ee,_e,v.entry,b,to,T?{label:v.label??V,replacePreviewId:D}:void 0);if(T){let Se=dt.previewUrl??"(no url returned)",et=dt.expiresAt?new Date(dt.expiresAt).toLocaleDateString():`${cw} days`,dr=dt.replacedVersion==null?null:`replaced v${dt.replacedVersion} \u2014 same URL`;if(tt())_(Kr(dr?"Preview replaced":"Preview deployed",[`${g.bold(ee)} ${g.green(`v${dt.version??"?"}`)} ${g.dim("not live")}`,`${g.bold(Se)}`,...dr?[g.dim(dr)]:[],g.dim(`expires ${et}`)]));else{let bl=dr?`; ${dr}`:"";_(`preview ${ee} v${dt.version??"?"} \u2192 ${Se} (expires ${et}; /a/${ee} unchanged${bl}).`)}_(`next: turbobase apps promote ${ee} ${dt.previewId??"<preview-id>"} # make it live`),_(` turbobase apps preview discard ${dt.previewId??"<preview-id>"}`);return}tt()?_(Kr("Deployed",[`${g.bold(ee)} ${g.green(`v${dt.version??"?"}`)} ${g.dim(dt.url??`/a/${ee}`)}`])):_(`deployed ${ee} \u2192 v${dt.version??"?"} (${dt.url??`/a/${ee}`}).`),Ye(dt),Gt(dt),await Mr(dt,k)}),c.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").action(async(d,f)=>{let v=await zU(d??".");v||x(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`);let T=Array.isArray(v.manifest.tables)?v.manifest.tables:[],k=Array.isArray(v.manifest.writes)?v.manifest.writes:[],b=Array.isArray(v.manifest.roles)?v.manifest.roles:[],$=Array.isArray(v.manifest.labels)?v.manifest.labels:[];if(T.length===0&&k.length===0&&b.length===0&&$.length===0)return _(`${v.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);let{baseUrl:E,token:N}=await te(f.baseUrl),j=new J({baseUrl:E,token:N});if(T.length>0){let D;try{D=await se("planning tables",()=>j.tablesPlan({claimedBy:f.as,tables:T}))}catch(V){ne(V,"extensions:deploy","plan tables"),Ri(V)}_(`claiming as ${g.bold(D.claimedBy)}`);for(let V of D.tables)Ti(V,{showClaimants:!0})}if(k.length>0||b.length>0||$.length>0){let D;try{D=await se("checking declared writes, roles and labels",()=>j.appsPlan({writes:k,roles:b,labels:$}))}catch(V){ne(V,"extensions:deploy","plan writes"),x(`plan writes failed: ${V instanceof Error?V.message:String(V)}`)}if(D.roles&&D.roles.verdicts.length>0){_(""),_(g.bold("roles"));let V=Math.max(...D.roles.verdicts.map(L=>L.name.length));for(let L of D.roles.verdicts){let ee=L.name.padEnd(V);if(L.action==="error")q(` ${g.bold("ERROR")} ${ee} \u2014 ${L.message??"cannot be created"}`);else if(L.action==="create"){let _e=L.addCapabilities?.length??0;_(` create ${ee} ${g.dim(`${_e} capabilit${_e===1?"y":"ies"}`)}`)}else if(L.action==="add_capabilities"){let _e=(L.addCapabilities??[]).map(Pe=>`+${Pe}`).join(", ");_(` add ${ee} ${g.dim(_e)}`)}else _(` ${g.dim("ok")} ${ee} ${g.dim("already up to date")}`)}D.roles.verdicts.some(L=>L.action!=="error")&&_(g.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}if(D.labels&&D.labels.verdicts.length>0){_(""),_(g.bold("labels"));let V=Math.max(...D.labels.verdicts.map(L=>L.name.length));for(let L of D.labels.verdicts){let ee=L.name.padEnd(V);if(L.action==="create")_(` create ${ee} ${g.dim(L.color)}`);else{let _e=L.declaredColor?`${L.color} \u2014 declared ${L.declaredColor}, the instance's colour is kept`:L.color;_(` ${g.dim("ok")} ${ee} ${g.dim(_e)}`)}}_(g.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}k.length>0&&_("");for(let V of D.verdicts){let L=`${V.source} ${V.recordType}.${V.op}`;V.allowed?V.heldForApproval?_(`${g.dim("HELD")} ${L} \u2014 allowed, but each write waits for operator approval.`):_(`${g.dim("ok")} ${L}`):q(`${g.bold("DENIED")} ${L}${V.rule?` \u2014 guardrail "${V.rule}"`:""} (${V.reason})`)}D.ok||(_(""),x(D.message??(D.roles&&!D.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}_(""),_(g.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),c.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f,v)=>{let{baseUrl:T,token:k}=await te(v.baseUrl),b=await se(`promoting ${f}`,()=>F(T,k,d,"promote",{previewId:f}));tt()?_(Kr("Promoted",[`${g.bold(d)} ${g.green(`v${b.version??"?"}`)} ${g.dim(b.url??`/a/${d}`)}`])):_(`promoted ${d} \u2192 v${b.version??"?"} is now live at ${b.url??`/a/${d}`}.`),Gt({labels:b.labels?{applied:!0,verdicts:b.labels}:null}),await Mr(b)});let l=c.command("preview").description("Inspect and manage an app's open previews.");l.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=await W(v,T,d);if(f.json)return _(JSON.stringify(k.previews,null,2));if(k.previews.length===0){_(`no open previews for ${d}.`);return}for(let b of k.previews){let $=b.label?` ${b.label}`:"",E=b.expiresAt?new Date(b.expiresAt).toLocaleDateString():"?";_(`v${b.version} ${b.previewId}${$} ${b.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,f,v)=>{let{baseUrl:T,token:k}=await te(v.baseUrl);await se(`discarding ${f}`,()=>F(T,k,d,"discard",{previewId:f})),_(`discarded ${f}.`)}),c.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=await se(`creating ${d}`,()=>p(v,T,{slug:d,name:f.name,description:f.description})),b=k.slug??d;tt()?_(Kr("Created",[`${g.bold(b)} ${g.dim(k.url??`/a/${b}`)}`])):_(`created ${b} (${k.url??`/a/${b}`}).`),_(`next: turbobase apps push ${b} . # store the source`),_(` turbobase apps deploy ${b} # build + go live`)});let u=Gi(fetch);async function p(d,f,v,T={}){let k=`${d.replace(/\/+$/,"")}/v1/apps`,b;try{b=await u(k,{method:"POST",headers:{Authorization:`Bearer ${f}`,"content-type":"application/json"},body:JSON.stringify({slug:v.slug,name:v.name??v.slug,description:v.description})})}catch($){x(`create request failed: ${$ instanceof Error?$.message:String($)}`)}if(b.status===401&&x("create unauthorized (401) \u2014 re-run `turbobase auth login`."),b.status===403&&x("create forbidden (403) \u2014 the PAT is not for an admin."),b.status===409){if(T.tolerateExisting)return{slug:v.slug,existed:!0};x(`an app with slug "${v.slug}" already exists.`)}return b.ok||x(`create failed: HTTP ${b.status} ${(await b.text().catch(()=>"")).slice(0,200)}`),await b.json().catch(()=>({}))}async function y(d,f,v){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/pull`,k;try{k=await u(T,{headers:{Authorization:`Bearer ${f}`}})}catch(b){x(`pull request failed: ${b instanceof Error?b.message:String(b)}`)}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 h(d,f,v){let T=ge(d),k=0;for(let[b,$]of Object.entries(f)){let E=ge(T,b);E!==T&&!E.startsWith(T+lg)&&x(`refusing to write outside ${T}: ${b}`),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(Dr(E),{recursive:!0}),await be.writeFile(E,$,"utf8"),k+=1}return k}function m(d){let f=d.indexOf(","),v=d.startsWith("data:")?f>=0?d.slice(f+1):"":d;if(!v)return null;try{let T=Buffer.from(v,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function w(d,f,v){let T=ge(d),k=async($,E)=>{let N=ge(T,$);N!==T&&!N.startsWith(T+lg)&&x(`refusing to write outside ${T}: ${$}`),v||await be.stat(N).then(()=>!0).catch(()=>!1)&&x(`${N} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await be.mkdir(Dr(N),{recursive:!0}),await be.writeFile(N,E)},b=`# ${f.title||"App change request"}
3870
+ `),"utf8"),_(`wrote ${N}${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 (${bs.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=>Lb(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=>Db(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,g)=>Mb(d,g)),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,g)=>Ub(d,g)),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=>qb(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,g)=>Bb(d,g)),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,g)=>Fb(d,g)),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&&v("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),d.from?Wb({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):Zb(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=>lw(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,g)=>uw(d,g)),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,g)=>dw(d,g)),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=>hw(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,g)=>pw(d,g)),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,g)=>mw(d,g));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 g;try{g=gr("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(k){v(k instanceof Error?k.message:String(k))}let x=ye(process.cwd(),g.relativePath);await eo(x,g.content)==="skipped"&&v(`refusing to overwrite existing file: ${x}`),_(`wrote ${x}`)}),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 g;try{g=gr("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(k){v(k instanceof Error?k.message:String(k))}let x=ye(process.cwd(),g.relativePath);await eo(x,g.content)==="skipped"&&v(`refusing to overwrite existing file: ${x}`),_(`wrote ${x}`)}),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 g;try{g=gr("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(k){v(k instanceof Error?k.message:String(k))}let x=ye(process.cwd(),g.relativePath);await eo(x,g.content)==="skipped"&&v(`refusing to overwrite existing file: ${x}`),_(`wrote ${x}`)}),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,g)=>{let x=cg(g.reporter),T=await ps(ye(process.cwd(),d)),k=ye(process.cwd(),g.samples),y=await ds(k);y.length===0&&!x&&_(`no samples found under ${k} \u2014 add JSON fixtures to dry-run against.`);let $;try{$=await oa(T,y.map(L=>L.fixture),{resolveDir:Mr(ye(process.cwd(),d))})}catch(L){v(`bundle failed: ${L instanceof Error?L.message:String(L)}`)}if(x){let L=WU($);_(ia(L,x)),gl(L.cases.some(M=>M.status==="failed")?1:0)}let E=0;for(let L of $){let M=L.pass?f.green("PASS"):f.red("FAIL");L.pass||(E+=1);let re=L.error?` (error: ${L.error})`:L.observed!==L.expected?` (expected ${L.expected}, observed ${L.observed})`:L.rejection?` (rejected: ${L.rejection.code??"rejected"})`:"";_(` ${M} ${L.name}${re}`)}let N=`${$.length-E}/${$.length} sample(s) passed.`;_(`
3871
+ ${E===0?f.green(N):f.yellow(N)}`),gl(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,g)=>{if(g.to){let $=await lg(),{baseUrl:E,token:N}=await Q(g.baseUrl),L=new G({baseUrl:E,token:N});try{let M=await se(`applying bundle to ${g.to}`,()=>L.configApply($,{prune:g.prune}));_(`applied bundle to ${g.to}: +${M.applied.add} ~${M.applied.change} -${M.applied.destroy}`+(M.backfillsQueued.length?` (${M.backfillsQueued.length} backfill(s) queued)`:""));let re=M.skippedDestroys??[];if(re.length>0){q(`${re.length} resource(s) exist on ${g.to} but are not declared by this project \u2014 NOT removed:`);for(let U of re)q(` ${U.kind} ${U.id}`);q("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(M){M instanceof le&&M.status===403&&v("apply forbidden (403) \u2014 the stored PAT is not for an admin."),v(`bundle apply failed: ${M instanceof Error?M.message:String(M)}`)}return}d||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:x,token:T}=await Q(g.baseUrl),k=await KU(ye(process.cwd(),d)),y=new G({baseUrl:x,token:T});try{let $=await se(`deploying ${CT(d)}`,()=>y.deploy(k));nt()?_(Wr("Deployed",[`${f.bold($.id)} ${mo($.status)} ${f.dim($.outcome)}`])):_(`deployed ${$.id} \u2192 status=${$.status} (${$.outcome}).`)}catch($){$ instanceof le&&$.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),v(`deploy failed: ${$ instanceof Error?$.message:String($)}`)}});let c=e.command("apps").description("Manage hosted apps served in your Turbobase app.");c.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,g,x)=>{let T=!!(x.preview||x.replace||x.replaceLabel);x.replace&&x.replaceLabel&&v("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let k=ye(process.cwd(),g??".");await _e.mkdir(k,{recursive:!0});let y=x.proposal??await S(k),{baseUrl:$,token:E}=await Q(x.baseUrl),N=new G({baseUrl:$,token:E}),L=!1;try{L=(await N.appsList()).some(be=>be.slug===d||be.id===d)}catch(be){te(be,"extensions:deploy","deploy"),v(`could not reach ${$}: ${be instanceof Error?be.message:String(be)}`)}if(!L){x.create||v(`no app "${d}" on ${$} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let be=await se(`creating app ${d}`,()=>p($,E,{slug:d},{tolerateExisting:!0}));be.existed||_(`created ${be.slug??d}.`)}let M;if(x.replace)if(typeof x.replace=="string")M=x.replace;else{let{previews:be}=await K($,E,d);if(be.length===0&&v(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),be.length>1){for(let Xe of be)_(` ${Xe.previewId} v${Xe.version}${Xe.label?` ${Xe.label}`:""} ${Xe.url}`);v(`${d} has ${be.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${be[0].previewId}\`.`)}M=be[0].previewId}let re;if(x.replaceLabel){let be=x.replaceLabel,{previews:Xe}=await K($,E,d),pr=Xe.filter(_l=>_l.label===be);pr.length>0?(M=pr[0].previewId,pr.length>1&&q(`${pr.length} open previews carry the label "${be}"; replacing the newest (${M}). Close the others with \`turbobase apps preview discard\`.`)):_(`no open preview labelled "${be}" \u2014 opening one.`),re=be}let U=be=>_e.stat(Ot(k,be)).then(()=>!0).catch(()=>!1),ne=d,Ee=k,ce=x.build!==!1;if(ce&&!await U("package.json"))if(await U("index.html"))_("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),ce=!1;else if(x.pull===!1)v(`${k} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let be=await se(`pulling ${d}`,()=>b($,E,d));ne=be.slug??d,await m(k,be.files,!0),_(`pulled generated source (rev ${be.rev}).`)}let Ce;if(ce){let be=yw();if(Ce={buildId:be,assetBase:bw(be)},x.install!==!1&&!await U("node_modules")){_("installing dependencies\u2026");try{await P(["install"],k)}catch(Xe){v(`npm install failed: ${Xe instanceof Error?Xe.message:String(Xe)}`)}}_("building\u2026");try{await P(["run","build"],k,{TURBOBASE_ASSET_BASE:Ce.assetBase})}catch(Xe){v(`build failed: ${Xe instanceof Error?Xe.message:String(Xe)}`)}await U("dist")||v(`no dist/ after build in ${k} \u2014 check the app's build script.`),Ee=Ot(k,"dist")}T&&!Ce&&v(`--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 Pe=await Ge($,E,ne,Ee,x.entry,y,Ce,T?{label:x.label??re,replacePreviewId:M}:void 0);if(T){let be=Pe.previewUrl??"(no url returned)",Xe=Pe.expiresAt?new Date(Pe.expiresAt).toLocaleDateString():`${ww} days`,pr=Pe.replacedVersion==null?null:`replaced v${Pe.replacedVersion} \u2014 same URL`;if(nt())_(Wr(pr?"Preview replaced":"Preview deployed",[`${f.bold(ne)} ${f.green(`v${Pe.version??"?"}`)} ${f.dim("not live")}`,`${f.bold(be)}`,...pr?[f.dim(pr)]:[],f.dim(`expires ${Xe}`)]));else{let _l=pr?`; ${pr}`:"";_(`preview ${ne} v${Pe.version??"?"} \u2192 ${be} (expires ${Xe}; /a/${ne} unchanged${_l}).`)}Jt(Pe),_(`next: turbobase apps promote ${ne} ${Pe.previewId??"<preview-id>"} # make it live`),_(` turbobase apps preview discard ${Pe.previewId??"<preview-id>"}`);return}nt()?_(Wr("Deployed",[`${f.bold(ne)} ${f.green(`v${Pe.version??"?"}`)} ${f.dim(Pe.url??`/a/${ne}`)}`])):_(`deployed ${ne} \u2192 v${Pe.version??"?"} (${Pe.url??`/a/${ne}`}).`),Jt(Pe),Ur(Pe),await qr(Pe,k)}),c.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").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,g)=>{let x=g.as?.startsWith("app:")?g.as.slice(4).trim():"";g.app!==void 0&&g.app.trim()===""&&v("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let T=g.app?.trim()??"";T&&x&&T!==x&&v(`--app ${T} and --as app:${x} name two different apps \u2014 pass one slug.`);let k=T||x||null,y=await XU(d??".");y||v(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`);let $=Array.isArray(y.manifest.tables)?y.manifest.tables:[],E=Array.isArray(y.manifest.writes)?y.manifest.writes:[],N=Array.isArray(y.manifest.roles)?y.manifest.roles:null,L=N??[],M=Array.isArray(y.manifest.labels)?y.manifest.labels:[],re=N!==null&&N.length===0;if($.length===0&&E.length===0&&L.length===0&&M.length===0){if(!re)return _(`${y.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(k===null){for(let ce of wu({app:null,roles:N}))_(ce.text);return}}let{baseUrl:U,token:ne}=await Q(g.baseUrl),Ee=new G({baseUrl:U,token:ne});if($.length>0){let ce;try{ce=await se("planning tables",()=>Ee.tablesPlan({claimedBy:g.as,tables:$}))}catch(Ce){te(Ce,"extensions:deploy","plan tables"),Pi(Ce)}_(`claiming as ${f.bold(ce.claimedBy)}`);for(let Ce of ce.tables)Ei(Ce,{showClaimants:!0})}if(E.length>0||L.length>0||M.length>0||re&&k!==null){let ce;try{ce=await se("checking declared writes, roles and labels",()=>Ee.appsPlan({writes:E,...N!==null?{roles:N}:{},labels:M,...k!==null?{app:k}:{}}))}catch(Ce){te(Ce,"extensions:deploy","plan writes"),v(`plan writes failed: ${Ce instanceof Error?Ce.message:String(Ce)}`)}ce.roles&&Je("plan",ce.roles.verdicts,ce.roles.retired);for(let Ce of wu({app:k,roles:N,retired:ce.roles?.retired??null}))_(Ce.text);if(ce.labels&&ce.labels.verdicts.length>0){_(""),_(f.bold("labels"));let Ce=Math.max(...ce.labels.verdicts.map(Pe=>Pe.name.length));for(let Pe of ce.labels.verdicts){let be=Pe.name.padEnd(Ce);if(Pe.action==="create")_(` create ${be} ${f.dim(Pe.color)}`);else{let Xe=Pe.declaredColor?`${Pe.color} \u2014 declared ${Pe.declaredColor}, the instance's colour is kept`:Pe.color;_(` ${f.dim("ok")} ${be} ${f.dim(Xe)}`)}}_(f.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 Ce of ce.verdicts){let Pe=`${Ce.source} ${Ce.recordType}.${Ce.op}`;Ce.allowed?Ce.heldForApproval?_(`${f.dim("HELD")} ${Pe} \u2014 allowed, but each write waits for operator approval.`):_(`${f.dim("ok")} ${Pe}`):q(`${f.bold("DENIED")} ${Pe}${Ce.rule?` \u2014 guardrail "${Ce.rule}"`:""} (${Ce.reason})`)}ce.ok||(_(""),v(ce.message??(ce.roles&&!ce.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.")))}_(""),_(f.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,g,x)=>{let{baseUrl:T,token:k}=await Q(x.baseUrl),y=await se(`promoting ${g}`,()=>B(T,k,d,"promote",{previewId:g}));nt()?_(Wr("Promoted",[`${f.bold(d)} ${f.green(`v${y.version??"?"}`)} ${f.dim(y.url??`/a/${d}`)}`])):_(`promoted ${d} \u2192 v${y.version??"?"} is now live at ${y.url??`/a/${d}`}.`);let $=db(y);Je("applied",$.verdicts,$.retired),Ur({labels:y.labels?{applied:!0,verdicts:y.labels}:null}),await qr(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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=await K(x,T,d);if(g.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 $=y.label?` ${y.label}`:"",E=y.expiresAt?new Date(y.expiresAt).toLocaleDateString():"?";_(`v${y.version} ${y.previewId}${$} ${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,g,x)=>{let{baseUrl:T,token:k}=await Q(x.baseUrl);await se(`discarding ${g}`,()=>B(T,k,d,"discard",{previewId:g})),_(`discarded ${g}.`)}),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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=await se(`creating ${d}`,()=>p(x,T,{slug:d,name:g.name,description:g.description})),y=k.slug??d;nt()?_(Wr("Created",[`${f.bold(y)} ${f.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=Yi(fetch);async function p(d,g,x,T={}){let k=`${d.replace(/\/+$/,"")}/v1/apps`,y;try{y=await u(k,{method:"POST",headers:{Authorization:`Bearer ${g}`,"content-type":"application/json"},body:JSON.stringify({slug:x.slug,name:x.name??x.slug,description:x.description})})}catch($){v(`create request failed: ${$ instanceof Error?$.message:String($)}`)}if(y.status===401&&v("create unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&v("create forbidden (403) \u2014 the PAT is not for an admin."),y.status===409){if(T.tolerateExisting)return{slug:x.slug,existed:!0};v(`an app with slug "${x.slug}" already exists.`)}return y.ok||v(`create failed: HTTP ${y.status} ${(await y.text().catch(()=>"")).slice(0,200)}`),await y.json().catch(()=>({}))}async function b(d,g,x){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(x)}/pull`,k;try{k=await u(T,{headers:{Authorization:`Bearer ${g}`}})}catch(y){v(`pull request failed: ${y instanceof Error?y.message:String(y)}`)}return k.status===401&&v("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),k.status===403&&v("pull forbidden (403) \u2014 the PAT is not for an admin."),k.status===404&&v(`no generated source for "${x}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),k.ok||v(`pull failed: HTTP ${k.status} ${(await k.text().catch(()=>"")).slice(0,200)}`),await k.json()}async function m(d,g,x){let T=ye(d),k=0;for(let[y,$]of Object.entries(g)){let E=ye(T,y);E!==T&&!E.startsWith(T+pg)&&v(`refusing to write outside ${T}: ${y}`),x||await _e.stat(E).then(()=>!0).catch(()=>!1)&&v(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await _e.mkdir(Mr(E),{recursive:!0}),await _e.writeFile(E,$,"utf8"),k+=1}return k}function h(d){let g=d.indexOf(","),x=d.startsWith("data:")?g>=0?d.slice(g+1):"":d;if(!x)return null;try{let T=Buffer.from(x,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function w(d,g,x){let T=ye(d),k=async($,E)=>{let N=ye(T,$);N!==T&&!N.startsWith(T+pg)&&v(`refusing to write outside ${T}: ${$}`),x||await _e.stat(N).then(()=>!0).catch(()=>!1)&&v(`${N} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await _e.mkdir(Mr(N),{recursive:!0}),await _e.writeFile(N,E)},y=`# ${g.title||"App change request"}
3781
3872
 
3782
- > Widget proposal \`${f.proposalId}\` \u2014 build this change, then ship it with
3783
- > \`turbobase apps deploy ${f.appSlug}\`. The deploy stamps this proposal complete.
3873
+ > Widget proposal \`${g.proposalId}\` \u2014 build this change, then ship it with
3874
+ > \`turbobase apps deploy ${g.appSlug}\`. The deploy stamps this proposal complete.
3784
3875
 
3785
- ${f.bodyMarkdown||"_No description provided._"}
3876
+ ${g.bodyMarkdown||"_No description provided._"}
3786
3877
 
3787
3878
  ## Screen context
3788
3879
 
3789
- `+(f.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
3790
- `);if(await k("PROPOSAL.md",b),f.screenshot){let $=m(f.screenshot);$&&await k("proposal-screenshot.png",$)}await k(It(".turbobase","proposal.json"),`${JSON.stringify({proposalId:f.proposalId},null,2)}
3791
- `)}async function S(d){try{let f=await be.readFile(It(d,".turbobase","proposal.json"),"utf8"),v=JSON.parse(f);return typeof v.proposalId=="string"&&v.proposalId?v.proposalId:void 0}catch{return}}async function R(d,f,v,T,k,b){let $=new J({baseUrl:d,token:f});try{return await $.appsPush(v,T,{note:k,proposalId:b})}catch(E){if(E instanceof ce){let N=E.body;if(E.status===401&&x("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&N?.error==="admin_required"&&x("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&ne(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&&(N?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&x("push rejected: the request body exceeded the instance limit."),x(`push rejected: ${N?.error??"too large"} (limit ${N?.limit??"?"}).`)),E.status===400){let j=N?.path?` in ${N.path}`:"",D=N?.reason?` (${N.reason})`:"";x(`push rejected: ${N?.error??"bad request"}${D}${j}.`)}}x(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function P(d,f,v){return new Promise((T,k)=>{let b=ug("npm",d,{cwd:f,stdio:"inherit",...v?{env:{...process.env,...v}}:{}});b.on("error",k),b.on("exit",$=>$===0?T():k(new Error(`npm ${d.join(" ")} exited ${$??"?"}`)))})}async function z(d,f,v,T){let k=`${d.replace(/\/+$/,"")}${v}`,b;try{b=await u(k,{method:T.method,headers:{Authorization:`Bearer ${f}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch($){x(`request failed: ${$ instanceof Error?$.message:String($)}`)}if(b.status===401&&x("unauthorized (401) \u2014 re-run `turbobase auth login`."),b.status===403&&x("forbidden (403) \u2014 the PAT is not for an admin."),!b.ok){let $=await b.text().catch(()=>""),E=$.slice(0,300);try{let N=JSON.parse($);E=N.message??N.error??E}catch{}x(`failed: HTTP ${b.status} ${E}`)}return await b.json().catch(()=>({}))}async function F(d,f,v,T,k){return await z(d,f,`/v1/apps/${encodeURIComponent(v)}/preview/${T}`,{method:"POST",body:k})}async function W(d,f,v){return{previews:(await z(d,f,`/v1/apps/${encodeURIComponent(v)}/previews`,{method:"GET"})).previews??[]}}async function Ke(d,f,v,T,k,b,$,E){let N;try{N=await se(`zipping ${T}`,()=>qy(T))}catch(L){x(`could not zip ${T}: ${L instanceof Error?L.message:String(L)}`)}N.fileCount===0&&x(`${T} is empty \u2014 the build produced nothing.`),N.buffer.byteLength>Ou&&x(`${T} zips to ${wT(N.buffer.byteLength)} \u2014 over the ${wT(Ou)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let j={Authorization:`Bearer ${f}`,"Content-Type":"application/zip"};k&&(j["x-app-entry"]=k),b&&(j["x-proposal-id"]=b),$&&(j["x-app-build-id"]=$.buildId,j["x-app-asset-base"]=$.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 D=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(v)}/deploy`,V;try{V=await se(`deploying ${v} (${N.fileCount} file${N.fileCount===1?"":"s"})`,()=>u(D,{method:"POST",headers:j,body:new Uint8Array(N.buffer)}))}catch(L){x(`deploy request failed: ${L instanceof Error?L.message:String(L)}`)}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 L=await V.text().catch(()=>""),ee={};try{ee=JSON.parse(L)}catch{}ee.error==="no_preview"&&x(`${ee.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 L=await V.text().catch(()=>""),ee=L.slice(0,300);try{let _e=JSON.parse(L);ee=_e.message??_e.error??ee}catch{}x(`deploy failed: HTTP ${V.status} ${ee}`)}return await V.json().catch(()=>({}))}function Ye(d){let f=d.roles;if(!f||f.verdicts.length===0)return;let v=f.verdicts.filter(k=>k.action!=="noop");if(v.length===0)return;_(""),_(g.bold(f.applied?"roles":"roles (preview \u2014 not applied)"));let T=Math.max(...v.map(k=>k.name.length));for(let k of v){let b=k.name.padEnd(T);if(k.action==="create"){let $=k.addCapabilities?.length??0;_(` created ${b} ${g.dim(`${$} capabilit${$===1?"y":"ies"}`)}`)}else if(k.action==="add_capabilities"){let $=(k.addCapabilities??[]).map(N=>`+${N}`).join(", "),E=k.holdersRestamped?g.dim(` (${k.holdersRestamped} holder${k.holdersRestamped===1?"":"s"} re-stamped)`):"";_(` updated ${b} ${g.dim($)}${E}`)}}_(g.dim(f.applied?" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.":" nothing was created \u2014 promoting this preview applies them."))}function Gt(d){let f=d.labels;if(!f||f.verdicts.length===0)return;let v=f.verdicts.filter(k=>k.action!=="noop");if(v.length===0)return;_(""),_(g.bold(f.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(...v.map(k=>k.name.length));for(let k of v){let b=k.name.padEnd(T);if(k.action==="detach")_(` removed ${b} ${g.dim("no longer declared in the manifest")}`);else if(k.action==="create")_(` created ${b} ${g.dim(k.color)}`);else{let $=k.declaredColor?`${k.color} \u2014 declared ${k.declaredColor}, the instance's colour is kept`:k.color;_(` added ${b} ${g.dim($)}`)}}_(g.dim(f.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 Mr(d,f){let v=eb(d,{localDocsModifiedAt:await mn(f)});v&&_(v.level==="warn"?g.yellow(v.message):g.dim(v.message))}async function mn(d){if(!d)return null;let f=null;for(let v of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await be.stat(It(d,v));(f===null||T.mtimeMs>f)&&(f=T.mtimeMs)}catch{}return f===null?null:new Date(f)}c.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(d,f,v)=>{let{baseUrl:T,token:k}=await te(v.baseUrl);if(v.proposal){let N=new J({baseUrl:T,token:k}),j;try{j=await se(`fetching proposal ${v.proposal}`,()=>N.appPullContext(v.proposal))}catch(_e){ne(_e,"extensions:deploy","pull proposal"),_e instanceof ce&&_e.status===404&&x(`no widget proposal "${v.proposal}" on ${T}.`),x(`could not fetch proposal ${v.proposal}: ${_e instanceof Error?_e.message:String(_e)}`)}let D=await se(`pulling ${j.appSlug}`,()=>y(T,k,j.appSlug)),V=f??d,L=ge(process.cwd(),V??j.appSlug);await be.mkdir(L,{recursive:!0});let ee=await h(L,D.files,!!v.force);await w(L,j,!!v.force),_(`pulled ${ee} file${ee===1?"":"s"} \u2192 ${L} (rev ${D.rev}), linked to proposal ${j.proposalId}.`),_(`next: cd ${fl(process.cwd(),L)||"."} && 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 b=await se(`pulling ${d}`,()=>y(T,k,d)),$=ge(process.cwd(),f??b.slug??d);await be.mkdir($,{recursive:!0});let E=await h($,b.files,!!v.force);_(`pulled ${E} file${E===1?"":"s"} \u2192 ${$} (rev ${b.rev}).`),_(`next: cd ${fl(process.cwd(),$)||"."} && turbobase apps deploy ${b.slug}`)}),c.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(d,f,v)=>{let T=ge(process.cwd(),f??d),k=await Xt(v.baseUrl).catch(()=>null),{scaffoldAppFiles:b,starterApp:$}=await Promise.resolve().then(()=>(qw(),Uw)),E=v.title??d,N=b({slug:d,title:E,appTsx:$(E),instanceOrigin:k?.baseUrl});await be.mkdir(T,{recursive:!0});let j=await h(T,N,!!v.force);if(_(`scaffolded ${j} file${j===1?"":"s"} \u2192 ${T}`),v.claude!==!1){let V=bu({baseUrl:k?.baseUrl,token:k?.token,appSlug:d}),L=0;for(let ee of V){let _e=await bT(It(T,ee.path),ee);(_e==="wrote"||_e==="merged")&&(L+=1)}_(`wired Claude Code: ${L} file${L===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),k||q("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let D=fl(process.cwd(),T)||".";_(`next: cd ${D} && npm install && npm run dev`),_(` turbobase apps create ${d}`),_(` turbobase apps push ${d} .`),_(` turbobase apps deploy ${d} .`)}),c.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new J({baseUrl:f,token:v}),k;try{k=await T.appsList()}catch(b){ne(b,"extensions:deploy","list apps"),x(`list apps failed: ${b instanceof Error?b.message:String(b)}`)}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>`.");_(er(k.map(b=>[b.slug,b.name,b.deployed?"yes":"no",b.sourceRev===null?"\u2014":`rev ${b.sourceRev}`,b.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),c.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(d,f,v)=>{let T=ge(process.cwd(),f??".");await be.stat(T).then(Pe=>Pe.isDirectory()).catch(()=>!1)||x(`${T} is not a directory.`);let{baseUrl:b,token:$}=await te(v.baseUrl),E=v.proposal??await S(T),{files:N,skipped:j,secrets:D,unstorable:V}=await sw(T),L=Object.keys(N).length;if(L===0&&x(`no source files found under ${T} (build output and node_modules are skipped).`),V.length>0){for(let Pe of V)q(`${Pe} 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 Pe of j)q(g.dim(`skipped binary file ${Pe}`));for(let Pe of D)q(g.dim(`skipped ${Pe} (holds credentials \u2014 never pushed)`));let ee=await se(`pushing ${L} file${L===1?"":"s"}`,()=>R(b,$,d,N,v.note,E));_(`pushed ${ee.files} file${ee.files===1?"":"s"} \u2192 ${ee.slug} rev ${ee.rev} (source only, nothing deployed).`);let _e=await gs(new J({baseUrl:b,token:$}),ee.slug);_e&&_e.entriesAdded>0&&_(`${_e.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),_(`next: turbobase apps deploy ${ee.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let f=await ig(),{baseUrl:v,token:T}=await te(d.baseUrl),k=new J({baseUrl:v,token:T}),b;try{b=await se(`planning against ${d.to??v}`,()=>k.configPlan(f))}catch($){x(`plan failed: ${$ instanceof Error?$.message:String($)}`)}jU(b,d.to??v)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let f=await ig(),{baseUrl:v,token:T}=await te(d.baseUrl),k=f.tenant??DU(v),b=ub(d.confirm,k);b.ok||x(`promote refused (fail-closed): ${b.reason}`);let $=new J({baseUrl:v,token:T});try{let E=await se(`promoting ${d.from} \u2192 ${d.to} (${k})`,()=>$.configApply(f,{prune:d.prune}));if(tt()){let j=[`${g.bold(`${d.from} \u2192 ${d.to}`)} ${g.dim(k??"")}`,`${Hr.add(String(E.applied.add))} ${Hr.change(String(E.applied.change))} ${Hr.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&j.push(g.dim(`${E.backfillsQueued.length} backfill(s) queued`)),_(Kr("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 N=E.skippedDestroys??[];if(N.length>0){q(`${N.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let j of N)q(` ${j.kind} ${j.id}`);q("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof ce&&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 or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(d,f)=>{let v=sg(f.reporter),T=ge(process.cwd(),d),k=await us(T),b=By(k);v?_(oa(IU(d,b),v)):_(Zy(d,b,{warn:g.yellow,ok:g.green,dim:g.dim})),f.ci&&b.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(d,f)=>{let v=sg(f.reporter),T=await zy(ge(process.cwd(),d));if(f.against){f.against!=="sandbox"&&x(`unknown --against target '${f.against}' (only 'sandbox' is supported).`);try{await Oy(du(T))}catch($){x($ instanceof Error?$.message:String($))}return}f.fixture||x("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await Ny(ge(process.cwd(),f.fixture))}catch($){x(`could not read fixture ${f.fixture}: ${$ instanceof Error?$.message:String($)}`)}let b=await Iy(T,k,f.fixture,{resolveDir:Dr(ge(process.cwd(),d))});if(v){let $=OU(b);_(oa($,v)),hl($.cases.some(E=>E.status==="failed")?1:0)}_(Ly(b,!!f.trace)),hl(b.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new J({baseUrl:f,token:v});try{await Yy(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:_})}catch(k){k instanceof ce&&k.status===403&&x("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof ce&&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 Ur=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Ur.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 Zb(d)}),Ur.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,f)=>{await Vb(d??[],f)}),Ur.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{await Hb(d,f)}),Ur.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,f)=>{await Kb(d,f)}),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,f)=>{await Wb(d,f)}),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,f)=>{await Gb(d,f)}),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,f)=>{await Jb(d,f)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(d,f)=>{let v=d.lastIndexOf("@"),T=v>0?d.slice(0,v):d,k=v>0?d.slice(v+1):void 0,b=iu();b||x(`marketplace not configured \u2014 set ${uo} and ${Ji}.
3792
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let $=au(b.registryUrl);$&&x($);let{baseUrl:E,token:N}=await te(f.baseUrl),j=new as(b),D;try{D=await se(`fetching ${d}`,()=>j.fetchBundle(T,k))}catch(Pe){x(`marketplace fetch failed for ${d}: ${Pe instanceof Error?Pe.message:String(Pe)}`)}let V=Ui(D.manifest),L=null;if(V.length>0){if(!f.connection){let Pe=V.map(to=>to.source_system).join(", ");x(`${D.name}@${D.version} declares a connection input (source: ${Pe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}L=f.connection}let ee=NU(D.bundle,D.name,D.kind),_e=new J({baseUrl:E,token:N});try{let Pe=await se(`installing ${D.name}@${D.version}`,()=>_e.deploy({...ee,provenance:"marketplace",...L?{connectionId:L}:{}}));_(`installed ${D.name}@${D.version} \u2192 ${Pe.id} (status=${Pe.status}, ${Pe.outcome})`+(L?` bound to connection ${L}.`:"."))}catch(Pe){Pe instanceof ce&&Pe.status===403&&x("install forbidden (403) \u2014 the stored PAT is not for an admin."),x(`install failed: ${Pe instanceof Error?Pe.message:String(Pe)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(d,f)=>{let v=iu();v||x(`marketplace not configured \u2014 set ${uo} and ${Ji}.
3793
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=au(v.registryUrl);T&&x(T);let k=ge(process.cwd(),d),b=await us(k),$=/\bdefineConduit\s*[<(]/.test(b)?"conduit":"hook",E={};if(f.manifest){let D=ge(process.cwd(),f.manifest),V;try{V=await be.readFile(D,"utf8")}catch{x(`manifest not found at ${f.manifest}.`)}let L;try{L=JSON.parse(V)}catch{x(`manifest is not valid JSON: ${f.manifest}.`)}(typeof L!="object"||L===null||Array.isArray(L))&&x("manifest must be a JSON object."),E=L}try{ql(E,b)}catch(D){D instanceof Vr&&x(D.message),x(`manifest validation failed: ${D instanceof Error?D.message:String(D)}`)}let N=new as(v);try{await se(`publishing ${f.name}@${f.pkgVersion}`,()=>N.publish({name:f.name,version:f.pkgVersion,kind:$,bundle:b,manifest:E}))}catch(D){D instanceof ce&&D.status===403&&x("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),D instanceof ce&&D.status===409&&x(`version already published \u2014 ${f.name}@${f.pkgVersion} exists. Bump the version.`),x(`publish failed: ${D instanceof Error?D.message:String(D)}`)}let j=Ui(E);_(`published ${f.name}@${f.pkgVersion} (kind=${$}) to the marketplace.`),j.length>0&&_(` declares ${j.length} connection input(s): ${j.map(D=>D.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let f=await Xt(d.baseUrl).catch(()=>null),v=bu({baseUrl:f?.baseUrl,token:f?.token}),T=0,k=0,b=0;for(let $ of v){let E=ge(process.cwd(),$.path),N=await bT(E,$);N==="wrote"?(T+=1,_(` wrote ${$.path}`)):N==="merged"?(b+=1,_(` merged ${$.path} (added the .mcp.json rule)`)):(k+=1,_(` skipped ${$.path} (exists)`))}_(`
3794
- project init: ${T} written, ${b} merged, ${k} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${yu} (non-destructive).`).action(async()=>{let d=tb(),f=0,v=0;for(let T of d){let k=ge(process.cwd(),T.path);await Qn(k,T.content,T.executable)==="wrote"?(f+=1,_(` wrote ${T.path}`)):(v+=1,_(` skipped ${T.path} (exists)`))}_(`
3795
- project ci: ${f} written, ${v} skipped.`),f>0&&(_(`
3796
- Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),_("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),_("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new J({baseUrl:f,token:v}),k;try{k=await T.catalogRecords()}catch(j){j instanceof ce&&(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 b=ge(process.cwd(),d.out),$=Dy(k,{event:d.event}),E=0,N=0;for(let{recordType:j,fixture:D}of $){let V=It(b,`${j}.json`),L=`${JSON.stringify(D,null,2)}
3797
- `;d.force?(await be.mkdir(Dr(V),{recursive:!0}),await be.writeFile(V,L,{mode:420}),E+=1,_(` wrote ${d.out}/${j}.json`)):await Qn(V,L)==="wrote"?(E+=1,_(` wrote ${d.out}/${j}.json`)):(N+=1,_(` skipped ${d.out}/${j}.json (exists \u2014 use --force to overwrite)`))}_(`
3798
- samples init: ${E} written, ${N} skipped.`)});let ur=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),$i=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??""],gl=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];ur.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new J({baseUrl:f,token:v}),k;try{k=await T.guardrailsList()}catch(b){ne(b,"extensions:deploy","list guardrails"),x(`list guardrails failed: ${b instanceof Error?b.message:String(b)}`)}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.
3799
- `+g.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(er(k.map($i),{head:gl})),_(g.dim(" first match wins; lower PRIO is evaluated first."))}),ur.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T}),b;try{b=await k.guardrailCreate({name:d,source:f.source,record:f.record,decision:f.decision,...f.op?{op:f.op}:{},...f.target?{target:f.target}:{},...f.actor?{actor:f.actor}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when?{when:f.when}:{},...f.reason?{reason:f.reason}:{},...f.disabled?{enabled:!1}:{},...f.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch($){ne($,"extensions:deploy","create a guardrail"),x(`create guardrail failed: ${$ instanceof Error?$.message:String($)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(b.name??b.id)} created${b.status==="active"?"":g.dim(` (${b.status} \u2014 activate it to take effect)`)}`),_(g.dim(` ${b.decision} ${b.source}/${b.record??b.op}${b.actor?` actor=${b.actor}`:""}${b.when?` where ${b.when}`:""} @prio ${b.priority}`)),_(g.dim(` verify with: turbobase guardrails test --source ${b.source==="*"?"<source>":b.source} --record <record>`))}),ur.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.decision===void 0&&f.priority===void 0&&f.when===void 0&&f.reason===void 0&&x("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T}),b;try{b=await k.guardrailUpdate(d,{...f.decision!==void 0?{decision:f.decision}:{},...Number.isFinite(f.priority)?{priority:Number(f.priority)}:{},...f.when!==void 0?{when:f.when}:{},...f.reason!==void 0?{reason:f.reason}:{}})}catch($){ne($,"extensions:deploy","edit a guardrail"),x(`edit guardrail failed: ${$ instanceof Error?$.message:String($)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(b.name??b.id)} updated`),_(g.dim(` ${b.decision} ${b.source}/${b.record??b.op}${b.when?` where ${b.when}`:""} @prio ${b.priority}`))});for(let[d,f,v]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])ur.command(`${d} <name>`).description(f==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,k)=>{let{baseUrl:b,token:$}=await te(k.baseUrl),E=new J({baseUrl:b,token:$});try{await E.guardrailUpdate(T,{status:f})}catch(N){ne(N,"extensions:deploy",`${d} a guardrail`),x(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(T)} ${v}`),f==="inactive"&&_(g.dim(" writes it was gating now fall through to the other rules."))});ur.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T});try{await k.guardrailDelete(d)}catch(b){ne(b,"extensions:deploy","delete a guardrail"),x(`delete guardrail failed: ${b instanceof Error?b.message:String(b)}`)}_(`${g.green("\u2713")} guardrail ${g.bold(d)} deleted`)}),ur.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T}),b=N=>N==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let N;try{N=await k.guardrailPostureGet()}catch(j){ne(j,"extensions:deploy","read the guardrail posture"),x(`read posture failed: ${j instanceof Error?j.message:String(j)}`)}_(`guardrail posture: ${g.bold(b(N.mode))}`),_(g.dim(N.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 $=d.trim().toLowerCase();$!=="allow"&&$!=="deny"&&x("posture must be 'allow' or 'deny'.");let E;try{E=await k.guardrailPostureSet($)}catch(N){ne(N,"extensions:deploy","set the guardrail posture"),x(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}_(`${g.green("\u2713")} guardrail posture set to ${g.bold(b(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>`."))}),ur.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let f;if(d.fields)try{f=JSON.parse(d.fields)}catch(E){x(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:v,token:T}=await te(d.baseUrl),k=new J({baseUrl:v,token:T}),b;try{b=await k.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...f?{fields:f}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){ne(E,"extensions:deploy","test guardrails"),x(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return _(JSON.stringify(b,null,2));let $=`${d.source}/${b.op??d.record}`;b.degraded?(_(`${g.red("\u2717")} ${$} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(g.dim(` ${b.reason}`))):b.allowed?_(`${g.green("\u2713")} ${$} \u2014 ${b.decision}`+(b.blockedBy?g.dim(` (rule ${b.blockedBy})`):g.dim(" (no rule matched)"))):(_(`${g.red("\u2717")} ${$} \u2014 ${b.decision} by ${g.bold(b.blockedBy??"?")} at the ${b.phase} gate`),b.message&&_(g.dim(` ${b.message}`))),b.decision==="require_confirm"&&_(g.yellow(" this write is HELD for operator approval, not refused.")),b.allowed||(process.exitCode=1)});let Jo=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Ti=(d,f={})=>{let v=`${g.bold(d.table)} ${g.dim(d.displayName)}`;_(d.exists===!1?`${v} ${g.dim("(new)")}`:v);for(let T of d.fields){let k=[T.required?"required":null].filter(Boolean).join(", "),b=f.showClaimants&&T.claimedBy?.length?` ${g.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${k?` (${k})`:""}${b}`)}f.showClaimants&&d.claimants.length>1&&_(g.dim(` claimed by ${d.claimants.join(", ")}`))};function Ri(d){if(d instanceof ce&&d.status===409){let f=d.body;f?.error==="table_conflict"&&f.message&&(q(f.message),process.exit(1))}x(`tables: ${d instanceof Error?d.message:String(d)}`)}let pg=async d=>{let f=It(ge(process.cwd(),d),"public","turbobase.json"),v=await be.readFile(f,"utf8").catch(()=>null);if(v===null)return null;let T;try{T=JSON.parse(v)}catch(b){x(`${f} is not valid JSON: ${b instanceof Error?b.message:String(b)}`)}let k=T.tables;return k===void 0?{tables:[],manifestPath:f}:(Array.isArray(k)||x(`${f}: "tables" must be an array.`),{tables:k,manifestPath:f})};Jo.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new J({baseUrl:f,token:v}),k;try{k=await T.tablesList()}catch(b){ne(b,"extensions:deploy","list tables"),x(`list tables failed: ${b instanceof Error?b.message:String(b)}`)}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>`.");_(er(k.map(b=>[b.table,b.displayName,String(b.fields.length),b.status,b.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Jo.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,f)=>{let v=await pg(d??".");if(v||x(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:k}=await te(f.baseUrl),b=new J({baseUrl:T,token:k}),$;try{$=await se("planning tables",()=>b.tablesPlan({claimedBy:f.as,tables:v.tables}))}catch(E){ne(E,"extensions:deploy","plan tables"),Ri(E)}_(`claiming as ${g.bold($.claimedBy)}`);for(let E of $.tables)Ti(E,{showClaimants:!0});_(""),_(g.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Jo.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,f)=>{let v=await pg(d??".");if(v||x(`no public/turbobase.json under ${ge(process.cwd(),d??".")}.`),v.tables.length===0)return _(`${v.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:k}=await te(f.baseUrl),b=new J({baseUrl:T,token:k}),$;try{$=await se("applying tables",()=>b.tablesApply({claimedBy:f.as,tables:v.tables}))}catch(E){ne(E,"extensions:deploy","apply tables"),Ri(E)}for(let E of $.tables)Ti(E,{showClaimants:!0});_(`applied ${$.tables.length} table${$.tables.length===1?"":"s"} as ${$.claimedBy}.`)}),Jo.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,f)=>[...f??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let v=f.field.map(E=>{let[N,j,D]=E.split(":");return(!N||!j)&&x(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),D!==void 0&&D!=="required"&&x(`--field "${E}": the third part may only be "required".`),{name:N,type:j,...D==="required"?{required:!0}:{}}}),{baseUrl:T,token:k}=await te(f.baseUrl),b=new J({baseUrl:T,token:k}),$;try{$=await se(`creating cr_${d}`,()=>b.tablesApply({tables:[{slug:d,displayName:f.name??d,fields:v,...f.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){ne(E,"extensions:deploy","create a table"),Ri(E)}for(let E of $.tables)Ti(E);_(""),_(g.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Jo.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{f.confirm!==d&&x(`drop refused: --confirm "${f.confirm}" does not match "${d}".`);let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T}),b;try{b=await se(`dropping cr_${d}`,()=>k.tablesDrop(d,f.confirm))}catch($){ne($,"extensions:deploy","drop a table"),x(`drop failed: ${$ instanceof Error?$.message:String($)}`)}if(!b.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${b.table} and every row in it.`)});let yl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");yl.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let f=ag(),v;try{v=await gw(f,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof bs&&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}`)}),yl.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let f=ag();await Bu(f).catch(()=>[]);let v;try{v=await yw(f,d)}catch(T){x(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}v||x(`no sandbox named '${d}'.`),_(`destroyed sandbox ${v.name} (dropped ${v.database}).`)}),yl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=ag(),f=await Bu(d).catch(()=>[]),v=await _a(),{active:T}=Fu(v);if(T.length===0)_("no active sandboxes.");else{for(let k of T)_(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);_(`
3800
- ${T.length} active sandbox(es).`)}f.length>0&&_(`(reaped ${f.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",la).action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new J({baseUrl:f,token:v}),k;try{k=await se("exporting instance config",()=>T.configExport())}catch(E){E instanceof ce&&(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 b=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
3801
- `,$=ge(process.cwd(),d.out,ps);await be.mkdir(Dr($),{recursive:!0}),await be.writeFile($,b,"utf8"),_(`wrote ${d.out}/${ps} (${b.split(`
3802
- `).length} lines).`)});let mg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),vT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],hg=()=>process.env.TURBOBASE_HOME?.trim()||It($U(),".turbobase"),xT=()=>"1.33.0",Ei=async()=>Promise.all(vT.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 Ei();for(let f of d)_(`${f.present?Oe.success("installed"):Oe.warn("missing")} ${g.bold(f.name)} \u2014 ${f.needs}`);d.some(f=>!f.present)&&_(`
3803
- run \`${hs} ext extras install\` to fetch them into ${hg()}.`)}),mg.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ei();if(d.every(N=>N.present)){_(Oe.success("extras already installed \u2014 nothing to do."));return}let f=hg();await be.mkdir(f,{recursive:!0});let v=d.filter(N=>!N.present).map(N=>N.name),T=Lu(process.platform,process.arch),k=async(N,j)=>{let{code:D,stderr:V}=await Si("npm",["install","--prefix",f,"--no-audit","--no-fund",...N]);D!==0&&x(`extras install failed while installing ${j} (npm exited ${D}).
3804
- ${V.trim()}
3805
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},b=v.filter(N=>N!=="isolated-vm");if(b.length>0){let N=b.map(j=>`${j}@${Nu[j]??"latest"}`);_(`installing ${N.join(", ")} \u2192 ${f}/node_modules \u2026`),await k(N,b.join(", "))}if(v.includes("isolated-vm")){let N=`isolated-vm@${Nu["isolated-vm"]}`;if(_(`installing ${N} \u2192 ${f}/node_modules \u2026`),await k(["--ignore-scripts",N],"isolated-vm"),lw.includes(T)){let D=`${zu}@${xT()}`;_(`fetching ${D} (no upstream binary for ${T}) \u2026`);let{code:V}=await Si("npm",["install","--prefix",f,"--no-audit","--no-fund","--ignore-scripts",D]);V!==0&&_(Oe.warn(`could not fetch ${D} \u2014 falling back to a source build.`))}let j=await uw({home:f});j.length>0&&_(` ${Oe.success("prebuilt")} ${j.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let $=await Ei(),E=$.filter(N=>!N.present).map(N=>N.name);if(E.includes("isolated-vm")){_(Oe.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${ju()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:N}=await Si("npm",["rebuild","--prefix",f,"isolated-vm"]);N===0&&($=await Ei(),E=$.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} (${ju()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(Oe.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let eo=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return eo.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let f=d.target==="approved"?"approved":d.target==="auto"?"auto":null;f||x(`--target must be 'auto' or 'approved' (got '${d.target}').`);let v=await MU(ge(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 b=(d.ref?await cg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await cg(["rev-parse","HEAD"]),$=d.gitRepo??process.env.GITHUB_REPOSITORY??await cg(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,N=d.prUrl??process.env.PR_URL??null,{baseUrl:j,token:D}=await te(d.baseUrl),V=new J({baseUrl:j,token:D}),L;try{L=await V.releaseDeploy({solutionId:d.solution??null,target:f,approvedBy:d.approvedBy??null,files:T>0?v:null,gitRepo:$,gitRef:E,gitSha:b,prUrl:N})}catch(ee){ne(ee,"releases:write","release deploy"),ee instanceof ce&&ee.status===404&&x("solution_not_found \u2014 no solution with that id."),x(`release deploy failed: ${ee instanceof Error?ee.message:String(ee)}`)}_(`release ${L.releaseId} enqueued \u2192 taskId=${L.taskId} (target=${f}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Su(()=>V.releaseStatus(L.releaseId),`release ${L.releaseId}`,d.intervalMs)}),eo.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T}),b;try{b=await k.releaseFiles(d)}catch(N){N instanceof ce&&N.status===404&&x(`release ${d} not found.`),N instanceof ce&&N.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.`),ne(N,"releases:write","pull a release"),x(`release pull failed: ${N instanceof Error?N.message:String(N)}`)}let $=ge(process.cwd(),f.dir),E=0;for(let[N,j]of[["owned",b.owned],["context",b.context]])for(let[D,V]of Object.entries(j)){let L=It($,N,D);await be.mkdir(Dr(L),{recursive:!0}),await be.writeFile(L,V,"utf8"),E++}await be.writeFile(It($,".turbobase-release.json"),JSON.stringify({releaseId:b.releaseId,version:b.version,contentDigest:b.contentDigest},null,2),"utf8"),_(`pulled release ${b.releaseId} (${b.status}) \u2192 ${$}
3806
- ${Object.keys(b.owned).length} owned file(s), ${Object.keys(b.context).length} context file(s), ${E} total
3807
- `+(b.logTail?`
3880
+ `+(g.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.
3881
+ `);if(await k("PROPOSAL.md",y),g.screenshot){let $=h(g.screenshot);$&&await k("proposal-screenshot.png",$)}await k(Ot(".turbobase","proposal.json"),`${JSON.stringify({proposalId:g.proposalId},null,2)}
3882
+ `)}async function S(d){try{let g=await _e.readFile(Ot(d,".turbobase","proposal.json"),"utf8"),x=JSON.parse(g);return typeof x.proposalId=="string"&&x.proposalId?x.proposalId:void 0}catch{return}}async function R(d,g,x,T,k,y){let $=new G({baseUrl:d,token:g});try{return await $.appsPush(x,T,{note:k,proposalId:y})}catch(E){if(E instanceof le){let N=E.body;if(E.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&N?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&te(E,"extensions:deploy","push app source"),E.status===404&&v(`no app "${x}" on this instance \u2014 create it with \`turbobase apps create ${x}\`.`),E.status===413&&(N?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${N?.error??"too large"} (limit ${N?.limit??"?"}).`)),E.status===400){let L=N?.path?` in ${N.path}`:"",M=N?.reason?` (${N.reason})`:"";v(`push rejected: ${N?.error??"bad request"}${M}${L}.`)}}v(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function P(d,g,x){return new Promise((T,k)=>{let y=hg("npm",d,{cwd:g,stdio:"inherit",...x?{env:{...process.env,...x}}:{}});y.on("error",k),y.on("exit",$=>$===0?T():k(new Error(`npm ${d.join(" ")} exited ${$??"?"}`)))})}async function z(d,g,x,T){let k=`${d.replace(/\/+$/,"")}${x}`,y;try{y=await u(k,{method:T.method,headers:{Authorization:`Bearer ${g}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch($){v(`request failed: ${$ instanceof Error?$.message:String($)}`)}if(y.status===401&&v("unauthorized (401) \u2014 re-run `turbobase auth login`."),y.status===403&&v("forbidden (403) \u2014 the PAT is not for an admin."),!y.ok){let $=await y.text().catch(()=>""),E=$.slice(0,300);try{let N=JSON.parse($);E=N.message??N.error??E}catch{}v(`failed: HTTP ${y.status} ${E}`)}return await y.json().catch(()=>({}))}async function B(d,g,x,T,k){return await z(d,g,`/v1/apps/${encodeURIComponent(x)}/preview/${T}`,{method:"POST",body:k})}async function K(d,g,x){return{previews:(await z(d,g,`/v1/apps/${encodeURIComponent(x)}/previews`,{method:"GET"})).previews??[]}}async function Ge(d,g,x,T,k,y,$,E){let N;try{N=await se(`zipping ${T}`,()=>Zy(T))}catch(U){v(`could not zip ${T}: ${U instanceof Error?U.message:String(U)}`)}N.fileCount===0&&v(`${T} is empty \u2014 the build produced nothing.`),N.buffer.byteLength>Lu&&v(`${T} zips to ${AT(N.buffer.byteLength)} \u2014 over the ${AT(Lu)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let L={Authorization:`Bearer ${g}`,"Content-Type":"application/zip"};k&&(L["x-app-entry"]=k),y&&(L["x-proposal-id"]=y),$&&(L["x-app-build-id"]=$.buildId,L["x-app-asset-base"]=$.assetBase),E&&(L["x-app-channel"]="preview",E.label&&(L["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(L["x-app-preview-replace"]=E.replacePreviewId));let M=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(x)}/deploy`,re;try{re=await se(`deploying ${x} (${N.fileCount} file${N.fileCount===1?"":"s"})`,()=>u(M,{method:"POST",headers:L,body:new Uint8Array(N.buffer)}))}catch(U){v(`deploy request failed: ${U instanceof Error?U.message:String(U)}`)}if(re.status===401&&v("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),re.status===403&&v("deploy forbidden (403) \u2014 the PAT is not for an admin."),re.status===404){let U=await re.text().catch(()=>""),ne={};try{ne=JSON.parse(U)}catch{}ne.error==="no_preview"&&v(`${ne.message??`no open preview to replace on ${x}`} \u2014 list them with \`turbobase apps preview list ${x}\`.`),v(`no app "${x}" on ${d} \u2014 create it with \`turbobase apps create ${x}\`.`)}if(!re.ok){let U=await re.text().catch(()=>""),ne=U.slice(0,300);try{let Ee=JSON.parse(U);ne=Ee.message??Ee.error??ne}catch{}v(`deploy failed: HTTP ${re.status} ${ne}`)}return await re.json().catch(()=>({}))}function Je(d,g,x){for(let T of ub({mode:d,verdicts:g,retired:x}))(T.stream==="err"?q:_)(T.text)}function Jt(d){let g=d.roles;g&&Je(g.applied?"applied":"preview",g.verdicts??[],g.retired)}function Ur(d){let g=d.labels;if(!g||g.verdicts.length===0)return;let x=g.verdicts.filter(k=>k.action!=="noop");if(x.length===0)return;_(""),_(f.bold(g.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(...x.map(k=>k.name.length));for(let k of x){let y=k.name.padEnd(T);if(k.action==="detach")_(` removed ${y} ${f.dim("no longer declared in the manifest")}`);else if(k.action==="create")_(` created ${y} ${f.dim(k.color)}`);else{let $=k.declaredColor?`${k.color} \u2014 declared ${k.declaredColor}, the instance's colour is kept`:k.color;_(` added ${y} ${f.dim($)}`)}}_(f.dim(g.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 qr(d,g){let x=nb(d,{localDocsModifiedAt:await Yo(g)});x&&_(x.level==="warn"?f.yellow(x.message):f.dim(x.message))}async function Yo(d){if(!d)return null;let g=null;for(let x of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await _e.stat(Ot(d,x));(g===null||T.mtimeMs>g)&&(g=T.mtimeMs)}catch{}return g===null?null:new Date(g)}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,g,x)=>{let{baseUrl:T,token:k}=await Q(x.baseUrl);if(x.proposal){let N=new G({baseUrl:T,token:k}),L;try{L=await se(`fetching proposal ${x.proposal}`,()=>N.appPullContext(x.proposal))}catch(Ee){te(Ee,"extensions:deploy","pull proposal"),Ee instanceof le&&Ee.status===404&&v(`no widget proposal "${x.proposal}" on ${T}.`),v(`could not fetch proposal ${x.proposal}: ${Ee instanceof Error?Ee.message:String(Ee)}`)}let M=await se(`pulling ${L.appSlug}`,()=>b(T,k,L.appSlug)),re=g??d,U=ye(process.cwd(),re??L.appSlug);await _e.mkdir(U,{recursive:!0});let ne=await m(U,M.files,!!x.force);await w(U,L,!!x.force),_(`pulled ${ne} file${ne===1?"":"s"} \u2192 ${U} (rev ${M.rev}), linked to proposal ${L.proposalId}.`),_(`next: cd ${yl(process.cwd(),U)||"."} && turbobase apps deploy ${L.appSlug}`);return}d||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let y=await se(`pulling ${d}`,()=>b(T,k,d)),$=ye(process.cwd(),g??y.slug??d);await _e.mkdir($,{recursive:!0});let E=await m($,y.files,!!x.force);_(`pulled ${E} file${E===1?"":"s"} \u2192 ${$} (rev ${y.rev}).`),_(`next: cd ${yl(process.cwd(),$)||"."} && 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,g,x)=>{let T=ye(process.cwd(),g??d),k=await Qt(x.baseUrl).catch(()=>null),{scaffoldAppFiles:y,starterApp:$}=await Promise.resolve().then(()=>(Xw(),Yw)),E=x.title??d,N=y({slug:d,title:E,appTsx:$(E),instanceOrigin:k?.baseUrl});await _e.mkdir(T,{recursive:!0});let L=await m(T,N,!!x.force);if(_(`scaffolded ${L} file${L===1?"":"s"} \u2192 ${T}`),x.claude!==!1){let re=vu({baseUrl:k?.baseUrl,token:k?.token,appSlug:d}),U=0;for(let ne of re){let Ee=await PT(Ot(T,ne.path),ne);(Ee==="wrote"||Ee==="merged")&&(U+=1)}_(`wired Claude Code: ${U} file${U===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),k||q("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let M=yl(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:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k;try{k=await T.appsList()}catch(y){te(y,"extensions:deploy","list apps"),v(`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>`.");_(tr(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,g,x)=>{let T=ye(process.cwd(),g??".");await _e.stat(T).then(ce=>ce.isDirectory()).catch(()=>!1)||v(`${T} is not a directory.`);let{baseUrl:y,token:$}=await Q(x.baseUrl),E=x.proposal??await S(T),{files:N,skipped:L,secrets:M,unstorable:re}=await gw(T),U=Object.keys(N).length;if(U===0&&v(`no source files found under ${T} (build output and node_modules are skipped).`),re.length>0){for(let ce of re)q(`${ce} contains a NUL byte (U+0000), which cannot be stored.`);v(`push aborted: ${re.length} ${re.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let ce of L)q(f.dim(`skipped binary file ${ce}`));for(let ce of M)q(f.dim(`skipped ${ce} (holds credentials \u2014 never pushed)`));let ne=await se(`pushing ${U} file${U===1?"":"s"}`,()=>R(y,$,d,N,x.note,E));_(`pushed ${ne.files} file${ne.files===1?"":"s"} \u2192 ${ne.slug} rev ${ne.rev} (source only, nothing deployed).`);let Ee=await ws(new G({baseUrl:y,token:$}),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 g=await lg(),{baseUrl:x,token:T}=await Q(d.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await se(`planning against ${d.to??x}`,()=>k.configPlan(g))}catch($){v(`plan failed: ${$ instanceof Error?$.message:String($)}`)}eq(y,d.to??x)}),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 g=await lg(),{baseUrl:x,token:T}=await Q(d.baseUrl),k=g.tenant??tq(x),y=vb(d.confirm,k);y.ok||v(`promote refused (fail-closed): ${y.reason}`);let $=new G({baseUrl:x,token:T});try{let E=await se(`promoting ${d.from} \u2192 ${d.to} (${k})`,()=>$.configApply(g,{prune:d.prune}));if(nt()){let L=[`${f.bold(`${d.from} \u2192 ${d.to}`)} ${f.dim(k??"")}`,`${Kr.add(String(E.applied.add))} ${Kr.change(String(E.applied.change))} ${Kr.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&L.push(f.dim(`${E.backfillsQueued.length} backfill(s) queued`)),_(Wr("Promoted",L))}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 N=E.skippedDestroys??[];if(N.length>0){q(`${N.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let L of N)q(` ${L.kind} ${L.id}`);q("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof le&&E.status===403&&v("promote forbidden (403) \u2014 the stored PAT is not for an admin."),v(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(d,g)=>{let x=cg(g.reporter),T=ye(process.cwd(),d),k=await ps(T),y=Hy(k);x?_(ia(GU(d,y),x)):_(Ky(d,y,{warn:f.yellow,ok:f.green,dim:f.dim})),g.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,g)=>{let x=cg(g.reporter),T=await Dy(ye(process.cwd(),d));if(g.against){g.against!=="sandbox"&&v(`unknown --against target '${g.against}' (only 'sandbox' is supported).`);try{await Ly(hu(T))}catch($){v($ instanceof Error?$.message:String($))}return}g.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await jy(ye(process.cwd(),g.fixture))}catch($){v(`could not read fixture ${g.fixture}: ${$ instanceof Error?$.message:String($)}`)}let y=await zy(T,k,g.fixture,{resolveDir:Mr(ye(process.cwd(),d))});if(x){let $=JU(y);_(ia($,x)),gl($.cases.some(E=>E.status==="failed")?1:0)}_(My(y,!!g.trace)),gl(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:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x});try{await eb(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:_})}catch(k){k instanceof le&&k.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof le&&k.status===409&&v("binding is not retryable (only divergent/blocked bindings can be retried)."),v(`ext binding failed: ${k instanceof Error?k.message:String(k)}`)}});let mn=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");mn.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 tw(d)}),mn.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,g)=>{await rw(d??[],g)}),mn.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,g)=>{await nw(d,g)}),mn.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,g)=>{await ow(d,g)}),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,g)=>{await sw(d,g)}),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,g)=>{await iw(d,g)}),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,g)=>{await aw(d,g)}),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,g)=>{let x=d.lastIndexOf("@"),T=x>0?d.slice(0,x):d,k=x>0?d.slice(x+1):void 0,y=cu();y||v(`marketplace not configured \u2014 set ${uo} and ${Xi}.
3883
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let $=lu(y.registryUrl);$&&v($);let{baseUrl:E,token:N}=await Q(g.baseUrl),L=new ls(y),M;try{M=await se(`fetching ${d}`,()=>L.fetchBundle(T,k))}catch(ce){v(`marketplace fetch failed for ${d}: ${ce instanceof Error?ce.message:String(ce)}`)}let re=Bi(M.manifest),U=null;if(re.length>0){if(!g.connection){let ce=re.map(Ce=>Ce.source_system).join(", ");v(`${M.name}@${M.version} declares a connection input (source: ${ce}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}U=g.connection}let ne=YU(M.bundle,M.name,M.kind),Ee=new G({baseUrl:E,token:N});try{let ce=await se(`installing ${M.name}@${M.version}`,()=>Ee.deploy({...ne,provenance:"marketplace",...U?{connectionId:U}:{}}));_(`installed ${M.name}@${M.version} \u2192 ${ce.id} (status=${ce.status}, ${ce.outcome})`+(U?` bound to connection ${U}.`:"."))}catch(ce){ce instanceof le&&ce.status===403&&v("install forbidden (403) \u2014 the stored PAT is not for an admin."),v(`install failed: ${ce instanceof Error?ce.message:String(ce)}`)}}),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,g)=>{let x=cu();x||v(`marketplace not configured \u2014 set ${uo} and ${Xi}.
3884
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=lu(x.registryUrl);T&&v(T);let k=ye(process.cwd(),d),y=await ps(k),$=/\bdefineConduit\s*[<(]/.test(y)?"conduit":"hook",E={};if(g.manifest){let M=ye(process.cwd(),g.manifest),re;try{re=await _e.readFile(M,"utf8")}catch{v(`manifest not found at ${g.manifest}.`)}let U;try{U=JSON.parse(re)}catch{v(`manifest is not valid JSON: ${g.manifest}.`)}(typeof U!="object"||U===null||Array.isArray(U))&&v("manifest must be a JSON object."),E=U}try{Fl(E,y)}catch(M){M instanceof Hr&&v(M.message),v(`manifest validation failed: ${M instanceof Error?M.message:String(M)}`)}let N=new ls(x);try{await se(`publishing ${g.name}@${g.pkgVersion}`,()=>N.publish({name:g.name,version:g.pkgVersion,kind:$,bundle:y,manifest:E}))}catch(M){M instanceof le&&M.status===403&&v("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),M instanceof le&&M.status===409&&v(`version already published \u2014 ${g.name}@${g.pkgVersion} exists. Bump the version.`),v(`publish failed: ${M instanceof Error?M.message:String(M)}`)}let L=Bi(E);_(`published ${g.name}@${g.pkgVersion} (kind=${$}) to the marketplace.`),L.length>0&&_(` declares ${L.length} connection input(s): ${L.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 g=await Qt(d.baseUrl).catch(()=>null),x=vu({baseUrl:g?.baseUrl,token:g?.token}),T=0,k=0,y=0;for(let $ of x){let E=ye(process.cwd(),$.path),N=await PT(E,$);N==="wrote"?(T+=1,_(` wrote ${$.path}`)):N==="merged"?(y+=1,_(` merged ${$.path} (added the .mcp.json rule)`)):(k+=1,_(` skipped ${$.path} (exists)`))}_(`
3885
+ project init: ${T} written, ${y} merged, ${k} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${_u} (non-destructive).`).action(async()=>{let d=pb(),g=0,x=0;for(let T of d){let k=ye(process.cwd(),T.path);await eo(k,T.content,T.executable)==="wrote"?(g+=1,_(` wrote ${T.path}`)):(x+=1,_(` skipped ${T.path} (exists)`))}_(`
3886
+ project ci: ${g} written, ${x} skipped.`),g>0&&(_(`
3887
+ 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:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k;try{k=await T.catalogRecords()}catch(L){L instanceof le&&(L.status===401||L.status===403)&&v("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),v(`catalog fetch failed: ${L instanceof Error?L.message:String(L)}`)}if(k.length===0){_("no records in the instance catalog \u2014 nothing to generate.");return}let y=ye(process.cwd(),d.out),$=qy(k,{event:d.event}),E=0,N=0;for(let{recordType:L,fixture:M}of $){let re=Ot(y,`${L}.json`),U=`${JSON.stringify(M,null,2)}
3888
+ `;d.force?(await _e.mkdir(Mr(re),{recursive:!0}),await _e.writeFile(re,U,{mode:420}),E+=1,_(` wrote ${d.out}/${L}.json`)):await eo(re,U)==="wrote"?(E+=1,_(` wrote ${d.out}/${L}.json`)):(N+=1,_(` skipped ${d.out}/${L}.json (exists \u2014 use --force to overwrite)`))}_(`
3889
+ samples init: ${E} written, ${N} skipped.`)});let dr=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),bl=d=>[d.name??f.dim(d.id.slice(0,8)),d.status==="active"?f.green("active"):d.status==="proposed"?f.yellow("proposed"):f.dim("inactive"),d.decision==="deny"?f.red(d.decision):d.decision==="require_confirm"?f.yellow(d.decision):f.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??f.dim("any"),d.when||f.dim("(always)"),d.reason??""],IT=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];dr.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:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k;try{k=await T.guardrailsList()}catch(y){te(y,"extensions:deploy","list guardrails"),v(`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.
3890
+ `+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));_(tr(k.map(bl),{head:IT})),_(f.dim(" first match wins; lower PRIO is evaluated first."))}),dr.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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.guardrailCreate({name:d,source:g.source,record:g.record,decision:g.decision,...g.op?{op:g.op}:{},...g.target?{target:g.target}:{},...g.actor?{actor:g.actor}:{},...Number.isFinite(g.priority)?{priority:Number(g.priority)}:{},...g.when?{when:g.when}:{},...g.reason?{reason:g.reason}:{},...g.disabled?{enabled:!1}:{},...g.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch($){te($,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${$ instanceof Error?$.message:String($)}`)}_(`${f.green("\u2713")} guardrail ${f.bold(y.name??y.id)} created${y.status==="active"?"":f.dim(` (${y.status} \u2014 activate it to take effect)`)}`),_(f.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.actor?` actor=${y.actor}`:""}${y.when?` where ${y.when}`:""} @prio ${y.priority}`)),_(f.dim(` verify with: turbobase guardrails test --source ${y.source==="*"?"<source>":y.source} --record <record>`))}),dr.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,g)=>{g.decision===void 0&&g.priority===void 0&&g.when===void 0&&g.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.guardrailUpdate(d,{...g.decision!==void 0?{decision:g.decision}:{},...Number.isFinite(g.priority)?{priority:Number(g.priority)}:{},...g.when!==void 0?{when:g.when}:{},...g.reason!==void 0?{reason:g.reason}:{}})}catch($){te($,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${$ instanceof Error?$.message:String($)}`)}_(`${f.green("\u2713")} guardrail ${f.bold(y.name??y.id)} updated`),_(f.dim(` ${y.decision} ${y.source}/${y.record??y.op}${y.when?` where ${y.when}`:""} @prio ${y.priority}`))});for(let[d,g,x]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])dr.command(`${d} <name>`).description(g==="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:$}=await Q(k.baseUrl),E=new G({baseUrl:y,token:$});try{await E.guardrailUpdate(T,{status:g})}catch(N){te(N,"extensions:deploy",`${d} a guardrail`),v(`${d} guardrail failed: ${N instanceof Error?N.message:String(N)}`)}_(`${f.green("\u2713")} guardrail ${f.bold(T)} ${x}`),g==="inactive"&&_(f.dim(" writes it was gating now fall through to the other rules."))});dr.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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T});try{await k.guardrailDelete(d)}catch(y){te(y,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${y instanceof Error?y.message:String(y)}`)}_(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),dr.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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y=N=>N==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let N;try{N=await k.guardrailPostureGet()}catch(L){te(L,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${L instanceof Error?L.message:String(L)}`)}_(`guardrail posture: ${f.bold(y(N.mode))}`),_(f.dim(N.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 $=d.trim().toLowerCase();$!=="allow"&&$!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await k.guardrailPostureSet($)}catch(N){te(N,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${N instanceof Error?N.message:String(N)}`)}_(`${f.green("\u2713")} guardrail posture set to ${f.bold(y(E.mode))}`),E.mode==="deny"&&_(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),dr.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 g;if(d.fields)try{g=JSON.parse(d.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:x,token:T}=await Q(d.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...g?{fields:g}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){te(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return _(JSON.stringify(y,null,2));let $=`${d.source}/${y.op??d.record}`;y.degraded?(_(`${f.red("\u2717")} ${$} \u2014 guardrail policy is UNREADABLE; writes fail closed`),_(f.dim(` ${y.reason}`))):y.allowed?_(`${f.green("\u2713")} ${$} \u2014 ${y.decision}`+(y.blockedBy?f.dim(` (rule ${y.blockedBy})`):f.dim(" (no rule matched)"))):(_(`${f.red("\u2717")} ${$} \u2014 ${y.decision} by ${f.bold(y.blockedBy??"?")} at the ${y.phase} gate`),y.message&&_(f.dim(` ${y.message}`))),y.decision==="require_confirm"&&_(f.yellow(" this write is HELD for operator approval, not refused.")),y.allowed||(process.exitCode=1)});let Xo=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Ei=(d,g={})=>{let x=`${f.bold(d.table)} ${f.dim(d.displayName)}`;_(d.exists===!1?`${x} ${f.dim("(new)")}`:x);for(let T of d.fields){let k=[T.required?"required":null].filter(Boolean).join(", "),y=g.showClaimants&&T.claimedBy?.length?` ${f.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";_(` ${T.column.padEnd(28)} ${T.type}${k?` (${k})`:""}${y}`)}g.showClaimants&&d.claimants.length>1&&_(f.dim(` claimed by ${d.claimants.join(", ")}`))};function Pi(d){if(d instanceof le&&d.status===409){let g=d.body;g?.error==="table_conflict"&&g.message&&(q(g.message),process.exit(1))}v(`tables: ${d instanceof Error?d.message:String(d)}`)}let fg=async d=>{let g=Ot(ye(process.cwd(),d),"public","turbobase.json"),x=await _e.readFile(g,"utf8").catch(()=>null);if(x===null)return null;let T;try{T=JSON.parse(x)}catch(y){v(`${g} is not valid JSON: ${y instanceof Error?y.message:String(y)}`)}let k=T.tables;return k===void 0?{tables:[],manifestPath:g}:(Array.isArray(k)||v(`${g}: "tables" must be an array.`),{tables:k,manifestPath:g})};Xo.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:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k;try{k=await T.tablesList()}catch(y){te(y,"extensions:deploy","list tables"),v(`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>`.");_(tr(k.map(y=>[y.table,y.displayName,String(y.fields.length),y.status,y.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Xo.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,g)=>{let x=await fg(d??".");if(x||v(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`),x.tables.length===0)return _(`${x.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:k}=await Q(g.baseUrl),y=new G({baseUrl:T,token:k}),$;try{$=await se("planning tables",()=>y.tablesPlan({claimedBy:g.as,tables:x.tables}))}catch(E){te(E,"extensions:deploy","plan tables"),Pi(E)}_(`claiming as ${f.bold($.claimedBy)}`);for(let E of $.tables)Ei(E,{showClaimants:!0});_(""),_(f.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Xo.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,g)=>{let x=await fg(d??".");if(x||v(`no public/turbobase.json under ${ye(process.cwd(),d??".")}.`),x.tables.length===0)return _(`${x.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:k}=await Q(g.baseUrl),y=new G({baseUrl:T,token:k}),$;try{$=await se("applying tables",()=>y.tablesApply({claimedBy:g.as,tables:x.tables}))}catch(E){te(E,"extensions:deploy","apply tables"),Pi(E)}for(let E of $.tables)Ei(E,{showClaimants:!0});_(`applied ${$.tables.length} table${$.tables.length===1?"":"s"} as ${$.claimedBy}.`)}),Xo.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,g)=>[...g??[],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,g)=>{let x=g.field.map(E=>{let[N,L,M]=E.split(":");return(!N||!L)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),M!==void 0&&M!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:N,type:L,...M==="required"?{required:!0}:{}}}),{baseUrl:T,token:k}=await Q(g.baseUrl),y=new G({baseUrl:T,token:k}),$;try{$=await se(`creating cr_${d}`,()=>y.tablesApply({tables:[{slug:d,displayName:g.name??d,fields:x,...g.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){te(E,"extensions:deploy","create a table"),Pi(E)}for(let E of $.tables)Ei(E);_(""),_(f.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Xo.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,g)=>{g.confirm!==d&&v(`drop refused: --confirm "${g.confirm}" does not match "${d}".`);let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await se(`dropping cr_${d}`,()=>k.tablesDrop(d,g.confirm))}catch($){te($,"extensions:deploy","drop a table"),v(`drop failed: ${$ instanceof Error?$.message:String($)}`)}if(!y.removed)return _(`no table named "${d}" on this instance \u2014 nothing dropped.`);_(`dropped ${y.table} and every row in it.`)});let wl=e.command("sandbox").description("Ephemeral local authoring sandboxes.");wl.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 g=ug(),x;try{x=await Rw(g,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof vs&&v(T.message),v(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}_(`sandbox ${x.name} ready.`),_(` source: ${x.fromTenant} (sampled ${Math.round(x.sampleFraction*100)}%, redacted)`),_(` url: ${x.url}`),_(` expires: ${x.expiresAt}`)}),wl.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 g=ug();await Hu(g).catch(()=>[]);let x;try{x=await Ew(g,d)}catch(T){v(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}x||v(`no sandbox named '${d}'.`),_(`destroyed sandbox ${x.name} (dropped ${x.database}).`)}),wl.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=ug(),g=await Hu(d).catch(()=>[]),x=await xa(),{active:T}=Vu(x);if(T.length===0)_("no active sandboxes.");else{for(let k of T)_(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);_(`
3891
+ ${T.length} active sandbox(es).`)}g.length>0&&_(`(reaped ${g.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.",da).action(async d=>{let{baseUrl:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k;try{k=await se("exporting instance config",()=>T.configExport())}catch(E){E instanceof le&&(E.status===401||E.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`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)}
3892
+ `,$=ye(process.cwd(),d.out,fs);await _e.mkdir(Mr($),{recursive:!0}),await _e.writeFile($,y,"utf8"),_(`wrote ${d.out}/${fs} (${y.split(`
3893
+ `).length} lines).`)});let gg=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),OT=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],yg=()=>process.env.TURBOBASE_HOME?.trim()||Ot(BU(),".turbobase"),NT=()=>"1.34.1",Ai=async()=>Promise.all(OT.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));gg.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Ai();for(let g of d)_(`${g.present?ze.success("installed"):ze.warn("missing")} ${f.bold(g.name)} \u2014 ${g.needs}`);d.some(g=>!g.present)&&_(`
3894
+ run \`${ys} ext extras install\` to fetch them into ${yg()}.`)}),gg.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Ai();if(d.every(N=>N.present)){_(ze.success("extras already installed \u2014 nothing to do."));return}let g=yg();await _e.mkdir(g,{recursive:!0});let x=d.filter(N=>!N.present).map(N=>N.name),T=Mu(process.platform,process.arch),k=async(N,L)=>{let{code:M,stderr:re}=await Ri("npm",["install","--prefix",g,"--no-audit","--no-fund",...N]);M!==0&&v(`extras install failed while installing ${L} (npm exited ${M}).
3895
+ ${re.trim()}
3896
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},y=x.filter(N=>N!=="isolated-vm");if(y.length>0){let N=y.map(L=>`${L}@${ju[L]??"latest"}`);_(`installing ${N.join(", ")} \u2192 ${g}/node_modules \u2026`),await k(N,y.join(", "))}if(x.includes("isolated-vm")){let N=`isolated-vm@${ju["isolated-vm"]}`;if(_(`installing ${N} \u2192 ${g}/node_modules \u2026`),await k(["--ignore-scripts",N],"isolated-vm"),_w.includes(T)){let M=`${Du}@${NT()}`;_(`fetching ${M} (no upstream binary for ${T}) \u2026`);let{code:re}=await Ri("npm",["install","--prefix",g,"--no-audit","--no-fund","--ignore-scripts",M]);re!==0&&_(ze.warn(`could not fetch ${M} \u2014 falling back to a source build.`))}let L=await vw({home:g});L.length>0&&_(` ${ze.success("prebuilt")} ${L.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let $=await Ai(),E=$.filter(N=>!N.present).map(N=>N.name);if(E.includes("isolated-vm")){_(ze.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Uu()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:N}=await Ri("npm",["rebuild","--prefix",g,"isolated-vm"]);N===0&&($=await Ai(),E=$.filter(L=>!L.present).map(L=>L.name))}E.length>0&&v(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Uu()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),_(ze.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let to=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return to.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 g=d.target==="approved"?"approved":d.target==="auto"?"auto":null;g||v(`--target must be 'auto' or 'approved' (got '${d.target}').`);let x=await rq(ye(process.cwd(),d.project??".")),T=Object.keys(x).length;!d.solution&&T===0&&v("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 dg(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await dg(["rev-parse","HEAD"]),$=d.gitRepo??process.env.GITHUB_REPOSITORY??await dg(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,N=d.prUrl??process.env.PR_URL??null,{baseUrl:L,token:M}=await Q(d.baseUrl),re=new G({baseUrl:L,token:M}),U;try{U=await re.releaseDeploy({solutionId:d.solution??null,target:g,approvedBy:d.approvedBy??null,files:T>0?x:null,gitRepo:$,gitRef:E,gitSha:y,prUrl:N})}catch(ne){te(ne,"releases:write","release deploy"),ne instanceof le&&ne.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${ne instanceof Error?ne.message:String(ne)}`)}_(`release ${U.releaseId} enqueued \u2192 taskId=${U.taskId} (target=${g}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Ru(()=>re.releaseStatus(U.releaseId),`release ${U.releaseId}`,d.intervalMs)}),to.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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.releaseFiles(d)}catch(N){N instanceof le&&N.status===404&&v(`release ${d} not found.`),N instanceof le&&N.status===409&&v(`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.`),te(N,"releases:write","pull a release"),v(`release pull failed: ${N instanceof Error?N.message:String(N)}`)}let $=ye(process.cwd(),g.dir),E=0;for(let[N,L]of[["owned",y.owned],["context",y.context]])for(let[M,re]of Object.entries(L)){let U=Ot($,N,M);await _e.mkdir(Mr(U),{recursive:!0}),await _e.writeFile(U,re,"utf8"),E++}await _e.writeFile(Ot($,".turbobase-release.json"),JSON.stringify({releaseId:y.releaseId,version:y.version,contentDigest:y.contentDigest},null,2),"utf8"),_(`pulled release ${y.releaseId} (${y.status}) \u2192 ${$}
3897
+ ${Object.keys(y.owned).length} owned file(s), ${Object.keys(y.context).length} context file(s), ${E} total
3898
+ `+(y.logTail?`
3808
3899
  the failure these bytes produced:
3809
- ${b.logTail.trim()}
3900
+ ${y.logTail.trim()}
3810
3901
  `:"")+`
3811
3902
  edit the files under owned/, then:
3812
- turbobase release push ${b.releaseId} --dir ${f.dir}`)}),eo.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T}),b=ge(process.cwd(),f.dir),$;try{$=await k.releaseFiles(d)}catch(L){L instanceof ce&&L.status===404&&x(`release ${d} not found.`),ne(L,"releases:write","push a release"),x(`release push failed: ${L instanceof Error?L.message:String(L)}`)}let E=async(L,ee)=>{try{return await be.readFile(It(b,L,ee),"utf8")}catch{return null}},N=[];for(let[L,ee]of Object.entries($.context)){let _e=await E("context",L);_e!==null&&_e!==ee&&N.push(L)}N.length>0&&x(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
3813
- `+N.map(L=>` context/${L}`).join(`
3814
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let j={...$.context},D=0;for(let[L,ee]of Object.entries($.owned)){let _e=await E("owned",L);j[L]=_e??ee,_e!==null&&_e!==ee&&D++}D===0&&_("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let V=f.target==="approved"?"approved":"auto";try{let L=await k.releasePush(d,{files:j,target:V,...f.approvedBy?{approvedBy:f.approvedBy}:{}});_(`pushed ${Object.keys(j).length} file(s) (${D} edited) \u2192 release ${L.releaseId} (task ${L.taskId}).
3903
+ turbobase release push ${y.releaseId} --dir ${g.dir}`)}),to.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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y=ye(process.cwd(),g.dir),$;try{$=await k.releaseFiles(d)}catch(U){U instanceof le&&U.status===404&&v(`release ${d} not found.`),te(U,"releases:write","push a release"),v(`release push failed: ${U instanceof Error?U.message:String(U)}`)}let E=async(U,ne)=>{try{return await _e.readFile(Ot(y,U,ne),"utf8")}catch{return null}},N=[];for(let[U,ne]of Object.entries($.context)){let Ee=await E("context",U);Ee!==null&&Ee!==ne&&N.push(U)}N.length>0&&v(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
3904
+ `+N.map(U=>` context/${U}`).join(`
3905
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let L={...$.context},M=0;for(let[U,ne]of Object.entries($.owned)){let Ee=await E("owned",U);L[U]=Ee??ne,Ee!==null&&Ee!==ne&&M++}M===0&&_("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let re=g.target==="approved"?"approved":"auto";try{let U=await k.releasePush(d,{files:L,target:re,...g.approvedBy?{approvedBy:g.approvedBy}:{}});_(`pushed ${Object.keys(L).length} file(s) (${M} edited) \u2192 release ${U.releaseId} (task ${U.taskId}).
3815
3906
  follow it with:
3816
- turbobase release status ${L.releaseId} --follow`)}catch(L){L instanceof ce&&L.status===403&&x("an approved target needs --approved-by (the deploy gate fails closed)."),L instanceof ce&&L.status===409&&x("that solution already has an active release \u2014 roll it back or wait for it."),ne(L,"releases:write","push a release"),x(`release push failed: ${L instanceof Error?L.message:String(L)}`)}}),eo.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T});if(f.follow){await Su(()=>k.releaseStatus(d),`release ${d}`,f.intervalMs);return}let b;try{b=await k.releaseStatus(d)}catch($){ne($,"releases:write","release status"),$ instanceof ce&&$.status===404&&x(`release ${d} not found.`),x(`release status failed: ${$ instanceof Error?$.message:String($)}`)}_(`release ${d}: status=${b.releaseStatus??"?"} stage=${b.stage} ${b.percent}%`+(b.runStatus?` (${b.runStatus})`:"")),b.outputTail&&_(b.outputTail.replace(/\n+$/,""))}),eo.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,f)=>{let{baseUrl:v,token:T}=await te(f.baseUrl),k=new J({baseUrl:v,token:T}),b;try{b=await k.releaseRollback(d)}catch($){ne($,"releases:write","release rollback"),$ instanceof ce&&$.status===404&&x(`release ${d} not found.`),$ instanceof ce&&$.status===409&&x(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),x(`release rollback failed: ${$ instanceof Error?$.message:String($)}`)}_(`release ${b.releaseId} rolled back \u2192 status=${b.release?.status??"rolled_back"}.`)}),eo.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new J({baseUrl:f,token:v}),k;try{k=await T.releaseList()}catch(b){ne(b,"releases:write","release list"),x(`release list failed: ${b instanceof Error?b.message:String(b)}`)}if(k.length===0){_("no releases.");return}if(tt())_(er(k.map(b=>[b.id,ho(b.status),b.target,b.backend,b.solutionTitles?.length?b.solutionTitles.map($=>`"${$}"`).join(", "):g.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let b of k){let $=b.solutionTitles?.length?` "${b.solutionTitles.join('", "')}"`:"";_(` ${b.id} ${b.status.padEnd(11)} target=${b.target} backend=${b.backend}${$}`)}_(`
3817
- ${k.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:f,token:v}=await te(d.baseUrl),T=new J({baseUrl:f,token:v}),k=d.limit?Number(d.limit):void 0,b=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await Jy(T,d.conduit,{...d.follow?{follow:!0}:{},...k!==void 0?{limit:k}:{},...b!==void 0?{intervalMs:b}:{},sink:_})}catch($){x(`logs --conduit failed: ${$ instanceof Error?$.message:String($)}`)}return}if(d.extension){try{let $=await T.logs(d.extension,k);$.length===0&&_(`no logs for ${d.extension}.`);for(let E of $)_(` [${E.level}] ${E.ts??""} ${E.message}`)}catch($){x(`logs --extension failed: ${$ instanceof Error?$.message:String($)}`)}return}try{await Xy(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}:{},...b!==void 0?{intervalMs:b}:{},sink:_})}catch($){x(`logs failed: ${$ instanceof Error?$.message:String($)}`)}}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{runAuthoringMcpServer:f}=await Promise.resolve().then(()=>(yT(),gT));await f({baseUrl:d.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
3818
- `)),t&&void 0,e}function NU(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 zU(t){let e=It(ge(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 LU(){let t=ge(process.cwd(),la,ps),e;try{e=await be.readFile(t,"utf8")}catch{x(`no config found \u2014 this project authors none (no ${da}/, ${pa}/, ${Wr} or ${Gr}) and there is no ${la}/${ps}.
3819
- Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return lb(e)}catch(r){x(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function ig(){let t=process.cwd();if(!await mb(t))return LU();let e;try{e=await hb(t,{inline:cu})}catch(r){x(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)q(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&x(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function jU(t,e){_(`plan against ${e}:`);for(let r of t.add)_(` ${Hr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)_(` ${Hr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)_(` ${Hr.destroy(`${r.kind} ${r.id}`)}`);_(`
3820
- ${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 DU(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function Si(t,e,r){return new Promise(n=>{let o=ug(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 ag(){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 Si("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 Si("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 MU(t){let e=ge(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=It(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=fl(e,a).split(lg).join("/");r[c]=await be.readFile(a,"utf8")}}};return await n(e),r}function cg(t){return new Promise(e=>{let r=ug("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 UU=!1;UU&&dg().parseAsync(process.argv).catch(t=>x(t instanceof Error?t.message:String(t)));dg().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3907
+ turbobase release status ${U.releaseId} --follow`)}catch(U){U instanceof le&&U.status===403&&v("an approved target needs --approved-by (the deploy gate fails closed)."),U instanceof le&&U.status===409&&v("that solution already has an active release \u2014 roll it back or wait for it."),te(U,"releases:write","push a release"),v(`release push failed: ${U instanceof Error?U.message:String(U)}`)}}),to.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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T});if(g.follow){await Ru(()=>k.releaseStatus(d),`release ${d}`,g.intervalMs);return}let y;try{y=await k.releaseStatus(d)}catch($){te($,"releases:write","release status"),$ instanceof le&&$.status===404&&v(`release ${d} not found.`),v(`release status failed: ${$ instanceof Error?$.message:String($)}`)}_(`release ${d}: status=${y.releaseStatus??"?"} stage=${y.stage} ${y.percent}%`+(y.runStatus?` (${y.runStatus})`:"")),y.outputTail&&_(y.outputTail.replace(/\n+$/,""))}),to.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,g)=>{let{baseUrl:x,token:T}=await Q(g.baseUrl),k=new G({baseUrl:x,token:T}),y;try{y=await k.releaseRollback(d)}catch($){te($,"releases:write","release rollback"),$ instanceof le&&$.status===404&&v(`release ${d} not found.`),$ instanceof le&&$.status===409&&v(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),v(`release rollback failed: ${$ instanceof Error?$.message:String($)}`)}_(`release ${y.releaseId} rolled back \u2192 status=${y.release?.status??"rolled_back"}.`)}),to.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:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k;try{k=await T.releaseList()}catch(y){te(y,"releases:write","release list"),v(`release list failed: ${y instanceof Error?y.message:String(y)}`)}if(k.length===0){_("no releases.");return}if(nt())_(tr(k.map(y=>[y.id,mo(y.status),y.target,y.backend,y.solutionTitles?.length?y.solutionTitles.map($=>`"${$}"`).join(", "):f.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let y of k){let $=y.solutionTitles?.length?` "${y.solutionTitles.join('", "')}"`:"";_(` ${y.id} ${y.status.padEnd(11)} target=${y.target} backend=${y.backend}${$}`)}_(`
3908
+ ${k.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:g,token:x}=await Q(d.baseUrl),T=new G({baseUrl:g,token:x}),k=d.limit?Number(d.limit):void 0,y=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await Qy(T,d.conduit,{...d.follow?{follow:!0}:{},...k!==void 0?{limit:k}:{},...y!==void 0?{intervalMs:y}:{},sink:_})}catch($){v(`logs --conduit failed: ${$ instanceof Error?$.message:String($)}`)}return}if(d.extension){try{let $=await T.logs(d.extension,k);$.length===0&&_(`no logs for ${d.extension}.`);for(let E of $)_(` [${E.level}] ${E.ts??""} ${E.message}`)}catch($){v(`logs --extension failed: ${$ instanceof Error?$.message:String($)}`)}return}try{await tb(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($){v(`logs failed: ${$ instanceof Error?$.message:String($)}`)}}),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:g}=await Promise.resolve().then(()=>(ET(),RT));await g({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(`
3909
+ `)),t&&void 0,e}function YU(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 XU(t){let e=Ot(ye(process.cwd(),t),"public","turbobase.json"),r=await _e.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){v(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&v(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function QU(){let t=ye(process.cwd(),da,fs),e;try{e=await _e.readFile(t,"utf8")}catch{v(`no config found \u2014 this project authors none (no ${ha}/, ${ma}/, ${Gr} or ${Jr}) and there is no ${da}/${fs}.
3910
+ Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return _b(e)}catch(r){v(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function lg(){let t=process.cwd();if(!await Sb(t))return QU();let e;try{e=await $b(t,{inline:uu})}catch(r){v(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)q(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&v(`${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 eq(t,e){_(`plan against ${e}:`);for(let r of t.add)_(` ${Kr.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)_(` ${Kr.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)_(` ${Kr.destroy(`${r.kind} ${r.id}`)}`);_(`
3911
+ ${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 tq(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function Ri(t,e,r){return new Promise(n=>{let o=hg(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 ug(){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 Ri("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 Ri("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 rq(t){let e=ye(t,"src"),r={},n=async o=>{let s;try{s=await _e.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=Ot(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let c=yl(e,a).split(pg).join("/");r[c]=await _e.readFile(a,"utf8")}}};return await n(e),r}function dg(t){return new Promise(e=>{let r=hg("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 nq=!1;nq&&mg().parseAsync(process.argv).catch(t=>v(t instanceof Error?t.message:String(t)));mg().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3821
3912
  `),process.exit(1)});