@turbobase/cli 1.30.0 → 1.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/turbobase.js CHANGED
@@ -1,29 +1,29 @@
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 xy=Object.create;var ji=Object.defineProperty;var $y=Object.getOwnPropertyDescriptor;var Ry=Object.getOwnPropertyNames;var Ty=Object.getPrototypeOf,Ey=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Vd=(t,e)=>{for(var n in e)ji(t,n,{get:e[n],enumerable:!0})},Py=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ry(e))!Ey.call(t,s)&&s!==n&&ji(t,s,{get:()=>e[s],enumerable:!(r=$y(e,s))||r.enumerable});return t};var Wd=(t,e,n)=>(n=t!=null?xy(Ty(t)):{},Py(e||!t||!t.__esModule?ji(n,"default",{value:t,enumerable:!0}):n,t));function un(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var fr=j(()=>{});import{z as pn}from"zod";function $s(t){let e=Di.safeParse(t);return e.success?(e.data.inputs??[]).filter(n=>n.type==="connection"):[]}function Ui(t,e){let n=Di.safeParse(t);if(!n.success)throw new Ht(`invalid manifest: ${n.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(Gd.test(e))throw new Ht('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 r=JSON.stringify(n.data);if(Gd.test(r))throw new Ht("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Jd,Yd,Di,Ht,Gd,Xd=j(()=>{Jd=pn.object({type:pn.literal("connection"),source_system:pn.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:pn.string().min(1).max(200).optional()}),Yd=pn.discriminatedUnion("type",[Jd]),Di=pn.object({inputs:pn.array(Yd).optional()}).passthrough(),Ht=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Gd=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Rs,Mi=j(()=>{Rs=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Be}from"zod";var qi,Zd,Qd=j(()=>{fr();Mi();qi=Be.object({id:Be.string().min(1,"hook id must be non-empty"),recordType:Be.union([Be.string().min(1),Be.array(Be.string().min(1)).min(1),Be.literal("*")]),event:Be.enum(Rs),source:Be.string().min(1).optional(),when:Be.unknown().optional(),run:Be.unknown(),failClosed:Be.boolean().optional(),timeoutMs:Be.number().int().positive().optional(),description:Be.string().optional(),systemReserved:Be.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"})}),Zd=un({kind:"hook",schema:qi,factoryName:"defineHook"})});var eu=j(()=>{Qd();Mi()});var Ts,zi=j(()=>{Ts=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as fe}from"zod";var tu,Cy,nu,Bi,ru,su=j(()=>{fr();zi();tu=fe.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),Cy=fe.object({recordType:fe.string().min(1,"reads[].recordType must be non-empty"),source:fe.string().min(1).optional(),columns:fe.array(tu).min(1,"reads[].columns must name at least one column"),by:fe.array(tu).optional(),maxRows:fe.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),nu=fe.object({source:fe.string().min(1,"to.source must be non-empty"),recordType:fe.string().min(1,"to.recordType must be non-empty")}),Bi=fe.object({id:fe.string().min(1,"conduit id must be non-empty"),on:fe.enum(Ts),from:fe.object({source:fe.string().min(1,"from.source must be non-empty"),recordType:fe.string().min(1,"from.recordType must be non-empty"),when:fe.unknown().optional()}),to:nu.optional(),mode:fe.enum(["dual-bind","one-shot"]).optional(),transform:fe.unknown().optional(),sequence:fe.array(fe.object({to:nu,transform:fe.unknown(),awaitSource:fe.boolean().optional()})).optional(),reads:fe.array(Cy).optional(),maxQueriesPerRun:fe.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:fe.unknown().optional(),cycleBudget:fe.number().int().positive().optional(),conflictStrategy:fe.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:fe.number().int().positive().optional(),description:fe.string().optional(),systemReserved:fe.boolean().optional()}).superRefine((t,e)=>{let n=t,r=n.to!==void 0||n.transform!==void 0,s=n.sequence!==void 0;r&&s?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!r&&!s?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):s?(n.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),n.sequence.forEach((u,p)=>{typeof u.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),n.from?.source&&u.to?.source&&n.from.source===u.to.source&&e.addIssue({code:"custom",path:["sequence",p,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(n.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof n.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let o=t.from?.when;o!==void 0&&typeof o!="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=n.from,l=n.to;a?.source&&l?.source&&a.source===l.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"})}),ru=un({kind:"conduit",schema:Bi,factoryName:"defineConduit"})});var ou=j(()=>{su();zi()});import{z as xe}from"zod";var Fi,iu,au=j(()=>{fr();Fi=xe.object({id:xe.string().min(1,"process id must be non-empty"),input:xe.object({type:xe.literal("object"),properties:xe.record(xe.unknown()).optional(),required:xe.array(xe.string()).optional()}).passthrough(),steps:xe.array(xe.object({id:xe.string().min(1,"step id must be non-empty"),recordType:xe.string().min(1,"step.recordType must be non-empty"),awaitSource:xe.boolean().optional(),build:xe.unknown(),description:xe.string().optional()})).min(1,"a process needs at least one step"),eachRow:xe.object({outstanding:xe.unknown(),key:xe.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:xe.enum(["stop","rollback"]).optional(),description:xe.string().optional()}).superRefine((t,e)=>{let n=t.eachRow;n&&typeof n.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 r=t.steps;if(!Array.isArray(r))return;let s=new Map;r.forEach((o,i)=>{let a=o;if(typeof a.build!="function"&&e.addIssue({code:"custom",path:["steps",i,"build"],message:"build must be a function"}),typeof a.id=="string"){let l=s.get(a.id);l!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${l} and ${i}) \u2014 step ids must be unique within a process`}):s.set(a.id,i)}})}),iu=un({kind:"process",schema:Fi,factoryName:"defineProcess"})});var lu=j(()=>{});var cu=j(()=>{au();lu()});async function By(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 n=await e.default(t,{defaultNonNullable:!1});return e.astToString(n)}async function As(t,e={}){return(e.transform??By)(t)}var Hi=j(()=>{});function Ki(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 du(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Vi(t){return`${du(t.source)}${du(t.recordType)}`}function Fy(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Hy(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 Wi(t){let e=Vi(t),n=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&n.push(t.description);let r=n.length===1?`/** ${n[0]} */`:`/**
5
- * ${n.join(`
4
+ var Eb=Object.create;var ji=Object.defineProperty;var Pb=Object.getOwnPropertyDescriptor;var Ab=Object.getOwnPropertyNames;var Cb=Object.getPrototypeOf,Ib=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Vd=(t,e)=>{for(var r in e)ji(t,r,{get:e[r],enumerable:!0})},Ob=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ab(e))!Ib.call(t,o)&&o!==r&&ji(t,o,{get:()=>e[o],enumerable:!(n=Pb(e,o))||n.enumerable});return t};var Wd=(t,e,r)=>(r=t!=null?Eb(Cb(t)):{},Ob(e||!t||!t.__esModule?ji(r,"default",{value:t,enumerable:!0}):r,t));function dr(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var hn=j(()=>{});import{z as ur}from"zod";function $o(t){let e=Di.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Ui(t,e){let r=Di.safeParse(t);if(!r.success)throw new Ht(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(Gd.test(e))throw new Ht('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(Gd.test(n))throw new Ht("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Jd,Yd,Di,Ht,Gd,Xd=j(()=>{Jd=ur.object({type:ur.literal("connection"),source_system:ur.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:ur.string().min(1).max(200).optional()}),Yd=ur.discriminatedUnion("type",[Jd]),Di=ur.object({inputs:ur.array(Yd).optional()}).passthrough(),Ht=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Gd=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ro,Mi=j(()=>{Ro=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Be}from"zod";var qi,Zd,Qd=j(()=>{hn();Mi();qi=Be.object({id:Be.string().min(1,"hook id must be non-empty"),recordType:Be.union([Be.string().min(1),Be.array(Be.string().min(1)).min(1),Be.literal("*")]),event:Be.enum(Ro),source:Be.string().min(1).optional(),when:Be.unknown().optional(),run:Be.unknown(),failClosed:Be.boolean().optional(),timeoutMs:Be.number().int().positive().optional(),description:Be.string().optional(),systemReserved:Be.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"})}),Zd=dr({kind:"hook",schema:qi,factoryName:"defineHook"})});var eu=j(()=>{Qd();Mi()});var Eo,zi=j(()=>{Eo=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as he}from"zod";var tu,jb,ru,Bi,nu,ou=j(()=>{hn();zi();tu=he.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),jb=he.object({recordType:he.string().min(1,"reads[].recordType must be non-empty"),source:he.string().min(1).optional(),columns:he.array(tu).min(1,"reads[].columns must name at least one column"),by:he.array(tu).optional(),maxRows:he.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),ru=he.object({source:he.string().min(1,"to.source must be non-empty"),recordType:he.string().min(1,"to.recordType must be non-empty")}),Bi=he.object({id:he.string().min(1,"conduit id must be non-empty"),on:he.enum(Eo),from:he.object({source:he.string().min(1,"from.source must be non-empty"),recordType:he.string().min(1,"from.recordType must be non-empty"),when:he.unknown().optional()}),to:ru.optional(),mode:he.enum(["dual-bind","one-shot"]).optional(),transform:he.unknown().optional(),sequence:he.array(he.object({to:ru,transform:he.unknown(),awaitSource:he.boolean().optional()})).optional(),reads:he.array(jb).optional(),maxQueriesPerRun:he.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:he.unknown().optional(),cycleBudget:he.number().int().positive().optional(),conflictStrategy:he.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:he.number().int().positive().optional(),description:he.string().optional(),systemReserved:he.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((u,p)=>{typeof u.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),r.from?.source&&u.to?.source&&r.from.source===u.to.source&&e.addIssue({code:"custom",path:["sequence",p,"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,l=r.to;a?.source&&l?.source&&a.source===l.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"})}),nu=dr({kind:"conduit",schema:Bi,factoryName:"defineConduit"})});var su=j(()=>{ou();zi()});import{z as Te}from"zod";var Fi,iu,au=j(()=>{hn();Fi=Te.object({id:Te.string().min(1,"process id must be non-empty"),input:Te.object({type:Te.literal("object"),properties:Te.record(Te.unknown()).optional(),required:Te.array(Te.string()).optional()}).passthrough(),steps:Te.array(Te.object({id:Te.string().min(1,"step id must be non-empty"),recordType:Te.string().min(1,"step.recordType must be non-empty"),awaitSource:Te.boolean().optional(),build:Te.unknown(),description:Te.string().optional()})).min(1,"a process needs at least one step"),eachRow:Te.object({outstanding:Te.unknown(),key:Te.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:Te.enum(["stop","rollback"]).optional(),description:Te.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 l=o.get(a.id);l!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${l} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})}),iu=dr({kind:"process",schema:Fi,factoryName:"defineProcess"})});var lu=j(()=>{});var cu=j(()=>{au();lu()});async function Vb(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 Co(t,e={}){return(e.transform??Vb)(t)}var Hi=j(()=>{});function Ki(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 du(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Vi(t){return`${du(t.source)}${du(t.recordType)}`}function Wb(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Gb(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 Wi(t){let e=Vi(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]} */`:`/**
5
+ * ${r.join(`
6
6
  * `)}
7
- */`;if(t.columns.length===0)return`${r}
7
+ */`;if(t.columns.length===0)return`${n}
8
8
  export interface ${e} {
9
9
  // no columns introspected
10
10
  [key: string]: unknown;
11
- }`;let s=t.columns.map(o=>{let i=Ki(o.pgType),a=o.nullable?"?":"",l=o.nullable?" | null":"";return` /** ${Hy(o)} */
12
- ${Fy(o.name)}${a}: ${i}${l};`});return`${r}
11
+ }`;let o=t.columns.map(s=>{let i=Ki(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${Gb(s)} */
12
+ ${Wb(s.name)}${a}: ${i}${l};`});return`${n}
13
13
  export interface ${e} {
14
- ${s.join(`
14
+ ${o.join(`
15
15
  `)}
16
- }`}function Is(t){return[...t.records].sort((r,s)=>`${r.source}:${r.recordType}`.localeCompare(`${s.source}:${s.recordType}`)).map(Wi).join(`
16
+ }`}function Io(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Wi).join(`
17
17
 
18
- `)}function uu(t){let e=new Map,n=(s,o)=>{let i=e.get(s);i||e.set(s,i=new Map);for(let a of o)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let s of t.records){s.table&&n(s.table,s.columns);for(let o of s.lines??[])n(o.table,o.columns)}let r={};for(let[s,o]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>o.get(a)===!1);if(o.get("parent_pg_row_id")===!1&&i){r[s]=["parent_pg_row_id",i];continue}if(o.get("pg_row_id")===!1){r[s]="pg_row_id";continue}if(o.get("external_id")===!1){r[s]="external_id";continue}}return r}function Ky(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Gi(t){let e=uu(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(([r,s])=>{let o=Array.isArray(s)?`[${s.map(i=>`'${i}'`).join(", ")}]`:`'${s}'`;return` ${Ky(r)}: ${o},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
19
- `)}var Ji=j(()=>{});function Vy(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function pu(t,e,n){let r=await n(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!r.ok)throw new Error(`types-gen: GET ${t} failed (${r.status} ${r.statusText})`);return r.json()}async function hn(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let n=Vy(t.baseUrl),r=await pu(n.records,t.token,e);if(!r||!Array.isArray(r.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let s=Is(r),o=[Wy,"// ----- Record shapes (from /v1/catalog/records) -----",s,"// ----- Keyset seek keys (derived from column nullability) -----",Gi(r)];if(!t.recordsOnly){let i=await pu(n.openapi,t.token,e),a=await As(i,t.openApi);o.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return o.join(`
18
+ `)}function uu(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 Jb(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Gi(t){let e=uu(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` ${Jb(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(`
19
+ `)}var Ji=j(()=>{});function Yb(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function pu(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 pr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=Yb(t.baseUrl),n=await pu(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=Io(n),s=[Xb,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Gi(n)];if(!t.recordsOnly){let i=await pu(r.openapi,t.token,e),a=await Co(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
20
20
 
21
21
  `)+`
22
- `}var Wy,hu=j(()=>{Hi();Ji();Ji();Hi();Wy=["/**"," * 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(`
23
- `)});var Yi=j(()=>{fr();Xd();eu();ou();cu();hu()});import{homedir as Gy}from"node:os";import{join as fu}from"node:path";import{promises as Xi}from"node:fs";function tt(t){return t.trim().replace(/\/+$/,"")}function Cs(){let t=process.env.TURBOBASE_HOME??fu(Gy(),".turbobase");return{dir:t,file:fu(t,"credentials")}}function mu(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function mr(){let{file:t}=Cs(),e;try{let o=await Xi.readFile(t,"utf8");e=JSON.parse(o)}catch(o){if(o.code==="ENOENT")return{tenants:{}};throw o}if(!e||typeof e!="object")return{tenants:{}};let n=e;if(n.tenants&&typeof n.tenants=="object"){let o={};for(let[a,l]of Object.entries(n.tenants))mu(l)&&(o[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof n.active=="string"&&o[n.active]?n.active:void 0,tenants:o}}let r={};for(let[o,i]of Object.entries(n))mu(i)&&(r[o]={token:i.token,updatedAt:i.updatedAt});return{active:Jy(r),tenants:r}}function Jy(t){let e,n="";for(let[r,s]of Object.entries(t))(!e||String(s.updatedAt)>n)&&(e=r,n=String(s.updatedAt));return e}async function Zi(t){let{dir:e,file:n}=Cs();await Xi.mkdir(e,{recursive:!0,mode:448}),await Xi.writeFile(n,JSON.stringify(t,null,2)+`
24
- `,{mode:384})}async function gu(t){let e=tt(t.baseUrl),n=await mr(),r=new Date().toISOString();return n.tenants[e]={token:t.token,updatedAt:r},n.active=e,await Zi(n),{baseUrl:e,token:t.token,updatedAt:r}}async function pt(t){let e=await mr();if(t){let o=tt(t),i=e.tenants[o];return i?{baseUrl:o,token:i.token,updatedAt:i.updatedAt}:null}let n=Object.keys(e.tenants),r=e.active&&e.tenants[e.active]?e.active:n.length===1?n[0]:void 0;if(!r)return null;let s=e.tenants[r];return{baseUrl:r,token:s.token,updatedAt:s.updatedAt}}async function Os(t){let e=tt(t),n=await mr(),r=n.tenants[e];return r?(n.active=e,await Zi(n),{baseUrl:e,token:r.token,updatedAt:r.updatedAt}):null}async function Qi(t){let e=await mr(),n=t?tt(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!n||!e.tenants[n])return null;if(delete e.tenants[n],e.active===n){let r=Object.keys(e.tenants);e.active=r.length===1?r[0]:void 0}return await Zi(e),n}async function Ct(){let t=await mr();return Object.entries(t.tenants).map(([e,n])=>({baseUrl:e,token:n.token,updatedAt:n.updatedAt}))}var gr=j(()=>{});function ta(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function Yy(t){if(t)try{return JSON.parse(t)}catch{return t}}function Xy(t,e){if(!t)return null;let n=t.trim();if(/^\d+$/.test(n))return Number(n)*1e3;let r=Date.parse(n);return Number.isNaN(r)?null:Math.max(0,r-e)}function Zy(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function Qy(t,e){let n=Xy(t.headers?.get?.("retry-after"),e),r="";try{r=await t.clone().text()}catch{return{maintenance:!1,delayMs:n}}let s=Yy(r),o=ta(t.status,s),i=typeof s?.error=="string"?s.error:void 0;return{maintenance:o,delayMs:n??Zy(r),error:i}}function ew(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 bu(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 ea(t){return`${Math.round(t/1e3)}s`}function tw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${ea(t.delayMs)} before retrying (${ea(t.remainingMs)} of the retry budget left).
25
- `)}function nw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${ea(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
26
- `)}function Ns(t,e={}){let n=e.budgetMs??6e5,r=e.defaultDelayMs??6e4,s=e.sleep??(u=>new Promise(p=>setTimeout(p,u))),o=e.now??(()=>Date.now()),i=e.onWait??tw,a=e.onGiveUp??nw;return async(u,p)=>{let m=o(),S=0;for(;;){let b=await t(u,p);if(b.status!==503||p&&!ew(p.body))return b;let _=n-(o()-m),{maintenance:R,delayMs:T,error:P}=await Qy(b,o());if(!R)return b;if(_<=0)return S>0&&a({waitedMs:o()-m,attempts:S,host:bu(u),error:P}),b;let N=T??r;N=Math.min(Math.max(N,1e3),12e4),N=Math.min(N,_),S+=1,i({attempt:S,delayMs:N,remainingMs:_,host:bu(u),error:P}),await s(N)}}}var na=j(()=>{});function yu(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t,n=typeof e.message=="string"&&e.message?e.message:e.error;return typeof n=="string"?n.trim():""}function rw(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function wu(t){let e=yu(t);return typeof t=="string"&&rw(e)?sw:e.slice(0,200)}function vu(t,e){return ta(t,e)}function ku(t){return t instanceof Z&&vu(t.status,t.body)}function iw(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Su(t){return t.replace(/\/+$/,"")}function ra(t=process.env){let e=(t[Cn]??"").trim(),n=(t[Ls]??"").trim();return!e||!n?null:{registryUrl:e,token:n}}function sa(t){let e;try{e=new URL(t)}catch{return`${Cn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&n?null:`${Cn} 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 Z,sw,ow,z,Cn,Ls,br,ht=j(()=>{na();Z=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="ApiError"}status;body};sw="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";ow="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";z=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Su(e.baseUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?n:Ns(n,e.retry??{})}async request(e,n,r,s){let o=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...r!==void 0?{"Content-Type":"application/json"}:{},...s??{}},...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){if(iw()){let u=yu(a);throw new Z(`${e} ${n} \u2192 ${o.status}${u?`: ${u}`:""}`,o.status,a)}if(vu(o.status,a))throw new Z(ow,o.status,a);let l=wu(a);throw new Z(`${e} ${n} \u2192 ${o.status}${l?`: ${l}`:""}`,o.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 n=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${n}`)).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 n=new URLSearchParams;e.status?.length&&n.set("status",e.status.join(",")),e.provenance?.length&&n.set("provenance",e.provenance.join(",")),e.recordType&&n.set("recordType",e.recordType),e.source&&n.set("source",e.source),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString();return(await this.request("GET",`/v1/extensions/proposals${r?`?${r}`:""}`)).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,n){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,n?{reason:n}:{})}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,n){let r=n&&n>0?`?limit=${Math.floor(n)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${r}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.limit&&n.limit>0&&r.set("limit",String(Math.floor(n.limit)));let s=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${s}`)).events??[]}async platformEvents(e={}){let n=new URLSearchParams;e.subsystem&&n.set("subsystem",e.subsystem),e.severity&&n.set("severity",e.severity),e.code&&n.set("code",e.code),e.since&&n.set("since",e.since),e.after&&n.set("after",e.after),e.correlationId&&n.set("correlationId",e.correlationId),e.extension&&n.set("extension",e.extension),e.conduit&&n.set("conduit",e.conduit),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/events${r}`)).events??[]}async bindings(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/bindings${r}`)).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,n,r={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:n,...r.note?{note:r.note}:{},...r.meta?{meta:r.meta}:{}},r.proposalId?{"x-proposal-id":r.proposalId}:void 0)}learningsPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.section&&n.set("section",e.section),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false");let r=n.toString();return this.request("GET",`/v1/learnings/pending${r?`?${r}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false"),e.reapply&&n.set("reapply","true");let r=n.toString();return this.request("GET",`/v1/learnings/rules-pending${r?`?${r}`:""}`)}rulesPush(e,n={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...n.app?{app:n.app}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.group===!1?{group:!1}:{},...n.reapply?{reapply:!0}:{}})}skillsList(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/skills${r?`?${r}`:""}`)}appSkillsPush(e,n,r){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...n],dryRun:r})}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 n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/docs${r?`?${r}`:""}`)}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,n={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...n.app?{app:n.app}:{},...n.section?{section:n.section}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.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,n={}){return this.request("POST","/v1/config/apply",{bundle:e,...n.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,n){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(n)}`)}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,n){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,n)).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,n){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:n.files,target:n.target,...n.approvedBy?{approvedBy:n.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Cn="TURBOBASE_REGISTRY_URL",Ls="TURBOBASE_REGISTRY_TOKEN";br=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Su(e.registryUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r){let s={Authorization:`Bearer ${this.token}`,Accept:"application/json"};r!==void 0&&(s["Content-Type"]="application/json");let o=await this.fetchImpl(`${this.registryUrl}${n}`,{method:e,headers:s,...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=wu(a);throw new Z(`${e} ${n} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,n){let r=n?`?version=${encodeURIComponent(n)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${r}`)}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 aw,statSync as lw}from"node:fs";import{resolve as js,sep as _u}from"node:path";function xu(t){if(dw.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function pw(t,e,n){let r=js(e,n),s=js(t);if(r!==s&&!r.startsWith(s+_u))return null;let o=[r];/\.(js|mjs|cjs)$/.test(r)&&o.push(r.replace(/\.js$/,".ts"),r.replace(/\.mjs$/,".mts"),r.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(r)||o.push(`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}/index.ts`,`${r}/index.js`);for(let i of o)if(i.startsWith(s+_u)&&aw(i)&&lw(i).isFile())return i;return null}function $u(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},n=>{if(n.kind==="entry-point")return null;if(xu(n.path))return{path:n.path,namespace:"extension-sdk"};let r=n.path.startsWith(".")||n.path.startsWith("/");if(r&&t){let o=pw(t,n.resolveDir,n.path);if(o)return{path:o}}return{errors:[{text:`extension ${r?`imports a sibling/local file ('${n.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:n.path.startsWith("node:")||fw(n.path)?`imports a Node builtin ('${n.path}')`:`imports an external module ('${n.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:uw,loader:"js"}))}}}function fw(t){let e=t.startsWith("node:")?t.slice(5):t;return hw.has(e.split("/")[0])}function Ru(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 Tu(){try{return(await import("esbuild")).build}catch(t){throw Ru("esbuild",t)}}async function mw(){try{return(await import("isolated-vm")).default}catch(t){throw Ru("isolated-vm",t)}}async function Ms(t,e={}){let n=await Tu(),r=e.resolveDir?js(e.resolveDir):void 0,s;try{s=await n({stdin:{contents:t,loader:"ts",resolveDir:r??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[$u(r)]})}catch(o){let a=o.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new Ds(a||`extension bundle failed: ${String(o)}`)}return s.outputFiles?.[0]?.text??""}async function oa(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let n=await Tu(),r=js(e),s=$u(r),o={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:xu(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await n({stdin:{contents:t,loader:"ts",resolveDir:r,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[o,s]})}catch(a){let u=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new Ds(u||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function yr(t,e,n={}){let r=n.timeoutMs??Us,s=n.memoryLimitMb??cw,o=n.member??"run",i={patches:[],logs:[]},a=await mw(),l=new a.Isolate({memoryLimit:s});try{let u=await l.createContext(),p=u.global,m=new a.Callback(Y=>{let K=JSON.parse(String(Y));i.rejection||(i.rejection=K)}),S=new a.Callback(Y=>{i.patches.push(JSON.parse(String(Y)))}),b=new a.Callback(Y=>{let K=JSON.parse(String(Y));i.logs.push(K)}),_=new a.Callback(Y=>{i.result=JSON.parse(String(Y))}),R=n.query,T=new a.Reference(async Y=>{if(!R)throw new Error("ctx.query is not available in this context");return JSON.stringify(await R(String(Y)))});await p.set("__tb_reject",m),await p.set("__tb_patch",S),await p.set("__tb_log",b),await p.set("__tb_result",_),await p.set("__tb_query",T),await p.set("__tb_ctx_json",JSON.stringify(gw(e)));let P=yw(t,o,n.stepIndex??0,!!n.query),D=await(await l.compileScript(P)).run(u,{timeout:r,promise:!0});return o==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function gw(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 bw(t){return`
22
+ `}var Xb,mu=j(()=>{Hi();Ji();Ji();Hi();Xb=["/**"," * 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(`
23
+ `)});var Yi=j(()=>{hn();Xd();eu();su();cu();mu()});import{homedir as Zb}from"node:os";import{join as hu}from"node:path";import{promises as Xi}from"node:fs";function tt(t){return t.trim().replace(/\/+$/,"")}function Oo(){let t=process.env.TURBOBASE_HOME??hu(Zb(),".turbobase");return{dir:t,file:hu(t,"credentials")}}function fu(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function fn(){let{file:t}=Oo(),e;try{let s=await Xi.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,l]of Object.entries(r.tenants))fu(l)&&(s[a]={token:l.token,updatedAt:l.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))fu(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:Qb(n),tenants:n}}function Qb(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 Zi(t){let{dir:e,file:r}=Oo();await Xi.mkdir(e,{recursive:!0,mode:448}),await Xi.writeFile(r,JSON.stringify(t,null,2)+`
24
+ `,{mode:384})}async function gu(t){let e=tt(t.baseUrl),r=await fn(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await Zi(r),{baseUrl:e,token:t.token,updatedAt:n}}async function pt(t){let e=await fn();if(t){let s=tt(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 No(t){let e=tt(t),r=await fn(),n=r.tenants[e];return n?(r.active=e,await Zi(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function Qi(t){let e=await fn(),r=t?tt(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 Zi(e),r}async function It(){let t=await fn();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var gn=j(()=>{});function ta(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function ew(t){if(t)try{return JSON.parse(t)}catch{return t}}function tw(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 rw(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function nw(t,e){let r=tw(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=ew(n),s=ta(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??rw(n),error:i}}function ow(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 yu(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 ea(t){return`${Math.round(t/1e3)}s`}function sw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${ea(t.delayMs)} before retrying (${ea(t.remainingMs)} of the retry budget left).
25
+ `)}function iw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${ea(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
26
+ `)}function Lo(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(u=>new Promise(p=>setTimeout(p,u))),s=e.now??(()=>Date.now()),i=e.onWait??sw,a=e.onGiveUp??iw;return async(u,p)=>{let f=s(),S=0;for(;;){let y=await t(u,p);if(y.status!==503||p&&!ow(p.body))return y;let k=r-(s()-f),{maintenance:$,delayMs:R,error:P}=await nw(y,s());if(!$)return y;if(k<=0)return S>0&&a({waitedMs:s()-f,attempts:S,host:yu(u),error:P}),y;let O=R??n;O=Math.min(Math.max(O,1e3),12e4),O=Math.min(O,k),S+=1,i({attempt:S,delayMs:O,remainingMs:k,host:yu(u),error:P}),await o(O)}}}var ra=j(()=>{});function bu(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 aw(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function wu(t){let e=bu(t);return typeof t=="string"&&aw(e)?lw:e.slice(0,200)}function vu(t,e){return ta(t,e)}function _u(t){return t instanceof Z&&vu(t.status,t.body)}function dw(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Su(t){return t.replace(/\/+$/,"")}function na(t=process.env){let e=(t[Cr]??"").trim(),r=(t[jo]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function oa(t){let e;try{e=new URL(t)}catch{return`${Cr} 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:`${Cr} 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 Z,lw,cw,z,Cr,jo,yn,mt=j(()=>{ra();Z=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};lw="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";cw="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";z=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Su(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:Lo(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(dw()){let u=bu(a);throw new Z(`${e} ${r} \u2192 ${s.status}${u?`: ${u}`:""}`,s.status,a)}if(vu(s.status,a))throw new Z(cw,s.status,a);let l=wu(a);throw new Z(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,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`)}},Cr="TURBOBASE_REGISTRY_URL",jo="TURBOBASE_REGISTRY_TOKEN";yn=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Su(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 l=wu(a);throw new Z(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,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 uw,statSync as pw}from"node:fs";import{resolve as Do,sep as ku}from"node:path";function Tu(t){if(hw.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function gw(t,e,r){let n=Do(e,r),o=Do(t);if(n!==o&&!n.startsWith(o+ku))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+ku)&&uw(i)&&pw(i).isFile())return i;return null}function xu(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Tu(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=gw(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:")||bw(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:fw,loader:"js"}))}}}function bw(t){let e=t.startsWith("node:")?t.slice(5):t;return yw.has(e.split("/")[0])}function $u(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 Ru(){try{return(await import("esbuild")).build}catch(t){throw $u("esbuild",t)}}async function ww(){try{return(await import("isolated-vm")).default}catch(t){throw $u("isolated-vm",t)}}async function qo(t,e={}){let r=await Ru(),n=e.resolveDir?Do(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:[xu(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new Uo(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function sa(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Ru(),n=Do(e),o=xu(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:Tu(l.path)?{path:l.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 u=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new Uo(u||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function bn(t,e,r={}){let n=r.timeoutMs??Mo,o=r.memoryLimitMb??mw,s=r.member??"run",i={patches:[],logs:[]},a=await ww(),l=new a.Isolate({memoryLimit:o});try{let u=await l.createContext(),p=u.global,f=new a.Callback(Y=>{let K=JSON.parse(String(Y));i.rejection||(i.rejection=K)}),S=new a.Callback(Y=>{i.patches.push(JSON.parse(String(Y)))}),y=new a.Callback(Y=>{let K=JSON.parse(String(Y));i.logs.push(K)}),k=new a.Callback(Y=>{i.result=JSON.parse(String(Y))}),$=r.query,R=new a.Reference(async Y=>{if(!$)throw new Error("ctx.query is not available in this context");return JSON.stringify(await $(String(Y)))});await p.set("__tb_reject",f),await p.set("__tb_patch",S),await p.set("__tb_log",y),await p.set("__tb_result",k),await p.set("__tb_query",R),await p.set("__tb_ctx_json",JSON.stringify(vw(e)));let P=Sw(t,s,r.stepIndex??0,!!r.query),D=await(await l.compileScript(P)).run(u,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function vw(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 _w(t){return`
27
27
  "use strict";
28
28
  (async () => {
29
29
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -46,7 +46,7 @@ ${s.join(`
46
46
  __tb_result(JSON.stringify(out == null ? null : String(out)));
47
47
  return undefined;
48
48
  })()
49
- `}function yw(t,e,n,r=!1){return e==="build"?ww(t,n):e==="outstanding"?bw(t):`
49
+ `}function Sw(t,e,r,n=!1){return e==="build"?kw(t,r):e==="outstanding"?_w(t):`
50
50
  "use strict";
51
51
  (async () => {
52
52
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -88,7 +88,7 @@ ${s.join(`
88
88
  canonicalStatus(args) {
89
89
  return String((args && args.raw) || '').trim().toLowerCase();
90
90
  },
91
- ${r?`async query(q) {
91
+ ${n?`async query(q) {
92
92
  const json = await __tb_query.apply(undefined, [String(q)], {
93
93
  arguments: { copy: true },
94
94
  result: { promise: true, copy: true },
@@ -117,8 +117,8 @@ ${s.join(`
117
117
  // right one without a kind discriminator. 'run'/'transform' are the body;
118
118
  // a conduit with a \`sequence\` has one transform per target, and
119
119
  // \`stepIndex\` picks which (turbobase-dev#1514, AC10).
120
- const fn = ${e==="when"?"(def.when || (def.from && def.from.when))":e==="transform"?`(Array.isArray(def.sequence) && def.sequence[${Number(n)}]
121
- ? def.sequence[${Number(n)}].transform
120
+ const fn = ${e==="when"?"(def.when || (def.from && def.from.when))":e==="transform"?`(Array.isArray(def.sequence) && def.sequence[${Number(r)}]
121
+ ? def.sequence[${Number(r)}].transform
122
122
  : def.transform)`:`def[${JSON.stringify(e)}]`};
123
123
  if (typeof fn !== 'function') {
124
124
  ${e==="when"?"return true;":e==="transform"?"throw new Error('conduit default export has no transform() function');":e==="idempotencyKey"?"throw new Error('conduit default export has no idempotencyKey() function');":"throw new Error('extension default export has no run() function');"}
@@ -127,7 +127,7 @@ ${s.join(`
127
127
  ${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":e==="idempotencyKey"?"__tb_result(JSON.stringify(out == null ? null : String(out)));":""}
128
128
  return ${e==="when"?"out":"undefined"};
129
129
  })()
130
- `}function ww(t,e){return`
130
+ `}function kw(t,e){return`
131
131
  "use strict";
132
132
  (async () => {
133
133
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -169,17 +169,17 @@ ${s.join(`
169
169
  __tb_result(JSON.stringify(out == null ? null : out));
170
170
  return undefined;
171
171
  })()
172
- `}var Us,cw,dw,uw,Ds,hw,qs=j(()=>{Us=200,cw=16,dw=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"]);uw=`
172
+ `}var Mo,mw,hw,fw,Uo,yw,zo=j(()=>{Mo=200,mw=16,hw=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"]);fw=`
173
173
  export const defineHook = (def) => def;
174
174
  export const defineConduit = (def) => def;
175
175
  export const defineProcess = (def) => def;
176
176
  export default defineHook;
177
- `;Ds=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};hw=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 ia}from"node:fs";import{join as vw}from"node:path";function kw(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 Sw(t,e,n){let r=e.name??n,s=e.expect??"pass";try{let{effects:o}=await yr(t,kw(e.context)),i=o.rejection?"reject":"pass";return{name:r,expected:s,observed:i,pass:i===s,rejection:o.rejection,patchCount:o.patches.length}}catch(o){return{name:r,expected:s,observed:"pass",pass:!1,patchCount:0,error:o instanceof Error?o.message:String(o)}}}async function zs(t,e,n={}){let r=await Ms(t,{resolveDir:n.resolveDir}),s=[];for(let o=0;o<e.length;o+=1)s.push(await Sw(r,e[o],`sample[${o}]`));return s}async function wr(t){let e;try{e=await ia.readdir(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e.sort()){if(!r.endsWith(".json"))continue;let s=await ia.readFile(vw(t,r),"utf8"),o=JSON.parse(s),i=Array.isArray(o)?o:[o];for(let a=0;a<i.length;a+=1){let l=i[a];n.push({file:r,fixture:{...l,name:l.name??`${r}${i.length>1?`#${a}`:""}`}})}}return n}function vr(t){return ia.readFile(t,"utf8")}var aa=j(()=>{qs()});function We(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function ev(t){let e=t.recordType;if(!e)throw new Ge("record type is required (e.g. --record=salesOrder)");let n=t.event??"before_save",r=t.template??"require-field",s=t.source,o=s?`
178
- source: ${JSON.stringify(s)},`:"",i,a;if(r==="blank")i=`
177
+ `;Uo=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};yw=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 ia}from"node:fs";import{join as Tw}from"node:path";function xw(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 $w(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await bn(t,xw(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 Bo(t,e,r={}){let n=await qo(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await $w(n,e[s],`sample[${s}]`));return o}async function wn(t){let e;try{e=await ia.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 ia.readFile(Tw(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let l=i[a];r.push({file:n,fixture:{...l,name:l.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function vn(t){return ia.readFile(t,"utf8")}var aa=j(()=>{zo()});function We(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function hv(t){let e=t.recordType;if(!e)throw new Ge("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
178
+ source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
179
179
  run: (ctx) => {
180
180
  // Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
181
181
  // with ctx.patch({...}); observe with ctx.log('info', '...').
182
- },`,a="custom";else if(r==="require-field"){let S=t.field;if(!S)throw new Ge("require-field template needs --field=<name>");i=`
182
+ },`,a="custom";else if(n==="require-field"){let S=t.field;if(!S)throw new Ge("require-field template needs --field=<name>");i=`
183
183
  run: (ctx) => {
184
184
  const v = ctx.payload[${JSON.stringify(S)}];
185
185
  if (v === undefined || v === null || v === '') {
@@ -189,7 +189,7 @@ export default defineHook;
189
189
  message: ${JSON.stringify(`${S} is required`)},
190
190
  });
191
191
  }
192
- },`,a=`require-field-${S}`}else if(r==="enforce-format"){let S=t.field;if(!S)throw new Ge("enforce-format template needs --field=<name>");if(!t.regex)throw new Ge("enforce-format template needs --regex=<pattern>");i=`
192
+ },`,a=`require-field-${S}`}else if(n==="enforce-format"){let S=t.field;if(!S)throw new Ge("enforce-format template needs --field=<name>");if(!t.regex)throw new Ge("enforce-format template needs --regex=<pattern>");i=`
193
193
  run: (ctx) => {
194
194
  const v = ctx.payload[${JSON.stringify(S)}];
195
195
  if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
@@ -199,8 +199,8 @@ export default defineHook;
199
199
  message: ${JSON.stringify(`${S} does not match expected format`)},
200
200
  });
201
201
  }
202
- },`,a=`enforce-format-${S}`}else throw new Ge(`unsupported template: ${r}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${We(t.regex).slice(0,24)}`:""}`,p=`/**
203
- * ${t.description??`${a} on ${e}.${n}`}
202
+ },`,a=`enforce-format-${S}`}else throw new Ge(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${We(t.regex).slice(0,24)}`:""}`,p=`/**
203
+ * ${t.description??`${a} on ${e}.${r}`}
204
204
  *
205
205
  * Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
206
206
  * \`turbobase ext deploy\`.
@@ -210,10 +210,10 @@ import { defineHook } from '@turbobase/extensions';
210
210
  export default defineHook<Record<string, unknown>>({
211
211
  id: ${JSON.stringify(l)},
212
212
  recordType: ${JSON.stringify(e)},
213
- event: ${JSON.stringify(n)},${o}${i}
213
+ event: ${JSON.stringify(r)},${s}${i}
214
214
  });
215
- `;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:p}}function tv(t){let e=t.recordType;if(!e)throw new Ge("record type is required (e.g. --record=order)");let n=t.source;if(!n)throw new Ge("--source is required (the origin source, e.g. --source=shopify)");let r=t.to;if(!r)throw new Ge("--to is required (the target source, e.g. --to=netsuite)");if(n===r)throw new Ge(`a conduit must bridge two DIFFERENT sources (got --source=${n} --to=${r}); use \`turbobase ext new hook\` for an intra-source transform`);let s=t.toRecordType??e,o=t.event??"after_canonicalize_inbound",i=t.id??`${We(n)}2${We(r)}:${We(e)}`,l=`/**
216
- * ${t.description??`Bridge ${n} ${e} \u2192 ${r} ${s} (${o}).`}
215
+ `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:p}}function fv(t){let e=t.recordType;if(!e)throw new Ge("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Ge("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Ge("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Ge(`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??`${We(r)}2${We(n)}:${We(e)}`,l=`/**
216
+ * ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
217
217
  *
218
218
  * Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
219
219
  * transform: read ctx, RETURN a { patch, createdFrom } \u2014 never call a source API
@@ -227,15 +227,15 @@ import { defineConduit } from '@turbobase/extensions';
227
227
 
228
228
  export default defineConduit<Record<string, unknown>>({
229
229
  id: ${JSON.stringify(i)},
230
- on: ${JSON.stringify(o)},
230
+ on: ${JSON.stringify(s)},
231
231
  from: {
232
- source: ${JSON.stringify(n)},
232
+ source: ${JSON.stringify(r)},
233
233
  recordType: ${JSON.stringify(e)},
234
234
  // when: (ctx) => true, // optional gate on the inbound payload
235
235
  },
236
236
  to: {
237
- source: ${JSON.stringify(r)},
238
- recordType: ${JSON.stringify(s)},
237
+ source: ${JSON.stringify(n)},
238
+ recordType: ${JSON.stringify(o)},
239
239
  },
240
240
  mode: 'dual-bind',
241
241
  conflictStrategy: 'merge',
@@ -247,7 +247,7 @@ export default defineConduit<Record<string, unknown>>({
247
247
  // ...mapped canonical fields...
248
248
  },
249
249
  createdFrom: {
250
- source: ${JSON.stringify(n)},
250
+ source: ${JSON.stringify(r)},
251
251
  recordType: ${JSON.stringify(e)},
252
252
  externalId: ctx.externalId,
253
253
  },
@@ -255,10 +255,10 @@ export default defineConduit<Record<string, unknown>>({
255
255
  },
256
256
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
257
257
  });
258
- `;return{relativePath:`conduits/${We(n)}-${We(e)}-to-${We(r)}-${We(s)}.ts`,content:l}}function nv(t){let e=t.recordType;if(!e)throw new Ge("record type is required (e.g. --record=purchaseOrder)");let n=t.then,r=t.onFailure??"stop";if(r!=="stop"&&r!=="rollback")throw new Ge(`--on-failure must be stop | rollback (got ${r})`);let s=n?`${We(e)}-then-${We(n)}`:We(e),o=t.id??`custom:process:${s}`,i=t.description??(n?`Raise a ${e}, wait for the source, then raise a ${n}.`:`Raise a ${e}.`),a=n?`
258
+ `;return{relativePath:`conduits/${We(r)}-${We(e)}-to-${We(n)}-${We(o)}.ts`,content:l}}function gv(t){let e=t.recordType;if(!e)throw new Ge("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Ge(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${We(e)}-then-${We(r)}`:We(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?`
259
259
  {
260
- id: ${JSON.stringify(We(n))},
261
- recordType: ${JSON.stringify(n)},
260
+ id: ${JSON.stringify(We(r))},
261
+ recordType: ${JSON.stringify(r)},
262
262
  build: (ctx) => ({
263
263
  parent: {
264
264
  // The first step declared awaitSource, so its source-minted id is here.
@@ -270,7 +270,7 @@ export default defineConduit<Record<string, unknown>>({
270
270
  * ${i}
271
271
  *
272
272
  * Scaffolded by \`turbobase ext new process\`. A process is INVOKED by an app
273
- * (POST /v1/processes/${o}) and runs its steps on the server, in order, through
273
+ * (POST /v1/processes/${s}) and runs its steps on the server, in order, through
274
274
  * the same write boundary the app's own writes use \u2014 hooks, guardrails and RLS
275
275
  * all apply, as the invoking user. Every step's \`build\` is PURE: it returns
276
276
  * the write payload and never calls a source API. Read with \`ctx.query\`
@@ -281,7 +281,7 @@ export default defineConduit<Record<string, unknown>>({
281
281
  import { defineProcess } from '@turbobase/extensions';
282
282
 
283
283
  export default defineProcess({
284
- id: ${JSON.stringify(o)},
284
+ id: ${JSON.stringify(s)},
285
285
  description: ${JSON.stringify(i)},
286
286
  input: {
287
287
  type: 'object',
@@ -293,7 +293,7 @@ export default defineProcess({
293
293
  steps: [
294
294
  {
295
295
  id: ${JSON.stringify(We(e))},
296
- recordType: ${JSON.stringify(e)},${n?`
296
+ recordType: ${JSON.stringify(e)},${r?`
297
297
  awaitSource: true,`:""}
298
298
  build: (ctx) => ({
299
299
  parent: {
@@ -302,21 +302,21 @@ export default defineProcess({
302
302
  }),
303
303
  },${a}
304
304
  ],
305
- onFailure: ${JSON.stringify(r)},
305
+ onFailure: ${JSON.stringify(n)},
306
306
  });
307
- `;return{relativePath:`processes/${s}.ts`,content:l}}function $t(t,e){let n=rv[t];if(!n)throw new Ge(`unknown extension kind '${t}'. Scaffoldable kinds: ${Zu.join(", ")}.`);return n(e)}var Zu,Ge,rv,Vs=j(()=>{Zu=["hook","conduit","process"];Ge=class extends Error{};rv={hook:ev,conduit:tv,process:nv}});var Ta,Ea=j(()=>{Ta=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function bS(t){let e=2166136261;for(let n=0;n<t.length;n+=1)e^=t.charCodeAt(n),e=Math.imul(e,16777619)>>>0;return e>>>0}function yS(t){return vh[bS(t)%vh.length]}function wS(t){let e=t.trim().split(/[\s\-_.]+/).filter(n=>/[a-z0-9]/i.test(n));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 kh(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Sh(t,e){let[n,r]=yS(t),s=kh(wS(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${kh(e)}">
307
+ `;return{relativePath:`processes/${o}.ts`,content:l}}function xt(t,e){let r=yv[t];if(!r)throw new Ge(`unknown extension kind '${t}'. Scaffoldable kinds: ${rp.join(", ")}.`);return r(e)}var rp,Ge,yv,Wo=j(()=>{rp=["hook","conduit","process"];Ge=class extends Error{};yv={hook:hv,conduit:fv,process:gv}});var Ra,Ea=j(()=>{Ra=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function CS(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 IS(t){return Tm[CS(t)%Tm.length]}function OS(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 xm(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function $m(t,e){let[r,n]=IS(t),o=xm(OS(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${xm(e)}">
308
308
  <defs>
309
309
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
310
- <stop offset="0" stop-color="${n}"/>
311
- <stop offset="1" stop-color="${r}"/>
310
+ <stop offset="0" stop-color="${r}"/>
311
+ <stop offset="1" stop-color="${n}"/>
312
312
  </linearGradient>
313
313
  </defs>
314
314
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
315
- <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">${s}</text>
315
+ <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>
316
316
  </svg>
317
- `}var vh,_h=j(()=>{vh=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Mh={};Vd(Mh,{CN_UTIL:()=>Ph,COMPONENTS_JSON:()=>Eh,MAIN_TSX:()=>Ih,STYLES_CSS:()=>Ch,TSCONFIG:()=>Th,TURBOBASE_CLIENT:()=>xh,UI_BADGE:()=>Lh,UI_BUTTON:()=>Oh,UI_CARD:()=>Nh,UI_INPUT:()=>Dh,UI_LABEL:()=>Uh,UI_TABLE:()=>jh,indexHtml:()=>Ah,instanceOriginFromEnv:()=>ES,packageJson:()=>$h,scaffoldAppFiles:()=>AS,starterApp:()=>IS,viteConfig:()=>Rh});function SS(t,e){let n=t.trim();if(n.length<=e)return n;let r=n.slice(0,e);return r.replace(/[\s\p{P}\p{S}]+$/u,"")||r}function _S(t){let e={name:SS(t.title,kS)},n=(t.description??"").trim().slice(0,vS);return n&&(e.description=n),e.icon="favicon.svg",e.learnings={...Ta},JSON.stringify(e,null,2)+`
318
- `}function $h(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:xS},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)}
319
- `}function TS(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 ES(t=process.env){let e=(t.TENANT_SLUG??"").trim(),n=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!n))return`https://${e}.${n}`}function Rh(t,e={}){let n=TS(e.instanceOrigin);return`import { defineConfig } from 'vite';
317
+ `}var Tm,Rm=j(()=>{Tm=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Fm={};Vd(Fm,{CN_UTIL:()=>Om,COMPONENTS_JSON:()=>Im,MAIN_TSX:()=>Lm,STYLES_CSS:()=>jm,TSCONFIG:()=>Cm,TURBOBASE_CLIENT:()=>Em,UI_BADGE:()=>Mm,UI_BUTTON:()=>Dm,UI_CARD:()=>Um,UI_INPUT:()=>zm,UI_LABEL:()=>Bm,UI_TABLE:()=>qm,indexHtml:()=>Nm,instanceOriginFromEnv:()=>BS,packageJson:()=>Pm,scaffoldAppFiles:()=>HS,starterApp:()=>KS,viteConfig:()=>Am});function jS(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 DS(t){let e={name:jS(t.title,LS)},r=(t.description??"").trim().slice(0,NS);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Ra},JSON.stringify(e,null,2)+`
318
+ `}function Pm(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:US},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)}
319
+ `}function zS(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 BS(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function Am(t,e={}){let r=zS(e.instanceOrigin);return`import { defineConfig } from 'vite';
320
320
  import { fileURLToPath, URL } from 'node:url';
321
321
  import react from '@vitejs/plugin-react';
322
322
  // Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
@@ -335,8 +335,8 @@ import tailwindcss from '@tailwindcss/vite';
335
335
  // you sign in, and the cookies land on localhost:3000. Override the targets
336
336
  // with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
337
337
  // them at boot; restart the dev server after changing one).
338
- const TENANT = process.env.SUPABASE_URL || '${n??$S}'; // /rest + the Realtime WS
339
- const API = process.env.TURBOBASE_API_URL || '${n??RS}'; // /v1, /auth, /login, /_app
338
+ const TENANT = process.env.SUPABASE_URL || '${r??MS}'; // /rest + the Realtime WS
339
+ const API = process.env.TURBOBASE_API_URL || '${r??qS}'; // /v1, /auth, /login, /_app
340
340
 
341
341
  // Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
342
342
  // this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
@@ -374,7 +374,7 @@ export default defineConfig({
374
374
  },
375
375
  build: { outDir: 'dist' },
376
376
  });
377
- `}function Ah(t){return`<!doctype html>
377
+ `}function Nm(t){return`<!doctype html>
378
378
  <html lang="en">
379
379
  <head>
380
380
  <meta charset="UTF-8" />
@@ -387,7 +387,7 @@ export default defineConfig({
387
387
  <script type="module" src="/src/main.tsx"></script>
388
388
  </body>
389
389
  </html>
390
- `}function AS(t){return{"package.json":$h(t.slug),"vite.config.ts":Rh(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":PS,"tsconfig.json":Th,"index.html":Ah(t.title),"public/turbobase.json":_S(t),"public/favicon.svg":Sh(t.slug,t.title),"src/main.tsx":Ih,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":xh,"src/styles.css":Ch,"components.json":Eh,"src/lib/utils.ts":Ph,"src/components/ui/button.tsx":Oh,"src/components/ui/card.tsx":Nh,"src/components/ui/badge.tsx":Lh,"src/components/ui/table.tsx":jh,"src/components/ui/input.tsx":Dh,"src/components/ui/label.tsx":Uh,"README.md":`# ${t.title}
390
+ `}function HS(t){return{"package.json":Pm(t.slug),"vite.config.ts":Am(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":FS,"tsconfig.json":Cm,"index.html":Nm(t.title),"public/turbobase.json":DS(t),"public/favicon.svg":$m(t.slug,t.title),"src/main.tsx":Lm,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Em,"src/styles.css":jm,"components.json":Im,"src/lib/utils.ts":Om,"src/components/ui/button.tsx":Dm,"src/components/ui/card.tsx":Um,"src/components/ui/badge.tsx":Mm,"src/components/ui/table.tsx":qm,"src/components/ui/input.tsx":zm,"src/components/ui/label.tsx":Bm,"README.md":`# ${t.title}
391
391
 
392
392
  \`\`\`sh
393
393
  npm install
@@ -408,7 +408,7 @@ every read comes back "permission denied", which looks like an RLS problem.
408
408
 
409
409
  \`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
410
410
  live access token and is gitignored \u2014 keep it that way.
411
- `}}function IS(t){return`import React from 'react';
411
+ `}}function KS(t){return`import React from 'react';
412
412
  import { Loader2, Trash2 } from 'lucide-react';
413
413
 
414
414
  import { select, write, del } from '@/lib/turbobase';
@@ -633,7 +633,7 @@ export default function App() {
633
633
  </main>
634
634
  );
635
635
  }
636
- `}var vS,kS,xh,Ar,xS,$S,RS,PS,Th,Eh,Ph,Ih,Ch,Oh,Nh,Lh,jh,Dh,Uh,qh=j(()=>{_h();Ea();vS=200,kS=60;xh=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
636
+ `}var NS,LS,Em,An,US,MS,qS,FS,Cm,Im,Om,Lm,jm,Dm,Um,Mm,qm,zm,Bm,Hm=j(()=>{Rm();Ea();NS=200,LS=60;Em=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
637
637
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
638
638
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
639
639
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -1108,6 +1108,13 @@ export interface BatchResult<T = unknown> {
1108
1108
  * query: the aliases it served, and any whose related rows were shortened by a
1109
1109
  * server-side bound. */
1110
1110
  stitched?: { aliases: string[]; truncated: string[] };
1111
+ /** \`true\` when this sub-query asked for more rows than the instance serves in
1112
+ * one page (1000) and there are more behind it, so \`rows\` is a PAGE and not
1113
+ * the set. Absent \u2014 never \`false\` \u2014 when the page is complete, so the check is
1114
+ * \`if (r.truncated)\`. Page on with \`offset\`, or ask for a total
1115
+ * (\`{ query, count: 'exact' }\`) to know how far. A sub-query whose own
1116
+ * \`limit\` is 1000 or less can never carry it. */
1117
+ truncated?: true;
1111
1118
  }
1112
1119
 
1113
1120
  /** One element of the list you pass batch(): the same path-and-query string you
@@ -1236,6 +1243,7 @@ async function batchChunk<T>(queries: BatchQuery[]): Promise<BatchResult<T>[]> {
1236
1243
  count?: number | null;
1237
1244
  contentRange?: string | null;
1238
1245
  stitched?: { aliases: string[]; truncated: string[] };
1246
+ truncated?: true;
1239
1247
  }[];
1240
1248
  };
1241
1249
  // \`ok\` \u2014 not \`status === 200\` \u2014 is what decides success, and a counted
@@ -1250,6 +1258,11 @@ async function batchChunk<T>(queries: BatchQuery[]): Promise<BatchResult<T>[]> {
1250
1258
  count: r.count ?? null,
1251
1259
  contentRange: r.contentRange ?? null,
1252
1260
  stitched: r.stitched,
1261
+ // Only when the instance set it. Spreading a \`truncated: undefined\` key
1262
+ // in instead would make \`'truncated' in r\` true on every complete page,
1263
+ // which is the one way a reader could still mistake a full set for a cut
1264
+ // one after all this.
1265
+ ...(r.truncated ? { truncated: true as const } : {}),
1253
1266
  }
1254
1267
  : {
1255
1268
  ok: false,
@@ -1650,7 +1663,7 @@ export async function selectPage<T = unknown>(
1650
1663
  }
1651
1664
  return { rows, nextCursor };
1652
1665
  }
1653
- `,Ar="src/types.ts",xS=`turbobase project types -o ${Ar} || node -e "if(require('node:fs').existsSync('${Ar}')){console.error('turbobase: could not refresh ${Ar} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Ar} 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 ${Ar}');process.exit(1)}"`;$S="http://localhost:54331",RS="http://localhost:4100";PS=`node_modules/
1666
+ `,An="src/types.ts",US=`turbobase project types -o ${An} || node -e "if(require('node:fs').existsSync('${An}')){console.error('turbobase: could not refresh ${An} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${An} 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 ${An}');process.exit(1)}"`;MS="http://localhost:54331",qS="http://localhost:4100";FS=`node_modules/
1654
1667
  dist/
1655
1668
  build/
1656
1669
 
@@ -1662,9 +1675,9 @@ build/
1662
1675
  !.env.example
1663
1676
 
1664
1677
  .DS_Store
1665
- `,Th=`${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)}
1666
- `,Eh=`${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)}
1667
- `,Ph=`import { clsx, type ClassValue } from 'clsx';
1678
+ `,Cm=`${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)}
1679
+ `,Im=`${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)}
1680
+ `,Om=`import { clsx, type ClassValue } from 'clsx';
1668
1681
  import { twMerge } from 'tailwind-merge';
1669
1682
 
1670
1683
  /**
@@ -1678,7 +1691,7 @@ import { twMerge } from 'tailwind-merge';
1678
1691
  export function cn(...inputs: ClassValue[]) {
1679
1692
  return twMerge(clsx(inputs));
1680
1693
  }
1681
- `;Ih=`import React from 'react';
1694
+ `;Lm=`import React from 'react';
1682
1695
  import { createRoot } from 'react-dom/client';
1683
1696
  import App from './App';
1684
1697
  import './styles.css';
@@ -1688,7 +1701,7 @@ createRoot(document.getElementById('root')!).render(
1688
1701
  <App />
1689
1702
  </React.StrictMode>,
1690
1703
  );
1691
- `,Ch=`@import 'tailwindcss';
1704
+ `,jm=`@import 'tailwindcss';
1692
1705
  @import 'tw-animate-css';
1693
1706
 
1694
1707
  /* Inter, self-hosted \u2014 the design system's font.
@@ -1776,7 +1789,7 @@ createRoot(document.getElementById('root')!).render(
1776
1789
  transition-duration: 0.01ms !important;
1777
1790
  }
1778
1791
  }
1779
- `,Oh=`import * as React from 'react';
1792
+ `,Dm=`import * as React from 'react';
1780
1793
  import { cva, type VariantProps } from 'class-variance-authority';
1781
1794
 
1782
1795
  import { cn } from '@/lib/utils';
@@ -1816,7 +1829,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
1816
1829
  Button.displayName = 'Button';
1817
1830
 
1818
1831
  export { Button, buttonVariants };
1819
- `,Nh=`import * as React from 'react';
1832
+ `,Um=`import * as React from 'react';
1820
1833
 
1821
1834
  import { cn } from '@/lib/utils';
1822
1835
 
@@ -1854,7 +1867,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
1854
1867
  CardContent.displayName = 'CardContent';
1855
1868
 
1856
1869
  export { Card, CardHeader, CardTitle, CardDescription, CardContent };
1857
- `,Lh=`import * as React from 'react';
1870
+ `,Mm=`import * as React from 'react';
1858
1871
  import { cva, type VariantProps } from 'class-variance-authority';
1859
1872
 
1860
1873
  import { cn } from '@/lib/utils';
@@ -1889,7 +1902,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
1889
1902
  }
1890
1903
 
1891
1904
  export { Badge, badgeVariants };
1892
- `,jh=`import * as React from 'react';
1905
+ `,qm=`import * as React from 'react';
1893
1906
 
1894
1907
  import { cn } from '@/lib/utils';
1895
1908
 
@@ -1948,7 +1961,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
1948
1961
  TableCell.displayName = 'TableCell';
1949
1962
 
1950
1963
  export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
1951
- `,Dh=`import * as React from 'react';
1964
+ `,zm=`import * as React from 'react';
1952
1965
 
1953
1966
  import { cn } from '@/lib/utils';
1954
1967
 
@@ -1968,7 +1981,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
1968
1981
  Input.displayName = 'Input';
1969
1982
 
1970
1983
  export { Input };
1971
- `,Uh=`import * as React from 'react';
1984
+ `,Bm=`import * as React from 'react';
1972
1985
 
1973
1986
  import { cn } from '@/lib/utils';
1974
1987
 
@@ -1985,51 +1998,51 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
1985
1998
  Label.displayName = 'Label';
1986
1999
 
1987
2000
  export { Label };
1988
- `});import*as zh from"zod/v3";import*as gn from"zod/v4-mini";function Rt(t){return!!t._zod}function bn(t){let e=Object.values(t);if(e.length===0)return gn.object({});let n=e.every(Rt),r=e.every(s=>!Rt(s));if(n)return gn.object(t);if(r)return zh.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Jt(t,e){return Rt(t)?gn.safeParse(t,e):t.safeParse(e)}async function io(t,e){return Rt(t)?await gn.safeParseAsync(t,e):await t.safeParseAsync(e)}function Yt(t){if(!t)return;let e;if(Rt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Bn(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return bn(t)}}if(Rt(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function CS(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function ao(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 ${CS(e.path)}`:e.message).join(`
1989
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Bh(t){return t.description}function Fh(t){if(Rt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Fn(t){if(Rt(t)){let o=t._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var Ir=j(()=>{});import*as c from"zod/v4";function af(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function lf(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var za,Hh,Xt,co,Te,Kh,Vh,CO,OS,NS,Ba,et,Cr,Wh,Oe,ot,it,Ne,uo,Gh,Fa,Jh,Yh,Ha,Or,W,Ka,Xh,Zh,OO,po,LS,ho,jS,Nr,Hn,Qh,DS,US,MS,qS,zS,BS,Va,FS,HS,Wa,fo,KS,VS,mo,WS,Lr,jr,GS,Dr,Kn,JS,Ur,go,bo,yo,NO,wo,vo,ko,ef,tf,nf,Ga,rf,Mr,Vn,sf,YS,So,XS,_o,ZS,Ja,QS,xo,e_,t_,n_,r_,s_,o_,i_,a_,l_,c_,$o,d_,u_,Ro,Ya,Xa,Za,p_,h_,f_,Qa,m_,g_,b_,y_,w_,of,To,v_,Eo,LO,k_,Wn,S_,jO,qr,__,el,x_,$_,R_,T_,E_,P_,A_,lo,I_,C_,O_,zr,tl,N_,L_,j_,D_,U_,M_,q_,z_,B_,F_,H_,K_,V_,W_,G_,J_,Y_,X_,Gn,Z_,Q_,ex,Po,tx,nx,rx,nl,sx,DO,UO,MO,qO,zO,BO,B,qa,Jn=j(()=>{za="2025-11-25",Hh=[za,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Xt="io.modelcontextprotocol/related-task",co="2.0",Te=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Kh=c.union([c.string(),c.number().int()]),Vh=c.string(),CO=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),OS=c.object({ttl:c.number().optional()}),NS=c.object({taskId:c.string()}),Ba=c.looseObject({progressToken:Kh.optional(),[Xt]:NS.optional()}),et=c.object({_meta:Ba.optional()}),Cr=et.extend({task:OS.optional()}),Wh=t=>Cr.safeParse(t).success,Oe=c.object({method:c.string(),params:et.loose().optional()}),ot=c.object({_meta:Ba.optional()}),it=c.object({method:c.string(),params:ot.loose().optional()}),Ne=c.looseObject({_meta:Ba.optional()}),uo=c.union([c.string(),c.number().int()]),Gh=c.object({jsonrpc:c.literal(co),id:uo,...Oe.shape}).strict(),Fa=t=>Gh.safeParse(t).success,Jh=c.object({jsonrpc:c.literal(co),...it.shape}).strict(),Yh=t=>Jh.safeParse(t).success,Ha=c.object({jsonrpc:c.literal(co),id:uo,result:Ne}).strict(),Or=t=>Ha.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"})(W||(W={}));Ka=c.object({jsonrpc:c.literal(co),id:uo.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),Xh=t=>Ka.safeParse(t).success,Zh=c.union([Gh,Jh,Ha,Ka]),OO=c.union([Ha,Ka]),po=Ne.strict(),LS=ot.extend({requestId:uo.optional(),reason:c.string().optional()}),ho=it.extend({method:c.literal("notifications/cancelled"),params:LS}),jS=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Nr=c.object({icons:c.array(jS).optional()}),Hn=c.object({name:c.string(),title:c.string().optional()}),Qh=Hn.extend({...Hn.shape,...Nr.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),DS=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),US=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:DS.optional(),url:Te.optional()}),c.record(c.string(),c.unknown()).optional())),MS=c.looseObject({list:Te.optional(),cancel:Te.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Te.optional()}).optional(),elicitation:c.looseObject({create:Te.optional()}).optional()}).optional()}),qS=c.looseObject({list:Te.optional(),cancel:Te.optional(),requests:c.looseObject({tools:c.looseObject({call:Te.optional()}).optional()}).optional()}),zS=c.object({experimental:c.record(c.string(),Te).optional(),sampling:c.object({context:Te.optional(),tools:Te.optional()}).optional(),elicitation:US.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:MS.optional(),extensions:c.record(c.string(),Te).optional()}),BS=et.extend({protocolVersion:c.string(),capabilities:zS,clientInfo:Qh}),Va=Oe.extend({method:c.literal("initialize"),params:BS}),FS=c.object({experimental:c.record(c.string(),Te).optional(),logging:Te.optional(),completions:Te.optional(),prompts:c.object({listChanged:c.boolean().optional()}).optional(),resources:c.object({subscribe:c.boolean().optional(),listChanged:c.boolean().optional()}).optional(),tools:c.object({listChanged:c.boolean().optional()}).optional(),tasks:qS.optional(),extensions:c.record(c.string(),Te).optional()}),HS=Ne.extend({protocolVersion:c.string(),capabilities:FS,serverInfo:Qh,instructions:c.string().optional()}),Wa=it.extend({method:c.literal("notifications/initialized"),params:ot.optional()}),fo=Oe.extend({method:c.literal("ping"),params:et.optional()}),KS=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),VS=c.object({...ot.shape,...KS.shape,progressToken:Kh}),mo=it.extend({method:c.literal("notifications/progress"),params:VS}),WS=et.extend({cursor:Vh.optional()}),Lr=Oe.extend({params:WS.optional()}),jr=Ne.extend({nextCursor:Vh.optional()}),GS=c.enum(["working","input_required","completed","failed","cancelled"]),Dr=c.object({taskId:c.string(),status:GS,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Kn=Ne.extend({task:Dr}),JS=ot.merge(Dr),Ur=it.extend({method:c.literal("notifications/tasks/status"),params:JS}),go=Oe.extend({method:c.literal("tasks/get"),params:et.extend({taskId:c.string()})}),bo=Ne.merge(Dr),yo=Oe.extend({method:c.literal("tasks/result"),params:et.extend({taskId:c.string()})}),NO=Ne.loose(),wo=Lr.extend({method:c.literal("tasks/list")}),vo=jr.extend({tasks:c.array(Dr)}),ko=Oe.extend({method:c.literal("tasks/cancel"),params:et.extend({taskId:c.string()})}),ef=Ne.merge(Dr),tf=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),nf=tf.extend({text:c.string()}),Ga=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),rf=tf.extend({blob:Ga}),Mr=c.enum(["user","assistant"]),Vn=c.object({audience:c.array(Mr).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),sf=c.object({...Hn.shape,...Nr.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Vn.optional(),_meta:c.optional(c.looseObject({}))}),YS=c.object({...Hn.shape,...Nr.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Vn.optional(),_meta:c.optional(c.looseObject({}))}),So=Lr.extend({method:c.literal("resources/list")}),XS=jr.extend({resources:c.array(sf)}),_o=Lr.extend({method:c.literal("resources/templates/list")}),ZS=jr.extend({resourceTemplates:c.array(YS)}),Ja=et.extend({uri:c.string()}),QS=Ja,xo=Oe.extend({method:c.literal("resources/read"),params:QS}),e_=Ne.extend({contents:c.array(c.union([nf,rf]))}),t_=it.extend({method:c.literal("notifications/resources/list_changed"),params:ot.optional()}),n_=Ja,r_=Oe.extend({method:c.literal("resources/subscribe"),params:n_}),s_=Ja,o_=Oe.extend({method:c.literal("resources/unsubscribe"),params:s_}),i_=ot.extend({uri:c.string()}),a_=it.extend({method:c.literal("notifications/resources/updated"),params:i_}),l_=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),c_=c.object({...Hn.shape,...Nr.shape,description:c.optional(c.string()),arguments:c.optional(c.array(l_)),_meta:c.optional(c.looseObject({}))}),$o=Lr.extend({method:c.literal("prompts/list")}),d_=jr.extend({prompts:c.array(c_)}),u_=et.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Ro=Oe.extend({method:c.literal("prompts/get"),params:u_}),Ya=c.object({type:c.literal("text"),text:c.string(),annotations:Vn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Xa=c.object({type:c.literal("image"),data:Ga,mimeType:c.string(),annotations:Vn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Za=c.object({type:c.literal("audio"),data:Ga,mimeType:c.string(),annotations:Vn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),p_=c.object({type:c.literal("tool_use"),name:c.string(),id:c.string(),input:c.record(c.string(),c.unknown()),_meta:c.record(c.string(),c.unknown()).optional()}),h_=c.object({type:c.literal("resource"),resource:c.union([nf,rf]),annotations:Vn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),f_=sf.extend({type:c.literal("resource_link")}),Qa=c.union([Ya,Xa,Za,f_,h_]),m_=c.object({role:Mr,content:Qa}),g_=Ne.extend({description:c.string().optional(),messages:c.array(m_)}),b_=it.extend({method:c.literal("notifications/prompts/list_changed"),params:ot.optional()}),y_=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),w_=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),of=c.object({...Hn.shape,...Nr.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Te).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Te).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:y_.optional(),execution:w_.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),To=Lr.extend({method:c.literal("tools/list")}),v_=jr.extend({tools:c.array(of)}),Eo=Ne.extend({content:c.array(Qa).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),LO=Eo.or(Ne.extend({toolResult:c.unknown()})),k_=Cr.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Wn=Oe.extend({method:c.literal("tools/call"),params:k_}),S_=it.extend({method:c.literal("notifications/tools/list_changed"),params:ot.optional()}),jO=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),qr=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),__=et.extend({level:qr}),el=Oe.extend({method:c.literal("logging/setLevel"),params:__}),x_=ot.extend({level:qr,logger:c.string().optional(),data:c.unknown()}),$_=it.extend({method:c.literal("notifications/message"),params:x_}),R_=c.object({name:c.string().optional()}),T_=c.object({hints:c.array(R_).optional(),costPriority:c.number().min(0).max(1).optional(),speedPriority:c.number().min(0).max(1).optional(),intelligencePriority:c.number().min(0).max(1).optional()}),E_=c.object({mode:c.enum(["auto","required","none"]).optional()}),P_=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Qa).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),A_=c.discriminatedUnion("type",[Ya,Xa,Za]),lo=c.discriminatedUnion("type",[Ya,Xa,Za,p_,P_]),I_=c.object({role:Mr,content:c.union([lo,c.array(lo)]),_meta:c.record(c.string(),c.unknown()).optional()}),C_=Cr.extend({messages:c.array(I_),modelPreferences:T_.optional(),systemPrompt:c.string().optional(),includeContext:c.enum(["none","thisServer","allServers"]).optional(),temperature:c.number().optional(),maxTokens:c.number().int(),stopSequences:c.array(c.string()).optional(),metadata:Te.optional(),tools:c.array(of).optional(),toolChoice:E_.optional()}),O_=Oe.extend({method:c.literal("sampling/createMessage"),params:C_}),zr=Ne.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Mr,content:A_}),tl=Ne.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Mr,content:c.union([lo,c.array(lo)])}),N_=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),L_=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),minLength:c.number().optional(),maxLength:c.number().optional(),format:c.enum(["email","uri","date","date-time"]).optional(),default:c.string().optional()}),j_=c.object({type:c.enum(["number","integer"]),title:c.string().optional(),description:c.string().optional(),minimum:c.number().optional(),maximum:c.number().optional(),default:c.number().optional()}),D_=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),U_=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),oneOf:c.array(c.object({const:c.string(),title:c.string()})),default:c.string().optional()}),M_=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),enumNames:c.array(c.string()).optional(),default:c.string().optional()}),q_=c.union([D_,U_]),z_=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({type:c.literal("string"),enum:c.array(c.string())}),default:c.array(c.string()).optional()}),B_=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({anyOf:c.array(c.object({const:c.string(),title:c.string()}))}),default:c.array(c.string()).optional()}),F_=c.union([z_,B_]),H_=c.union([M_,q_,F_]),K_=c.union([H_,N_,L_,j_]),V_=Cr.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),K_),required:c.array(c.string()).optional()})}),W_=Cr.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),G_=c.union([V_,W_]),J_=Oe.extend({method:c.literal("elicitation/create"),params:G_}),Y_=ot.extend({elicitationId:c.string()}),X_=it.extend({method:c.literal("notifications/elicitation/complete"),params:Y_}),Gn=Ne.extend({action:c.enum(["accept","decline","cancel"]),content:c.preprocess(t=>t===null?void 0:t,c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional())}),Z_=c.object({type:c.literal("ref/resource"),uri:c.string()}),Q_=c.object({type:c.literal("ref/prompt"),name:c.string()}),ex=et.extend({ref:c.union([Q_,Z_]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Po=Oe.extend({method:c.literal("completion/complete"),params:ex});tx=Ne.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),nx=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),rx=Oe.extend({method:c.literal("roots/list"),params:et.optional()}),nl=Ne.extend({roots:c.array(nx)}),sx=it.extend({method:c.literal("notifications/roots/list_changed"),params:ot.optional()}),DO=c.union([fo,Va,Po,el,Ro,$o,So,_o,xo,r_,o_,Wn,To,go,yo,wo,ko]),UO=c.union([ho,mo,Wa,sx,Ur]),MO=c.union([po,zr,tl,Gn,nl,bo,vo,Kn]),qO=c.union([fo,O_,J_,rx,go,yo,wo,ko]),zO=c.union([ho,mo,$_,a_,t_,S_,b_,Ur,X_]),BO=c.union([po,HS,tx,g_,d_,XS,ZS,e_,Eo,v_,bo,vo,Kn]),B=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===W.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new qa(s.elicitations,n)}return new t(e,n,r)}},qa=class extends B{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Zt(t){return t==="completed"||t==="failed"||t==="cancelled"}var cf=j(()=>{});var uf,df,pf,Ao=j(()=>{uf=Symbol("Let zodToJsonSchema decide on which parser to use"),df={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"},pf=t=>typeof t=="string"?{...df,name:t}:{...df,...t}});var hf,rl=j(()=>{Ao();hf=t=>{let e=pf(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}}});function sl(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function le(t,e,n,r,s){t[e]=n,sl(t,e,r,s)}var Qt=j(()=>{});var Io,Co=j(()=>{Io=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")}});function ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Io(e,t.currentPath):e.join("/")}}var at=j(()=>{Co()});import{ZodFirstPartyTypeKind as ox}from"zod/v3";function ff(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ox.ZodAny&&(n.items=X(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&le(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&le(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(le(n,"minItems",t.exactLength.value,t.exactLength.message,e),le(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var ol=j(()=>{Qt();Re()});function mf(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?le(n,"minimum",r.value,r.message,e):le(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),le(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?le(n,"maximum",r.value,r.message,e):le(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),le(n,"maximum",r.value,r.message,e));break;case"multipleOf":le(n,"multipleOf",r.value,r.message,e);break}return n}var il=j(()=>{Qt()});function gf(){return{type:"boolean"}}var al=j(()=>{});function Oo(t,e){return X(t.type._def,e)}var No=j(()=>{Re()});var bf,ll=j(()=>{Re();bf=(t,e)=>X(t.innerType._def,e)});function cl(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>cl(t,e,s))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ix(t,e)}}var ix,dl=j(()=>{Qt();ix=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":le(n,"minimum",r.value,r.message,e);break;case"max":le(n,"maximum",r.value,r.message,e);break}return n}});function yf(t,e){return{...X(t.innerType._def,e),default:t.defaultValue()}}var ul=j(()=>{Re()});function wf(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):ke(e)}var pl=j(()=>{Re();at()});function vf(t){return{type:"string",enum:Array.from(t.values)}}var hl=j(()=>{});function kf(t,e){let n=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return n.forEach(o=>{if(ax(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(r=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...l}=o;i=l}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}var ax,fl=j(()=>{Re();ax=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Sf(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var ml=j(()=>{});function Lo(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":le(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":le(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":bt(n,"email",r.message,e);break;case"format:idn-email":bt(n,"idn-email",r.message,e);break;case"pattern:zod":Fe(n,gt.email,r.message,e);break}break;case"url":bt(n,"uri",r.message,e);break;case"uuid":bt(n,"uuid",r.message,e);break;case"regex":Fe(n,r.regex,r.message,e);break;case"cuid":Fe(n,gt.cuid,r.message,e);break;case"cuid2":Fe(n,gt.cuid2,r.message,e);break;case"startsWith":Fe(n,RegExp(`^${bl(r.value,e)}`),r.message,e);break;case"endsWith":Fe(n,RegExp(`${bl(r.value,e)}$`),r.message,e);break;case"datetime":bt(n,"date-time",r.message,e);break;case"date":bt(n,"date",r.message,e);break;case"time":bt(n,"time",r.message,e);break;case"duration":bt(n,"duration",r.message,e);break;case"length":le(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),le(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{Fe(n,RegExp(bl(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&bt(n,"ipv4",r.message,e),r.version!=="v4"&&bt(n,"ipv6",r.message,e);break}case"base64url":Fe(n,gt.base64url,r.message,e);break;case"jwt":Fe(n,gt.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Fe(n,gt.ipv4Cidr,r.message,e),r.version!=="v4"&&Fe(n,gt.ipv6Cidr,r.message,e);break}case"emoji":Fe(n,gt.emoji(),r.message,e);break;case"ulid":{Fe(n,gt.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{bt(n,"binary",r.message,e);break}case"contentEncoding:base64":{le(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Fe(n,gt.base64,r.message,e);break}}break}case"nanoid":Fe(n,gt.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function bl(t,e){return e.patternStrategy==="escape"?cx(t):t}function cx(t){let e="";for(let n=0;n<t.length;n++)lx.has(t[n])||(e+="\\"),e+=t[n];return e}function bt(t,e,n,r){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):le(t,"format",e,n,r)}function Fe(t,e,n,r){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:_f(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):le(t,"pattern",_f(e,r),n,r)}function _f(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let l=0;l<r.length;l++){if(o){s+=r[l],o=!1;continue}if(n.i){if(i){if(r[l].match(/[a-z]/)){a?(s+=r[l],s+=`${r[l-2]}-${r[l]}`.toUpperCase(),a=!1):r[l+1]==="-"&&r[l+2]?.match(/[a-z]/)?(s+=r[l],a=!0):s+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){s+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(n.m){if(r[l]==="^"){s+=`(^|(?<=[\r
1990
- ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
1991
- ]))`;continue}}if(n.s&&r[l]==="."){s+=i?`${r[l]}\r
1992
- `:`[${r[l]}\r
1993
- ]`;continue}s+=r[l],r[l]==="\\"?o=!0:i&&r[l]==="]"?i=!1:!i&&r[l]==="["&&(i=!0)}try{new RegExp(s)}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 s}var gl,gt,lx,jo=j(()=>{Qt();gt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(gl===void 0&&(gl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gl),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-_]*$/};lx=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Br}from"zod/v3";function Do(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===Br.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Br.ZodString&&t.keyType._def.checks?.length){let{type:r,...s}=Lo(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===Br.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Br.ZodBranded&&t.keyType._def.type._def.typeName===Br.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=Oo(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var Uo=j(()=>{Re();jo();No();at()});function xf(t,e){if(e.mapStrategy==="record")return Do(t,e);let n=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||ke(e),r=X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var yl=j(()=>{Re();Uo();at()});function $f(t){let e=t.values,r=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(r.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}var wl=j(()=>{});function Rf(t){return t.target==="openAi"?void 0:{not:ke({...t,currentPath:[...t.currentPath,"not"]})}}var vl=j(()=>{at()});function Tf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var kl=j(()=>{});function Pf(t,e){if(e.target==="openApi3")return Ef(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Fr&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=Fr[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.reduce((s,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(o._def.value===null)return[...s,"null"];default:return s}},[]);if(r.length===n.length){let s=r.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:n.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,s)=>[...r,...s._def.values.filter(o=>!r.includes(o))],[])};return Ef(t,e)}var Fr,Ef,Mo=j(()=>{Re();Fr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Ef=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>X(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0}});function Af(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:Fr[t.innerType._def.typeName],nullable:!0}:{type:[Fr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var Sl=j(()=>{Re();Mo()});function If(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",sl(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?le(n,"minimum",r.value,r.message,e):le(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),le(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?le(n,"maximum",r.value,r.message,e):le(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),le(n,"maximum",r.value,r.message,e));break;case"multipleOf":le(n,"multipleOf",r.value,r.message,e);break}return n}var _l=j(()=>{Qt()});function Cf(t,e){let n=e.target==="openAi",r={type:"object",properties:{}},s=[],o=t.shape();for(let a in o){let l=o[a];if(l===void 0||l._def===void 0)continue;let u=ux(l);u&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=X(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(r.properties[a]=p,u||s.push(a))}s.length&&(r.required=s);let i=dx(t,e);return i!==void 0&&(r.additionalProperties=i),r}function dx(t,e){if(t.catchall._def.typeName!=="ZodNever")return X(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 ux(t){try{return t.isOptional()}catch{return!0}}var xl=j(()=>{Re()});var Of,$l=j(()=>{Re();at();Of=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:ke(e)},n]}:ke(e)}});var Nf,Rl=j(()=>{Re();Nf=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let n=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=X(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function Lf(t,e){return X(t.type._def,e)}var Tl=j(()=>{Re()});function jf(t,e){let r={type:"array",uniqueItems:!0,items:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&le(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&le(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var El=j(()=>{Qt();Re()});function Df(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>X(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>X(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var Pl=j(()=>{Re()});function Uf(t){return{not:ke(t)}}var Al=j(()=>{at()});function Mf(t){return ke(t)}var Il=j(()=>{at()});var qf,Cl=j(()=>{Re();qf=(t,e)=>X(t.innerType._def,e)});import{ZodFirstPartyTypeKind as ie}from"zod/v3";var zf,Ol=j(()=>{at();ol();il();al();No();ll();dl();ul();pl();hl();fl();ml();yl();wl();vl();kl();Sl();_l();xl();$l();Rl();Tl();Uo();El();jo();Pl();Al();Mo();Il();Cl();zf=(t,e,n)=>{switch(e){case ie.ZodString:return Lo(t,n);case ie.ZodNumber:return If(t,n);case ie.ZodObject:return Cf(t,n);case ie.ZodBigInt:return mf(t,n);case ie.ZodBoolean:return gf();case ie.ZodDate:return cl(t,n);case ie.ZodUndefined:return Uf(n);case ie.ZodNull:return Tf(n);case ie.ZodArray:return ff(t,n);case ie.ZodUnion:case ie.ZodDiscriminatedUnion:return Pf(t,n);case ie.ZodIntersection:return kf(t,n);case ie.ZodTuple:return Df(t,n);case ie.ZodRecord:return Do(t,n);case ie.ZodLiteral:return Sf(t,n);case ie.ZodEnum:return vf(t);case ie.ZodNativeEnum:return $f(t);case ie.ZodNullable:return Af(t,n);case ie.ZodOptional:return Of(t,n);case ie.ZodMap:return xf(t,n);case ie.ZodSet:return jf(t,n);case ie.ZodLazy:return()=>t.getter()._def;case ie.ZodPromise:return Lf(t,n);case ie.ZodNaN:case ie.ZodNever:return Rf(n);case ie.ZodEffects:return wf(t,n);case ie.ZodAny:return ke(n);case ie.ZodUnknown:return Mf(n);case ie.ZodDefault:return yf(t,n);case ie.ZodBranded:return Oo(t,n);case ie.ZodReadonly:return qf(t,n);case ie.ZodCatch:return bf(t,n);case ie.ZodPipeline:return Nf(t,n);case ie.ZodFunction:case ie.ZodVoid:case ie.ZodSymbol:return;default:return(r=>{})(e)}}});function X(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==uf)return a}if(r&&!n){let a=px(r,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=zf(t,t.typeName,e),i=typeof o=="function"?X(o(),e):o;if(i&&hx(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var px,hx,Re=j(()=>{Ao();Ol();Co();at();px=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Io(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),ke(e)):e.$refStrategy==="seen"?ke(e):void 0}},hx=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var Bf=j(()=>{});var Nl,Ll=j(()=>{Re();rl();at();Nl=(t,e)=>{let n=hf(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:X(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??ke(n)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=X(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??ke(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=s===void 0?r?{...o,[n.definitionPath]:r}:o:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,s].join("/"),[n.definitionPath]:{...r,[s]:o}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 Ff=j(()=>{Ao();rl();Qt();Co();Re();Bf();at();ol();il();al();No();ll();dl();ul();pl();hl();fl();ml();yl();wl();vl();kl();Sl();_l();xl();$l();Rl();Tl();Cl();Uo();El();jo();Pl();Al();Mo();Il();Ol();Ll();Ll()});import*as Hf from"zod/v4-mini";function fx(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function jl(t,e){return Rt(t)?Hf.toJSONSchema(t,{target:fx(e?.target),io:e?.pipeStrategy??"input"}):Nl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Dl(t){let n=Yt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Fn(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Ul(t,e){let n=Jt(t,e);if(!n.success)throw n.error;return n.data}var Ml=j(()=>{Ir();Ff()});function Kf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vf(t,e){let n={...t};for(let r in e){let s=r,o=e[s];if(o===void 0)continue;let i=n[s];Kf(i)&&Kf(o)?n[s]={...i,...o}:n[s]=o}return n}var mx,qo,Wf=j(()=>{Ir();Jn();cf();Ml();mx=6e4,qo=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(ho,n=>{this._oncancel(n)}),this.setNotificationHandler(mo,n=>{this._onprogress(n)}),this.setRequestHandler(fo,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(go,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new B(W.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(yo,async(n,r)=>{let s=async()=>{let o=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,r.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(l);else{let m=l,S=new B(m.error.code,m.error.message,m.error.data);p(S)}else{let m=a.type==="response"?"Response":"Error";this._onerror(new Error(`${m} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new B(W.InvalidParams,`Task not found: ${o}`);if(!Zt(i.status))return await this._waitForTaskUpdate(o,r.signal),await s();if(Zt(i.status)){let a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Xt]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(wo,async(n,r)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new B(W.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(ko,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new B(W.InvalidParams,`Task not found: ${n.params.taskId}`);if(Zt(s.status))throw new B(W.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new B(W.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof B?s:new B(W.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,n,r,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),B.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.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 n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=o=>{r?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),Or(o)||Xh(o)?this._onresponse(o):Fa(o)?this._onrequest(o,i):Yh(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=B.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Xt]?.taskId;if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:W.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(m=>this._onerror(new Error(`Failed to enqueue error response: ${m}`))):s?.send(p).catch(m=>this._onerror(new Error(`Failed to send an error response: ${m}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Wh(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:i.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let m={relatedRequestId:e.id};o&&(m.relatedTask={taskId:o}),await this.notification(p,m)},sendRequest:async(p,m,S)=>{if(i.signal.aborted)throw new B(W.ConnectionClosed,"Request was cancelled");let b={...S,relatedRequestId:e.id};o&&!b.relatedTask&&(b.relatedTask={taskId:o});let _=b.relatedTask?.taskId??o;return _&&l&&await l.updateTaskStatus(_,"input_required"),await this.request(p,m,b)},authInfo:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(e,u)).then(async p=>{if(i.signal.aborted)return;let m={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:m,timestamp:Date.now()},s?.sessionId):await s?.send(m)},async p=>{if(i.signal.aborted)return;let m={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:W.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:m,timestamp:Date.now()},s?.sessionId):await s?.send(m)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:n,...r}=e.params,s=Number(n),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(s),a=this._timeoutInfo.get(s);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(l){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),i(l);return}o(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Or(e))r(e);else{let i=new B(e.error.code,e.error.message,e.error.data);r(i)}return}let s=this._responseHandlers.get(n);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let o=!1;if(Or(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"&&(o=!0,this._taskProgressTokens.set(a.taskId,n))}}if(o||this._progressHandlers.delete(n),Or(e))s(e);else{let i=B.fromError(e.error.code,e.error.message,e.error.data);s(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,n,r){let{task:s}=r??{};if(!s){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof B?i:new B(W.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Kn,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new B(W.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Zt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)}:a.status==="failed"?yield{type:"error",error:new B(W.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(W.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof B?i:new B(W.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=r??{};return new Promise((u,p)=>{let m=N=>{p(N)};if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(N){m(N);return}r?.signal?.throwIfAborted();let S=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:S};r?.onprogress&&(this._progressHandlers.set(S,r.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:S}}),a&&(b.params={...b.params,task:a}),l&&(b.params={...b.params,_meta:{...b.params?._meta||{},[Xt]:l}});let _=N=>{this._responseHandlers.delete(S),this._progressHandlers.delete(S),this._cleanupTimeout(S),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:S,reason:String(N)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(Y=>this._onerror(new Error(`Failed to send cancellation: ${Y}`)));let D=N instanceof B?N:new B(W.RequestTimeout,String(N));p(D)};this._responseHandlers.set(S,N=>{if(!r?.signal?.aborted){if(N instanceof Error)return p(N);try{let D=Jt(n,N.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),r?.signal?.addEventListener("abort",()=>{_(r?.signal?.reason)});let R=r?.timeout??mx,T=()=>_(B.fromError(W.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(S,R,r?.maxTotalTimeout,T,r?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let N=D=>{let Y=this._responseHandlers.get(S);Y?Y(D):this._onerror(new Error(`Response handler missing for side-channeled request ${S}`))};this._requestResolvers.set(S,N),this._enqueueTaskMessage(P,{type:"request",message:b,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(S),p(D)})}else this._transport.send(b,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(N=>{this._cleanupTimeout(S),p(N)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},bo,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},vo,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},ef,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Xt]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.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"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Xt]:n.relatedTask}}}),this._transport?.send(a,n).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Xt]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Dl(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,o)=>{let i=Ul(e,s);return Promise.resolve(n(i,o))})}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,n){let r=Dl(e);this._notificationHandlers.set(r,s=>{let o=Ul(e,s);return Promise.resolve(n(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,n,r,s)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let s of r)if(s.type==="request"&&Fa(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new B(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(r=s.pollInterval)}catch{}return new Promise((s,o)=>{if(n.aborted){o(new B(W.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new B(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await r.createTask(s,e.id,{method:e.method,params:e.params},n)},getTask:async s=>{let o=await r.getTask(s,n);if(!o)throw new B(W.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await r.storeTaskResult(s,o,i,n);let a=await r.getTask(s,n);if(a){let l=Ur.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Zt(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>r.getTaskResult(s,n),updateTaskStatus:async(s,o,i)=>{let a=await r.getTask(s,n);if(!a)throw new B(W.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Zt(a.status))throw new B(W.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(s,o,i,n);let l=await r.getTask(s,n);if(l){let u=Ur.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Zt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var Vr=M(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var Hr=class{};he._CodeOrName=Hr;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var yn=class extends Hr{constructor(e){if(super(),!he.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}}};he.Name=yn;var lt=class extends Hr{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((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof yn&&(n[r.str]=(n[r.str]||0)+1),n),{})}};he._Code=lt;he.nil=new lt("");function Gf(t,...e){let n=[t[0]],r=0;for(;r<e.length;)zl(n,e[r]),n.push(t[++r]);return new lt(n)}he._=Gf;var ql=new lt("+");function Jf(t,...e){let n=[Kr(t[0])],r=0;for(;r<e.length;)n.push(ql),zl(n,e[r]),n.push(ql,Kr(t[++r]));return gx(n),new lt(n)}he.str=Jf;function zl(t,e){e instanceof lt?t.push(...e._items):e instanceof yn?t.push(e):t.push(wx(e))}he.addCodeArg=zl;function gx(t){let e=1;for(;e<t.length-1;){if(t[e]===ql){let n=bx(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function bx(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof yn||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 yn))return`"${t}${e.slice(1)}`}function yx(t,e){return e.emptyStr()?t:t.emptyStr()?e:Jf`${t}${e}`}he.strConcat=yx;function wx(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Kr(Array.isArray(t)?t.join(","):t)}function vx(t){return new lt(Kr(t))}he.stringify=vx;function Kr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Kr;function kx(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new lt(`.${t}`):Gf`[${t}]`}he.getProperty=kx;function Sx(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new lt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=Sx;function _x(t){return new lt(t.toString())}he.regexpCode=_x});var Hl=M(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.ValueScope=Ye.ValueScopeName=Ye.Scope=Ye.varKinds=Ye.UsedValueState=void 0;var Je=Vr(),Bl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},zo;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(zo||(Ye.UsedValueState=zo={}));Ye.varKinds={const:new Je.Name("const"),let:new Je.Name("let"),var:new Je.Name("var")};var Bo=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Je.Name?e:this.name(e)}name(e){return new Je.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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}}};Ye.Scope=Bo;var Fo=class extends Je.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Je._)`.${new Je.Name(n)}[${r}]`}};Ye.ValueScopeName=Fo;var xx=(0,Je._)`\n`,Fl=class extends Bo{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?xx:Je.nil}}get(){return this._scope}name(e){return new Fo(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(r=n.key)!==null&&r!==void 0?r:n.ref,a=this._values[o];if(a){let p=a.get(i);if(p)return p}else a=this._values[o]=new Map;a.set(i,s);let l=this._scope[o]||(this._scope[o]=[]),u=l.length;return l[u]=n.ref,s.setValue(n,{property:o,itemIndex:u}),s}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,Je._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},n,r)}_reduceValues(e,n,r={},s){let o=Je.nil;for(let i in e){let a=e[i];if(!a)continue;let l=r[i]=r[i]||new Map;a.forEach(u=>{if(l.has(u))return;l.set(u,zo.Started);let p=n(u);if(p){let m=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const;o=(0,Je._)`${o}${m} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,Je._)`${o}${p}${this.opts._n}`;else throw new Bl(u);l.set(u,zo.Completed)})}return o}};Ye.ValueScope=Fl});var te=M(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var ce=Vr(),yt=Hl(),en=Vr();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return en._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return en.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return en.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return en.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return en.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return en.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return en.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return en.Name}});var Wo=Hl();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Wo.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Wo.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Wo.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Wo.varKinds}});ne.operators={GT:new ce._Code(">"),GTE:new ce._Code(">="),LT:new ce._Code("<"),LTE:new ce._Code("<="),EQ:new ce._Code("==="),NEQ:new ce._Code("!=="),NOT:new ce._Code("!"),OR:new ce._Code("||"),AND:new ce._Code("&&"),ADD:new ce._Code("+")};var jt=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Kl=class extends jt{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?yt.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${s};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Xn(this.rhs,e,n)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},Ho=class extends jt{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof ce.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Xn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return Vo(e,this.rhs)}},Vl=class extends Ho{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wl=class extends jt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gl=class extends jt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Jl=class extends jt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yl=class extends jt{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Xn(this.code,e,n),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},Wr=class extends jt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,s=r.length;for(;s--;){let o=r[s];o.optimizeNames(e,n)||($x(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>kn(e,n.names),{})}},Dt=class extends Wr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Xl=class extends Wr{},Yn=class extends Dt{};Yn.kind="else";var wn=class t extends Dt{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Yn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(Yf(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Xn(this.condition,e,n),this}get names(){let e=super.names;return Vo(e,this.condition),this.else&&kn(e,this.else.names),e}};wn.kind="if";var vn=class extends Dt{};vn.kind="for";var Zl=class extends vn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Xn(this.iteration,e,n),this}get names(){return kn(super.names,this.iteration.names)}},Ql=class extends vn{constructor(e,n,r,s){super(),this.varKind=e,this.name=n,this.from=r,this.to=s}render(e){let n=e.es5?yt.varKinds.var:this.varKind,{name:r,from:s,to:o}=this;return`for(${n} ${r}=${s}; ${r}<${o}; ${r}++)`+super.render(e)}get names(){let e=Vo(super.names,this.from);return Vo(e,this.to)}},Ko=class extends vn{constructor(e,n,r,s){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Xn(this.iterable,e,n),this}get names(){return kn(super.names,this.iterable.names)}},Gr=class extends Dt{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Gr.kind="func";var Jr=class extends Wr{render(e){return"return "+super.render(e)}};Jr.kind="return";var ec=class extends Dt{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,s;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(s=this.finally)===null||s===void 0||s.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&kn(e,this.catch.names),this.finally&&kn(e,this.finally.names),e}},Yr=class extends Dt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Yr.kind="catch";var Xr=class extends Dt{render(e){return"finally"+super.render(e)}};Xr.kind="finally";var tc=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
1994
- `:""},this._extScope=e,this._scope=new yt.Scope({parent:e}),this._nodes=[new Xl]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,s){let o=this._scope.toName(n);return r!==void 0&&s&&(this._constants[o.str]=r),this._leafNode(new Kl(e,o,r)),o}const(e,n,r){return this._def(yt.varKinds.const,e,n,r)}let(e,n,r){return this._def(yt.varKinds.let,e,n,r)}var(e,n,r){return this._def(yt.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new Ho(e,n,r))}add(e,n){return this._leafNode(new Vl(e,ne.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Yl(e)),this}object(...e){let n=["{"];for(let[r,s]of e)n.length>1&&n.push(","),n.push(r),(r!==s||this.opts.es5)&&(n.push(":"),(0,ce.addCodeArg)(n,s));return n.push("}"),new ce._Code(n)}if(e,n,r){if(this._blockNode(new wn(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new wn(e))}else(){return this._elseNode(new Yn)}endIf(){return this._endBlockNode(wn,Yn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Zl(e),n)}forRange(e,n,r,s,o=this.opts.es5?yt.varKinds.var:yt.varKinds.let){let i=this._scope.toName(e);return this._for(new Ql(o,i,n,r),()=>s(i))}forOf(e,n,r,s=yt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=n instanceof ce.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ce._)`${i}.length`,a=>{this.var(o,(0,ce._)`${i}[${a}]`),r(o)})}return this._for(new Ko("of",s,o,n),()=>r(o))}forIn(e,n,r,s=this.opts.es5?yt.varKinds.var:yt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ce._)`Object.keys(${n})`,r);let o=this._scope.toName(e);return this._for(new Ko("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(vn)}label(e){return this._leafNode(new Wl(e))}break(e){return this._leafNode(new Gl(e))}return(e){let n=new Jr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Jr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new ec;if(this._blockNode(s),this.code(e),n){let o=this.name("e");this._currNode=s.catch=new Yr(o),n(o)}return r&&(this._currNode=s.finally=new Xr,this.code(r)),this._endBlockNode(Yr,Xr)}throw(e){return this._leafNode(new Jl(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=ce.nil,r,s){return this._blockNode(new Gr(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Gr)}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,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof wn))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};ne.CodeGen=tc;function kn(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function Vo(t,e){return e instanceof ce._CodeOrName?kn(t,e.names):t}function Xn(t,e,n){if(t instanceof ce.Name)return r(t);if(!s(t))return t;return new ce._Code(t._items.reduce((o,i)=>(i instanceof ce.Name&&(i=r(i)),i instanceof ce._Code?o.push(...i._items):o.push(i),o),[]));function r(o){let i=n[o.str];return i===void 0||e[o.str]!==1?o:(delete e[o.str],i)}function s(o){return o instanceof ce._Code&&o._items.some(i=>i instanceof ce.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function $x(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Yf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${nc(t)}`}ne.not=Yf;var Rx=Xf(ne.operators.AND);function Tx(...t){return t.reduce(Rx)}ne.and=Tx;var Ex=Xf(ne.operators.OR);function Px(...t){return t.reduce(Ex)}ne.or=Px;function Xf(t){return(e,n)=>e===ce.nil?n:n===ce.nil?e:(0,ce._)`${nc(e)} ${t} ${nc(n)}`}function nc(t){return t instanceof ce.Name?t:(0,ce._)`(${t})`}});var ue=M(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var be=te(),Ax=Vr();function Ix(t){let e={};for(let n of t)e[n]=!0;return e}re.toHash=Ix;function Cx(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(em(t,e),!tm(e,t.self.RULES.all))}re.alwaysValidSchema=Cx;function em(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let s=r.RULES.keywords;for(let o in e)s[o]||sm(t,`unknown keyword: "${o}"`)}re.checkUnknownRules=em;function tm(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}re.schemaHasRules=tm;function Ox(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}re.schemaHasRulesButRef=Ox;function Nx({topSchemaRef:t,schemaPath:e},n,r,s){if(!s){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,be._)`${n}`}return(0,be._)`${t}${e}${(0,be.getProperty)(r)}`}re.schemaRefOrVal=Nx;function Lx(t){return nm(decodeURIComponent(t))}re.unescapeFragment=Lx;function jx(t){return encodeURIComponent(sc(t))}re.escapeFragment=jx;function sc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=sc;function nm(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=nm;function Dx(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}re.eachItem=Dx;function Zf({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(s,o,i,a)=>{let l=i===void 0?o:i instanceof be.Name?(o instanceof be.Name?t(s,o,i):e(s,o,i),i):o instanceof be.Name?(e(s,i,o),o):n(o,i);return a===be.Name&&!(l instanceof be.Name)?r(s,l):l}}re.mergeEvaluated={props:Zf({mergeNames:(t,e,n)=>t.if((0,be._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,be._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,be._)`${n} || {}`).code((0,be._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,be._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,be._)`${n} || {}`),oc(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:rm}),items:Zf({mergeNames:(t,e,n)=>t.if((0,be._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,be._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,be._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,be._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function rm(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,be._)`{}`);return e!==void 0&&oc(t,n,e),n}re.evaluatedPropsToName=rm;function oc(t,e,n){Object.keys(n).forEach(r=>t.assign((0,be._)`${e}${(0,be.getProperty)(r)}`,!0))}re.setEvaluated=oc;var Qf={};function Ux(t,e){return t.scopeValue("func",{ref:e,code:Qf[e.code]||(Qf[e.code]=new Ax._Code(e.code))})}re.useFunc=Ux;var rc;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(rc||(re.Type=rc={}));function Mx(t,e,n){if(t instanceof be.Name){let r=e===rc.Num;return n?r?(0,be._)`"[" + ${t} + "]"`:(0,be._)`"['" + ${t} + "']"`:r?(0,be._)`"/" + ${t}`:(0,be._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,be.getProperty)(t).toString():"/"+sc(t)}re.getErrorPath=Mx;function sm(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=sm});var Ut=M(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var Me=te(),qx={data:new Me.Name("data"),valCxt:new Me.Name("valCxt"),instancePath:new Me.Name("instancePath"),parentData:new Me.Name("parentData"),parentDataProperty:new Me.Name("parentDataProperty"),rootData:new Me.Name("rootData"),dynamicAnchors:new Me.Name("dynamicAnchors"),vErrors:new Me.Name("vErrors"),errors:new Me.Name("errors"),this:new Me.Name("this"),self:new Me.Name("self"),scope:new Me.Name("scope"),json:new Me.Name("json"),jsonPos:new Me.Name("jsonPos"),jsonLen:new Me.Name("jsonLen"),jsonPart:new Me.Name("jsonPart")};ic.default=qx});var Zr=M(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.extendErrors=qe.resetErrorsCount=qe.reportExtraError=qe.reportError=qe.keyword$DataError=qe.keywordError=void 0;var pe=te(),Go=ue(),He=Ut();qe.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};qe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function zx(t,e=qe.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=am(t,e,n);r??(i||a)?om(o,l):im(s,(0,pe._)`[${l}]`)}qe.reportError=zx;function Bx(t,e=qe.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=am(t,e,n);om(s,a),o||i||im(r,He.default.vErrors)}qe.reportExtraError=Bx;function Fx(t,e){t.assign(He.default.errors,e),t.if((0,pe._)`${He.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${He.default.vErrors}.length`,e),()=>t.assign(He.default.vErrors,null)))}qe.resetErrorsCount=Fx;function Hx({gen:t,keyword:e,schemaValue:n,data:r,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,He.default.errors,a=>{t.const(i,(0,pe._)`${He.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(He.default.instancePath,o.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,n),t.assign((0,pe._)`${i}.data`,r))})}qe.extendErrors=Hx;function om(t,e){let n=t.const("err",e);t.if((0,pe._)`${He.default.vErrors} === null`,()=>t.assign(He.default.vErrors,(0,pe._)`[${n}]`),(0,pe._)`${He.default.vErrors}.push(${n})`),t.code((0,pe._)`${He.default.errors}++`)}function im(t,e){let{gen:n,validateName:r,schemaEnv:s}=t;s.$async?n.throw((0,pe._)`new ${t.ValidationError}(${e})`):(n.assign((0,pe._)`${r}.errors`,e),n.return(!1))}var Sn={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function am(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,pe._)`{}`:Kx(t,e,n)}function Kx(t,e,n={}){let{gen:r,it:s}=t,o=[Vx(s,n),Wx(t,n)];return Gx(t,e,o),r.object(...o)}function Vx({errorPath:t},{instancePath:e}){let n=e?(0,pe.str)`${t}${(0,Go.getErrorPath)(e,Go.Type.Str)}`:t;return[He.default.instancePath,(0,pe.strConcat)(He.default.instancePath,n)]}function Wx({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let s=r?e:(0,pe.str)`${e}/${t}`;return n&&(s=(0,pe.str)`${s}${(0,Go.getErrorPath)(n,Go.Type.Str)}`),[Sn.schemaPath,s]}function Gx(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:m}=a;r.push([Sn.keyword,s],[Sn.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&r.push([Sn.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([Sn.schema,i],[Sn.parentSchema,(0,pe._)`${p}${m}`],[He.default.data,o]),u&&r.push([Sn.propertyName,u])}});var cm=M(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.boolOrEmptySchema=Zn.topBoolOrEmptySchema=void 0;var Jx=Zr(),Yx=te(),Xx=Ut(),Zx={message:"boolean schema is false"};function Qx(t){let{gen:e,schema:n,validateName:r}=t;n===!1?lm(t,!1):typeof n=="object"&&n.$async===!0?e.return(Xx.default.data):(e.assign((0,Yx._)`${r}.errors`,null),e.return(!0))}Zn.topBoolOrEmptySchema=Qx;function e$(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),lm(t)):n.var(e,!0)}Zn.boolOrEmptySchema=e$;function lm(t,e){let{gen:n,data:r}=t,s={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Jx.reportError)(s,Zx,void 0,e)}});var ac=M(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.getRules=Qn.isJSONType=void 0;var t$=["string","number","integer","boolean","null","object","array"],n$=new Set(t$);function r$(t){return typeof t=="string"&&n$.has(t)}Qn.isJSONType=r$;function s$(){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:{}}}Qn.getRules=s$});var lc=M(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.shouldUseRule=tn.shouldUseGroup=tn.schemaHasRulesForType=void 0;function o$({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&dm(t,r)}tn.schemaHasRulesForType=o$;function dm(t,e){return e.rules.some(n=>um(t,n))}tn.shouldUseGroup=dm;function um(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}tn.shouldUseRule=um});var Qr=M(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;var i$=ac(),a$=lc(),l$=Zr(),ee=te(),pm=ue(),er;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(er||(ze.DataType=er={}));function c$(t){let e=hm(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}ze.getSchemaTypes=c$;function hm(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(i$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ze.getJSONTypes=hm;function d$(t,e){let{gen:n,data:r,opts:s}=t,o=u$(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,a$.schemaHasRulesForType)(t,e[0]));if(i){let a=dc(e,r,s.strictNumbers,er.Wrong);n.if(a,()=>{o.length?p$(t,e,o):uc(t)})}return i}ze.coerceAndCheckDataType=d$;var fm=new Set(["string","number","integer","boolean","null"]);function u$(t,e){return e?t.filter(n=>fm.has(n)||e==="array"&&n==="array"):[]}function p$(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,ee._)`typeof ${s}`),a=r.let("coerced",(0,ee._)`undefined`);o.coerceTypes==="array"&&r.if((0,ee._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,ee._)`${s}[0]`).assign(i,(0,ee._)`typeof ${s}`).if(dc(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,ee._)`${a} !== undefined`);for(let u of n)(fm.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);r.else(),uc(t),r.endIf(),r.if((0,ee._)`${a} !== undefined`,()=>{r.assign(s,a),h$(t,a)});function l(u){switch(u){case"string":r.elseIf((0,ee._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ee._)`"" + ${s}`).elseIf((0,ee._)`${s} === null`).assign(a,(0,ee._)`""`);return;case"number":r.elseIf((0,ee._)`${i} == "boolean" || ${s} === null
1995
- || (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,ee._)`+${s}`);return;case"integer":r.elseIf((0,ee._)`${i} === "boolean" || ${s} === null
1996
- || (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,ee._)`+${s}`);return;case"boolean":r.elseIf((0,ee._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,ee._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ee._)`${s} === "" || ${s} === 0 || ${s} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ee._)`${i} === "string" || ${i} === "number"
1997
- || ${i} === "boolean" || ${s} === null`).assign(a,(0,ee._)`[${s}]`)}}}function h$({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${n}]`,r))}function cc(t,e,n,r=er.Correct){let s=r===er.Correct?ee.operators.EQ:ee.operators.NEQ,o;switch(t){case"null":return(0,ee._)`${e} ${s} null`;case"array":o=(0,ee._)`Array.isArray(${e})`;break;case"object":o=(0,ee._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,ee._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,ee._)`typeof ${e} ${s} ${t}`}return r===er.Correct?o:(0,ee.not)(o);function i(a=ee.nil){return(0,ee.and)((0,ee._)`typeof ${e} == "number"`,a,n?(0,ee._)`isFinite(${e})`:ee.nil)}}ze.checkDataType=cc;function dc(t,e,n,r){if(t.length===1)return cc(t[0],e,n,r);let s,o=(0,pm.toHash)(t);if(o.array&&o.object){let i=(0,ee._)`typeof ${e} != "object"`;s=o.null?i:(0,ee._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=ee.nil;o.number&&delete o.integer;for(let i in o)s=(0,ee.and)(s,cc(i,e,n,r));return s}ze.checkDataTypes=dc;var f$={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function uc(t){let e=m$(t);(0,l$.reportError)(e,f$)}ze.reportTypeError=uc;function m$(t){let{gen:e,data:n,schema:r}=t,s=(0,pm.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var gm=M(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.assignDefaults=void 0;var tr=te(),g$=ue();function b$(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)mm(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>mm(t,o,s.default))}Jo.assignDefaults=b$;function mm(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,tr._)`${o}${(0,tr.getProperty)(e)}`;if(s){(0,g$.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,tr._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,tr._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,tr._)`${a} = ${(0,tr.stringify)(n)}`)}});var ct=M(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.validateUnion=ge.validateArray=ge.usePattern=ge.callValidateCode=ge.schemaProperties=ge.allSchemaProperties=ge.noPropertyInData=ge.propertyInData=ge.isOwnProperty=ge.hasPropFunc=ge.reportMissingProp=ge.checkMissingProp=ge.checkReportMissingProp=void 0;var we=te(),pc=ue(),nn=Ut(),y$=ue();function w$(t,e){let{gen:n,data:r,it:s}=t;n.if(fc(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,we._)`${e}`},!0),t.error()})}ge.checkReportMissingProp=w$;function v$({gen:t,data:e,it:{opts:n}},r,s){return(0,we.or)(...r.map(o=>(0,we.and)(fc(t,e,o,n.ownProperties),(0,we._)`${s} = ${o}`)))}ge.checkMissingProp=v$;function k$(t,e){t.setParams({missingProperty:e},!0),t.error()}ge.reportMissingProp=k$;function bm(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,we._)`Object.prototype.hasOwnProperty`})}ge.hasPropFunc=bm;function hc(t,e,n){return(0,we._)`${bm(t)}.call(${e}, ${n})`}ge.isOwnProperty=hc;function S$(t,e,n,r){let s=(0,we._)`${e}${(0,we.getProperty)(n)} !== undefined`;return r?(0,we._)`${s} && ${hc(t,e,n)}`:s}ge.propertyInData=S$;function fc(t,e,n,r){let s=(0,we._)`${e}${(0,we.getProperty)(n)} === undefined`;return r?(0,we.or)(s,(0,we.not)(hc(t,e,n))):s}ge.noPropertyInData=fc;function ym(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ge.allSchemaProperties=ym;function _$(t,e){return ym(e).filter(n=>!(0,pc.alwaysValidSchema)(t,e[n]))}ge.schemaProperties=_$;function x$({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,l,u){let p=u?(0,we._)`${t}, ${e}, ${r}${s}`:e,m=[[nn.default.instancePath,(0,we.strConcat)(nn.default.instancePath,o)],[nn.default.parentData,i.parentData],[nn.default.parentDataProperty,i.parentDataProperty],[nn.default.rootData,nn.default.rootData]];i.opts.dynamicRef&&m.push([nn.default.dynamicAnchors,nn.default.dynamicAnchors]);let S=(0,we._)`${p}, ${n.object(...m)}`;return l!==we.nil?(0,we._)`${a}.call(${l}, ${S})`:(0,we._)`${a}(${S})`}ge.callValidateCode=x$;var $$=(0,we._)`new RegExp`;function R$({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(n,r);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,we._)`${s.code==="new RegExp"?$$:(0,y$.useFunc)(t,s)}(${n}, ${r})`})}ge.usePattern=R$;function T$(t){let{gen:e,data:n,keyword:r,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let l=e.const("len",(0,we._)`${n}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:pc.Type.Num},o),e.if((0,we.not)(o),a)})}}ge.validateArray=T$;function E$(t){let{gen:e,schema:n,keyword:r,it:s}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(l=>(0,pc.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((l,u)=>{let p=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,we._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,we.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ge.validateUnion=E$});var km=M(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.validateKeywordUsage=Tt.validSchemaType=Tt.funcKeywordCode=Tt.macroKeywordCode=void 0;var Ke=te(),_n=Ut(),P$=ct(),A$=Zr();function I$(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=vm(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:Ke.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Tt.macroKeywordCode=I$;function C$(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;N$(l,e);let u=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=vm(r,s,u),m=r.let("valid");t.block$data(m,S),t.ok((n=e.valid)!==null&&n!==void 0?n:m);function S(){if(e.errors===!1)R(),e.modifying&&wm(t),T(()=>t.error());else{let P=e.async?b():_();e.modifying&&wm(t),T(()=>O$(t,P))}}function b(){let P=r.let("ruleErrs",null);return r.try(()=>R((0,Ke._)`await `),N=>r.assign(m,!1).if((0,Ke._)`${N} instanceof ${l.ValidationError}`,()=>r.assign(P,(0,Ke._)`${N}.errors`),()=>r.throw(N))),P}function _(){let P=(0,Ke._)`${p}.errors`;return r.assign(P,null),R(Ke.nil),P}function R(P=e.async?(0,Ke._)`await `:Ke.nil){let N=l.opts.passContext?_n.default.this:_n.default.self,D=!("compile"in e&&!a||e.schema===!1);r.assign(m,(0,Ke._)`${P}${(0,P$.callValidateCode)(t,p,N,D)}`,e.modifying)}function T(P){var N;r.if((0,Ke.not)((N=e.valid)!==null&&N!==void 0?N:m),P)}}Tt.funcKeywordCode=C$;function wm(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Ke._)`${r.parentData}[${r.parentDataProperty}]`))}function O$(t,e){let{gen:n}=t;n.if((0,Ke._)`Array.isArray(${e})`,()=>{n.assign(_n.default.vErrors,(0,Ke._)`${_n.default.vErrors} === null ? ${e} : ${_n.default.vErrors}.concat(${e})`).assign(_n.default.errors,(0,Ke._)`${_n.default.vErrors}.length`),(0,A$.extendErrors)(t)},()=>t.error())}function N$({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function vm(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Ke.stringify)(n)})}function L$(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Tt.validSchemaType=L$;function j$({schema:t,opts:e,self:n,errSchemaPath:r},s,o){if(Array.isArray(s.keyword)?!s.keyword.includes(o):s.keyword!==o)throw new Error("ajv implementation error");let i=s.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${o}: ${i.join(",")}`);if(s.validateSchema&&!s.validateSchema(t[o])){let l=`keyword "${o}" value is invalid at path "${r}": `+n.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(l);else throw new Error(l)}}Tt.validateKeywordUsage=j$});var _m=M(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.extendSubschemaMode=rn.extendSubschemaData=rn.getSubschema=void 0;var Et=te(),Sm=ue();function D$(t,{keyword:e,schemaProp:n,schema:r,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Et._)`${t.schemaPath}${(0,Et.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Et._)`${t.schemaPath}${(0,Et.getProperty)(e)}${(0,Et.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Sm.escapeFragment)(n)}`}}if(r!==void 0){if(s===void 0||o===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:r,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}rn.getSubschema=D$;function U$(t,e,{dataProp:n,dataPropType:r,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:p,opts:m}=e,S=a.let("data",(0,Et._)`${e.data}${(0,Et.getProperty)(n)}`,!0);l(S),t.errorPath=(0,Et.str)`${u}${(0,Sm.getErrorPath)(n,r,m.jsPropertySyntax)}`,t.parentDataProperty=(0,Et._)`${n}`,t.dataPathArr=[...p,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Et.Name?s:a.let("data",s,!0);l(u),i!==void 0&&(t.propertyName=i)}o&&(t.dataTypes=o);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}rn.extendSubschemaData=U$;function M$(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:s,allErrors:o}){r!==void 0&&(t.compositeRule=r),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=n}rn.extendSubschemaMode=M$});var mc=M((sD,xm)=>{"use strict";xm.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,s,o;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(s=r;s--!==0;)if(!t(e[s],n[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(o=Object.keys(e),r=o.length,r!==Object.keys(n).length)return!1;for(s=r;s--!==0;)if(!Object.prototype.hasOwnProperty.call(n,o[s]))return!1;for(s=r;s--!==0;){var i=o[s];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var Rm=M((oD,$m)=>{"use strict";var sn=$m.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},s=n.post||function(){};Yo(e,r,s,t,"",t)};sn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Yo(t,e,n,r,s,o,i,a,l,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,s,o,i,a,l,u);for(var p in r){var m=r[p];if(Array.isArray(m)){if(p in sn.arrayKeywords)for(var S=0;S<m.length;S++)Yo(t,e,n,m[S],s+"/"+p+"/"+S,o,s,p,r,S)}else if(p in sn.propsKeywords){if(m&&typeof m=="object")for(var b in m)Yo(t,e,n,m[b],s+"/"+p+"/"+q$(b),o,s,p,r,b)}else(p in sn.keywords||t.allKeys&&!(p in sn.skipKeywords))&&Yo(t,e,n,m,s+"/"+p,o,s,p,r)}n(r,s,o,i,a,l,u)}}function q$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var es=M(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var z$=ue(),B$=mc(),F$=Rm(),H$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function K$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!gc(t):e?Tm(t)<=e:!1}Xe.inlineRef=K$;var V$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gc(t){for(let e in t){if(V$.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(gc)||typeof n=="object"&&gc(n))return!0}return!1}function Tm(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!H$.has(n)&&(typeof t[n]=="object"&&(0,z$.eachItem)(t[n],r=>e+=Tm(r)),e===1/0))return 1/0}return e}function Em(t,e="",n){n!==!1&&(e=nr(e));let r=t.parse(e);return Pm(t,r)}Xe.getFullPath=Em;function Pm(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=Pm;var W$=/#\/?$/;function nr(t){return t?t.replace(W$,""):""}Xe.normalizeId=nr;function G$(t,e,n){return n=nr(n),t.resolve(e,n)}Xe.resolveUrl=G$;var J$=/^[a-z_][-a-z0-9._]*$/i;function Y$(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=nr(t[n]||e),o={"":s},i=Em(r,s,!1),a={},l=new Set;return F$(t,{allKeys:!0},(m,S,b,_)=>{if(_===void 0)return;let R=i+S,T=o[_];typeof m[n]=="string"&&(T=P.call(this,m[n])),N.call(this,m.$anchor),N.call(this,m.$dynamicAnchor),o[S]=T;function P(D){let Y=this.opts.uriResolver.resolve;if(D=nr(T?Y(T,D):D),l.has(D))throw p(D);l.add(D);let K=this.refs[D];return typeof K=="string"&&(K=this.refs[K]),typeof K=="object"?u(m,K.schema,D):D!==nr(R)&&(D[0]==="#"?(u(m,a[D],D),a[D]=m):this.refs[D]=R),D}function N(D){if(typeof D=="string"){if(!J$.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(m,S,b){if(S!==void 0&&!B$(m,S))throw p(b)}function p(m){return new Error(`reference "${m}" resolves to more than one schema`)}}Xe.getSchemaRefs=Y$});var rs=M(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.getData=on.KeywordCxt=on.validateFunctionCode=void 0;var Nm=cm(),Am=Qr(),yc=lc(),Xo=Qr(),X$=gm(),ns=km(),bc=_m(),F=te(),Q=Ut(),Z$=es(),Mt=ue(),ts=Zr();function Q$(t){if(Dm(t)&&(Um(t),jm(t))){nR(t);return}Lm(t,()=>(0,Nm.topBoolOrEmptySchema)(t))}on.validateFunctionCode=Q$;function Lm({gen:t,validateName:e,schema:n,schemaEnv:r,opts:s},o){s.code.es5?t.func(e,(0,F._)`${Q.default.data}, ${Q.default.valCxt}`,r.$async,()=>{t.code((0,F._)`"use strict"; ${Im(n,s)}`),tR(t,s),t.code(o)}):t.func(e,(0,F._)`${Q.default.data}, ${eR(s)}`,r.$async,()=>t.code(Im(n,s)).code(o))}function eR(t){return(0,F._)`{${Q.default.instancePath}="", ${Q.default.parentData}, ${Q.default.parentDataProperty}, ${Q.default.rootData}=${Q.default.data}${t.dynamicRef?(0,F._)`, ${Q.default.dynamicAnchors}={}`:F.nil}}={}`}function tR(t,e){t.if(Q.default.valCxt,()=>{t.var(Q.default.instancePath,(0,F._)`${Q.default.valCxt}.${Q.default.instancePath}`),t.var(Q.default.parentData,(0,F._)`${Q.default.valCxt}.${Q.default.parentData}`),t.var(Q.default.parentDataProperty,(0,F._)`${Q.default.valCxt}.${Q.default.parentDataProperty}`),t.var(Q.default.rootData,(0,F._)`${Q.default.valCxt}.${Q.default.rootData}`),e.dynamicRef&&t.var(Q.default.dynamicAnchors,(0,F._)`${Q.default.valCxt}.${Q.default.dynamicAnchors}`)},()=>{t.var(Q.default.instancePath,(0,F._)`""`),t.var(Q.default.parentData,(0,F._)`undefined`),t.var(Q.default.parentDataProperty,(0,F._)`undefined`),t.var(Q.default.rootData,Q.default.data),e.dynamicRef&&t.var(Q.default.dynamicAnchors,(0,F._)`{}`)})}function nR(t){let{schema:e,opts:n,gen:r}=t;Lm(t,()=>{n.$comment&&e.$comment&&qm(t),aR(t),r.let(Q.default.vErrors,null),r.let(Q.default.errors,0),n.unevaluated&&rR(t),Mm(t),dR(t)})}function rR(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,F._)`${n}.evaluated`),e.if((0,F._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${t.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${t.evaluated}.items`,(0,F._)`undefined`))}function Im(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${n} */`:F.nil}function sR(t,e){if(Dm(t)&&(Um(t),jm(t))){oR(t,e);return}(0,Nm.boolOrEmptySchema)(t,e)}function jm({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function Dm(t){return typeof t.schema!="boolean"}function oR(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&qm(t),lR(t),cR(t);let o=r.const("_errs",Q.default.errors);Mm(t,o),r.var(e,(0,F._)`${o} === ${Q.default.errors}`)}function Um(t){(0,Mt.checkUnknownRules)(t),iR(t)}function Mm(t,e){if(t.opts.jtd)return Cm(t,[],!1,e);let n=(0,Am.getSchemaTypes)(t.schema),r=(0,Am.coerceAndCheckDataType)(t,n);Cm(t,n,!r,e)}function iR(t){let{schema:e,errSchemaPath:n,opts:r,self:s}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Mt.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function aR(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Mt.checkStrictMode)(t,"default is ignored in the schema root")}function lR(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,Z$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function cR(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function qm({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:s}){let o=n.$comment;if(s.$comment===!0)t.code((0,F._)`${Q.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,F.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,F._)`${Q.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function dR(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=t;n.$async?e.if((0,F._)`${Q.default.errors} === 0`,()=>e.return(Q.default.data),()=>e.throw((0,F._)`new ${s}(${Q.default.vErrors})`)):(e.assign((0,F._)`${r}.errors`,Q.default.vErrors),o.unevaluated&&uR(t),e.return((0,F._)`${Q.default.errors} === 0`))}function uR({gen:t,evaluated:e,props:n,items:r}){n instanceof F.Name&&t.assign((0,F._)`${e}.props`,n),r instanceof F.Name&&t.assign((0,F._)`${e}.items`,r)}function Cm(t,e,n,r){let{gen:s,schema:o,data:i,allErrors:a,opts:l,self:u}=t,{RULES:p}=u;if(o.$ref&&(l.ignoreKeywordsWithRef||!(0,Mt.schemaHasRulesButRef)(o,p))){s.block(()=>Bm(t,"$ref",p.all.$ref.definition));return}l.jtd||pR(t,e),s.block(()=>{for(let S of p.rules)m(S);m(p.post)});function m(S){(0,yc.shouldUseGroup)(o,S)&&(S.type?(s.if((0,Xo.checkDataType)(S.type,i,l.strictNumbers)),Om(t,S),e.length===1&&e[0]===S.type&&n&&(s.else(),(0,Xo.reportTypeError)(t)),s.endIf()):Om(t,S),a||s.if((0,F._)`${Q.default.errors} === ${r||0}`))}}function Om(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,X$.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,yc.shouldUseRule)(r,o)&&Bm(t,o.keyword,o.definition,e.type)})}function pR(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(hR(t,e),t.opts.allowUnionTypes||fR(t,e),mR(t,t.dataTypes))}function hR(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{zm(t.dataTypes,n)||wc(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),bR(t,e)}}function fR(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&wc(t,"use allowUnionTypes to allow union type keyword")}function mR(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,yc.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>gR(e,i))&&wc(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function gR(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function zm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function bR(t,e){let n=[];for(let r of t.dataTypes)zm(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function wc(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Mt.checkStrictMode)(t,e,t.opts.strictTypes)}var Zo=class{constructor(e,n,r){if((0,ns.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Mt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Fm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ns.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Q.default.errors))}result(e,n,r){this.failResult((0,F.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,F.not)(e),void 0,n)}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:n}=this;this.fail((0,F._)`${n} !== undefined && (${(0,F.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?ts.reportExtraError:ts.reportError)(this,this.def.error,n)}$dataError(){(0,ts.reportError)(this,this.def.$dataError||ts.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ts.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=F.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=F.nil,n=F.nil){if(!this.$data)return;let{gen:r,schemaCode:s,schemaType:o,def:i}=this;r.if((0,F.or)((0,F._)`${s} === undefined`,n)),e!==F.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:s,it:o}=this;return(0,F.or)(i(),a());function i(){if(r.length){if(!(n instanceof F.Name))throw new Error("ajv implementation error");let l=Array.isArray(r)?r:[r];return(0,F._)`${(0,Xo.checkDataTypes)(l,n,o.opts.strictNumbers,Xo.DataType.Wrong)}`}return F.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,F._)`!${l}(${n})`}return F.nil}}subschema(e,n){let r=(0,bc.getSubschema)(this.it,e);(0,bc.extendSubschemaData)(r,this.it,e),(0,bc.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return sR(s,n),s}mergeEvaluated(e,n){let{it:r,gen:s}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Mt.mergeEvaluated.props(s,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Mt.mergeEvaluated.items(s,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:s}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return s.if(n,()=>this.mergeEvaluated(e,F.Name)),!0}};on.KeywordCxt=Zo;function Bm(t,e,n,r){let s=new Zo(t,n,e);"code"in n?n.code(s,r):s.$data&&n.validate?(0,ns.funcKeywordCode)(s,n):"macro"in n?(0,ns.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,ns.funcKeywordCode)(s,n)}var yR=/^\/(?:[^~]|~0|~1)*$/,wR=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Fm(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return Q.default.rootData;if(t[0]==="/"){if(!yR.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Q.default.rootData}else{let u=wR.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+u[1];if(s=u[2],s==="#"){if(p>=e)throw new Error(l("property/index",p));return r[e-p]}if(p>e)throw new Error(l("data",p));if(o=n[e-p],!s)return o}let i=o,a=s.split("/");for(let u of a)u&&(o=(0,F._)`${o}${(0,F.getProperty)((0,Mt.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${o}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}on.getData=Fm});var Qo=M(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var vc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};kc.default=vc});var ss=M(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Sc=es(),_c=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Sc.resolveUrl)(e,n,r),this.missingSchema=(0,Sc.normalizeId)((0,Sc.getFullPath)(e,this.missingRef))}};xc.default=_c});var ti=M(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.resolveSchema=dt.getCompilingSchema=dt.resolveRef=dt.compileSchema=dt.SchemaEnv=void 0;var wt=te(),vR=Qo(),xn=Ut(),vt=es(),Hm=ue(),kR=rs(),rr=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,vt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};dt.SchemaEnv=rr;function Rc(t){let e=Km.call(this,t);if(e)return e;let n=(0,vt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new wt.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:vR.default,code:(0,wt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:xn.default.data,parentData:xn.default.parentData,parentDataProperty:xn.default.parentDataProperty,dataNames:[xn.default.data],dataPathArr:[wt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,wt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:wt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,wt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,kR.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let m=i.toString();p=`${i.scopeRefs(xn.default.scope)}return ${m}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let b=new Function(`${xn.default.self}`,`${xn.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:b}),b.errors=null,b.schema=t.schema,b.schemaEnv=t,t.$async&&(b.$async=!0),this.opts.code.source===!0&&(b.source={validateName:l,validateCode:m,scopeValues:i._values}),this.opts.unevaluated){let{props:_,items:R}=u;b.evaluated={props:_ instanceof wt.Name?void 0:_,items:R instanceof wt.Name?void 0:R,dynamicProps:_ instanceof wt.Name,dynamicItems:R instanceof wt.Name},b.source&&(b.source.evaluated=(0,wt.stringify)(b.evaluated))}return t.validate=b,t}catch(m){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),m}finally{this._compilations.delete(t)}}dt.compileSchema=Rc;function SR(t,e,n){var r;n=(0,vt.resolveUrl)(this.opts.uriResolver,e,n);let s=t.refs[n];if(s)return s;let o=$R.call(this,t,n);if(o===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(o=new rr({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=_R.call(this,o)}dt.resolveRef=SR;function _R(t){return(0,vt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Rc.call(this,t)}function Km(t){for(let e of this._compilations)if(xR(e,t))return e}dt.getCompilingSchema=Km;function xR(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function $R(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||ei.call(this,t,e)}function ei(t,e){let n=this.opts.uriResolver.parse(e),r=(0,vt._getFullPath)(this.opts.uriResolver,n),s=(0,vt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===s)return $c.call(this,n,t);let o=(0,vt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=ei.call(this,t,i);return typeof a?.schema!="object"?void 0:$c.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Rc.call(this,i),o===(0,vt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(s=(0,vt.resolveUrl)(this.opts.uriResolver,s,u)),new rr({schema:a,schemaId:l,root:t,baseId:s})}return $c.call(this,n,i)}}dt.resolveSchema=ei;var RR=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function $c(t,{baseId:e,schema:n,root:r}){var s;if(((s=t.fragment)===null||s===void 0?void 0:s[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;let l=n[(0,Hm.unescapeFragment)(a)];if(l===void 0)return;n=l;let u=typeof n=="object"&&n[this.opts.schemaId];!RR.has(a)&&u&&(e=(0,vt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,Hm.schemaHasRulesButRef)(n,this.RULES)){let a=(0,vt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=ei.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new rr({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var Vm=M((uD,TR)=>{TR.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 Pc=M((pD,Zm)=>{"use strict";var ER=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Gm=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),Tc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Jm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),PR=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ec(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var AR=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Wm(t){return t.length=0,!0}function IR(t,e,n){if(t.length){let r=Ec(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function CR(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=IR;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,r,n))break;if(++e>7){n.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),r.push(":");continue}else if(u==="%"){if(!a(s,r,n))break;a=Wm}else{s.push(u);continue}}return s.length&&(a===Wm?n.zone=s.join(""):i?r.push(s.join("")):r.push(Ec(s))),n.address=r.join(""),n}function Ym(t){if(OR(t,":")<2)return{host:t,isIPV6:!1};let e=CR(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function OR(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function NR(t){let e=t,n=[],r=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(s===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(s===3&&e==="/.."){n.length!==0&&n.pop(),n.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),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}var LR={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},jR=/[@/?#:]/g,DR=/[@/?#]/g;function Xm(t,e){let n=e?DR:jR;return n.lastIndex=0,t.replace(n,r=>LR[r])}function UR(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(Tc(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&Jm(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function MR(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(Tc(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&Jm(o)?e+=o:e+="%"+s,n+=2;continue}}PR(t[n])?e+=t[n]:e+=escape(t[n])}return e}function qR(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(Tc(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function zR(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Gm(n)){let r=Ym(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Xm(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Zm.exports={nonSimpleDomain:AR,recomposeAuthority:zR,reescapeHostDelimiters:Xm,normalizePercentEncoding:UR,normalizePathEncoding:MR,escapePreservingEscapes:qR,removeDotSegments:NR,isIPv4:Gm,isUUID:ER,normalizeIPv6:Ym,stringArrayToHexStripped:Ec}});var rg=M((hD,ng)=>{"use strict";var{isUUID:BR}=Pc(),FR=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,HR=["http","https","ws","wss","urn","urn:uuid"];function KR(t){return HR.indexOf(t)!==-1}function Ac(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 Qm(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function eg(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 VR(t){return t.secure=Ac(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function WR(t){if((t.port===(Ac(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,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function GR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(FR);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let s=`${r}:${e.nid||t.nid}`,o=Ic(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function JR(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),s=`${n}:${e.nid||r}`,o=Ic(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function YR(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!BR(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function XR(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var tg={scheme:"http",domainHost:!0,parse:Qm,serialize:eg},ZR={scheme:"https",domainHost:tg.domainHost,parse:Qm,serialize:eg},ni={scheme:"ws",domainHost:!0,parse:VR,serialize:WR},QR={scheme:"wss",domainHost:ni.domainHost,parse:ni.parse,serialize:ni.serialize},eT={scheme:"urn",parse:GR,serialize:JR,skipNormalize:!0},tT={scheme:"urn:uuid",parse:YR,serialize:XR,skipNormalize:!0},ri={http:tg,https:ZR,ws:ni,wss:QR,urn:eT,"urn:uuid":tT};Object.setPrototypeOf(ri,null);function Ic(t){return t&&(ri[t]||ri[t.toLowerCase()])||void 0}ng.exports={wsIsSecure:Ac,SCHEMES:ri,isValidSchemeName:KR,getSchemeHandler:Ic}});var lg=M((fD,ii)=>{"use strict";var{normalizeIPv6:nT,removeDotSegments:os,recomposeAuthority:rT,normalizePercentEncoding:sT,normalizePathEncoding:oT,escapePreservingEscapes:iT,reescapeHostDelimiters:aT,isIPv4:lT,nonSimpleDomain:cT}=Pc(),{SCHEMES:dT,getSchemeHandler:og}=rg();function uT(t,e){return typeof t=="string"?t=yT(t,e):typeof t=="object"&&(t=oi($n(t,e),e)),t}function pT(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=si(t,r),{parsed:i,malformedAuthorityOrPort:a}=si(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=ig(s,i,r,!0);return r.skipEscape=!0,$n(l,r)}function ig(t,e,n,r){let s={};return r||(t=oi($n(t,n),n),e=oi($n(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=os(e.path||""),s.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=os(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=os(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?s.path="/"+e.path:t.path?s.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:s.path=e.path,s.path=os(s.path)),s.query=e.query):(s.path=t.path,e.query!==void 0?s.query=e.query:s.query=t.query),s.userinfo=t.userinfo,s.host=t.host,s.port=t.port),s.scheme=t.scheme),s.fragment=e.fragment,s}function hT(t,e,n){let r=sg(t,n),s=sg(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function $n(t,e){let n={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:""},r=Object.assign({},e),s=[],o=og(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=sT(n.path):(n.path=iT(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=rT(n);if(i!==void 0&&(r.reference!=="suffix"&&s.push("//"),s.push(i),n.path&&n.path[0]!=="/"&&s.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!o||!o.absolutePath)&&(a=os(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return n.query!==void 0&&s.push("?",n.query),n.fragment!==void 0&&s.push("#",n.fragment),s.join("")}var fT=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,mT=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,gT=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function bT(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 si(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,o=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let i=t.match(mT);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(gT);if(a!==null){let u=a[1],p=u.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",s=!0):u.length!==p.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",s=!0))}let l=t.match(fT);if(l){r.scheme=l[1],r.userinfo=l[3],r.host=l[4],r.port=parseInt(l[5],10),r.path=l[6]||"",r.query=l[7],r.fragment=l[8],isNaN(r.port)&&(r.port=l[5]);let u=bT(r,l);if(u!==void 0&&(r.error=r.error||u,s=!0),r.host)if(lT(r.host)===!1){let S=nT(r.host);r.host=S.host.toLowerCase(),o=S.isIPV6}else o=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let p=og(n.scheme||r.scheme);if(!n.unicodeSupport&&(!p||!p.unicodeSupport)&&r.host&&(n.domainHost||p&&p.domainHost)&&o===!1&&cT(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(m){r.error=r.error||"Host's domain name can not be converted to ASCII: "+m}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=aT(unescape(r.host),o))),r.path&&(r.path=oT(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}p&&p.parse&&p.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:s}}function oi(t,e){return si(t,e).parsed}function yT(t,e){return ag(t,e).normalized}function ag(t,e){let{parsed:n,malformedAuthorityOrPort:r}=si(t,e);return{normalized:r?t:$n(n,e),malformedAuthorityOrPort:r}}function sg(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=ag(t,e);return r?void 0:n}if(typeof t=="object")return $n(t,e)}var Cc={SCHEMES:dT,normalize:uT,resolve:pT,resolveComponent:ig,equal:hT,serialize:$n,parse:oi};ii.exports=Cc;ii.exports.default=Cc;ii.exports.fastUri=Cc});var dg=M(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var cg=lg();cg.code='require("ajv/dist/runtime/uri").default';Oc.default=cg});var yg=M(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var wT=rs();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return wT.KeywordCxt}});var sr=te();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return sr._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return sr.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return sr.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return sr.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return sr.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return sr.CodeGen}});var vT=Qo(),mg=ss(),kT=ac(),is=ti(),ST=te(),as=es(),ai=Qr(),Lc=ue(),ug=Vm(),_T=dg(),gg=(t,e)=>new RegExp(t,e);gg.code="new RegExp";var xT=["removeAdditional","useDefaults","coerceTypes"],$T=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),RT={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."},TT={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},pg=200;function ET(t){var e,n,r,s,o,i,a,l,u,p,m,S,b,_,R,T,P,N,D,Y,K,Ae,De,zt,Bt;let dn=t.strict,Ft=(e=t.code)===null||e===void 0?void 0:e.optimize,_t=Ft===!0||Ft===void 0?1:Ft||0,ks=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:gg,Oi=(s=t.uriResolver)!==null&&s!==void 0?s:_T.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:dn)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:dn)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:dn)!==null&&p!==void 0?p:"log",strictTuples:(S=(m=t.strictTuples)!==null&&m!==void 0?m:dn)!==null&&S!==void 0?S:"log",strictRequired:(_=(b=t.strictRequired)!==null&&b!==void 0?b:dn)!==null&&_!==void 0?_:!1,code:t.code?{...t.code,optimize:_t,regExp:ks}:{optimize:_t,regExp:ks},loopRequired:(R=t.loopRequired)!==null&&R!==void 0?R:pg,loopEnum:(T=t.loopEnum)!==null&&T!==void 0?T:pg,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(N=t.messages)!==null&&N!==void 0?N:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(Y=t.schemaId)!==null&&Y!==void 0?Y:"$id",addUsedSchema:(K=t.addUsedSchema)!==null&&K!==void 0?K:!0,validateSchema:(Ae=t.validateSchema)!==null&&Ae!==void 0?Ae:!0,validateFormats:(De=t.validateFormats)!==null&&De!==void 0?De:!0,unicodeRegExp:(zt=t.unicodeRegExp)!==null&&zt!==void 0?zt:!0,int32range:(Bt=t.int32range)!==null&&Bt!==void 0?Bt:!0,uriResolver:Oi}}var ls=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,...ET(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new ST.ValueScope({scope:{},prefixes:$T,es5:n,lines:r}),this.logger=NT(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,kT.getRules)(),hg.call(this,RT,e,"NOT SUPPORTED"),hg.call(this,TT,e,"DEPRECATED","warn"),this._metaOpts=CT.call(this),e.formats&&AT.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&IT.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),PT.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=ug;r==="id"&&(s={...ug},s.id=s.$id,delete s.$id),n&&e&&this.addMetaSchema(s,s[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let s=r(n);return"$async"in r||(this.errors=r.errors),s}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return s.call(this,e,n);async function s(p,m){await o.call(this,p.$schema);let S=this._addSchema(p,m);return S.validate||i.call(this,S)}async function o(p){p&&!this.getSchema(p)&&await s.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(m){if(!(m instanceof mg.default))throw m;return a.call(this,m),await l.call(this,m.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:m}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${m} cannot be resolved`)}async function l(p){let m=await u.call(this,p);this.refs[p]||await o.call(this,m.$schema),this.refs[p]||this.addSchema(m,p,n)}async function u(p){let m=this._loading[p];if(m)return m;try{return await(this._loading[p]=r(p))}finally{delete this._loading[p]}}}addSchema(e,n,r,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,s);return this}let o;if(typeof e=="object"){let{schemaId:i}=this.opts;if(o=e[i],o!==void 0&&typeof o!="string")throw new Error(`schema ${i} must be string`)}return n=(0,as.normalizeId)(n||o),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,s,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(r,e);if(!s&&n){let o="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(o);else throw new Error(o)}return s}getSchema(e){let n;for(;typeof(n=fg.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new is.SchemaEnv({schema:{},schemaId:r});if(n=is.resolveSchema.call(this,s,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}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 n=fg.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,as.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(jT.call(this,r,n),!n)return(0,Lc.eachItem)(r,o=>Nc.call(this,o)),this;UT.call(this,n);let s={...n,type:(0,ai.getJSONTypes)(n.type),schemaType:(0,ai.getJSONTypes)(n.schemaType)};return(0,Lc.eachItem)(r,s.type.length===0?o=>Nc.call(this,o,s):o=>s.type.forEach(i=>Nc.call(this,o,s,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let s=r.rules.findIndex(o=>o.keyword===e);s>=0&&r.rules.splice(s,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${r}${s.instancePath} ${s.message}`).reduce((s,o)=>s+n+o)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of n){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in r){let l=r[a];if(typeof l!="object")continue;let{$data:u}=l.definition,p=i[a];u&&p&&(i[a]=bg(p))}}return e}_removeAllSchemas(e,n){for(let r in e){let s=e[r];(!n||n.test(r))&&(typeof s=="string"?delete e[r]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[r]))}}_addSchema(e,n,r,s=this.opts.validateSchema,o=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 l=this._cache.get(e);if(l!==void 0)return l;r=(0,as.normalizeId)(i||r);let u=as.getSchemaRefs.call(this,e,r);return l=new is.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(l.schema,l),o&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=l),s&&this.validateSchema(e,!0),l}_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):is.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{is.compileSchema.call(this,e)}finally{this.opts=n}}};ls.ValidationError=vT.default;ls.MissingRefError=mg.default;Le.default=ls;function hg(t,e,n,r="error"){for(let s in t){let o=s;o in e&&this.logger[r](`${n}: option ${s}. ${t[o]}`)}}function fg(t){return t=(0,as.normalizeId)(t),this.schemas[t]||this.refs[t]}function PT(){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 AT(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function IT(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 n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function CT(){let t={...this.opts};for(let e of xT)delete t[e];return t}var OT={log(){},warn(){},error(){}};function NT(t){if(t===!1)return OT;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 LT=/^[a-z_$][a-z0-9_$:-]*$/i;function jT(t,e){let{RULES:n}=this;if((0,Lc.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!LT.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Nc(t,e,n){var r;let s=e?.post;if(n&&s)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:o}=this,i=s?o.post:o.rules.find(({type:l})=>l===n);if(i||(i={type:n,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,ai.getJSONTypes)(e.type),schemaType:(0,ai.getJSONTypes)(e.schemaType)}};e.before?DT.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(l=>this.addKeyword(l))}function DT(t,e,n){let r=t.rules.findIndex(s=>s.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function UT(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=bg(e)),t.validateSchema=this.compile(e,!0))}var MT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function bg(t){return{anyOf:[t,MT]}}});var wg=M(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var qT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jc.default=qT});var _g=M(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.callRef=Rn.getValidate=void 0;var zT=ss(),vg=ct(),Ze=te(),or=Ut(),kg=ti(),li=ue(),BT={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:l}=r,{root:u}=o;if((n==="#"||n==="#/")&&s===u.baseId)return m();let p=kg.resolveRef.call(l,u,s,n);if(p===void 0)throw new zT.default(r.opts.uriResolver,s,n);if(p instanceof kg.SchemaEnv)return S(p);return b(p);function m(){if(o===u)return ci(t,i,o,o.$async);let _=e.scopeValue("root",{ref:u});return ci(t,(0,Ze._)`${_}.validate`,u,u.$async)}function S(_){let R=Sg(t,_);ci(t,R,_,_.$async)}function b(_){let R=e.scopeValue("schema",a.code.source===!0?{ref:_,code:(0,Ze.stringify)(_)}:{ref:_}),T=e.name("valid"),P=t.subschema({schema:_,dataTypes:[],schemaPath:Ze.nil,topSchemaRef:R,errSchemaPath:n},T);t.mergeEvaluated(P),t.ok(T)}}};function Sg(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Ze._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Rn.getValidate=Sg;function ci(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,u=l.passContext?or.default.this:Ze.nil;r?p():m();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let _=s.let("valid");s.try(()=>{s.code((0,Ze._)`await ${(0,vg.callValidateCode)(t,e,u)}`),b(e),i||s.assign(_,!0)},R=>{s.if((0,Ze._)`!(${R} instanceof ${o.ValidationError})`,()=>s.throw(R)),S(R),i||s.assign(_,!1)}),t.ok(_)}function m(){t.result((0,vg.callValidateCode)(t,e,u),()=>b(e),()=>S(e))}function S(_){let R=(0,Ze._)`${_}.errors`;s.assign(or.default.vErrors,(0,Ze._)`${or.default.vErrors} === null ? ${R} : ${or.default.vErrors}.concat(${R})`),s.assign(or.default.errors,(0,Ze._)`${or.default.vErrors}.length`)}function b(_){var R;if(!o.opts.unevaluated)return;let T=(R=n?.validate)===null||R===void 0?void 0:R.evaluated;if(o.props!==!0)if(T&&!T.dynamicProps)T.props!==void 0&&(o.props=li.mergeEvaluated.props(s,T.props,o.props));else{let P=s.var("props",(0,Ze._)`${_}.evaluated.props`);o.props=li.mergeEvaluated.props(s,P,o.props,Ze.Name)}if(o.items!==!0)if(T&&!T.dynamicItems)T.items!==void 0&&(o.items=li.mergeEvaluated.items(s,T.items,o.items));else{let P=s.var("items",(0,Ze._)`${_}.evaluated.items`);o.items=li.mergeEvaluated.items(s,P,o.items,Ze.Name)}}}Rn.callRef=ci;Rn.default=BT});var xg=M(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var FT=wg(),HT=_g(),KT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",FT.default,HT.default];Dc.default=KT});var $g=M(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var di=te(),an=di.operators,ui={maximum:{okStr:"<=",ok:an.LTE,fail:an.GT},minimum:{okStr:">=",ok:an.GTE,fail:an.LT},exclusiveMaximum:{okStr:"<",ok:an.LT,fail:an.GTE},exclusiveMinimum:{okStr:">",ok:an.GT,fail:an.LTE}},VT={message:({keyword:t,schemaCode:e})=>(0,di.str)`must be ${ui[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,di._)`{comparison: ${ui[t].okStr}, limit: ${e}}`},WT={keyword:Object.keys(ui),type:"number",schemaType:"number",$data:!0,error:VT,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,di._)`${n} ${ui[e].fail} ${r} || isNaN(${n})`)}};Uc.default=WT});var Rg=M(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var cs=te(),GT={message:({schemaCode:t})=>(0,cs.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,cs._)`{multipleOf: ${t}}`},JT={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:GT,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,cs._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,cs._)`${i} !== parseInt(${i})`;t.fail$data((0,cs._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Mc.default=JT});var Eg=M(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});function Tg(t){let e=t.length,n=0,r=0,s;for(;r<e;)n++,s=t.charCodeAt(r++),s>=55296&&s<=56319&&r<e&&(s=t.charCodeAt(r),(s&64512)===56320&&r++);return n}qc.default=Tg;Tg.code='require("ajv/dist/runtime/ucs2length").default'});var Pg=M(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var Tn=te(),YT=ue(),XT=Eg(),ZT={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Tn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Tn._)`{limit: ${t}}`},QT={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:ZT,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?Tn.operators.GT:Tn.operators.LT,i=s.opts.unicode===!1?(0,Tn._)`${n}.length`:(0,Tn._)`${(0,YT.useFunc)(t.gen,XT.default)}(${n})`;t.fail$data((0,Tn._)`${i} ${o} ${r}`)}};zc.default=QT});var Ag=M(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var eE=ct(),tE=ue(),ir=te(),nE={message:({schemaCode:t})=>(0,ir.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ir._)`{pattern: ${t}}`},rE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:nE,code(t){let{gen:e,data:n,$data:r,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,ir._)`new RegExp`:(0,tE.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,ir._)`${u}(${o}, ${a}).test(${n})`),()=>e.assign(p,!1)),t.fail$data((0,ir._)`!${p}`)}else{let l=(0,eE.usePattern)(t,s);t.fail$data((0,ir._)`!${l}.test(${n})`)}}};Bc.default=rE});var Ig=M(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var ds=te(),sE={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,ds.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,ds._)`{limit: ${t}}`},oE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:sE,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?ds.operators.GT:ds.operators.LT;t.fail$data((0,ds._)`Object.keys(${n}).length ${s} ${r}`)}};Fc.default=oE});var Cg=M(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var us=ct(),ps=te(),iE=ue(),aE={message:({params:{missingProperty:t}})=>(0,ps.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ps._)`{missingProperty: ${t}}`},lE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:aE,code(t){let{gen:e,schema:n,schemaCode:r,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&n.length===0)return;let l=n.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let b=t.parentSchema.properties,{definedProperties:_}=t.it;for(let R of n)if(b?.[R]===void 0&&!_.has(R)){let T=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${R}" is not defined at "${T}" (strictRequired)`;(0,iE.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(ps.nil,m);else for(let b of n)(0,us.checkReportMissingProp)(t,b)}function p(){let b=e.let("missing");if(l||o){let _=e.let("valid",!0);t.block$data(_,()=>S(b,_)),t.ok(_)}else e.if((0,us.checkMissingProp)(t,n,b)),(0,us.reportMissingProp)(t,b),e.else()}function m(){e.forOf("prop",r,b=>{t.setParams({missingProperty:b}),e.if((0,us.noPropertyInData)(e,s,b,a.ownProperties),()=>t.error())})}function S(b,_){t.setParams({missingProperty:b}),e.forOf(b,r,()=>{e.assign(_,(0,us.propertyInData)(e,s,b,a.ownProperties)),e.if((0,ps.not)(_),()=>{t.error(),e.break()})},ps.nil)}}};Hc.default=lE});var Og=M(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var hs=te(),cE={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,hs.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,hs._)`{limit: ${t}}`},dE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:cE,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?hs.operators.GT:hs.operators.LT;t.fail$data((0,hs._)`${n}.length ${s} ${r}`)}};Kc.default=dE});var pi=M(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var Ng=mc();Ng.code='require("ajv/dist/runtime/equal").default';Vc.default=Ng});var Lg=M(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Wc=Qr(),je=te(),uE=ue(),pE=pi(),hE={message:({params:{i:t,j:e}})=>(0,je.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,je._)`{i: ${t}, j: ${e}}`},fE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:hE,code(t){let{gen:e,data:n,$data:r,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!r&&!s)return;let l=e.let("valid"),u=o.items?(0,Wc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,je._)`${i} === false`),t.ok(l);function p(){let _=e.let("i",(0,je._)`${n}.length`),R=e.let("j");t.setParams({i:_,j:R}),e.assign(l,!0),e.if((0,je._)`${_} > 1`,()=>(m()?S:b)(_,R))}function m(){return u.length>0&&!u.some(_=>_==="object"||_==="array")}function S(_,R){let T=e.name("item"),P=(0,Wc.checkDataTypes)(u,T,a.opts.strictNumbers,Wc.DataType.Wrong),N=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${_}--;`,()=>{e.let(T,(0,je._)`${n}[${_}]`),e.if(P,(0,je._)`continue`),u.length>1&&e.if((0,je._)`typeof ${T} == "string"`,(0,je._)`${T} += "_"`),e.if((0,je._)`typeof ${N}[${T}] == "number"`,()=>{e.assign(R,(0,je._)`${N}[${T}]`),t.error(),e.assign(l,!1).break()}).code((0,je._)`${N}[${T}] = ${_}`)})}function b(_,R){let T=(0,uE.useFunc)(e,pE.default),P=e.name("outer");e.label(P).for((0,je._)`;${_}--;`,()=>e.for((0,je._)`${R} = ${_}; ${R}--;`,()=>e.if((0,je._)`${T}(${n}[${_}], ${n}[${R}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Gc.default=fE});var jg=M(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Jc=te(),mE=ue(),gE=pi(),bE={message:"must be equal to constant",params:({schemaCode:t})=>(0,Jc._)`{allowedValue: ${t}}`},yE={keyword:"const",$data:!0,error:bE,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,Jc._)`!${(0,mE.useFunc)(e,gE.default)}(${n}, ${s})`):t.fail((0,Jc._)`${o} !== ${n}`)}};Yc.default=yE});var Dg=M(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var fs=te(),wE=ue(),vE=pi(),kE={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,fs._)`{allowedValues: ${t}}`},SE={keyword:"enum",schemaType:"array",$data:!0,error:kE,code(t){let{gen:e,data:n,$data:r,schema:s,schemaCode:o,it:i}=t;if(!r&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,l,u=()=>l??(l=(0,wE.useFunc)(e,vE.default)),p;if(a||r)p=e.let("valid"),t.block$data(p,m);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let b=e.const("vSchema",o);p=(0,fs.or)(...s.map((_,R)=>S(b,R)))}t.pass(p);function m(){e.assign(p,!1),e.forOf("v",o,b=>e.if((0,fs._)`${u()}(${n}, ${b})`,()=>e.assign(p,!0).break()))}function S(b,_){let R=s[_];return typeof R=="object"&&R!==null?(0,fs._)`${u()}(${n}, ${b}[${_}])`:(0,fs._)`${n} === ${R}`}}};Xc.default=SE});var Ug=M(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var _E=$g(),xE=Rg(),$E=Pg(),RE=Ag(),TE=Ig(),EE=Cg(),PE=Og(),AE=Lg(),IE=jg(),CE=Dg(),OE=[_E.default,xE.default,$E.default,RE.default,TE.default,EE.default,PE.default,AE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},IE.default,CE.default];Zc.default=OE});var ed=M(ms=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});ms.validateAdditionalItems=void 0;var En=te(),Qc=ue(),NE={message:({params:{len:t}})=>(0,En.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,En._)`{limit: ${t}}`},LE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:NE,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Qc.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Mg(t,r)}};function Mg(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,En._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,En._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Qc.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,En._)`${a} <= ${e.length}`);n.if((0,En.not)(u),()=>l(u)),t.ok(u)}function l(u){n.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Qc.Type.Num},u),i.allErrors||n.if((0,En.not)(u),()=>n.break())})}}ms.validateAdditionalItems=Mg;ms.default=LE});var td=M(gs=>{"use strict";Object.defineProperty(gs,"__esModule",{value:!0});gs.validateTuple=void 0;var qg=te(),hi=ue(),jE=ct(),DE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return zg(t,"additionalItems",e);n.items=!0,!(0,hi.alwaysValidSchema)(n,e)&&t.ok((0,jE.validateArray)(t))}};function zg(t,e,n=t.schema){let{gen:r,parentSchema:s,data:o,keyword:i,it:a}=t;p(s),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=hi.mergeEvaluated.items(r,n.length,a.items));let l=r.name("valid"),u=r.const("len",(0,qg._)`${o}.length`);n.forEach((m,S)=>{(0,hi.alwaysValidSchema)(a,m)||(r.if((0,qg._)`${u} > ${S}`,()=>t.subschema({keyword:i,schemaProp:S,dataProp:S},l)),t.ok(l))});function p(m){let{opts:S,errSchemaPath:b}=a,_=n.length,R=_===m.minItems&&(_===m.maxItems||m[e]===!1);if(S.strictTuples&&!R){let T=`"${i}" is ${_}-tuple, but minItems or maxItems/${e} are not specified or different at path "${b}"`;(0,hi.checkStrictMode)(a,T,S.strictTuples)}}}gs.validateTuple=zg;gs.default=DE});var Bg=M(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var UE=td(),ME={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,UE.validateTuple)(t,"items")};nd.default=ME});var Hg=M(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var Fg=te(),qE=ue(),zE=ct(),BE=ed(),FE={message:({params:{len:t}})=>(0,Fg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Fg._)`{limit: ${t}}`},HE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:FE,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,qE.alwaysValidSchema)(r,e)&&(s?(0,BE.validateAdditionalItems)(t,s):t.ok((0,zE.validateArray)(t)))}};rd.default=HE});var Kg=M(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var ut=te(),fi=ue(),KE={message:({params:{min:t,max:e}})=>e===void 0?(0,ut.str)`must contain at least ${t} valid item(s)`:(0,ut.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ut._)`{minContains: ${t}}`:(0,ut._)`{minContains: ${t}, maxContains: ${e}}`},VE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:KE,code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t,i,a,{minContains:l,maxContains:u}=r;o.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=e.const("len",(0,ut._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,fi.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,fi.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,fi.alwaysValidSchema)(o,n)){let R=(0,ut._)`${p} >= ${i}`;a!==void 0&&(R=(0,ut._)`${R} && ${p} <= ${a}`),t.pass(R);return}o.items=!0;let m=e.name("valid");a===void 0&&i===1?b(m,()=>e.if(m,()=>e.break())):i===0?(e.let(m,!0),a!==void 0&&e.if((0,ut._)`${s}.length > 0`,S)):(e.let(m,!1),S()),t.result(m,()=>t.reset());function S(){let R=e.name("_valid"),T=e.let("count",0);b(R,()=>e.if(R,()=>_(T)))}function b(R,T){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:fi.Type.Num,compositeRule:!0},R),T()})}function _(R){e.code((0,ut._)`${R}++`),a===void 0?e.if((0,ut._)`${R} >= ${i}`,()=>e.assign(m,!0).break()):(e.if((0,ut._)`${R} > ${a}`,()=>e.assign(m,!1).break()),i===1?e.assign(m,!0):e.if((0,ut._)`${R} >= ${i}`,()=>e.assign(m,!0)))}}};sd.default=VE});var Gg=M(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.validateSchemaDeps=Pt.validatePropertyDeps=Pt.error=void 0;var od=te(),WE=ue(),bs=ct();Pt.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,od.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,od._)`{property: ${t},
1998
- missingProperty: ${r},
2001
+ `});import*as Km from"zod/v3";import*as fr from"zod/v4-mini";function $t(t){return!!t._zod}function gr(t){let e=Object.values(t);if(e.length===0)return fr.object({});let r=e.every($t),n=e.every(o=>!$t(o));if(r)return fr.object(t);if(n)return Km.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Jt(t,e){return $t(t)?fr.safeParse(t,e):t.safeParse(e)}async function as(t,e){return $t(t)?await fr.safeParseAsync(t,e):await t.safeParseAsync(e)}function Yt(t){if(!t)return;let e;if($t(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function zr(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 gr(t)}}if($t(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 VS(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function ls(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 ${VS(e.path)}`:e.message).join(`
2002
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Vm(t){return t.description}function Wm(t){if($t(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Br(t){if($t(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 Cn=j(()=>{});import*as c from"zod/v4";function dh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function uh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var za,Gm,Xt,ds,Re,Jm,Ym,eN,WS,GS,Ba,et,In,Xm,Oe,st,it,Ne,us,Zm,Fa,Qm,eh,Ha,On,W,Ka,th,rh,tN,ps,JS,ms,YS,Nn,Fr,nh,XS,ZS,QS,ek,tk,rk,Va,nk,ok,Wa,hs,sk,ik,fs,ak,Ln,jn,lk,Dn,Hr,ck,Un,gs,ys,bs,rN,ws,vs,_s,oh,sh,ih,Ga,ah,Mn,Kr,lh,dk,Ss,uk,ks,pk,Ja,mk,Ts,hk,fk,gk,yk,bk,wk,vk,_k,Sk,kk,xs,Tk,xk,$s,Ya,Xa,Za,$k,Rk,Ek,Qa,Pk,Ak,Ck,Ik,Ok,ch,Rs,Nk,Es,nN,Lk,Vr,jk,oN,qn,Dk,el,Uk,Mk,qk,zk,Bk,Fk,Hk,cs,Kk,Vk,Wk,zn,tl,Gk,Jk,Yk,Xk,Zk,Qk,eT,tT,rT,nT,oT,sT,iT,aT,lT,cT,dT,uT,Wr,pT,mT,hT,Ps,fT,gT,yT,rl,bT,sN,iN,aN,lN,cN,dN,B,qa,Gr=j(()=>{za="2025-11-25",Gm=[za,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Xt="io.modelcontextprotocol/related-task",ds="2.0",Re=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Jm=c.union([c.string(),c.number().int()]),Ym=c.string(),eN=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),WS=c.object({ttl:c.number().optional()}),GS=c.object({taskId:c.string()}),Ba=c.looseObject({progressToken:Jm.optional(),[Xt]:GS.optional()}),et=c.object({_meta:Ba.optional()}),In=et.extend({task:WS.optional()}),Xm=t=>In.safeParse(t).success,Oe=c.object({method:c.string(),params:et.loose().optional()}),st=c.object({_meta:Ba.optional()}),it=c.object({method:c.string(),params:st.loose().optional()}),Ne=c.looseObject({_meta:Ba.optional()}),us=c.union([c.string(),c.number().int()]),Zm=c.object({jsonrpc:c.literal(ds),id:us,...Oe.shape}).strict(),Fa=t=>Zm.safeParse(t).success,Qm=c.object({jsonrpc:c.literal(ds),...it.shape}).strict(),eh=t=>Qm.safeParse(t).success,Ha=c.object({jsonrpc:c.literal(ds),id:us,result:Ne}).strict(),On=t=>Ha.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"})(W||(W={}));Ka=c.object({jsonrpc:c.literal(ds),id:us.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),th=t=>Ka.safeParse(t).success,rh=c.union([Zm,Qm,Ha,Ka]),tN=c.union([Ha,Ka]),ps=Ne.strict(),JS=st.extend({requestId:us.optional(),reason:c.string().optional()}),ms=it.extend({method:c.literal("notifications/cancelled"),params:JS}),YS=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Nn=c.object({icons:c.array(YS).optional()}),Fr=c.object({name:c.string(),title:c.string().optional()}),nh=Fr.extend({...Fr.shape,...Nn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),XS=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),ZS=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:XS.optional(),url:Re.optional()}),c.record(c.string(),c.unknown()).optional())),QS=c.looseObject({list:Re.optional(),cancel:Re.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Re.optional()}).optional(),elicitation:c.looseObject({create:Re.optional()}).optional()}).optional()}),ek=c.looseObject({list:Re.optional(),cancel:Re.optional(),requests:c.looseObject({tools:c.looseObject({call:Re.optional()}).optional()}).optional()}),tk=c.object({experimental:c.record(c.string(),Re).optional(),sampling:c.object({context:Re.optional(),tools:Re.optional()}).optional(),elicitation:ZS.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:QS.optional(),extensions:c.record(c.string(),Re).optional()}),rk=et.extend({protocolVersion:c.string(),capabilities:tk,clientInfo:nh}),Va=Oe.extend({method:c.literal("initialize"),params:rk}),nk=c.object({experimental:c.record(c.string(),Re).optional(),logging:Re.optional(),completions:Re.optional(),prompts:c.object({listChanged:c.boolean().optional()}).optional(),resources:c.object({subscribe:c.boolean().optional(),listChanged:c.boolean().optional()}).optional(),tools:c.object({listChanged:c.boolean().optional()}).optional(),tasks:ek.optional(),extensions:c.record(c.string(),Re).optional()}),ok=Ne.extend({protocolVersion:c.string(),capabilities:nk,serverInfo:nh,instructions:c.string().optional()}),Wa=it.extend({method:c.literal("notifications/initialized"),params:st.optional()}),hs=Oe.extend({method:c.literal("ping"),params:et.optional()}),sk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),ik=c.object({...st.shape,...sk.shape,progressToken:Jm}),fs=it.extend({method:c.literal("notifications/progress"),params:ik}),ak=et.extend({cursor:Ym.optional()}),Ln=Oe.extend({params:ak.optional()}),jn=Ne.extend({nextCursor:Ym.optional()}),lk=c.enum(["working","input_required","completed","failed","cancelled"]),Dn=c.object({taskId:c.string(),status:lk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Hr=Ne.extend({task:Dn}),ck=st.merge(Dn),Un=it.extend({method:c.literal("notifications/tasks/status"),params:ck}),gs=Oe.extend({method:c.literal("tasks/get"),params:et.extend({taskId:c.string()})}),ys=Ne.merge(Dn),bs=Oe.extend({method:c.literal("tasks/result"),params:et.extend({taskId:c.string()})}),rN=Ne.loose(),ws=Ln.extend({method:c.literal("tasks/list")}),vs=jn.extend({tasks:c.array(Dn)}),_s=Oe.extend({method:c.literal("tasks/cancel"),params:et.extend({taskId:c.string()})}),oh=Ne.merge(Dn),sh=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),ih=sh.extend({text:c.string()}),Ga=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),ah=sh.extend({blob:Ga}),Mn=c.enum(["user","assistant"]),Kr=c.object({audience:c.array(Mn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),lh=c.object({...Fr.shape,...Nn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Kr.optional(),_meta:c.optional(c.looseObject({}))}),dk=c.object({...Fr.shape,...Nn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Kr.optional(),_meta:c.optional(c.looseObject({}))}),Ss=Ln.extend({method:c.literal("resources/list")}),uk=jn.extend({resources:c.array(lh)}),ks=Ln.extend({method:c.literal("resources/templates/list")}),pk=jn.extend({resourceTemplates:c.array(dk)}),Ja=et.extend({uri:c.string()}),mk=Ja,Ts=Oe.extend({method:c.literal("resources/read"),params:mk}),hk=Ne.extend({contents:c.array(c.union([ih,ah]))}),fk=it.extend({method:c.literal("notifications/resources/list_changed"),params:st.optional()}),gk=Ja,yk=Oe.extend({method:c.literal("resources/subscribe"),params:gk}),bk=Ja,wk=Oe.extend({method:c.literal("resources/unsubscribe"),params:bk}),vk=st.extend({uri:c.string()}),_k=it.extend({method:c.literal("notifications/resources/updated"),params:vk}),Sk=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),kk=c.object({...Fr.shape,...Nn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(Sk)),_meta:c.optional(c.looseObject({}))}),xs=Ln.extend({method:c.literal("prompts/list")}),Tk=jn.extend({prompts:c.array(kk)}),xk=et.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),$s=Oe.extend({method:c.literal("prompts/get"),params:xk}),Ya=c.object({type:c.literal("text"),text:c.string(),annotations:Kr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Xa=c.object({type:c.literal("image"),data:Ga,mimeType:c.string(),annotations:Kr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Za=c.object({type:c.literal("audio"),data:Ga,mimeType:c.string(),annotations:Kr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),$k=c.object({type:c.literal("tool_use"),name:c.string(),id:c.string(),input:c.record(c.string(),c.unknown()),_meta:c.record(c.string(),c.unknown()).optional()}),Rk=c.object({type:c.literal("resource"),resource:c.union([ih,ah]),annotations:Kr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ek=lh.extend({type:c.literal("resource_link")}),Qa=c.union([Ya,Xa,Za,Ek,Rk]),Pk=c.object({role:Mn,content:Qa}),Ak=Ne.extend({description:c.string().optional(),messages:c.array(Pk)}),Ck=it.extend({method:c.literal("notifications/prompts/list_changed"),params:st.optional()}),Ik=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Ok=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),ch=c.object({...Fr.shape,...Nn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Re).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Re).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:Ik.optional(),execution:Ok.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Rs=Ln.extend({method:c.literal("tools/list")}),Nk=jn.extend({tools:c.array(ch)}),Es=Ne.extend({content:c.array(Qa).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),nN=Es.or(Ne.extend({toolResult:c.unknown()})),Lk=In.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Vr=Oe.extend({method:c.literal("tools/call"),params:Lk}),jk=it.extend({method:c.literal("notifications/tools/list_changed"),params:st.optional()}),oN=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),qn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Dk=et.extend({level:qn}),el=Oe.extend({method:c.literal("logging/setLevel"),params:Dk}),Uk=st.extend({level:qn,logger:c.string().optional(),data:c.unknown()}),Mk=it.extend({method:c.literal("notifications/message"),params:Uk}),qk=c.object({name:c.string().optional()}),zk=c.object({hints:c.array(qk).optional(),costPriority:c.number().min(0).max(1).optional(),speedPriority:c.number().min(0).max(1).optional(),intelligencePriority:c.number().min(0).max(1).optional()}),Bk=c.object({mode:c.enum(["auto","required","none"]).optional()}),Fk=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Qa).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Hk=c.discriminatedUnion("type",[Ya,Xa,Za]),cs=c.discriminatedUnion("type",[Ya,Xa,Za,$k,Fk]),Kk=c.object({role:Mn,content:c.union([cs,c.array(cs)]),_meta:c.record(c.string(),c.unknown()).optional()}),Vk=In.extend({messages:c.array(Kk),modelPreferences:zk.optional(),systemPrompt:c.string().optional(),includeContext:c.enum(["none","thisServer","allServers"]).optional(),temperature:c.number().optional(),maxTokens:c.number().int(),stopSequences:c.array(c.string()).optional(),metadata:Re.optional(),tools:c.array(ch).optional(),toolChoice:Bk.optional()}),Wk=Oe.extend({method:c.literal("sampling/createMessage"),params:Vk}),zn=Ne.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Mn,content:Hk}),tl=Ne.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Mn,content:c.union([cs,c.array(cs)])}),Gk=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),Jk=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),minLength:c.number().optional(),maxLength:c.number().optional(),format:c.enum(["email","uri","date","date-time"]).optional(),default:c.string().optional()}),Yk=c.object({type:c.enum(["number","integer"]),title:c.string().optional(),description:c.string().optional(),minimum:c.number().optional(),maximum:c.number().optional(),default:c.number().optional()}),Xk=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),Zk=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),oneOf:c.array(c.object({const:c.string(),title:c.string()})),default:c.string().optional()}),Qk=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),enumNames:c.array(c.string()).optional(),default:c.string().optional()}),eT=c.union([Xk,Zk]),tT=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({type:c.literal("string"),enum:c.array(c.string())}),default:c.array(c.string()).optional()}),rT=c.object({type:c.literal("array"),title:c.string().optional(),description:c.string().optional(),minItems:c.number().optional(),maxItems:c.number().optional(),items:c.object({anyOf:c.array(c.object({const:c.string(),title:c.string()}))}),default:c.array(c.string()).optional()}),nT=c.union([tT,rT]),oT=c.union([Qk,eT,nT]),sT=c.union([oT,Gk,Jk,Yk]),iT=In.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),sT),required:c.array(c.string()).optional()})}),aT=In.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),lT=c.union([iT,aT]),cT=Oe.extend({method:c.literal("elicitation/create"),params:lT}),dT=st.extend({elicitationId:c.string()}),uT=it.extend({method:c.literal("notifications/elicitation/complete"),params:dT}),Wr=Ne.extend({action:c.enum(["accept","decline","cancel"]),content:c.preprocess(t=>t===null?void 0:t,c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional())}),pT=c.object({type:c.literal("ref/resource"),uri:c.string()}),mT=c.object({type:c.literal("ref/prompt"),name:c.string()}),hT=et.extend({ref:c.union([mT,pT]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Ps=Oe.extend({method:c.literal("completion/complete"),params:hT});fT=Ne.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),gT=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),yT=Oe.extend({method:c.literal("roots/list"),params:et.optional()}),rl=Ne.extend({roots:c.array(gT)}),bT=it.extend({method:c.literal("notifications/roots/list_changed"),params:st.optional()}),sN=c.union([hs,Va,Ps,el,$s,xs,Ss,ks,Ts,yk,wk,Vr,Rs,gs,bs,ws,_s]),iN=c.union([ms,fs,Wa,bT,Un]),aN=c.union([ps,zn,tl,Wr,rl,ys,vs,Hr]),lN=c.union([hs,Wk,cT,yT,gs,bs,ws,_s]),cN=c.union([ms,fs,Mk,_k,fk,jk,Ck,Un,uT]),dN=c.union([ps,ok,fT,Ak,Tk,uk,pk,hk,Es,Nk,ys,vs,Hr]),B=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===W.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new qa(o.elicitations,r)}return new t(e,r,n)}},qa=class extends B{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Zt(t){return t==="completed"||t==="failed"||t==="cancelled"}var ph=j(()=>{});var hh,mh,fh,As=j(()=>{hh=Symbol("Let zodToJsonSchema decide on which parser to use"),mh={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"},fh=t=>typeof t=="string"?{...mh,name:t}:{...mh,...t}});var gh,nl=j(()=>{As();gh=t=>{let e=fh(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 ol(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function le(t,e,r,n,o){t[e]=r,ol(t,e,n,o)}var Qt=j(()=>{});var Cs,Is=j(()=>{Cs=(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 _e(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Cs(e,t.currentPath):e.join("/")}}var at=j(()=>{Is()});import{ZodFirstPartyTypeKind as wT}from"zod/v3";function yh(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==wT.ZodAny&&(r.items=X(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&le(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&le(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(le(r,"minItems",t.exactLength.value,t.exactLength.message,e),le(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var sl=j(()=>{Qt();$e()});function bh(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?le(r,"minimum",n.value,n.message,e):le(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(r,"maximum",n.value,n.message,e):le(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",n.value,n.message,e));break;case"multipleOf":le(r,"multipleOf",n.value,n.message,e);break}return r}var il=j(()=>{Qt()});function wh(){return{type:"boolean"}}var al=j(()=>{});function Os(t,e){return X(t.type._def,e)}var Ns=j(()=>{$e()});var vh,ll=j(()=>{$e();vh=(t,e)=>X(t.innerType._def,e)});function cl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>cl(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 vT(t,e)}}var vT,dl=j(()=>{Qt();vT=(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":le(r,"minimum",n.value,n.message,e);break;case"max":le(r,"maximum",n.value,n.message,e);break}return r}});function _h(t,e){return{...X(t.innerType._def,e),default:t.defaultValue()}}var ul=j(()=>{$e()});function Sh(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):_e(e)}var pl=j(()=>{$e();at()});function kh(t){return{type:"string",enum:Array.from(t.values)}}var ml=j(()=>{});function Th(t,e){let r=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(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(_T(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,...l}=s;i=l}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var _T,hl=j(()=>{$e();_T=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function xh(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 fl=j(()=>{});function Ls(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":le(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":yt(r,"email",n.message,e);break;case"format:idn-email":yt(r,"idn-email",n.message,e);break;case"pattern:zod":Fe(r,gt.email,n.message,e);break}break;case"url":yt(r,"uri",n.message,e);break;case"uuid":yt(r,"uuid",n.message,e);break;case"regex":Fe(r,n.regex,n.message,e);break;case"cuid":Fe(r,gt.cuid,n.message,e);break;case"cuid2":Fe(r,gt.cuid2,n.message,e);break;case"startsWith":Fe(r,RegExp(`^${yl(n.value,e)}`),n.message,e);break;case"endsWith":Fe(r,RegExp(`${yl(n.value,e)}$`),n.message,e);break;case"datetime":yt(r,"date-time",n.message,e);break;case"date":yt(r,"date",n.message,e);break;case"time":yt(r,"time",n.message,e);break;case"duration":yt(r,"duration",n.message,e);break;case"length":le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Fe(r,RegExp(yl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&yt(r,"ipv4",n.message,e),n.version!=="v4"&&yt(r,"ipv6",n.message,e);break}case"base64url":Fe(r,gt.base64url,n.message,e);break;case"jwt":Fe(r,gt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Fe(r,gt.ipv4Cidr,n.message,e),n.version!=="v4"&&Fe(r,gt.ipv6Cidr,n.message,e);break}case"emoji":Fe(r,gt.emoji(),n.message,e);break;case"ulid":{Fe(r,gt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{yt(r,"binary",n.message,e);break}case"contentEncoding:base64":{le(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Fe(r,gt.base64,n.message,e);break}}break}case"nanoid":Fe(r,gt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function yl(t,e){return e.patternStrategy==="escape"?kT(t):t}function kT(t){let e="";for(let r=0;r<t.length;r++)ST.has(t[r])||(e+="\\"),e+=t[r];return e}function yt(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}}})):le(t,"format",e,r,n)}function Fe(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:$h(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):le(t,"pattern",$h(e,n),r,n)}function $h(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 l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],a=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
2003
+ ]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
2004
+ ]))`;continue}}if(r.s&&n[l]==="."){o+=i?`${n[l]}\r
2005
+ `:`[${n[l]}\r
2006
+ ]`;continue}o+=n[l],n[l]==="\\"?s=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(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 gl,gt,ST,js=j(()=>{Qt();gt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(gl===void 0&&(gl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gl),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-_]*$/};ST=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Bn}from"zod/v3";function Ds(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===Bn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??_e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Bn.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Ls(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Bn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Bn.ZodBranded&&t.keyType._def.type._def.typeName===Bn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Os(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Us=j(()=>{$e();js();Ns();at()});function Rh(t,e){if(e.mapStrategy==="record")return Ds(t,e);let r=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||_e(e),n=X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||_e(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var bl=j(()=>{$e();Us();at()});function Eh(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 wl=j(()=>{});function Ph(t){return t.target==="openAi"?void 0:{not:_e({...t,currentPath:[...t.currentPath,"not"]})}}var vl=j(()=>{at()});function Ah(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var _l=j(()=>{});function Ih(t,e){if(e.target==="openApi3")return Ch(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Fn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Fn[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 Ch(t,e)}var Fn,Ch,Ms=j(()=>{$e();Fn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Ch=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>X(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 Oh(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:Fn[t.innerType._def.typeName],nullable:!0}:{type:[Fn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Sl=j(()=>{$e();Ms()});function Nh(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",ol(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?le(r,"minimum",n.value,n.message,e):le(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(r,"maximum",n.value,n.message,e):le(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",n.value,n.message,e));break;case"multipleOf":le(r,"multipleOf",n.value,n.message,e);break}return r}var kl=j(()=>{Qt()});function Lh(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let l=s[a];if(l===void 0||l._def===void 0)continue;let u=xT(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=X(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,u||o.push(a))}o.length&&(n.required=o);let i=TT(t,e);return i!==void 0&&(n.additionalProperties=i),n}function TT(t,e){if(t.catchall._def.typeName!=="ZodNever")return X(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 xT(t){try{return t.isOptional()}catch{return!0}}var Tl=j(()=>{$e()});var jh,xl=j(()=>{$e();at();jh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:_e(e)},r]}:_e(e)}});var Dh,$l=j(()=>{$e();Dh=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let r=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Uh(t,e){return X(t.type._def,e)}var Rl=j(()=>{$e()});function Mh(t,e){let n={type:"array",uniqueItems:!0,items:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&le(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&le(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var El=j(()=>{Qt();$e()});function qh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Pl=j(()=>{$e()});function zh(t){return{not:_e(t)}}var Al=j(()=>{at()});function Bh(t){return _e(t)}var Cl=j(()=>{at()});var Fh,Il=j(()=>{$e();Fh=(t,e)=>X(t.innerType._def,e)});import{ZodFirstPartyTypeKind as ie}from"zod/v3";var Hh,Ol=j(()=>{at();sl();il();al();Ns();ll();dl();ul();pl();ml();hl();fl();bl();wl();vl();_l();Sl();kl();Tl();xl();$l();Rl();Us();El();js();Pl();Al();Ms();Cl();Il();Hh=(t,e,r)=>{switch(e){case ie.ZodString:return Ls(t,r);case ie.ZodNumber:return Nh(t,r);case ie.ZodObject:return Lh(t,r);case ie.ZodBigInt:return bh(t,r);case ie.ZodBoolean:return wh();case ie.ZodDate:return cl(t,r);case ie.ZodUndefined:return zh(r);case ie.ZodNull:return Ah(r);case ie.ZodArray:return yh(t,r);case ie.ZodUnion:case ie.ZodDiscriminatedUnion:return Ih(t,r);case ie.ZodIntersection:return Th(t,r);case ie.ZodTuple:return qh(t,r);case ie.ZodRecord:return Ds(t,r);case ie.ZodLiteral:return xh(t,r);case ie.ZodEnum:return kh(t);case ie.ZodNativeEnum:return Eh(t);case ie.ZodNullable:return Oh(t,r);case ie.ZodOptional:return jh(t,r);case ie.ZodMap:return Rh(t,r);case ie.ZodSet:return Mh(t,r);case ie.ZodLazy:return()=>t.getter()._def;case ie.ZodPromise:return Uh(t,r);case ie.ZodNaN:case ie.ZodNever:return Ph(r);case ie.ZodEffects:return Sh(t,r);case ie.ZodAny:return _e(r);case ie.ZodUnknown:return Bh(r);case ie.ZodDefault:return _h(t,r);case ie.ZodBranded:return Os(t,r);case ie.ZodReadonly:return Fh(t,r);case ie.ZodCatch:return vh(t,r);case ie.ZodPipeline:return Dh(t,r);case ie.ZodFunction:case ie.ZodVoid:case ie.ZodSymbol:return;default:return(n=>{})(e)}}});function X(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==hh)return a}if(n&&!r){let a=$T(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=Hh(t,t.typeName,e),i=typeof s=="function"?X(s(),e):s;if(i&&RT(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var $T,RT,$e=j(()=>{As();Ol();Is();at();$T=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Cs(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`),_e(e)):e.$refStrategy==="seen"?_e(e):void 0}},RT=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Kh=j(()=>{});var Nl,Ll=j(()=>{$e();nl();at();Nl=(t,e)=>{let r=gh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:X(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??_e(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=X(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??_e(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 Vh=j(()=>{As();nl();Qt();Is();$e();Kh();at();sl();il();al();Ns();ll();dl();ul();pl();ml();hl();fl();bl();wl();vl();_l();Sl();kl();Tl();xl();$l();Rl();Il();Us();El();js();Pl();Al();Ms();Cl();Ol();Ll();Ll()});import*as Wh from"zod/v4-mini";function ET(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function jl(t,e){return $t(t)?Wh.toJSONSchema(t,{target:ET(e?.target),io:e?.pipeStrategy??"input"}):Nl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Dl(t){let r=Yt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Br(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Ul(t,e){let r=Jt(t,e);if(!r.success)throw r.error;return r.data}var Ml=j(()=>{Cn();Vh()});function Gh(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Jh(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];Gh(i)&&Gh(s)?r[o]={...i,...s}:r[o]=s}return r}var PT,qs,Yh=j(()=>{Cn();Gr();ph();Ml();PT=6e4,qs=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(ms,r=>{this._oncancel(r)}),this.setNotificationHandler(fs,r=>{this._onprogress(r)}),this.setRequestHandler(hs,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gs,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(W.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(bs,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 l=a.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(l);else{let f=l,S=new B(f.error.code,f.error.message,f.error.data);p(S)}else{let f=a.type==="response"?"Response":"Error";this._onerror(new Error(`${f} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new B(W.InvalidParams,`Task not found: ${s}`);if(!Zt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Zt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Xt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ws,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 B(W.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(_s,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(Zt(o.status))throw new B(W.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 B(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof B?o:new B(W.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),B.fromError(W.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),On(s)||th(s)?this._onresponse(s):Fa(s)?this._onrequest(s,i):eh(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=B.fromError(W.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?.[Xt]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:W.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):o?.send(p).catch(f=>this._onerror(new Error(`Failed to send an error response: ${f}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Xm(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let f={relatedRequestId:e.id};s&&(f.relatedTask={taskId:s}),await this.notification(p,f)},sendRequest:async(p,f,S)=>{if(i.signal.aborted)throw new B(W.ConnectionClosed,"Request was cancelled");let y={...S,relatedRequestId:e.id};s&&!y.relatedTask&&(y.relatedTask={taskId:s});let k=y.relatedTask?.taskId??s;return k&&l&&await l.updateTaskStatus(k,"input_required"),await this.request(p,f,y)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async p=>{if(i.signal.aborted)return;let f={result:p,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)},async p=>{if(i.signal.aborted)return;let f={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:W.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:f,timestamp:Date.now()},o?.sessionId):await o?.send(f)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).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(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),On(e))n(e);else{let i=new B(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(On(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),On(e))o(e);else{let i=B.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 B?i:new B(W.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Hr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new B(W.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Zt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new B(W.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(W.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof B?i:new B(W.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((u,p)=>{let f=O=>{p(O)};if(!this._transport){f(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(O){f(O);return}n?.signal?.throwIfAborted();let S=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:S};n?.onprogress&&(this._progressHandlers.set(S,n.onprogress),y.params={...e.params,_meta:{...e.params?._meta||{},progressToken:S}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[Xt]:l}});let k=O=>{this._responseHandlers.delete(S),this._progressHandlers.delete(S),this._cleanupTimeout(S),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:S,reason:String(O)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(Y=>this._onerror(new Error(`Failed to send cancellation: ${Y}`)));let D=O instanceof B?O:new B(W.RequestTimeout,String(O));p(D)};this._responseHandlers.set(S,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return p(O);try{let D=Jt(r,O.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{k(n?.signal?.reason)});let $=n?.timeout??PT,R=()=>k(B.fromError(W.RequestTimeout,"Request timed out",{timeout:$}));this._setupTimeout(S,$,n?.maxTotalTimeout,R,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let O=D=>{let Y=this._responseHandlers.get(S);Y?Y(D):this._onerror(new Error(`Response handler missing for side-channeled request ${S}`))};this._requestResolvers.set(S,O),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(S),p(D)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(O=>{this._cleanupTimeout(S),p(O)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ys,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},vs,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},oh,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||{},[Xt]: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||{},[Xt]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Xt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Dl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Ul(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=Dl(e);this._notificationHandlers.set(n,o=>{let s=Ul(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"&&Fa(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new B(W.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 B(W.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new B(W.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 B(W.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 l=Un.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Zt(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 B(W.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Zt(a.status))throw new B(W.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 l=await n.getTask(o,r);if(l){let u=Un.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Zt(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Vn=M(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.regexpCode=me.getEsmExportName=me.getProperty=me.safeStringify=me.stringify=me.strConcat=me.addCodeArg=me.str=me._=me.nil=me._Code=me.Name=me.IDENTIFIER=me._CodeOrName=void 0;var Hn=class{};me._CodeOrName=Hn;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var yr=class extends Hn{constructor(e){if(super(),!me.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}}};me.Name=yr;var lt=class extends Hn{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 yr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=lt;me.nil=new lt("");function Xh(t,...e){let r=[t[0]],n=0;for(;n<e.length;)zl(r,e[n]),r.push(t[++n]);return new lt(r)}me._=Xh;var ql=new lt("+");function Zh(t,...e){let r=[Kn(t[0])],n=0;for(;n<e.length;)r.push(ql),zl(r,e[n]),r.push(ql,Kn(t[++n]));return AT(r),new lt(r)}me.str=Zh;function zl(t,e){e instanceof lt?t.push(...e._items):e instanceof yr?t.push(e):t.push(OT(e))}me.addCodeArg=zl;function AT(t){let e=1;for(;e<t.length-1;){if(t[e]===ql){let r=CT(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function CT(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof yr||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 yr))return`"${t}${e.slice(1)}`}function IT(t,e){return e.emptyStr()?t:t.emptyStr()?e:Zh`${t}${e}`}me.strConcat=IT;function OT(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Kn(Array.isArray(t)?t.join(","):t)}function NT(t){return new lt(Kn(t))}me.stringify=NT;function Kn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=Kn;function LT(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new lt(`.${t}`):Xh`[${t}]`}me.getProperty=LT;function jT(t){if(typeof t=="string"&&me.IDENTIFIER.test(t))return new lt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}me.getEsmExportName=jT;function DT(t){return new lt(t.toString())}me.regexpCode=DT});var Hl=M(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.ValueScope=Ye.ValueScopeName=Ye.Scope=Ye.varKinds=Ye.UsedValueState=void 0;var Je=Vn(),Bl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},zs;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(zs||(Ye.UsedValueState=zs={}));Ye.varKinds={const:new Je.Name("const"),let:new Je.Name("let"),var:new Je.Name("var")};var Bs=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Je.Name?e:this.name(e)}name(e){return new Je.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}}};Ye.Scope=Bs;var Fs=class extends Je.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Je._)`.${new Je.Name(r)}[${n}]`}};Ye.ValueScopeName=Fs;var UT=(0,Je._)`\n`,Fl=class extends Bs{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?UT:Je.nil}}get(){return this._scope}name(e){return new Fs(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 p=a.get(i);if(p)return p}else a=this._values[s]=new Map;a.set(i,o);let l=this._scope[s]||(this._scope[s]=[]),u=l.length;return l[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),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,Je._)`${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=Je.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(u=>{if(l.has(u))return;l.set(u,zs.Started);let p=r(u);if(p){let f=this.opts.es5?Ye.varKinds.var:Ye.varKinds.const;s=(0,Je._)`${s}${f} ${u} = ${p};${this.opts._n}`}else if(p=o?.(u))s=(0,Je._)`${s}${p}${this.opts._n}`;else throw new Bl(u);l.set(u,zs.Completed)})}return s}};Ye.ValueScope=Fl});var te=M(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.or=re.and=re.not=re.CodeGen=re.operators=re.varKinds=re.ValueScopeName=re.ValueScope=re.Scope=re.Name=re.regexpCode=re.stringify=re.getProperty=re.nil=re.strConcat=re.str=re._=void 0;var ce=Vn(),bt=Hl(),er=Vn();Object.defineProperty(re,"_",{enumerable:!0,get:function(){return er._}});Object.defineProperty(re,"str",{enumerable:!0,get:function(){return er.str}});Object.defineProperty(re,"strConcat",{enumerable:!0,get:function(){return er.strConcat}});Object.defineProperty(re,"nil",{enumerable:!0,get:function(){return er.nil}});Object.defineProperty(re,"getProperty",{enumerable:!0,get:function(){return er.getProperty}});Object.defineProperty(re,"stringify",{enumerable:!0,get:function(){return er.stringify}});Object.defineProperty(re,"regexpCode",{enumerable:!0,get:function(){return er.regexpCode}});Object.defineProperty(re,"Name",{enumerable:!0,get:function(){return er.Name}});var Ws=Hl();Object.defineProperty(re,"Scope",{enumerable:!0,get:function(){return Ws.Scope}});Object.defineProperty(re,"ValueScope",{enumerable:!0,get:function(){return Ws.ValueScope}});Object.defineProperty(re,"ValueScopeName",{enumerable:!0,get:function(){return Ws.ValueScopeName}});Object.defineProperty(re,"varKinds",{enumerable:!0,get:function(){return Ws.varKinds}});re.operators={GT:new ce._Code(">"),GTE:new ce._Code(">="),LT:new ce._Code("<"),LTE:new ce._Code("<="),EQ:new ce._Code("==="),NEQ:new ce._Code("!=="),NOT:new ce._Code("!"),OR:new ce._Code("||"),AND:new ce._Code("&&"),ADD:new ce._Code("+")};var jt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Kl=class extends jt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?bt.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=Yr(this.rhs,e,r)),this}get names(){return this.rhs instanceof ce._CodeOrName?this.rhs.names:{}}},Hs=class extends jt{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 ce.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Yr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ce.Name?{}:{...this.lhs.names};return Vs(e,this.rhs)}},Vl=class extends Hs{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wl=class extends jt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gl=class extends jt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Jl=class extends jt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yl=class extends jt{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=Yr(this.code,e,r),this}get names(){return this.code instanceof ce._CodeOrName?this.code.names:{}}},Wn=class extends jt{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)||(MT(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>vr(e,r.names),{})}},Dt=class extends Wn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Xl=class extends Wn{},Jr=class extends Dt{};Jr.kind="else";var br=class t extends Dt{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 Jr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Qh(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=Yr(this.condition,e,r),this}get names(){let e=super.names;return Vs(e,this.condition),this.else&&vr(e,this.else.names),e}};br.kind="if";var wr=class extends Dt{};wr.kind="for";var Zl=class extends wr{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=Yr(this.iteration,e,r),this}get names(){return vr(super.names,this.iteration.names)}},Ql=class extends wr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?bt.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=Vs(super.names,this.from);return Vs(e,this.to)}},Ks=class extends wr{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=Yr(this.iterable,e,r),this}get names(){return vr(super.names,this.iterable.names)}},Gn=class extends Dt{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)}};Gn.kind="func";var Jn=class extends Wn{render(e){return"return "+super.render(e)}};Jn.kind="return";var ec=class extends Dt{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&&vr(e,this.catch.names),this.finally&&vr(e,this.finally.names),e}},Yn=class extends Dt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Yn.kind="catch";var Xn=class extends Dt{render(e){return"finally"+super.render(e)}};Xn.kind="finally";var tc=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2007
+ `:""},this._extScope=e,this._scope=new bt.Scope({parent:e}),this._nodes=[new Xl]}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 Kl(e,s,n)),s}const(e,r,n){return this._def(bt.varKinds.const,e,r,n)}let(e,r,n){return this._def(bt.varKinds.let,e,r,n)}var(e,r,n){return this._def(bt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Hs(e,r,n))}add(e,r){return this._leafNode(new Vl(e,re.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new Yl(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,ce.addCodeArg)(r,o));return r.push("}"),new ce._Code(r)}if(e,r,n){if(this._blockNode(new br(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 br(e))}else(){return this._elseNode(new Jr)}endIf(){return this._endBlockNode(br,Jr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Zl(e),r)}forRange(e,r,n,o,s=this.opts.es5?bt.varKinds.var:bt.varKinds.let){let i=this._scope.toName(e);return this._for(new Ql(s,i,r,n),()=>o(i))}forOf(e,r,n,o=bt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ce.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ce._)`${i}.length`,a=>{this.var(s,(0,ce._)`${i}[${a}]`),n(s)})}return this._for(new Ks("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?bt.varKinds.var:bt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ce._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ks("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(wr)}label(e){return this._leafNode(new Wl(e))}break(e){return this._leafNode(new Gl(e))}return(e){let r=new Jn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Jn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ec;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Yn(s),r(s)}return n&&(this._currNode=o.finally=new Xn,this.code(n)),this._endBlockNode(Yn,Xn)}throw(e){return this._leafNode(new Jl(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=ce.nil,n,o){return this._blockNode(new Gn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Gn)}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 br))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}};re.CodeGen=tc;function vr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Vs(t,e){return e instanceof ce._CodeOrName?vr(t,e.names):t}function Yr(t,e,r){if(t instanceof ce.Name)return n(t);if(!o(t))return t;return new ce._Code(t._items.reduce((s,i)=>(i instanceof ce.Name&&(i=n(i)),i instanceof ce._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 ce._Code&&s._items.some(i=>i instanceof ce.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function MT(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Qh(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${rc(t)}`}re.not=Qh;var qT=ef(re.operators.AND);function zT(...t){return t.reduce(qT)}re.and=zT;var BT=ef(re.operators.OR);function FT(...t){return t.reduce(BT)}re.or=FT;function ef(t){return(e,r)=>e===ce.nil?r:r===ce.nil?e:(0,ce._)`${rc(e)} ${t} ${rc(r)}`}function rc(t){return t instanceof ce.Name?t:(0,ce._)`(${t})`}});var ue=M(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.checkStrictMode=ne.getErrorPath=ne.Type=ne.useFunc=ne.setEvaluated=ne.evaluatedPropsToName=ne.mergeEvaluated=ne.eachItem=ne.unescapeJsonPointer=ne.escapeJsonPointer=ne.escapeFragment=ne.unescapeFragment=ne.schemaRefOrVal=ne.schemaHasRulesButRef=ne.schemaHasRules=ne.checkUnknownRules=ne.alwaysValidSchema=ne.toHash=void 0;var ye=te(),HT=Vn();function KT(t){let e={};for(let r of t)e[r]=!0;return e}ne.toHash=KT;function VT(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(nf(t,e),!of(e,t.self.RULES.all))}ne.alwaysValidSchema=VT;function nf(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]||lf(t,`unknown keyword: "${s}"`)}ne.checkUnknownRules=nf;function of(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ne.schemaHasRules=of;function WT(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ne.schemaHasRulesButRef=WT;function GT({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ye._)`${r}`}return(0,ye._)`${t}${e}${(0,ye.getProperty)(n)}`}ne.schemaRefOrVal=GT;function JT(t){return sf(decodeURIComponent(t))}ne.unescapeFragment=JT;function YT(t){return encodeURIComponent(oc(t))}ne.escapeFragment=YT;function oc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=oc;function sf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=sf;function XT(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ne.eachItem=XT;function tf({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof ye.Name?(s instanceof ye.Name?t(o,s,i):e(o,s,i),i):s instanceof ye.Name?(e(o,i,s),s):r(s,i);return a===ye.Name&&!(l instanceof ye.Name)?n(o,l):l}}ne.mergeEvaluated={props:tf({mergeNames:(t,e,r)=>t.if((0,ye._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ye._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ye._)`${r} || {}`).code((0,ye._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ye._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ye._)`${r} || {}`),sc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:af}),items:tf({mergeNames:(t,e,r)=>t.if((0,ye._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ye._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ye._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ye._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function af(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ye._)`{}`);return e!==void 0&&sc(t,r,e),r}ne.evaluatedPropsToName=af;function sc(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ye._)`${e}${(0,ye.getProperty)(n)}`,!0))}ne.setEvaluated=sc;var rf={};function ZT(t,e){return t.scopeValue("func",{ref:e,code:rf[e.code]||(rf[e.code]=new HT._Code(e.code))})}ne.useFunc=ZT;var nc;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(nc||(ne.Type=nc={}));function QT(t,e,r){if(t instanceof ye.Name){let n=e===nc.Num;return r?n?(0,ye._)`"[" + ${t} + "]"`:(0,ye._)`"['" + ${t} + "']"`:n?(0,ye._)`"/" + ${t}`:(0,ye._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ye.getProperty)(t).toString():"/"+oc(t)}ne.getErrorPath=QT;function lf(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=lf});var Ut=M(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var Me=te(),ex={data:new Me.Name("data"),valCxt:new Me.Name("valCxt"),instancePath:new Me.Name("instancePath"),parentData:new Me.Name("parentData"),parentDataProperty:new Me.Name("parentDataProperty"),rootData:new Me.Name("rootData"),dynamicAnchors:new Me.Name("dynamicAnchors"),vErrors:new Me.Name("vErrors"),errors:new Me.Name("errors"),this:new Me.Name("this"),self:new Me.Name("self"),scope:new Me.Name("scope"),json:new Me.Name("json"),jsonPos:new Me.Name("jsonPos"),jsonLen:new Me.Name("jsonLen"),jsonPart:new Me.Name("jsonPart")};ic.default=ex});var Zn=M(qe=>{"use strict";Object.defineProperty(qe,"__esModule",{value:!0});qe.extendErrors=qe.resetErrorsCount=qe.reportExtraError=qe.reportError=qe.keyword$DataError=qe.keywordError=void 0;var pe=te(),Gs=ue(),He=Ut();qe.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};qe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function tx(t,e=qe.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,l=uf(t,e,r);n??(i||a)?cf(s,l):df(o,(0,pe._)`[${l}]`)}qe.reportError=tx;function rx(t,e=qe.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=uf(t,e,r);cf(o,a),s||i||df(n,He.default.vErrors)}qe.reportExtraError=rx;function nx(t,e){t.assign(He.default.errors,e),t.if((0,pe._)`${He.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${He.default.vErrors}.length`,e),()=>t.assign(He.default.vErrors,null)))}qe.resetErrorsCount=nx;function ox({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,He.default.errors,a=>{t.const(i,(0,pe._)`${He.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(He.default.instancePath,s.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,r),t.assign((0,pe._)`${i}.data`,n))})}qe.extendErrors=ox;function cf(t,e){let r=t.const("err",e);t.if((0,pe._)`${He.default.vErrors} === null`,()=>t.assign(He.default.vErrors,(0,pe._)`[${r}]`),(0,pe._)`${He.default.vErrors}.push(${r})`),t.code((0,pe._)`${He.default.errors}++`)}function df(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,pe._)`new ${t.ValidationError}(${e})`):(r.assign((0,pe._)`${n}.errors`,e),r.return(!1))}var _r={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function uf(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,pe._)`{}`:sx(t,e,r)}function sx(t,e,r={}){let{gen:n,it:o}=t,s=[ix(o,r),ax(t,r)];return lx(t,e,s),n.object(...s)}function ix({errorPath:t},{instancePath:e}){let r=e?(0,pe.str)`${t}${(0,Gs.getErrorPath)(e,Gs.Type.Str)}`:t;return[He.default.instancePath,(0,pe.strConcat)(He.default.instancePath,r)]}function ax({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,pe.str)`${e}/${t}`;return r&&(o=(0,pe.str)`${o}${(0,Gs.getErrorPath)(r,Gs.Type.Str)}`),[_r.schemaPath,o]}function lx(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:f}=a;n.push([_r.keyword,o],[_r.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&n.push([_r.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([_r.schema,i],[_r.parentSchema,(0,pe._)`${p}${f}`],[He.default.data,s]),u&&n.push([_r.propertyName,u])}});var mf=M(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.boolOrEmptySchema=Xr.topBoolOrEmptySchema=void 0;var cx=Zn(),dx=te(),ux=Ut(),px={message:"boolean schema is false"};function mx(t){let{gen:e,schema:r,validateName:n}=t;r===!1?pf(t,!1):typeof r=="object"&&r.$async===!0?e.return(ux.default.data):(e.assign((0,dx._)`${n}.errors`,null),e.return(!0))}Xr.topBoolOrEmptySchema=mx;function hx(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),pf(t)):r.var(e,!0)}Xr.boolOrEmptySchema=hx;function pf(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,cx.reportError)(o,px,void 0,e)}});var ac=M(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.getRules=Zr.isJSONType=void 0;var fx=["string","number","integer","boolean","null","object","array"],gx=new Set(fx);function yx(t){return typeof t=="string"&&gx.has(t)}Zr.isJSONType=yx;function bx(){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:{}}}Zr.getRules=bx});var lc=M(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.shouldUseRule=tr.shouldUseGroup=tr.schemaHasRulesForType=void 0;function wx({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&hf(t,n)}tr.schemaHasRulesForType=wx;function hf(t,e){return e.rules.some(r=>ff(t,r))}tr.shouldUseGroup=hf;function ff(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))}tr.shouldUseRule=ff});var Qn=M(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.reportTypeError=ze.checkDataTypes=ze.checkDataType=ze.coerceAndCheckDataType=ze.getJSONTypes=ze.getSchemaTypes=ze.DataType=void 0;var vx=ac(),_x=lc(),Sx=Zn(),ee=te(),gf=ue(),Qr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Qr||(ze.DataType=Qr={}));function kx(t){let e=yf(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}ze.getSchemaTypes=kx;function yf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(vx.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ze.getJSONTypes=yf;function Tx(t,e){let{gen:r,data:n,opts:o}=t,s=xx(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,_x.schemaHasRulesForType)(t,e[0]));if(i){let a=dc(e,n,o.strictNumbers,Qr.Wrong);r.if(a,()=>{s.length?$x(t,e,s):uc(t)})}return i}ze.coerceAndCheckDataType=Tx;var bf=new Set(["string","number","integer","boolean","null"]);function xx(t,e){return e?t.filter(r=>bf.has(r)||e==="array"&&r==="array"):[]}function $x(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ee._)`typeof ${o}`),a=n.let("coerced",(0,ee._)`undefined`);s.coerceTypes==="array"&&n.if((0,ee._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ee._)`${o}[0]`).assign(i,(0,ee._)`typeof ${o}`).if(dc(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ee._)`${a} !== undefined`);for(let u of r)(bf.has(u)||u==="array"&&s.coerceTypes==="array")&&l(u);n.else(),uc(t),n.endIf(),n.if((0,ee._)`${a} !== undefined`,()=>{n.assign(o,a),Rx(t,a)});function l(u){switch(u){case"string":n.elseIf((0,ee._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ee._)`"" + ${o}`).elseIf((0,ee._)`${o} === null`).assign(a,(0,ee._)`""`);return;case"number":n.elseIf((0,ee._)`${i} == "boolean" || ${o} === null
2008
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ee._)`+${o}`);return;case"integer":n.elseIf((0,ee._)`${i} === "boolean" || ${o} === null
2009
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ee._)`+${o}`);return;case"boolean":n.elseIf((0,ee._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ee._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ee._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ee._)`${i} === "string" || ${i} === "number"
2010
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,ee._)`[${o}]`)}}}function Rx({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${r}]`,n))}function cc(t,e,r,n=Qr.Correct){let o=n===Qr.Correct?ee.operators.EQ:ee.operators.NEQ,s;switch(t){case"null":return(0,ee._)`${e} ${o} null`;case"array":s=(0,ee._)`Array.isArray(${e})`;break;case"object":s=(0,ee._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ee._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ee._)`typeof ${e} ${o} ${t}`}return n===Qr.Correct?s:(0,ee.not)(s);function i(a=ee.nil){return(0,ee.and)((0,ee._)`typeof ${e} == "number"`,a,r?(0,ee._)`isFinite(${e})`:ee.nil)}}ze.checkDataType=cc;function dc(t,e,r,n){if(t.length===1)return cc(t[0],e,r,n);let o,s=(0,gf.toHash)(t);if(s.array&&s.object){let i=(0,ee._)`typeof ${e} != "object"`;o=s.null?i:(0,ee._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ee.nil;s.number&&delete s.integer;for(let i in s)o=(0,ee.and)(o,cc(i,e,r,n));return o}ze.checkDataTypes=dc;var Ex={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function uc(t){let e=Px(t);(0,Sx.reportError)(e,Ex)}ze.reportTypeError=uc;function Px(t){let{gen:e,data:r,schema:n}=t,o=(0,gf.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var vf=M(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.assignDefaults=void 0;var en=te(),Ax=ue();function Cx(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)wf(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>wf(t,s,o.default))}Js.assignDefaults=Cx;function wf(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,en._)`${s}${(0,en.getProperty)(e)}`;if(o){(0,Ax.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,en._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,en._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,en._)`${a} = ${(0,en.stringify)(r)}`)}});var ct=M(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.validateUnion=ge.validateArray=ge.usePattern=ge.callValidateCode=ge.schemaProperties=ge.allSchemaProperties=ge.noPropertyInData=ge.propertyInData=ge.isOwnProperty=ge.hasPropFunc=ge.reportMissingProp=ge.checkMissingProp=ge.checkReportMissingProp=void 0;var we=te(),pc=ue(),rr=Ut(),Ix=ue();function Ox(t,e){let{gen:r,data:n,it:o}=t;r.if(hc(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,we._)`${e}`},!0),t.error()})}ge.checkReportMissingProp=Ox;function Nx({gen:t,data:e,it:{opts:r}},n,o){return(0,we.or)(...n.map(s=>(0,we.and)(hc(t,e,s,r.ownProperties),(0,we._)`${o} = ${s}`)))}ge.checkMissingProp=Nx;function Lx(t,e){t.setParams({missingProperty:e},!0),t.error()}ge.reportMissingProp=Lx;function _f(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,we._)`Object.prototype.hasOwnProperty`})}ge.hasPropFunc=_f;function mc(t,e,r){return(0,we._)`${_f(t)}.call(${e}, ${r})`}ge.isOwnProperty=mc;function jx(t,e,r,n){let o=(0,we._)`${e}${(0,we.getProperty)(r)} !== undefined`;return n?(0,we._)`${o} && ${mc(t,e,r)}`:o}ge.propertyInData=jx;function hc(t,e,r,n){let o=(0,we._)`${e}${(0,we.getProperty)(r)} === undefined`;return n?(0,we.or)(o,(0,we.not)(mc(t,e,r))):o}ge.noPropertyInData=hc;function Sf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ge.allSchemaProperties=Sf;function Dx(t,e){return Sf(e).filter(r=>!(0,pc.alwaysValidSchema)(t,e[r]))}ge.schemaProperties=Dx;function Ux({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,u){let p=u?(0,we._)`${t}, ${e}, ${n}${o}`:e,f=[[rr.default.instancePath,(0,we.strConcat)(rr.default.instancePath,s)],[rr.default.parentData,i.parentData],[rr.default.parentDataProperty,i.parentDataProperty],[rr.default.rootData,rr.default.rootData]];i.opts.dynamicRef&&f.push([rr.default.dynamicAnchors,rr.default.dynamicAnchors]);let S=(0,we._)`${p}, ${r.object(...f)}`;return l!==we.nil?(0,we._)`${a}.call(${l}, ${S})`:(0,we._)`${a}(${S})`}ge.callValidateCode=Ux;var Mx=(0,we._)`new RegExp`;function qx({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,we._)`${o.code==="new RegExp"?Mx:(0,Ix.useFunc)(t,o)}(${r}, ${n})`})}ge.usePattern=qx;function zx(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 l=e.const("len",(0,we._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:pc.Type.Num},s),e.if((0,we.not)(s),a)})}}ge.validateArray=zx;function Bx(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,pc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,u)=>{let p=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,we._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,we.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ge.validateUnion=Bx});var xf=M(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.validateKeywordUsage=Rt.validSchemaType=Rt.funcKeywordCode=Rt.macroKeywordCode=void 0;var Ke=te(),Sr=Ut(),Fx=ct(),Hx=Zn();function Kx(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),l=Tf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ke.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Rt.macroKeywordCode=Kx;function Vx(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=t;Gx(l,e);let u=!a&&e.compile?e.compile.call(l.self,s,i,l):e.validate,p=Tf(n,o,u),f=n.let("valid");t.block$data(f,S),t.ok((r=e.valid)!==null&&r!==void 0?r:f);function S(){if(e.errors===!1)$(),e.modifying&&kf(t),R(()=>t.error());else{let P=e.async?y():k();e.modifying&&kf(t),R(()=>Wx(t,P))}}function y(){let P=n.let("ruleErrs",null);return n.try(()=>$((0,Ke._)`await `),O=>n.assign(f,!1).if((0,Ke._)`${O} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ke._)`${O}.errors`),()=>n.throw(O))),P}function k(){let P=(0,Ke._)`${p}.errors`;return n.assign(P,null),$(Ke.nil),P}function $(P=e.async?(0,Ke._)`await `:Ke.nil){let O=l.opts.passContext?Sr.default.this:Sr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(f,(0,Ke._)`${P}${(0,Fx.callValidateCode)(t,p,O,D)}`,e.modifying)}function R(P){var O;n.if((0,Ke.not)((O=e.valid)!==null&&O!==void 0?O:f),P)}}Rt.funcKeywordCode=Vx;function kf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ke._)`${n.parentData}[${n.parentDataProperty}]`))}function Wx(t,e){let{gen:r}=t;r.if((0,Ke._)`Array.isArray(${e})`,()=>{r.assign(Sr.default.vErrors,(0,Ke._)`${Sr.default.vErrors} === null ? ${e} : ${Sr.default.vErrors}.concat(${e})`).assign(Sr.default.errors,(0,Ke._)`${Sr.default.vErrors}.length`),(0,Hx.extendErrors)(t)},()=>t.error())}function Gx({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Tf(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,Ke.stringify)(r)})}function Jx(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")}Rt.validSchemaType=Jx;function Yx({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 l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Rt.validateKeywordUsage=Yx});var Rf=M(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.extendSubschemaMode=nr.extendSubschemaData=nr.getSubschema=void 0;var Et=te(),$f=ue();function Xx(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,Et._)`${t.schemaPath}${(0,Et.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Et._)`${t.schemaPath}${(0,Et.getProperty)(e)}${(0,Et.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,$f.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')}nr.getSubschema=Xx;function Zx(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:u,dataPathArr:p,opts:f}=e,S=a.let("data",(0,Et._)`${e.data}${(0,Et.getProperty)(r)}`,!0);l(S),t.errorPath=(0,Et.str)`${u}${(0,$f.getErrorPath)(r,n,f.jsPropertySyntax)}`,t.parentDataProperty=(0,Et._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Et.Name?o:a.let("data",o,!0);l(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}nr.extendSubschemaData=Zx;function Qx(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}nr.extendSubschemaMode=Qx});var fc=M(($D,Ef)=>{"use strict";Ef.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 Af=M((RD,Pf)=>{"use strict";var or=Pf.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(){};Ys(e,n,o,t,"",t)};or.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};or.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};or.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};or.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 Ys(t,e,r,n,o,s,i,a,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,l,u);for(var p in n){var f=n[p];if(Array.isArray(f)){if(p in or.arrayKeywords)for(var S=0;S<f.length;S++)Ys(t,e,r,f[S],o+"/"+p+"/"+S,s,o,p,n,S)}else if(p in or.propsKeywords){if(f&&typeof f=="object")for(var y in f)Ys(t,e,r,f[y],o+"/"+p+"/"+e$(y),s,o,p,n,y)}else(p in or.keywords||t.allKeys&&!(p in or.skipKeywords))&&Ys(t,e,r,f,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,u)}}function e$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var eo=M(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.getSchemaRefs=Xe.resolveUrl=Xe.normalizeId=Xe._getFullPath=Xe.getFullPath=Xe.inlineRef=void 0;var t$=ue(),r$=fc(),n$=Af(),o$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function s$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!gc(t):e?Cf(t)<=e:!1}Xe.inlineRef=s$;var i$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gc(t){for(let e in t){if(i$.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(gc)||typeof r=="object"&&gc(r))return!0}return!1}function Cf(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!o$.has(r)&&(typeof t[r]=="object"&&(0,t$.eachItem)(t[r],n=>e+=Cf(n)),e===1/0))return 1/0}return e}function If(t,e="",r){r!==!1&&(e=tn(e));let n=t.parse(e);return Of(t,n)}Xe.getFullPath=If;function Of(t,e){return t.serialize(e).split("#")[0]+"#"}Xe._getFullPath=Of;var a$=/#\/?$/;function tn(t){return t?t.replace(a$,""):""}Xe.normalizeId=tn;function l$(t,e,r){return r=tn(r),t.resolve(e,r)}Xe.resolveUrl=l$;var c$=/^[a-z_][-a-z0-9._]*$/i;function d$(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=tn(t[r]||e),s={"":o},i=If(n,o,!1),a={},l=new Set;return n$(t,{allKeys:!0},(f,S,y,k)=>{if(k===void 0)return;let $=i+S,R=s[k];typeof f[r]=="string"&&(R=P.call(this,f[r])),O.call(this,f.$anchor),O.call(this,f.$dynamicAnchor),s[S]=R;function P(D){let Y=this.opts.uriResolver.resolve;if(D=tn(R?Y(R,D):D),l.has(D))throw p(D);l.add(D);let K=this.refs[D];return typeof K=="string"&&(K=this.refs[K]),typeof K=="object"?u(f,K.schema,D):D!==tn($)&&(D[0]==="#"?(u(f,a[D],D),a[D]=f):this.refs[D]=$),D}function O(D){if(typeof D=="string"){if(!c$.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(f,S,y){if(S!==void 0&&!r$(f,S))throw p(y)}function p(f){return new Error(`reference "${f}" resolves to more than one schema`)}}Xe.getSchemaRefs=d$});var no=M(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.getData=sr.KeywordCxt=sr.validateFunctionCode=void 0;var Uf=mf(),Nf=Qn(),bc=lc(),Xs=Qn(),u$=vf(),ro=xf(),yc=Rf(),F=te(),Q=Ut(),p$=eo(),Mt=ue(),to=Zn();function m$(t){if(zf(t)&&(Bf(t),qf(t))){g$(t);return}Mf(t,()=>(0,Uf.topBoolOrEmptySchema)(t))}sr.validateFunctionCode=m$;function Mf({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,F._)`${Q.default.data}, ${Q.default.valCxt}`,n.$async,()=>{t.code((0,F._)`"use strict"; ${Lf(r,o)}`),f$(t,o),t.code(s)}):t.func(e,(0,F._)`${Q.default.data}, ${h$(o)}`,n.$async,()=>t.code(Lf(r,o)).code(s))}function h$(t){return(0,F._)`{${Q.default.instancePath}="", ${Q.default.parentData}, ${Q.default.parentDataProperty}, ${Q.default.rootData}=${Q.default.data}${t.dynamicRef?(0,F._)`, ${Q.default.dynamicAnchors}={}`:F.nil}}={}`}function f$(t,e){t.if(Q.default.valCxt,()=>{t.var(Q.default.instancePath,(0,F._)`${Q.default.valCxt}.${Q.default.instancePath}`),t.var(Q.default.parentData,(0,F._)`${Q.default.valCxt}.${Q.default.parentData}`),t.var(Q.default.parentDataProperty,(0,F._)`${Q.default.valCxt}.${Q.default.parentDataProperty}`),t.var(Q.default.rootData,(0,F._)`${Q.default.valCxt}.${Q.default.rootData}`),e.dynamicRef&&t.var(Q.default.dynamicAnchors,(0,F._)`${Q.default.valCxt}.${Q.default.dynamicAnchors}`)},()=>{t.var(Q.default.instancePath,(0,F._)`""`),t.var(Q.default.parentData,(0,F._)`undefined`),t.var(Q.default.parentDataProperty,(0,F._)`undefined`),t.var(Q.default.rootData,Q.default.data),e.dynamicRef&&t.var(Q.default.dynamicAnchors,(0,F._)`{}`)})}function g$(t){let{schema:e,opts:r,gen:n}=t;Mf(t,()=>{r.$comment&&e.$comment&&Hf(t),_$(t),n.let(Q.default.vErrors,null),n.let(Q.default.errors,0),r.unevaluated&&y$(t),Ff(t),T$(t)})}function y$(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,F._)`${r}.evaluated`),e.if((0,F._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${t.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${t.evaluated}.items`,(0,F._)`undefined`))}function Lf(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${r} */`:F.nil}function b$(t,e){if(zf(t)&&(Bf(t),qf(t))){w$(t,e);return}(0,Uf.boolOrEmptySchema)(t,e)}function qf({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 zf(t){return typeof t.schema!="boolean"}function w$(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Hf(t),S$(t),k$(t);let s=n.const("_errs",Q.default.errors);Ff(t,s),n.var(e,(0,F._)`${s} === ${Q.default.errors}`)}function Bf(t){(0,Mt.checkUnknownRules)(t),v$(t)}function Ff(t,e){if(t.opts.jtd)return jf(t,[],!1,e);let r=(0,Nf.getSchemaTypes)(t.schema),n=(0,Nf.coerceAndCheckDataType)(t,r);jf(t,r,!n,e)}function v$(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Mt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function _$(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Mt.checkStrictMode)(t,"default is ignored in the schema root")}function S$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,p$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function k$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Hf({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,F._)`${Q.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,F.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,F._)`${Q.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function T$(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,F._)`${Q.default.errors} === 0`,()=>e.return(Q.default.data),()=>e.throw((0,F._)`new ${o}(${Q.default.vErrors})`)):(e.assign((0,F._)`${n}.errors`,Q.default.vErrors),s.unevaluated&&x$(t),e.return((0,F._)`${Q.default.errors} === 0`))}function x$({gen:t,evaluated:e,props:r,items:n}){r instanceof F.Name&&t.assign((0,F._)`${e}.props`,r),n instanceof F.Name&&t.assign((0,F._)`${e}.items`,n)}function jf(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:u}=t,{RULES:p}=u;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,Mt.schemaHasRulesButRef)(s,p))){o.block(()=>Vf(t,"$ref",p.all.$ref.definition));return}l.jtd||$$(t,e),o.block(()=>{for(let S of p.rules)f(S);f(p.post)});function f(S){(0,bc.shouldUseGroup)(s,S)&&(S.type?(o.if((0,Xs.checkDataType)(S.type,i,l.strictNumbers)),Df(t,S),e.length===1&&e[0]===S.type&&r&&(o.else(),(0,Xs.reportTypeError)(t)),o.endIf()):Df(t,S),a||o.if((0,F._)`${Q.default.errors} === ${n||0}`))}}function Df(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,u$.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,bc.shouldUseRule)(n,s)&&Vf(t,s.keyword,s.definition,e.type)})}function $$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(R$(t,e),t.opts.allowUnionTypes||E$(t,e),P$(t,t.dataTypes))}function R$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Kf(t.dataTypes,r)||wc(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),C$(t,e)}}function E$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&wc(t,"use allowUnionTypes to allow union type keyword")}function P$(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,bc.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>A$(e,i))&&wc(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function A$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Kf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function C$(t,e){let r=[];for(let n of t.dataTypes)Kf(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function wc(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Mt.checkStrictMode)(t,e,t.opts.strictTypes)}var Zs=class{constructor(e,r,n){if((0,ro.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,Mt.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",Wf(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ro.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",Q.default.errors))}result(e,r,n){this.failResult((0,F.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,F.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,F._)`${r} !== undefined && (${(0,F.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?to.reportExtraError:to.reportError)(this,this.def.error,r)}$dataError(){(0,to.reportError)(this,this.def.$dataError||to.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,to.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=F.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=F.nil,r=F.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,F.or)((0,F._)`${o} === undefined`,r)),e!==F.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,F.or)(i(),a());function i(){if(n.length){if(!(r instanceof F.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,F._)`${(0,Xs.checkDataTypes)(l,r,s.opts.strictNumbers,Xs.DataType.Wrong)}`}return F.nil}function a(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,F._)`!${l}(${r})`}return F.nil}}subschema(e,r){let n=(0,yc.getSubschema)(this.it,e);(0,yc.extendSubschemaData)(n,this.it,e),(0,yc.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return b$(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Mt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Mt.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,F.Name)),!0}};sr.KeywordCxt=Zs;function Vf(t,e,r,n){let o=new Zs(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ro.funcKeywordCode)(o,r):"macro"in r?(0,ro.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ro.funcKeywordCode)(o,r)}var I$=/^\/(?:[^~]|~0|~1)*$/,O$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Wf(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return Q.default.rootData;if(t[0]==="/"){if(!I$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=Q.default.rootData}else{let u=O$.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+u[1];if(o=u[2],o==="#"){if(p>=e)throw new Error(l("property/index",p));return n[e-p]}if(p>e)throw new Error(l("data",p));if(s=r[e-p],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,F._)`${s}${(0,F.getProperty)((0,Mt.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}sr.getData=Wf});var Qs=M(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var vc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};_c.default=vc});var oo=M(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var Sc=eo(),kc=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Sc.resolveUrl)(e,r,n),this.missingSchema=(0,Sc.normalizeId)((0,Sc.getFullPath)(e,this.missingRef))}};Tc.default=kc});var ti=M(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.resolveSchema=dt.getCompilingSchema=dt.resolveRef=dt.compileSchema=dt.SchemaEnv=void 0;var wt=te(),N$=Qs(),kr=Ut(),vt=eo(),Gf=ue(),L$=no(),rn=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,vt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};dt.SchemaEnv=rn;function $c(t){let e=Jf.call(this,t);if(e)return e;let r=(0,vt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new wt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:N$.default,code:(0,wt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:kr.default.data,parentData:kr.default.parentData,parentDataProperty:kr.default.parentDataProperty,dataNames:[kr.default.data],dataPathArr:[wt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,wt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:wt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,wt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,L$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let f=i.toString();p=`${i.scopeRefs(kr.default.scope)}return ${f}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let y=new Function(`${kr.default.self}`,`${kr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=t.schema,y.schemaEnv=t,t.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:$}=u;y.evaluated={props:k instanceof wt.Name?void 0:k,items:$ instanceof wt.Name?void 0:$,dynamicProps:k instanceof wt.Name,dynamicItems:$ instanceof wt.Name},y.source&&(y.source.evaluated=(0,wt.stringify)(y.evaluated))}return t.validate=y,t}catch(f){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),f}finally{this._compilations.delete(t)}}dt.compileSchema=$c;function j$(t,e,r){var n;r=(0,vt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=M$.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 rn({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=D$.call(this,s)}dt.resolveRef=j$;function D$(t){return(0,vt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:$c.call(this,t)}function Jf(t){for(let e of this._compilations)if(U$(e,t))return e}dt.getCompilingSchema=Jf;function U$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function M$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||ei.call(this,t,e)}function ei(t,e){let r=this.opts.uriResolver.parse(e),n=(0,vt._getFullPath)(this.opts.uriResolver,r),o=(0,vt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return xc.call(this,r,t);let s=(0,vt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=ei.call(this,t,i);return typeof a?.schema!="object"?void 0:xc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||$c.call(this,i),s===(0,vt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(o=(0,vt.resolveUrl)(this.opts.uriResolver,o,u)),new rn({schema:a,schemaId:l,root:t,baseId:o})}return xc.call(this,r,i)}}dt.resolveSchema=ei;var q$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xc(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 l=r[(0,Gf.unescapeFragment)(a)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!q$.has(a)&&u&&(e=(0,vt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Gf.schemaHasRulesButRef)(r,this.RULES)){let a=(0,vt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=ei.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new rn({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Yf=M((OD,z$)=>{z$.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 Pc=M((ND,rg)=>{"use strict";var B$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Zf=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),Rc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Qf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),F$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Ec(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 H$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Xf(t){return t.length=0,!0}function K$(t,e,r){if(t.length){let n=Ec(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function V$(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=K$;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=Xf}else{o.push(u);continue}}return o.length&&(a===Xf?r.zone=o.join(""):i?n.push(o.join("")):n.push(Ec(o))),r.address=n.join(""),r}function eg(t){if(W$(t,":")<2)return{host:t,isIPV6:!1};let e=V$(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 W$(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function G$(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 J$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Y$=/[@/?#:]/g,X$=/[@/?#]/g;function tg(t,e){let r=e?X$:Y$;return r.lastIndex=0,t.replace(r,n=>J$[n])}function Z$(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(Rc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Qf(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function Q$(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(Rc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Qf(s)?e+=s:e+="%"+o,r+=2;continue}}F$(t[r])?e+=t[r]:e+=escape(t[r])}return e}function eR(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(Rc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function tR(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Zf(r)){let n=eg(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=tg(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}rg.exports={nonSimpleDomain:H$,recomposeAuthority:tR,reescapeHostDelimiters:tg,normalizePercentEncoding:Z$,normalizePathEncoding:Q$,escapePreservingEscapes:eR,removeDotSegments:G$,isIPv4:Zf,isUUID:B$,normalizeIPv6:eg,stringArrayToHexStripped:Ec}});var ag=M((LD,ig)=>{"use strict";var{isUUID:rR}=Pc(),nR=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,oR=["http","https","ws","wss","urn","urn:uuid"];function sR(t){return oR.indexOf(t)!==-1}function Ac(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 ng(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function og(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 iR(t){return t.secure=Ac(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function aR(t){if((t.port===(Ac(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 lR(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(nR);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=Cc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function cR(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=Cc(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 dR(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!rR(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function uR(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var sg={scheme:"http",domainHost:!0,parse:ng,serialize:og},pR={scheme:"https",domainHost:sg.domainHost,parse:ng,serialize:og},ri={scheme:"ws",domainHost:!0,parse:iR,serialize:aR},mR={scheme:"wss",domainHost:ri.domainHost,parse:ri.parse,serialize:ri.serialize},hR={scheme:"urn",parse:lR,serialize:cR,skipNormalize:!0},fR={scheme:"urn:uuid",parse:dR,serialize:uR,skipNormalize:!0},ni={http:sg,https:pR,ws:ri,wss:mR,urn:hR,"urn:uuid":fR};Object.setPrototypeOf(ni,null);function Cc(t){return t&&(ni[t]||ni[t.toLowerCase()])||void 0}ig.exports={wsIsSecure:Ac,SCHEMES:ni,isValidSchemeName:sR,getSchemeHandler:Cc}});var pg=M((jD,ii)=>{"use strict";var{normalizeIPv6:gR,removeDotSegments:so,recomposeAuthority:yR,normalizePercentEncoding:bR,normalizePathEncoding:wR,escapePreservingEscapes:vR,reescapeHostDelimiters:_R,isIPv4:SR,nonSimpleDomain:kR}=Pc(),{SCHEMES:TR,getSchemeHandler:cg}=ag();function xR(t,e){return typeof t=="string"?t=IR(t,e):typeof t=="object"&&(t=si(Tr(t,e),e)),t}function $R(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=oi(t,n),{parsed:i,malformedAuthorityOrPort:a}=oi(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let l=dg(o,i,n,!0);return n.skipEscape=!0,Tr(l,n)}function dg(t,e,r,n){let o={};return n||(t=si(Tr(t,r),r),e=si(Tr(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=so(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=so(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=so(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=so(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 RR(t,e,r){let n=lg(t,r),o=lg(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Tr(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=cg(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=bR(r.path):(r.path=vR(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=yR(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=so(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 ER=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,PR=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,AR=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function CR(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 oi(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(PR);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(AR);if(a!==null){let u=a[1],p=u.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):u.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let l=t.match(ER);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],isNaN(n.port)&&(n.port=l[5]);let u=CR(n,l);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(SR(n.host)===!1){let S=gR(n.host);n.host=S.host.toLowerCase(),s=S.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 p=cg(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&kR(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(f){n.error=n.error||"Host's domain name can not be converted to ASCII: "+f}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=_R(unescape(n.host),s))),n.path&&(n.path=wR(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}p&&p.parse&&p.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function si(t,e){return oi(t,e).parsed}function IR(t,e){return ug(t,e).normalized}function ug(t,e){let{parsed:r,malformedAuthorityOrPort:n}=oi(t,e);return{normalized:n?t:Tr(r,e),malformedAuthorityOrPort:n}}function lg(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=ug(t,e);return n?void 0:r}if(typeof t=="object")return Tr(t,e)}var Ic={SCHEMES:TR,normalize:xR,resolve:$R,resolveComponent:dg,equal:RR,serialize:Tr,parse:si};ii.exports=Ic;ii.exports.default=Ic;ii.exports.fastUri=Ic});var hg=M(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var mg=pg();mg.code='require("ajv/dist/runtime/uri").default';Oc.default=mg});var Sg=M(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.CodeGen=Le.Name=Le.nil=Le.stringify=Le.str=Le._=Le.KeywordCxt=void 0;var OR=no();Object.defineProperty(Le,"KeywordCxt",{enumerable:!0,get:function(){return OR.KeywordCxt}});var nn=te();Object.defineProperty(Le,"_",{enumerable:!0,get:function(){return nn._}});Object.defineProperty(Le,"str",{enumerable:!0,get:function(){return nn.str}});Object.defineProperty(Le,"stringify",{enumerable:!0,get:function(){return nn.stringify}});Object.defineProperty(Le,"nil",{enumerable:!0,get:function(){return nn.nil}});Object.defineProperty(Le,"Name",{enumerable:!0,get:function(){return nn.Name}});Object.defineProperty(Le,"CodeGen",{enumerable:!0,get:function(){return nn.CodeGen}});var NR=Qs(),wg=oo(),LR=ac(),io=ti(),jR=te(),ao=eo(),ai=Qn(),Lc=ue(),fg=Yf(),DR=hg(),vg=(t,e)=>new RegExp(t,e);vg.code="new RegExp";var UR=["removeAdditional","useDefaults","coerceTypes"],MR=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),qR={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."},zR={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},gg=200;function BR(t){var e,r,n,o,s,i,a,l,u,p,f,S,y,k,$,R,P,O,D,Y,K,Ae,De,zt,Bt;let cr=t.strict,Ft=(e=t.code)===null||e===void 0?void 0:e.optimize,kt=Ft===!0||Ft===void 0?1:Ft||0,So=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:vg,Oi=(o=t.uriResolver)!==null&&o!==void 0?o:DR.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:cr)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:cr)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:cr)!==null&&p!==void 0?p:"log",strictTuples:(S=(f=t.strictTuples)!==null&&f!==void 0?f:cr)!==null&&S!==void 0?S:"log",strictRequired:(k=(y=t.strictRequired)!==null&&y!==void 0?y:cr)!==null&&k!==void 0?k:!1,code:t.code?{...t.code,optimize:kt,regExp:So}:{optimize:kt,regExp:So},loopRequired:($=t.loopRequired)!==null&&$!==void 0?$:gg,loopEnum:(R=t.loopEnum)!==null&&R!==void 0?R:gg,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(O=t.messages)!==null&&O!==void 0?O:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(Y=t.schemaId)!==null&&Y!==void 0?Y:"$id",addUsedSchema:(K=t.addUsedSchema)!==null&&K!==void 0?K:!0,validateSchema:(Ae=t.validateSchema)!==null&&Ae!==void 0?Ae:!0,validateFormats:(De=t.validateFormats)!==null&&De!==void 0?De:!0,unicodeRegExp:(zt=t.unicodeRegExp)!==null&&zt!==void 0?zt:!0,int32range:(Bt=t.int32range)!==null&&Bt!==void 0?Bt:!0,uriResolver:Oi}}var lo=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,...BR(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new jR.ValueScope({scope:{},prefixes:MR,es5:r,lines:n}),this.logger=GR(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,LR.getRules)(),yg.call(this,qR,e,"NOT SUPPORTED"),yg.call(this,zR,e,"DEPRECATED","warn"),this._metaOpts=VR.call(this),e.formats&&HR.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&KR.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),FR.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=fg;n==="id"&&(o={...fg},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(p,f){await s.call(this,p.$schema);let S=this._addSchema(p,f);return S.validate||i.call(this,S)}async function s(p){p&&!this.getSchema(p)&&await o.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(f){if(!(f instanceof wg.default))throw f;return a.call(this,f),await l.call(this,f.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:f}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${f} cannot be resolved`)}async function l(p){let f=await u.call(this,p);this.refs[p]||await s.call(this,f.$schema),this.refs[p]||this.addSchema(f,p,r)}async function u(p){let f=this._loading[p];if(f)return f;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}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,ao.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=bg.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new io.SchemaEnv({schema:{},schemaId:n});if(r=io.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=bg.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,ao.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(YR.call(this,n,r),!r)return(0,Lc.eachItem)(n,s=>Nc.call(this,s)),this;ZR.call(this,r);let o={...r,type:(0,ai.getJSONTypes)(r.type),schemaType:(0,ai.getJSONTypes)(r.schemaType)};return(0,Lc.eachItem)(n,o.type.length===0?s=>Nc.call(this,s,o):s=>o.type.forEach(i=>Nc.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 l=n[a];if(typeof l!="object")continue;let{$data:u}=l.definition,p=i[a];u&&p&&(i[a]=_g(p))}}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 l=this._cache.get(e);if(l!==void 0)return l;n=(0,ao.normalizeId)(i||n);let u=ao.getSchemaRefs.call(this,e,n);return l=new io.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(l.schema,l),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&this.validateSchema(e,!0),l}_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):io.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{io.compileSchema.call(this,e)}finally{this.opts=r}}};lo.ValidationError=NR.default;lo.MissingRefError=wg.default;Le.default=lo;function yg(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 bg(t){return t=(0,ao.normalizeId)(t),this.schemas[t]||this.refs[t]}function FR(){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 HR(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function KR(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 VR(){let t={...this.opts};for(let e of UR)delete t[e];return t}var WR={log(){},warn(){},error(){}};function GR(t){if(t===!1)return WR;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 JR=/^[a-z_$][a-z0-9_$:-]*$/i;function YR(t,e){let{RULES:r}=this;if((0,Lc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!JR.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 Nc(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:l})=>l===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,ai.getJSONTypes)(e.type),schemaType:(0,ai.getJSONTypes)(e.schemaType)}};e.before?XR.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function XR(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 ZR(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=_g(e)),t.validateSchema=this.compile(e,!0))}var QR={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function _g(t){return{anyOf:[t,QR]}}});var kg=M(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var eE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jc.default=eE});var Rg=M(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.callRef=xr.getValidate=void 0;var tE=oo(),Tg=ct(),Ze=te(),on=Ut(),xg=ti(),li=ue(),rE={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return f();let p=xg.resolveRef.call(l,u,o,r);if(p===void 0)throw new tE.default(n.opts.uriResolver,o,r);if(p instanceof xg.SchemaEnv)return S(p);return y(p);function f(){if(s===u)return ci(t,i,s,s.$async);let k=e.scopeValue("root",{ref:u});return ci(t,(0,Ze._)`${k}.validate`,u,u.$async)}function S(k){let $=$g(t,k);ci(t,$,k,k.$async)}function y(k){let $=e.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,Ze.stringify)(k)}:{ref:k}),R=e.name("valid"),P=t.subschema({schema:k,dataTypes:[],schemaPath:Ze.nil,topSchemaRef:$,errSchemaPath:r},R);t.mergeEvaluated(P),t.ok(R)}}};function $g(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Ze._)`${r.scopeValue("wrapper",{ref:e})}.validate`}xr.getValidate=$g;function ci(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:l}=s,u=l.passContext?on.default.this:Ze.nil;n?p():f();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=o.let("valid");o.try(()=>{o.code((0,Ze._)`await ${(0,Tg.callValidateCode)(t,e,u)}`),y(e),i||o.assign(k,!0)},$=>{o.if((0,Ze._)`!(${$} instanceof ${s.ValidationError})`,()=>o.throw($)),S($),i||o.assign(k,!1)}),t.ok(k)}function f(){t.result((0,Tg.callValidateCode)(t,e,u),()=>y(e),()=>S(e))}function S(k){let $=(0,Ze._)`${k}.errors`;o.assign(on.default.vErrors,(0,Ze._)`${on.default.vErrors} === null ? ${$} : ${on.default.vErrors}.concat(${$})`),o.assign(on.default.errors,(0,Ze._)`${on.default.vErrors}.length`)}function y(k){var $;if(!s.opts.unevaluated)return;let R=($=r?.validate)===null||$===void 0?void 0:$.evaluated;if(s.props!==!0)if(R&&!R.dynamicProps)R.props!==void 0&&(s.props=li.mergeEvaluated.props(o,R.props,s.props));else{let P=o.var("props",(0,Ze._)`${k}.evaluated.props`);s.props=li.mergeEvaluated.props(o,P,s.props,Ze.Name)}if(s.items!==!0)if(R&&!R.dynamicItems)R.items!==void 0&&(s.items=li.mergeEvaluated.items(o,R.items,s.items));else{let P=o.var("items",(0,Ze._)`${k}.evaluated.items`);s.items=li.mergeEvaluated.items(o,P,s.items,Ze.Name)}}}xr.callRef=ci;xr.default=rE});var Eg=M(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var nE=kg(),oE=Rg(),sE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",nE.default,oE.default];Dc.default=sE});var Pg=M(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var di=te(),ir=di.operators,ui={maximum:{okStr:"<=",ok:ir.LTE,fail:ir.GT},minimum:{okStr:">=",ok:ir.GTE,fail:ir.LT},exclusiveMaximum:{okStr:"<",ok:ir.LT,fail:ir.GTE},exclusiveMinimum:{okStr:">",ok:ir.GT,fail:ir.LTE}},iE={message:({keyword:t,schemaCode:e})=>(0,di.str)`must be ${ui[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,di._)`{comparison: ${ui[t].okStr}, limit: ${e}}`},aE={keyword:Object.keys(ui),type:"number",schemaType:"number",$data:!0,error:iE,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,di._)`${r} ${ui[e].fail} ${n} || isNaN(${r})`)}};Uc.default=aE});var Ag=M(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var co=te(),lE={message:({schemaCode:t})=>(0,co.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,co._)`{multipleOf: ${t}}`},cE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:lE,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,co._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,co._)`${i} !== parseInt(${i})`;t.fail$data((0,co._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Mc.default=cE});var Ig=M(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});function Cg(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}qc.default=Cg;Cg.code='require("ajv/dist/runtime/ucs2length").default'});var Og=M(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var $r=te(),dE=ue(),uE=Ig(),pE={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,$r.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,$r._)`{limit: ${t}}`},mE={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:pE,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?$r.operators.GT:$r.operators.LT,i=o.opts.unicode===!1?(0,$r._)`${r}.length`:(0,$r._)`${(0,dE.useFunc)(t.gen,uE.default)}(${r})`;t.fail$data((0,$r._)`${i} ${s} ${n}`)}};zc.default=mE});var Ng=M(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var hE=ct(),fE=ue(),sn=te(),gE={message:({schemaCode:t})=>(0,sn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,sn._)`{pattern: ${t}}`},yE={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:gE,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:l}=i.opts.code,u=l.code==="new RegExp"?(0,sn._)`new RegExp`:(0,fE.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,sn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,sn._)`!${p}`)}else{let l=(0,hE.usePattern)(t,o);t.fail$data((0,sn._)`!${l}.test(${r})`)}}};Bc.default=yE});var Lg=M(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var uo=te(),bE={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,uo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,uo._)`{limit: ${t}}`},wE={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:bE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?uo.operators.GT:uo.operators.LT;t.fail$data((0,uo._)`Object.keys(${r}).length ${o} ${n}`)}};Fc.default=wE});var jg=M(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var po=ct(),mo=te(),vE=ue(),_E={message:({params:{missingProperty:t}})=>(0,mo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,mo._)`{missingProperty: ${t}}`},SE={keyword:"required",type:"object",schemaType:"array",$data:!0,error:_E,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 l=r.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let y=t.parentSchema.properties,{definedProperties:k}=t.it;for(let $ of r)if(y?.[$]===void 0&&!k.has($)){let R=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${$}" is not defined at "${R}" (strictRequired)`;(0,vE.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||s)t.block$data(mo.nil,f);else for(let y of r)(0,po.checkReportMissingProp)(t,y)}function p(){let y=e.let("missing");if(l||s){let k=e.let("valid",!0);t.block$data(k,()=>S(y,k)),t.ok(k)}else e.if((0,po.checkMissingProp)(t,r,y)),(0,po.reportMissingProp)(t,y),e.else()}function f(){e.forOf("prop",n,y=>{t.setParams({missingProperty:y}),e.if((0,po.noPropertyInData)(e,o,y,a.ownProperties),()=>t.error())})}function S(y,k){t.setParams({missingProperty:y}),e.forOf(y,n,()=>{e.assign(k,(0,po.propertyInData)(e,o,y,a.ownProperties)),e.if((0,mo.not)(k),()=>{t.error(),e.break()})},mo.nil)}}};Hc.default=SE});var Dg=M(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var ho=te(),kE={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ho.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ho._)`{limit: ${t}}`},TE={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:kE,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ho.operators.GT:ho.operators.LT;t.fail$data((0,ho._)`${r}.length ${o} ${n}`)}};Kc.default=TE});var pi=M(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var Ug=fc();Ug.code='require("ajv/dist/runtime/equal").default';Vc.default=Ug});var Mg=M(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var Wc=Qn(),je=te(),xE=ue(),$E=pi(),RE={message:({params:{i:t,j:e}})=>(0,je.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,je._)`{i: ${t}, j: ${e}}`},EE={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RE,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let l=e.let("valid"),u=s.items?(0,Wc.getSchemaTypes)(s.items):[];t.block$data(l,p,(0,je._)`${i} === false`),t.ok(l);function p(){let k=e.let("i",(0,je._)`${r}.length`),$=e.let("j");t.setParams({i:k,j:$}),e.assign(l,!0),e.if((0,je._)`${k} > 1`,()=>(f()?S:y)(k,$))}function f(){return u.length>0&&!u.some(k=>k==="object"||k==="array")}function S(k,$){let R=e.name("item"),P=(0,Wc.checkDataTypes)(u,R,a.opts.strictNumbers,Wc.DataType.Wrong),O=e.const("indices",(0,je._)`{}`);e.for((0,je._)`;${k}--;`,()=>{e.let(R,(0,je._)`${r}[${k}]`),e.if(P,(0,je._)`continue`),u.length>1&&e.if((0,je._)`typeof ${R} == "string"`,(0,je._)`${R} += "_"`),e.if((0,je._)`typeof ${O}[${R}] == "number"`,()=>{e.assign($,(0,je._)`${O}[${R}]`),t.error(),e.assign(l,!1).break()}).code((0,je._)`${O}[${R}] = ${k}`)})}function y(k,$){let R=(0,xE.useFunc)(e,$E.default),P=e.name("outer");e.label(P).for((0,je._)`;${k}--;`,()=>e.for((0,je._)`${$} = ${k}; ${$}--;`,()=>e.if((0,je._)`${R}(${r}[${k}], ${r}[${$}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Gc.default=EE});var qg=M(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var Jc=te(),PE=ue(),AE=pi(),CE={message:"must be equal to constant",params:({schemaCode:t})=>(0,Jc._)`{allowedValue: ${t}}`},IE={keyword:"const",$data:!0,error:CE,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Jc._)`!${(0,PE.useFunc)(e,AE.default)}(${r}, ${o})`):t.fail((0,Jc._)`${s} !== ${r}`)}};Yc.default=IE});var zg=M(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var fo=te(),OE=ue(),NE=pi(),LE={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,fo._)`{allowedValues: ${t}}`},jE={keyword:"enum",schemaType:"array",$data:!0,error:LE,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,l,u=()=>l??(l=(0,OE.useFunc)(e,NE.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=e.const("vSchema",s);p=(0,fo.or)(...o.map((k,$)=>S(y,$)))}t.pass(p);function f(){e.assign(p,!1),e.forOf("v",s,y=>e.if((0,fo._)`${u()}(${r}, ${y})`,()=>e.assign(p,!0).break()))}function S(y,k){let $=o[k];return typeof $=="object"&&$!==null?(0,fo._)`${u()}(${r}, ${y}[${k}])`:(0,fo._)`${r} === ${$}`}}};Xc.default=jE});var Bg=M(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var DE=Pg(),UE=Ag(),ME=Og(),qE=Ng(),zE=Lg(),BE=jg(),FE=Dg(),HE=Mg(),KE=qg(),VE=zg(),WE=[DE.default,UE.default,ME.default,qE.default,zE.default,BE.default,FE.default,HE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},KE.default,VE.default];Zc.default=WE});var ed=M(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.validateAdditionalItems=void 0;var Rr=te(),Qc=ue(),GE={message:({params:{len:t}})=>(0,Rr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Rr._)`{limit: ${t}}`},JE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:GE,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Qc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Fg(t,n)}};function Fg(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Rr._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Rr._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Qc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Rr._)`${a} <= ${e.length}`);r.if((0,Rr.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,a,p=>{t.subschema({keyword:s,dataProp:p,dataPropType:Qc.Type.Num},u),i.allErrors||r.if((0,Rr.not)(u),()=>r.break())})}}go.validateAdditionalItems=Fg;go.default=JE});var td=M(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.validateTuple=void 0;var Hg=te(),mi=ue(),YE=ct(),XE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Kg(t,"additionalItems",e);r.items=!0,!(0,mi.alwaysValidSchema)(r,e)&&t.ok((0,YE.validateArray)(t))}};function Kg(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=mi.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),u=n.const("len",(0,Hg._)`${s}.length`);r.forEach((f,S)=>{(0,mi.alwaysValidSchema)(a,f)||(n.if((0,Hg._)`${u} > ${S}`,()=>t.subschema({keyword:i,schemaProp:S,dataProp:S},l)),t.ok(l))});function p(f){let{opts:S,errSchemaPath:y}=a,k=r.length,$=k===f.minItems&&(k===f.maxItems||f[e]===!1);if(S.strictTuples&&!$){let R=`"${i}" is ${k}-tuple, but minItems or maxItems/${e} are not specified or different at path "${y}"`;(0,mi.checkStrictMode)(a,R,S.strictTuples)}}}yo.validateTuple=Kg;yo.default=XE});var Vg=M(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var ZE=td(),QE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,ZE.validateTuple)(t,"items")};rd.default=QE});var Gg=M(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var Wg=te(),e0=ue(),t0=ct(),r0=ed(),n0={message:({params:{len:t}})=>(0,Wg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Wg._)`{limit: ${t}}`},o0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:n0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,e0.alwaysValidSchema)(n,e)&&(o?(0,r0.validateAdditionalItems)(t,o):t.ok((0,t0.validateArray)(t)))}};nd.default=o0});var Jg=M(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var ut=te(),hi=ue(),s0={message:({params:{min:t,max:e}})=>e===void 0?(0,ut.str)`must contain at least ${t} valid item(s)`:(0,ut.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ut._)`{minContains: ${t}}`:(0,ut._)`{minContains: ${t}, maxContains: ${e}}`},i0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:s0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:l,maxContains:u}=n;s.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=e.const("len",(0,ut._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,hi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,hi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,hi.alwaysValidSchema)(s,r)){let $=(0,ut._)`${p} >= ${i}`;a!==void 0&&($=(0,ut._)`${$} && ${p} <= ${a}`),t.pass($);return}s.items=!0;let f=e.name("valid");a===void 0&&i===1?y(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),a!==void 0&&e.if((0,ut._)`${o}.length > 0`,S)):(e.let(f,!1),S()),t.result(f,()=>t.reset());function S(){let $=e.name("_valid"),R=e.let("count",0);y($,()=>e.if($,()=>k(R)))}function y($,R){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:hi.Type.Num,compositeRule:!0},$),R()})}function k($){e.code((0,ut._)`${$}++`),a===void 0?e.if((0,ut._)`${$} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,ut._)`${$} > ${a}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,ut._)`${$} >= ${i}`,()=>e.assign(f,!0)))}}};od.default=i0});var Zg=M(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.validateSchemaDeps=Pt.validatePropertyDeps=Pt.error=void 0;var sd=te(),a0=ue(),bo=ct();Pt.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,sd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,sd._)`{property: ${t},
2011
+ missingProperty: ${n},
1999
2012
  depsCount: ${e},
2000
- deps: ${n}}`};var GE={keyword:"dependencies",type:"object",schemaType:"object",error:Pt.error,code(t){let[e,n]=JE(t);Vg(t,e),Wg(t,n)}};function JE({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let s=Array.isArray(t[r])?e:n;s[r]=t[r]}return[e,n]}function Vg(t,e=t.schema){let{gen:n,data:r,it:s}=t;if(Object.keys(e).length===0)return;let o=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,bs.propertyInData)(n,r,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?n.if(l,()=>{for(let u of a)(0,bs.checkReportMissingProp)(t,u)}):(n.if((0,od._)`${l} && (${(0,bs.checkMissingProp)(t,a,o)})`),(0,bs.reportMissingProp)(t,o),n.else())}}Pt.validatePropertyDeps=Vg;function Wg(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,WE.alwaysValidSchema)(o,e[a])||(n.if((0,bs.propertyInData)(n,r,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>n.var(i,!0)),t.ok(i))}Pt.validateSchemaDeps=Wg;Pt.default=GE});var Yg=M(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var Jg=te(),YE=ue(),XE={message:"property name must be valid",params:({params:t})=>(0,Jg._)`{propertyName: ${t.propertyName}}`},ZE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:XE,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,YE.alwaysValidSchema)(s,n))return;let o=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,Jg.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};id.default=ZE});var ld=M(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var mi=ct(),kt=te(),QE=Ut(),gi=ue(),e0={message:"must NOT have additional properties",params:({params:t})=>(0,kt._)`{additionalProperty: ${t.additionalProperty}}`},t0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:e0,code(t){let{gen:e,schema:n,parentSchema:r,data:s,errsCount:o,it:i}=t;if(!o)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,gi.alwaysValidSchema)(i,n))return;let u=(0,mi.allSchemaProperties)(r.properties),p=(0,mi.allSchemaProperties)(r.patternProperties);m(),t.ok((0,kt._)`${o} === ${QE.default.errors}`);function m(){e.forIn("key",s,T=>{!u.length&&!p.length?_(T):e.if(S(T),()=>_(T))})}function S(T){let P;if(u.length>8){let N=(0,gi.schemaRefOrVal)(i,r.properties,"properties");P=(0,mi.isOwnProperty)(e,N,T)}else u.length?P=(0,kt.or)(...u.map(N=>(0,kt._)`${T} === ${N}`)):P=kt.nil;return p.length&&(P=(0,kt.or)(P,...p.map(N=>(0,kt._)`${(0,mi.usePattern)(t,N)}.test(${T})`))),(0,kt.not)(P)}function b(T){e.code((0,kt._)`delete ${s}[${T}]`)}function _(T){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){b(T);return}if(n===!1){t.setParams({additionalProperty:T}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,gi.alwaysValidSchema)(i,n)){let P=e.name("valid");l.removeAdditional==="failing"?(R(T,P,!1),e.if((0,kt.not)(P),()=>{t.reset(),b(T)})):(R(T,P),a||e.if((0,kt.not)(P),()=>e.break()))}}function R(T,P,N){let D={keyword:"additionalProperties",dataProp:T,dataPropType:gi.Type.Str};N===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};ad.default=t0});var Qg=M(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var n0=rs(),Xg=ct(),cd=ue(),Zg=ld(),r0={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:s,it:o}=t;o.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Zg.default.code(new n0.KeywordCxt(o,Zg.default,"additionalProperties"));let i=(0,Xg.allSchemaProperties)(n);for(let m of i)o.definedProperties.add(m);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=cd.mergeEvaluated.props(e,(0,cd.toHash)(i),o.props));let a=i.filter(m=>!(0,cd.alwaysValidSchema)(o,n[m]));if(a.length===0)return;let l=e.name("valid");for(let m of a)u(m)?p(m):(e.if((0,Xg.propertyInData)(e,s,m,o.opts.ownProperties)),p(m),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(m),t.ok(l);function u(m){return o.opts.useDefaults&&!o.compositeRule&&n[m].default!==void 0}function p(m){t.subschema({keyword:"properties",schemaProp:m,dataProp:m},l)}}};dd.default=r0});var rb=M(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var eb=ct(),bi=te(),tb=ue(),nb=ue(),s0={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,eb.allSchemaProperties)(n),l=a.filter(R=>(0,tb.alwaysValidSchema)(o,n[R]));if(a.length===0||l.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,p=e.name("valid");o.props!==!0&&!(o.props instanceof bi.Name)&&(o.props=(0,nb.evaluatedPropsToName)(e,o.props));let{props:m}=o;S();function S(){for(let R of a)u&&b(R),o.allErrors?_(R):(e.var(p,!0),_(R),e.if(p))}function b(R){for(let T in u)new RegExp(R).test(T)&&(0,tb.checkStrictMode)(o,`property ${T} matches pattern ${R} (use allowMatchingProperties)`)}function _(R){e.forIn("key",r,T=>{e.if((0,bi._)`${(0,eb.usePattern)(t,R)}.test(${T})`,()=>{let P=l.includes(R);P||t.subschema({keyword:"patternProperties",schemaProp:R,dataProp:T,dataPropType:nb.Type.Str},p),o.opts.unevaluated&&m!==!0?e.assign((0,bi._)`${m}[${T}]`,!0):!P&&!o.allErrors&&e.if((0,bi.not)(p),()=>e.break())})})}}};ud.default=s0});var sb=M(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var o0=ue(),i0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,o0.alwaysValidSchema)(r,n)){t.fail();return}let s=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},s),t.failResult(s,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};pd.default=i0});var ob=M(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var a0=ct(),l0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:a0.validateUnion,error:{message:"must match a schema in anyOf"}};hd.default=l0});var ib=M(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var yi=te(),c0=ue(),d0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,yi._)`{passingSchemas: ${t.passing}}`},u0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:d0,code(t){let{gen:e,schema:n,parentSchema:r,it:s}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(s.opts.discriminator&&r.discriminator)return;let o=n,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((p,m)=>{let S;(0,c0.alwaysValidSchema)(s,p)?e.var(l,!0):S=t.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},l),m>0&&e.if((0,yi._)`${l} && ${i}`).assign(i,!1).assign(a,(0,yi._)`[${a}, ${m}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,m),S&&t.mergeEvaluated(S,yi.Name)})})}}};fd.default=u0});var ab=M(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var p0=ue(),h0={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let s=e.name("valid");n.forEach((o,i)=>{if((0,p0.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};md.default=h0});var db=M(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var wi=te(),cb=ue(),f0={message:({params:t})=>(0,wi.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,wi._)`{failingKeyword: ${t.ifClause}}`},m0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:f0,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,cb.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=lb(r,"then"),o=lb(r,"else");if(!s&&!o)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),s&&o){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,u("then",p),u("else",p))}else s?e.if(a,u("then")):e.if((0,wi.not)(a),u("else"));t.pass(i,()=>t.error(!0));function l(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function u(p,m){return()=>{let S=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(S,i),m?e.assign(m,(0,wi._)`${p}`):t.setParams({ifClause:p})}}}};function lb(t,e){let n=t.schema[e];return n!==void 0&&!(0,cb.alwaysValidSchema)(t,n)}gd.default=m0});var ub=M(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var g0=ue(),b0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,g0.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};bd.default=b0});var pb=M(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var y0=ed(),w0=Bg(),v0=td(),k0=Hg(),S0=Kg(),_0=Gg(),x0=Yg(),$0=ld(),R0=Qg(),T0=rb(),E0=sb(),P0=ob(),A0=ib(),I0=ab(),C0=db(),O0=ub();function N0(t=!1){let e=[E0.default,P0.default,A0.default,I0.default,C0.default,O0.default,x0.default,$0.default,_0.default,R0.default,T0.default];return t?e.push(w0.default,k0.default):e.push(y0.default,v0.default),e.push(S0.default),e}yd.default=N0});var hb=M(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var _e=te(),L0={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},j0={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:L0,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:m}=a;if(!l.validateFormats)return;s?S():b();function S(){let _=n.scopeValue("formats",{ref:m.formats,code:l.code.formats}),R=n.const("fDef",(0,_e._)`${_}[${i}]`),T=n.let("fType"),P=n.let("format");n.if((0,_e._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>n.assign(T,(0,_e._)`${R}.type || "string"`).assign(P,(0,_e._)`${R}.validate`),()=>n.assign(T,(0,_e._)`"string"`).assign(P,R)),t.fail$data((0,_e.or)(N(),D()));function N(){return l.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${P}`}function D(){let Y=p.$async?(0,_e._)`(${R}.async ? await ${P}(${r}) : ${P}(${r}))`:(0,_e._)`${P}(${r})`,K=(0,_e._)`(typeof ${P} == "function" ? ${Y} : ${P}.test(${r}))`;return(0,_e._)`${P} && ${P} !== true && ${T} === ${e} && !${K}`}}function b(){let _=m.formats[o];if(!_){N();return}if(_===!0)return;let[R,T,P]=D(_);R===e&&t.pass(Y());function N(){if(l.strictSchema===!1){m.logger.warn(K());return}throw new Error(K());function K(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function D(K){let Ae=K instanceof RegExp?(0,_e.regexpCode)(K):l.code.formats?(0,_e._)`${l.code.formats}${(0,_e.getProperty)(o)}`:void 0,De=n.scopeValue("formats",{key:o,ref:K,code:Ae});return typeof K=="object"&&!(K instanceof RegExp)?[K.type||"string",K.validate,(0,_e._)`${De}.validate`]:["string",K,De]}function Y(){if(typeof _=="object"&&!(_ instanceof RegExp)&&_.async){if(!p.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${P}(${r})`}return typeof T=="function"?(0,_e._)`${P}(${r})`:(0,_e._)`${P}.test(${r})`}}}};wd.default=j0});var fb=M(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var D0=hb(),U0=[D0.default];vd.default=U0});var mb=M(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.contentVocabulary=ar.metadataVocabulary=void 0;ar.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ar.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var bb=M(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var M0=xg(),q0=Ug(),z0=pb(),B0=fb(),gb=mb(),F0=[M0.default,q0.default,(0,z0.default)(),B0.default,gb.metadataVocabulary,gb.contentVocabulary];kd.default=F0});var wb=M(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.DiscrError=void 0;var yb;(function(t){t.Tag="tag",t.Mapping="mapping"})(yb||(vi.DiscrError=yb={}))});var kb=M(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var lr=te(),Sd=wb(),vb=ti(),H0=ss(),K0=ue(),V0={message:({params:{discrError:t,tagName:e}})=>t===Sd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,lr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},W0={keyword:"discriminator",type:"object",schemaType:"object",error:V0,code(t){let{gen:e,data:n,schema:r,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),u=e.const("tag",(0,lr._)`${n}${(0,lr.getProperty)(a)}`);e.if((0,lr._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:Sd.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let b=S();e.if(!1);for(let _ in b)e.elseIf((0,lr._)`${u} === ${_}`),e.assign(l,m(b[_]));e.else(),t.error(!1,{discrError:Sd.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function m(b){let _=e.name("valid"),R=t.subschema({keyword:"oneOf",schemaProp:b},_);return t.mergeEvaluated(R,lr.Name),_}function S(){var b;let _={},R=P(s),T=!0;for(let Y=0;Y<i.length;Y++){let K=i[Y];if(K?.$ref&&!(0,K0.schemaHasRulesButRef)(K,o.self.RULES)){let De=K.$ref;if(K=vb.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,De),K instanceof vb.SchemaEnv&&(K=K.schema),K===void 0)throw new H0.default(o.opts.uriResolver,o.baseId,De)}let Ae=(b=K?.properties)===null||b===void 0?void 0:b[a];if(typeof Ae!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);T=T&&(R||P(K)),N(Ae,Y)}if(!T)throw new Error(`discriminator: "${a}" must be required`);return _;function P({required:Y}){return Array.isArray(Y)&&Y.includes(a)}function N(Y,K){if(Y.const)D(Y.const,K);else if(Y.enum)for(let Ae of Y.enum)D(Ae,K);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(Y,K){if(typeof Y!="string"||Y in _)throw new Error(`discriminator: "${a}" values must be unique strings`);_[Y]=K}}}};_d.default=W0});var Sb=M((n1,G0)=>{G0.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 $d=M((ve,xd)=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.MissingRefError=ve.ValidationError=ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=ve.Ajv=void 0;var J0=yg(),Y0=bb(),X0=kb(),_b=Sb(),Z0=["/properties"],ki="http://json-schema.org/draft-07/schema",cr=class extends J0.default{_addVocabularies(){super._addVocabularies(),Y0.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(X0.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(_b,Z0):_b;this.addMetaSchema(e,ki,!1),this.refs["http://json-schema.org/schema"]=ki}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ki)?ki:void 0)}};ve.Ajv=cr;xd.exports=ve=cr;xd.exports.Ajv=cr;Object.defineProperty(ve,"__esModule",{value:!0});ve.default=cr;var Q0=rs();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return Q0.KeywordCxt}});var dr=te();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return dr._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return dr.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return dr.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return dr.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return dr.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return dr.CodeGen}});var eP=Qo();Object.defineProperty(ve,"ValidationError",{enumerable:!0,get:function(){return eP.default}});var tP=ss();Object.defineProperty(ve,"MissingRefError",{enumerable:!0,get:function(){return tP.default}})});var Ib=M(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.formatNames=It.fastFormats=It.fullFormats=void 0;function At(t,e){return{validate:t,compare:e}}It.fullFormats={date:At(Tb,Pd),time:At(Td(!0),Ad),"date-time":At(xb(!0),Pb),"iso-time":At(Td(),Eb),"iso-date-time":At(xb(),Ab),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:aP,"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:fP,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:lP,int32:{type:"number",validate:uP},int64:{type:"number",validate:pP},float:{type:"number",validate:Rb},double:{type:"number",validate:Rb},password:!0,binary:!0};It.fastFormats={...It.fullFormats,date:At(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pd),time:At(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ad),"date-time":At(/^\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,Pb),"iso-time":At(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Eb),"iso-date-time":At(/^\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,Ab),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};It.formatNames=Object.keys(It.fullFormats);function nP(t){return t%4===0&&(t%100!==0||t%400===0)}var rP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,sP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Tb(t){let e=rP.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],s=+e[3];return r>=1&&r<=12&&s>=1&&s<=(r===2&&nP(n)?29:sP[r])}function Pd(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Rd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Td(t){return function(n){let r=Rd.exec(n);if(!r)return!1;let s=+r[1],o=+r[2],i=+r[3],a=r[4],l=r[5]==="-"?-1:1,u=+(r[6]||0),p=+(r[7]||0);if(u>23||p>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let m=o-p*l,S=s-u*l-(m<0?1:0);return(S===23||S===-1)&&(m===59||m===-1)&&i<61}}function Ad(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function Eb(t,e){if(!(t&&e))return;let n=Rd.exec(t),r=Rd.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var Ed=/t|\s/i;function xb(t){let e=Td(t);return function(r){let s=r.split(Ed);return s.length===2&&Tb(s[0])&&e(s[1])}}function Pb(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function Ab(t,e){if(!(t&&e))return;let[n,r]=t.split(Ed),[s,o]=e.split(Ed),i=Pd(n,s);if(i!==void 0)return i||Ad(r,o)}var oP=/\/|:/,iP=/^(?:[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 aP(t){return oP.test(t)&&iP.test(t)}var $b=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function lP(t){return $b.lastIndex=0,$b.test(t)}var cP=-(2**31),dP=2**31-1;function uP(t){return Number.isInteger(t)&&t<=dP&&t>=cP}function pP(t){return Number.isInteger(t)}function Rb(){return!0}var hP=/[^\\]\\Z/;function fP(t){if(hP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Cb=M(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.formatLimitDefinition=void 0;var mP=$d(),St=te(),ln=St.operators,Si={formatMaximum:{okStr:"<=",ok:ln.LTE,fail:ln.GT},formatMinimum:{okStr:">=",ok:ln.GTE,fail:ln.LT},formatExclusiveMaximum:{okStr:"<",ok:ln.LT,fail:ln.GTE},formatExclusiveMinimum:{okStr:">",ok:ln.GT,fail:ln.LTE}},gP={message:({keyword:t,schemaCode:e})=>(0,St.str)`should be ${Si[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,St._)`{comparison: ${Si[t].okStr}, limit: ${e}}`};ur.formatLimitDefinition={keyword:Object.keys(Si),type:"string",schemaType:"string",$data:!0,error:gP,code(t){let{gen:e,data:n,schemaCode:r,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let l=new mP.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let S=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),b=e.const("fmt",(0,St._)`${S}[${l.schemaCode}]`);t.fail$data((0,St.or)((0,St._)`typeof ${b} != "object"`,(0,St._)`${b} instanceof RegExp`,(0,St._)`typeof ${b}.compare != "function"`,m(b)))}function p(){let S=l.schema,b=a.formats[S];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${s}": format "${S}" does not define "compare" function`);let _=e.scopeValue("formats",{key:S,ref:b,code:i.code.formats?(0,St._)`${i.code.formats}${(0,St.getProperty)(S)}`:void 0});t.fail$data(m(_))}function m(S){return(0,St._)`${S}.compare(${n}, ${r}) ${Si[s].fail} 0`}},dependencies:["format"]};var bP=t=>(t.addKeyword(ur.formatLimitDefinition),t);ur.default=bP});var jb=M((ys,Lb)=>{"use strict";Object.defineProperty(ys,"__esModule",{value:!0});var pr=Ib(),yP=Cb(),Id=te(),Ob=new Id.Name("fullFormats"),wP=new Id.Name("fastFormats"),Cd=(t,e={keywords:!0})=>{if(Array.isArray(e))return Nb(t,e,pr.fullFormats,Ob),t;let[n,r]=e.mode==="fast"?[pr.fastFormats,wP]:[pr.fullFormats,Ob],s=e.formats||pr.formatNames;return Nb(t,s,n,r),e.keywords&&(0,yP.default)(t),t};Cd.get=(t,e="full")=>{let r=(e==="fast"?pr.fastFormats:pr.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Nb(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Id._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}Lb.exports=ys=Cd;Object.defineProperty(ys,"__esModule",{value:!0});ys.default=Cd});function vP(){let t=new Db.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ub.default)(t),t}var Db,Ub,_i,Mb=j(()=>{Db=Wd($d(),1),Ub=Wd(jb(),1);_i=class{constructor(e){this._ajv=e??vP()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}}});var xi,qb=j(()=>{Jn();xi=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let s=e.messages[e.messages.length-1],o=Array.isArray(s.content)?s.content:[s.content],i=o.some(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],u=l.some(p=>p.type==="tool_use");if(i){if(o.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let p=new Set(l.filter(S=>S.type==="tool_use").map(S=>S.id)),m=new Set(o.filter(S=>S.type==="tool_result").map(S=>S.toolUseId));if(p.size!==m.size||![...p].every(S=>m.has(S)))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},zr,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},Gn,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}}});function zb(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function Bb(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Fb=j(()=>{});var $i,Hb=j(()=>{Wf();Jn();Mb();Ir();qb();Fb();$i=class extends qo{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(qr.options.map((r,s)=>[r,s])),this.isMessageIgnored=(r,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new _i,this.setRequestHandler(Va,r=>this._oninitialize(r)),this.setNotificationHandler(Wa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(el,async(r,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=qr.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new xi(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Vf(this._capabilities,e)}setRequestHandler(e,n){let s=Yt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=Fn(s);if(typeof o!="string")throw new Error("Schema method literal must be a string");if(o==="tools/call"){let a=async(l,u)=>{let p=Jt(Wn,l);if(!p.success){let _=p.error instanceof Error?p.error.message:String(p.error);throw new B(W.InvalidParams,`Invalid tools/call request: ${_}`)}let{params:m}=p.data,S=await Promise.resolve(n(l,u));if(m.task){let _=Jt(Kn,S);if(!_.success){let R=_.error instanceof Error?_.error.message:String(_.error);throw new B(W.InvalidParams,`Invalid task creation result: ${R}`)}return _.data}let b=Jt(Eo,S);if(!b.success){let _=b.error instanceof Error?b.error.message:String(b.error);throw new B(W.InvalidParams,`Invalid tools/call result: ${_}`)}return b.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}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){Bb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&zb(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Hh.includes(n)?n:za,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"},po)}async createMessage(e,n){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 r=e.messages[e.messages.length-1],s=Array.isArray(r.content)?r.content:[r.content],o=s.some(u=>u.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]:[],l=a.some(u=>u.type==="tool_use");if(o){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(a.filter(m=>m.type==="tool_use").map(m=>m.id)),p=new Set(s.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(u.size!==p.size||![...u].every(m=>p.has(m)))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},tl,n):this.request({method:"sampling/createMessage",params:e},zr,n)}async elicitInput(e,n){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},Gn,n)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let s=e.mode==="form"?e:{...e,mode:"form"},o=await this.request({method:"elicitation/create",params:s},Gn,n);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new B(W.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof B?i:new B(W.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,n){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}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},nl,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))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 Od(t){return!!t&&typeof t=="object"&&Vb in t}function Wb(t){return t[Vb]?.complete}var Vb,Kb,Gb=j(()=>{Vb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Kb||(Kb={}))});var Jb=j(()=>{});function SP(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"),!kP.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,s,o)=>o.indexOf(r)===s);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function _P(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 Nd(t){let e=SP(t);return _P(t,e.warnings),e.isValid}var kP,Yb=j(()=>{kP=/^[A-Za-z0-9._-]{1,128}$/});var Ri,Xb=j(()=>{Ri=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let s={taskSupport:"required",...n.execution};if(s.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,s,n._meta,r)}}});import{ZodOptional as xP}from"zod";function ey(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function ty(t){return"_def"in t||"_zod"in t||ey(t)}function Ld(t){return typeof t!="object"||t===null||ty(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(ey)}function Zb(t){if(t){if(Ld(t))return bn(t);if(!ty(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function RP(t){let e=Yt(t);return e?Object.entries(e).map(([n,r])=>{let s=Bh(r),o=Fh(r);return{name:n,description:s,required:!o}}):[]}function cn(t){let n=Yt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Fn(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function Qb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ti,$P,ws,ny=j(()=>{Hb();Ir();Ml();Jn();Gb();Jb();Yb();Xb();Ti=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new $i(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Ri(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(cn(To)),this.server.assertCanSetRequestHandler(cn(Wn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(To,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let s=Bn(n.inputSchema);return s?jl(s,{strictUnions:!0,pipeStrategy:"input"}):$P})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=Bn(n.outputSchema);s&&(r.outputSchema=jl(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Wn,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new B(W.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new B(W.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=r.execution?.taskSupport,i="createTask"in r.handler;if((o==="required"||o==="optional")&&!i)throw new B(W.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new B(W.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),l=await this.executeToolHandler(r,a,n);return s||await this.validateToolOutput(r,l,e.params.name),l}catch(r){if(r instanceof B&&r.code===W.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let o=Bn(e.inputSchema)??e.inputSchema,i=await io(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",l=ao(a);throw new B(W.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${l}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new B(W.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=Bn(e.outputSchema),o=await io(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=ao(i);throw new B(W.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let s=e.handler;if("createTask"in s){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(n,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(n,r))}else{let i=s;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,n.params.arguments,n.params.name),o=e.handler,i={...r,taskStore:r.taskStore},a=s?await Promise.resolve(o.createTask(s,i)):await Promise.resolve(o.createTask(i)),l=a.task.taskId,u=a.task,p=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(S=>setTimeout(S,p));let m=await r.taskStore.getTask(l);if(!m)throw new B(W.InternalError,`Task ${l} not found during polling`);u=m}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cn(Po)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Po,async e=>{switch(e.params.ref.type){case"ref/prompt":return af(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return lf(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(W.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new B(W.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new B(W.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return ws;let o=Yt(r.argsSchema)?.[e.params.argument.name];if(!Od(o))return ws;let i=Wb(o);if(!i)return ws;let a=await i(e.params.argument.value,e.params.context);return Qb(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return ws;throw new B(W.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ws;let o=await s(e.params.argument.value,e.params.context);return Qb(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(cn(So)),this.server.assertCanSetRequestHandler(cn(_o)),this.server.assertCanSetRequestHandler(cn(xo)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(So,async(e,n)=>{let r=Object.entries(this._registeredResources).filter(([o,i])=>i.enabled).map(([o,i])=>({uri:o,name:i.name,...i.metadata})),s=[];for(let o of Object.values(this._registeredResourceTemplates)){if(!o.resourceTemplate.listCallback)continue;let i=await o.resourceTemplate.listCallback(n);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...r,...s]}}),this.server.setRequestHandler(_o,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(xo,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new B(W.InvalidParams,`Resource ${r} disabled`);return s.readCallback(r,n)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(r.toString());if(i)return o.readCallback(r,i,n)}throw new B(W.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(cn($o)),this.server.assertCanSetRequestHandler(cn(Ro)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler($o,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?RP(n.argsSchema):void 0}))})),this.server.setRequestHandler(Ro,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new B(W.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new B(W.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=Bn(r.argsSchema),o=await io(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",u=ao(l);throw new B(W.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let s=r.callback;return await Promise.resolve(s(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let s;typeof r[0]=="object"&&(s=r.shift());let o=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,s,o);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,n,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,s){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let o=this._createRegisteredResource(e,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let o=this._createRegisteredResourceTemplate(e,r.title,n,r,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,n,r,s,o){let i={name:e,title:n,metadata:s,readCallback:o,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!==r&&(delete this._registeredResources[r],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[r]=i,i}_createRegisteredResourceTemplate(e,n,r,s,o){let i={resourceTemplate:r,title:n,metadata:s,readCallback:o,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,s,o){let i={title:n,description:r,argsSchema:s===void 0?void 0:bn(s),callback:o,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,s&&Object.values(s).some(l=>{let u=l instanceof xP?l._def?.innerType:l;return Od(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,l,u){Nd(e);let p={title:n,description:r,inputSchema:Zb(s),outputSchema:Zb(o),annotations:i,execution:a,_meta:l,handler:u,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:m=>{typeof m.name<"u"&&m.name!==e&&(typeof m.name=="string"&&Nd(m.name),delete this._registeredTools[e],m.name&&(this._registeredTools[m.name]=p)),typeof m.title<"u"&&(p.title=m.title),typeof m.description<"u"&&(p.description=m.description),typeof m.paramsSchema<"u"&&(p.inputSchema=bn(m.paramsSchema)),typeof m.outputSchema<"u"&&(p.outputSchema=bn(m.outputSchema)),typeof m.callback<"u"&&(p.handler=m.callback),typeof m.annotations<"u"&&(p.annotations=m.annotations),typeof m._meta<"u"&&(p._meta=m._meta),typeof m.enabled<"u"&&(p.enabled=m.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(e,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,s,o,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let l=n[0];if(Ld(l))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Ld(n[0])&&(i=n.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:s,description:o,inputSchema:i,outputSchema:a,annotations:l,_meta:u}=n;return this._createRegisteredTool(e,s,o,i,a,l,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let s;n.length>1&&(s=n.shift());let o=n[0],i=this._createRegisteredPrompt(e,void 0,r,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=n,a=this._createRegisteredPrompt(e,s,o,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},$P={type:"object",properties:{}};ws={completion:{values:[],hasMore:!1}}});function EP(t){return Zh.parse(JSON.parse(t))}function ry(t){return JSON.stringify(t)+`
2001
- `}var TP,Ei,sy=j(()=>{Jn();TP=10*1024*1024,Ei=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??TP}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(`
2002
- `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),EP(n)}clear(){this._buffer=void 0}}});import oy from"node:process";var Pi,iy=j(()=>{sy();Pi=class{constructor(e=oy.stdin,n=oy.stdout,r){this._stdin=e,this._stdout=n,this._started=!1,this._ondata=s=>{try{this._readBuffer.append(s),this.processReadBuffer()}catch(o){this.onerror?.(o),this.close().catch(()=>{})}},this._onerror=s=>{this.onerror?.(s)},this._readBuffer=new Ei({maxBufferSize:r?.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(n=>{let r=ry(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var ay,ly=j(()=>{ay=[]});var by={};Vd(by,{AUTHORING_MCP_SERVER_NAME:()=>py,AUTHORING_MCP_SERVER_VERSION:()=>hy,AUTHORING_RESOURCES:()=>LP,AUTHORING_TOOLS:()=>NP,AUTHORING_TOOLS_PUBLIC:()=>gy,buildAuthoringMcpServer:()=>my,resolveSamplesDir:()=>fy,runAuthoringMcpServer:()=>jP});import{promises as PP}from"node:fs";import{isAbsolute as AP,resolve as Ai,sep as IP}from"node:path";import{z as q}from"zod";function uy(){return dy??=import("../mcp/grounding.js").then(e=>e,()=>null),dy}function fy(t,e){if(e===void 0)return Ai(process.cwd(),t??"samples");let n=Ai(e);if(t===void 0)return n;if(AP(t))return null;let r=Ai(n,t);return r===n||r.startsWith(n+IP)?r:null}function Se(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function OP(t,e={}){let n=e.fetchImpl??fetch;try{let r=await n(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return r.ok?((await r.json()).extensions??[]).map(o=>o.hookId).filter(o=>typeof o=="string"):null}catch{return null}}async function my(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let b=await pt(t.baseUrl);if(!b)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:b.baseUrl,token:b.token}}let n=t.grounding??{},r=await uy(),s=null;if(r)try{let b=await e();s={surface:"mcp-authoring",baseUrl:b.baseUrl,token:b.token}}catch{s=null}let o=r&&s?await r.loadActiveSources(s,n):[],i={...n,loadActiveSourcesImpl:async()=>o},a=[],l=[];if(r&&s){try{a=await r.listMcpPromptSkills(s,i)}catch{a=[]}try{l=(await r.listRecipesForSurface(s,i)).map(b=>({id:b.id,record_type:b.record_type,intent:b.intent}))}catch{l=[]}}let u=s?await OP(s,n):null,p=new Ti({name:py,version:hy},r?{instructions:r.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??s?.baseUrl??t.baseUrl??"this instance",sources:o,recipeIntents:l,promptNames:a.map(b=>b.id),deployedExtensions:u,docsToken:n.docsToken??r.docsPublicToken()})}:void 0);if(r&&s){let b=s;for(let _ of a)p.registerPrompt(_.id,{title:_.name,description:_.description},async()=>{let R=await r.getMcpPromptSkill(b,_.id,n);if(!R)throw new Error(`unknown prompt: ${_.id}`);return{description:R.description,messages:[{role:"user",content:{type:"text",text:(R.prompts??[]).join(`
2003
-
2004
- `)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:b,token:_}=await e(),R=await fetch(`${b}/v1/catalog/records`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return Se(await R.json())}),p.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:q.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:q.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:b,source:_})=>{let{baseUrl:R,token:T}=await e(),P=_?`?source=${encodeURIComponent(_)}`:"",N=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(b)}${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(N.status===404)throw new Error(`unknown record type "${b}" \u2014 list them with catalog_get.`);if(!N.ok)throw new Error(`record anatomy fetch failed: ${N.status}`);return Se(await N.json())}),p.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:q.array(q.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:q.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:b,source:_})=>{let{baseUrl:R,token:T}=await e(),P=new URLSearchParams({types:b.join(",")});_&&P.set("source",_);let N=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(N.status===404)throw new Error(`none of those record types resolved: ${b.join(", ")} \u2014 list them with catalog_get.`);if(!N.ok)throw new Error(`common columns fetch failed: ${N.status}`);return Se(await N.json())}),p.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:b,token:_}=await e(),R=await fetch(`${b}/v1/catalog/census`,{headers:{Authorization:`Bearer ${_}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return Se(await R.json())}),p.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:q.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:q.enum(cy).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:q.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:b,kind:_,limit:R})=>{let{baseUrl:T,token:P}=await e(),N=new URLSearchParams({q:b});_&&N.set("kind",_),R!==void 0&&N.set("limit",String(R));let D=await fetch(`${T}/v1/catalog/objects?${N}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Se(await D.json())}),p.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:q.enum(cy),externalId:q.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:b,externalId:_})=>{let{baseUrl:R,token:T}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(b)}/${encodeURIComponent(_)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${b}:${_} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Se(await P.json())}),p.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:q.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:q.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:b,limit:_})=>{let{baseUrl:R,token:T}=await e(),P=new URLSearchParams({q:b});_!==void 0&&P.set("limit",String(_));let N=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!N.ok)throw new Error(`kb search failed: ${N.status}`);return Se(await N.json())}),p.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:q.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:b})=>{let{baseUrl:_,token:R}=await e(),T=await fetch(`${_}/v1/kb/document/${encodeURIComponent(b)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!T.ok&&T.status!==404)throw new Error(`kb document fetch failed: ${T.status}`);return Se(await T.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:q.boolean().optional()}},async({recordsOnly:b})=>{let{baseUrl:_,token:R}=await e();return{content:[{type:"text",text:await hn({baseUrl:_,token:R,recordsOnly:b})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:q.string(),event:q.string().optional(),template:q.enum(["require-field","enforce-format","blank"]).optional(),field:q.string().optional(),regex:q.string().optional(),source:q.string().optional(),id:q.string().optional()}},async b=>{let _=$t("hook",{recordType:b.recordType,event:b.event,template:b.template,field:b.field,regex:b.regex,source:b.source,id:b.id});return Se({path:_.relativePath,content:_.content})}),p.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:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:q.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:q.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:q.string().optional().describe("Target record type (defaults to the trigger record type)."),event:q.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:q.string().optional()}},async b=>{let _=$t("conduit",{recordType:b.recordType,source:b.source,to:b.to,toRecordType:b.toRecordType,event:b.event,id:b.id});return Se({path:_.relativePath,content:_.content})}),p.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:q.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:q.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:q.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:q.string().optional()}},async b=>{let _=$t("process",{recordType:b.recordType,then:b.then,onFailure:b.onFailure,id:b.id});return Se({path:_.relativePath,content:_.content})}),p.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:q.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:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:q.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:q.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:q.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:q.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:q.array(q.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async b=>{let{baseUrl:_,token:R}=await e(),T=new z({baseUrl:_,token:R});return Se(await T.authorConduit({intent:b.intent,from:{source:b.fromSource,recordType:b.fromRecordType},to:{source:b.toSource,recordType:b.toRecordType},...b.intentId?{intentId:b.intentId}:{},...b.columns?.length?{columns:b.columns}:{}}))}),p.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:q.string().describe("The extension TS source."),samplesDir:q.string().optional().describe('Samples directory (default "samples").')}},async({source:b,samplesDir:_})=>{let R=fy(_,t.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:CP})}],isError:!0};let T;try{T=await wr(R)}catch(D){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 D}let P=await zs(b,T.map(D=>D.fixture)),N=P.filter(D=>!D.pass).length;return Se({total:P.length,passed:P.length-N,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:q.string(),recordType:q.string(),event:q.string(),source:q.string().describe('Adapter id or "standalone".'),sourceCode:q.string().describe("The verbatim extension TS."),extensionKind:q.string().optional()}},async b=>{let{baseUrl:_,token:R}=await e(),P=await new z({baseUrl:_,token:R}).deploy({id:b.id,recordType:b.recordType,event:b.event,source:b.source,sourceCode:b.sourceCode,extensionKind:b.extensionKind});return Se(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:q.string(),limit:q.number().int().positive().optional()}},async({id:b,limit:_})=>{let{baseUrl:R,token:T}=await e(),P=new z({baseUrl:R,token:T});return Se({id:b,logs:await P.logs(b,_)})}),p.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:b,token:_}=await e(),R=new z({baseUrl:b,token:_});return Se(await R.appsList())}),p.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:q.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:q.string().optional().describe("Display name (defaults to the slug)."),description:q.string().optional().describe("Short description.")}},async({slug:b,name:_,description:R})=>{let{baseUrl:T,token:P}=await e(),N=new z({baseUrl:T,token:P});return Se(await N.appsCreate({slug:b,name:_,description:R}))}),p.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:q.string().describe("App slug or id.")}},async({app:b})=>{let{baseUrl:_,token:R}=await e(),T=new z({baseUrl:_,token:R});return Se(await T.appsPull(b))}),p.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:q.string().describe("App slug or id."),files:q.record(q.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:q.string().optional().describe("Short note stored with the revision.")}},async({app:b,files:_,note:R})=>{let{baseUrl:T,token:P}=await e(),N=new z({baseUrl:T,token:P});return Se(await N.appsPush(b,_,{note:R}))});let m=q.object({name:q.string().describe("Field name (lowercase identifier)."),type:q.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:q.boolean().optional()}),S=q.object({slug:q.string().describe("Table slug; the physical table is cr_<slug>."),displayName:q.string().optional(),fields:q.array(m).describe("At least one field."),rowLevelOwner:q.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.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:b,token:_}=await e(),R=new z({baseUrl:b,token:_});return Se(await R.tablesList())}),p.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:q.array(S),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:_})=>{let{baseUrl:R,token:T}=await e(),P=new z({baseUrl:R,token:T});return Se(await P.tablesPlan({tables:b,claimedBy:_}))}),p.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:q.array(S),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:_})=>{let{baseUrl:R,token:T}=await e(),P=new z({baseUrl:R,token:T});return Se(await P.tablesApply({tables:b,claimedBy:_}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async b=>{let{baseUrl:_,token:R}=await e(),P=await(await fetch(`${_}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:b.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async b=>{let{baseUrl:_,token:R}=await e(),T=await hn({baseUrl:_,token:R});return{contents:[{uri:b.href,mimeType:"text/plain",text:T}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async b=>{let _=Ai(process.cwd(),"samples"),R=[];try{R=(await PP.readdir(_)).filter(P=>P.endsWith(".json"))}catch{R=[]}let T=await wr(_);return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:T.map(P=>P.fixture)},null,2)}]}}),p.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 b=>{let _=await uy(),R=[];if(_){let{baseUrl:T,token:P}=await e();R=await _.listRecipesForSurface({surface:"mcp-authoring",baseUrl:T,token:P},n)}return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function jP(t={}){let e=await my(t),n=new Pi;await e.connect(n)}var cy,dy,py,hy,CP,gy,NP,LP,yy=j(()=>{ny();iy();Yi();gr();ht();aa();Vs();ly();cy=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];py="turbobase-authoring",hy="0.1.0";CP="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.";gy=["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"],NP=[...gy,...ay],LP=["catalog:///","types://all","samples:///","recipes:///"]});Yi();gr();ht();aa();import{spawn as zd}from"node:child_process";import{promises as oe}from"node:fs";import{homedir as DP}from"node:os";import{basename as ky,dirname as qt,join as Qe,relative as Ci,resolve as se,sep as qd}from"node:path";import{Command as UP}from"commander";qs();import{promises as Pu}from"node:fs";function Eu(t,e){return e===t?"same-type-merge":"different-type-mint"}var Au=4;function la(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=On(t,"id"),n=On(t,"on"),r=On(t,"source"),s=On(t,"recordType"),o=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=On(l[1]??"","source"),p=On(l[1]??"","recordType");u&&p&&o.push({source:u,recordType:p})}let i=o[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!s||!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:n,fromSource:r,fromRecordType:s,toSource:i.source,toRecordType:i.recordType,targets:o,cycleBudget:a?Number(a[1]):Au}}function On(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function _w(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 Iu(t,e,n="fixture",r={}){let s=e.name??n,o=[],i;try{i=la(t)}catch(u){return{fixtureName:s,conduit:$w(),guards:o,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}let a=_w(e),l=Object.entries(e.atlasLinks??{}).map(([u,p])=>({key:u,resolved:p}));try{let u=await Ms(t,{resolveDir:r.resolveDir}),m=!!(await yr(u,a,{member:"when",timeoutMs:Us})).whenResult;o.push({name:"from.when",status:m?"passed":"failed",detail:m?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let S=e.hop??0;if(o.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${S} 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)`}),o.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),o.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!m)return{fixtureName:s,conduit:i,guards:o,whenPassed:m,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let b=[],_=[],R=[];for(let P=0;P<i.targets.length;P+=1){let N=i.targets[P],D=await yr(u,{...a,materialized:R.map(Bt=>({...Bt}))},{member:"transform",stepIndex:P,timeoutMs:Us});b.push(...D.effects.logs);let Y=D.effects.result;if(!Y||typeof Y!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let K=Y,Ae=Eu(i.fromRecordType,N.recordType),{wouldWriteBindings:De,masterAction:zt}=xw(i,N,Ae,e);_.push({to:N,transformResult:K,applyBranch:Ae,wouldWriteBindings:De,masterAction:zt}),R.push({source:N.source,recordType:N.recordType,masterTable:`<${N.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let T=_[0];return{fixtureName:s,conduit:i,guards:o,whenPassed:m,atlasResolutions:l,transformResult:T.transformResult,applyBranch:T.applyBranch,wouldWriteBindings:T.wouldWriteBindings,masterAction:T.masterAction,targets:_,logs:b}}catch(u){return{fixtureName:s,conduit:i,guards:o,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}}function xw(t,e,n,r){return n==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source: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 $w(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Au}}async function Cu(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 Ou(t){let e=await Pu.readFile(t,"utf8");return JSON.parse(e)}function Nu(t){return Pu.readFile(t,"utf8")}function Lu(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;let r=t.targets.length>1;if(!e){if(!t.whenPassed)return`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;if(r){let a=t.targets.reduce((l,u)=>l+u.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.targets.length} targets in sequence (${a} binding(s) would be written)`}return`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${n.id}`);let o=(n.targets.length>0?n.targets:[{source:n.toSource,recordType:n.toRecordType}]).map(a=>`${a.source}.${a.recordType}`).join(" \u2192 ");s.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${o}${n.on?` on=${n.on}`:""}`),s.push(""),s.push("guards (dispatch order):");for(let a of t.guards){let l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";s.push(` ${l} ${a.name} [${a.status}] \u2014 ${a.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let a of t.atlasResolutions)s.push(` ${a.key} \u2192 ${a.resolved===null?"null (no Atlas link \u2014 noted)":a.resolved}`);if(!t.whenPassed)return s.push(""),s.push("transform: SKIPPED (from.when gate did not fire)."),s.join(`
2005
- `);let i=t.targets.length>0?t.targets:[{to:{source:n.toSource,recordType:n.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(i.forEach((a,l)=>{let u=r?` (target ${l+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";s.push(""),s.push(`transform${u} \u2192 patch:`),s.push(Rw(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&s.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),s.push(""),s.push(`apply-branch${u}: ${a.applyBranch}`),s.push(` ${a.masterAction}`),s.push(""),s.push(`bindings that WOULD be written (txn_source_link)${u}:`);for(let p of a.wouldWriteBindings)s.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.why}`)}),t.logs.length>0){s.push(""),s.push("conduit logs:");for(let a of t.logs)s.push(` [${a.level}] ${a.message}${a.meta?` ${JSON.stringify(a.meta)}`:""}`)}return s.join(`
2006
- `)}function Rw(t,e){return t.split(`
2007
- `).map(n=>e+n).join(`
2008
- `)}var Tw="2026-01-01",ju="2026-01-01T00:00:00.000Z";function Ew(t,e){let n=t.trim().toLowerCase();return n==="boolean"||n==="bool"?!1:n==="smallint"||n==="integer"||n==="int"||n==="int2"||n==="int4"||n==="int8"||n==="bigint"||n==="serial"||n==="bigserial"?1:n==="numeric"||n==="decimal"||n==="real"||n==="double precision"||n==="float4"||n==="float8"||n==="money"?0:n==="date"?Tw:n.startsWith("timestamp")?ju:n.startsWith("time")?"00:00:00":n==="json"||n==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:ju}:{}:n==="uuid"?"00000000-0000-0000-0000-000000000000":n==="array"||n.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function Pw(t){let e={};for(let n of t.columns)e[n.name]=Ew(n.pgType,n.name);return e}function Aw(t,e={}){let n=e.event??"before_save";return{name:`${t.recordType} ${n} (generated)`,context:{recordType:t.recordType,event:n,source:t.source,payload:Pw(t)},expect:e.expect??"pass"}}function Du(t,e={}){return t.map(n=>({recordType:n.recordType,fixture:Aw(n,e)}))}import{promises as Uu}from"node:fs";import{join as Mu,relative as Iw,sep as Cw}from"node:path";var Ow=67324752,Nw=33639248,Lw=101010256,jw=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function Dw(t){let e=4294967295;for(let n=0;n<t.length;n++)e=jw[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}async function Uw(t){let e=[];async function n(r){let s=await Uu.readdir(r,{withFileTypes:!0});for(let o of s){let i=Mu(r,o.name);o.isDirectory()?await n(i):o.isFile()&&e.push(Iw(t,i).split(Cw).join("/"))}}return await n(t),e.sort(),e}async function qu(t){let e=await Uw(t),n=[],r=[],s=0;for(let a of e){let l=Buffer.from(a,"utf8"),u=await Uu.readFile(Mu(t,a)),p=Dw(u),m=Buffer.alloc(30+l.length);m.writeUInt32LE(Ow,0),m.writeUInt16LE(20,4),m.writeUInt16LE(0,6),m.writeUInt16LE(0,8),m.writeUInt32LE(p,14),m.writeUInt32LE(u.length,18),m.writeUInt32LE(u.length,22),m.writeUInt16LE(l.length,26),l.copy(m,30),n.push(m,u);let S=Buffer.alloc(46+l.length);S.writeUInt32LE(Nw,0),S.writeUInt16LE(20,4),S.writeUInt16LE(20,6),S.writeUInt16LE(0,10),S.writeUInt32LE(p,16),S.writeUInt32LE(u.length,20),S.writeUInt32LE(u.length,24),S.writeUInt16LE(l.length,28),S.writeUInt32LE(s,42),l.copy(S,46),r.push(S),s+=m.length+u.length}let o=Buffer.concat(r),i=Buffer.alloc(22);return i.writeUInt32LE(Lw,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(o.length,12),i.writeUInt32LE(s,16),{buffer:Buffer.concat([...n,o,i]),fileCount:e.length}}na();function Mw(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function Bs(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function qw(t){let e=zw(t,"from"),r=zu(t,"to").map(s=>({source:Bs(s,"source"),recordType:Bs(s,"recordType")}));return{fromSource:e?Bs(e,"source"):void 0,fromRecordType:e?Bs(e,"recordType"):void 0,toSource:r[0]?.source,toRecordType:r[0]?.recordType,targets:r}}function zw(t,e){return zu(t,e)[0]??null}function zu(t,e){let n=[],r=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),s;for(;(s=r.exec(t))!==null;){let o=0,i=s.index+s[0].length-1;for(let a=i;a<t.length;a+=1){let l=t[a];if(l==="{")o+=1;else if(l==="}"&&(o-=1,o===0)){n.push(t.slice(i+1,a)),r.lastIndex=a+1;break}}}return n}function Bw(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let n=e.index+e[0].length,r=0,s=null,o=n;for(;o<t.length;o+=1){let l=t[o];if(s){l==="\\"?o+=1:l===s&&(s=null);continue}if(l==="'"||l==='"'||l==="`"){s=l;continue}if(l==="("||l==="{"||l==="[")r+=1;else if(l===")"||l==="}"||l==="]"){if(r===0)break;r-=1}else if(l===","&&r===0)break}let i=t.slice(n,o),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function Fw(t,e){let n=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return n?Number(n[1]):void 0}function Hw(t){return/\bcreatedFrom\b/.test(t)}function Bu(t){let e=Mw(t),n=[];if(e==="hook")return{kind:e,warnings:n};let{fromSource:r,fromRecordType:s,toRecordType:o,targets:i}=qw(t);for(let p of i)if(r&&p.source&&r===p.source){n.push({rule:"same-source-conduit",message:`from.source and to.source are both '${r}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let a=Bw(t);if(a!==null){let p=/\bexternalId\b/.test(a),m=/\bfromSource\b/.test(a);!p&&!m&&n.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 l=i.find(p=>p.recordType&&s&&p.recordType!==s)?.recordType??(s!==o?o:void 0);s&&l&&!Hw(t)&&n.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${l}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${l} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let u=Fw(t,"cycleBudget");return u!==void 0&&(u<1?n.push({rule:"cycle-budget-too-low",message:`cycleBudget=${u} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):u>20&&n.push({rule:"cycle-budget-too-high",message:`cycleBudget=${u} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:n}}function Fu(t,e,n={}){let r=n.warn??(a=>a),s=n.ok??(a=>a),o=n.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${s("ok")} \u2014 no warnings.`),i.join(`
2009
- `);for(let a of e.warnings)i.push(` ${r("WARN")} ${o(`[${a.rule}]`)} ${a.message}`),i.push(` ${o("\u2192 fix:")} ${a.fix}`);return i.push(`
2010
- lint: ${r(`${e.warnings.length} warning(s).`)}`),i.join(`
2011
- `)}function Hu(t){return t.cases.filter(e=>e.status==="failed").length}function kr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Kw(t){let e=Hu(t),n=[];n.push('<?xml version="1.0" encoding="UTF-8"?>'),n.push(`<testsuite name="${kr(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let r of t.cases){let s=` <testcase name="${kr(r.name)}"`;if(r.status==="passed"){n.push(`${s} />`);continue}n.push(`${s}>`);let o=r.detail??"failed",i=r.type?` type="${kr(r.type)}"`:"";n.push(` <failure${i} message="${kr(o)}">${kr(o)}</failure>`),n.push(" </testcase>")}return n.push("</testsuite>"),`${n.join(`
2013
+ deps: ${r}}`};var l0={keyword:"dependencies",type:"object",schemaType:"object",error:Pt.error,code(t){let[e,r]=c0(t);Yg(t,e),Xg(t,r)}};function c0({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 Yg(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 l=(0,bo.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let u of a)(0,bo.checkReportMissingProp)(t,u)}):(r.if((0,sd._)`${l} && (${(0,bo.checkMissingProp)(t,a,s)})`),(0,bo.reportMissingProp)(t,s),r.else())}}Pt.validatePropertyDeps=Yg;function Xg(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,a0.alwaysValidSchema)(s,e[a])||(r.if((0,bo.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}Pt.validateSchemaDeps=Xg;Pt.default=l0});var ey=M(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var Qg=te(),d0=ue(),u0={message:"property name must be valid",params:({params:t})=>(0,Qg._)`{propertyName: ${t.propertyName}}`},p0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:u0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,d0.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,Qg.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};id.default=p0});var ld=M(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var fi=ct(),_t=te(),m0=Ut(),gi=ue(),h0={message:"must NOT have additional properties",params:({params:t})=>(0,_t._)`{additionalProperty: ${t.additionalProperty}}`},f0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:h0,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:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,gi.alwaysValidSchema)(i,r))return;let u=(0,fi.allSchemaProperties)(n.properties),p=(0,fi.allSchemaProperties)(n.patternProperties);f(),t.ok((0,_t._)`${s} === ${m0.default.errors}`);function f(){e.forIn("key",o,R=>{!u.length&&!p.length?k(R):e.if(S(R),()=>k(R))})}function S(R){let P;if(u.length>8){let O=(0,gi.schemaRefOrVal)(i,n.properties,"properties");P=(0,fi.isOwnProperty)(e,O,R)}else u.length?P=(0,_t.or)(...u.map(O=>(0,_t._)`${R} === ${O}`)):P=_t.nil;return p.length&&(P=(0,_t.or)(P,...p.map(O=>(0,_t._)`${(0,fi.usePattern)(t,O)}.test(${R})`))),(0,_t.not)(P)}function y(R){e.code((0,_t._)`delete ${o}[${R}]`)}function k(R){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){y(R);return}if(r===!1){t.setParams({additionalProperty:R}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,gi.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?($(R,P,!1),e.if((0,_t.not)(P),()=>{t.reset(),y(R)})):($(R,P),a||e.if((0,_t.not)(P),()=>e.break()))}}function $(R,P,O){let D={keyword:"additionalProperties",dataProp:R,dataPropType:gi.Type.Str};O===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};ad.default=f0});var ny=M(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var g0=no(),ty=ct(),cd=ue(),ry=ld(),y0={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&&ry.default.code(new g0.KeywordCxt(s,ry.default,"additionalProperties"));let i=(0,ty.allSchemaProperties)(r);for(let f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=cd.mergeEvaluated.props(e,(0,cd.toHash)(i),s.props));let a=i.filter(f=>!(0,cd.alwaysValidSchema)(s,r[f]));if(a.length===0)return;let l=e.name("valid");for(let f of a)u(f)?p(f):(e.if((0,ty.propertyInData)(e,o,f,s.opts.ownProperties)),p(f),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function u(f){return s.opts.useDefaults&&!s.compositeRule&&r[f].default!==void 0}function p(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};dd.default=y0});var ay=M(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var oy=ct(),yi=te(),sy=ue(),iy=ue(),b0={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,oy.allSchemaProperties)(r),l=a.filter($=>(0,sy.alwaysValidSchema)(s,r[$]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,p=e.name("valid");s.props!==!0&&!(s.props instanceof yi.Name)&&(s.props=(0,iy.evaluatedPropsToName)(e,s.props));let{props:f}=s;S();function S(){for(let $ of a)u&&y($),s.allErrors?k($):(e.var(p,!0),k($),e.if(p))}function y($){for(let R in u)new RegExp($).test(R)&&(0,sy.checkStrictMode)(s,`property ${R} matches pattern ${$} (use allowMatchingProperties)`)}function k($){e.forIn("key",n,R=>{e.if((0,yi._)`${(0,oy.usePattern)(t,$)}.test(${R})`,()=>{let P=l.includes($);P||t.subschema({keyword:"patternProperties",schemaProp:$,dataProp:R,dataPropType:iy.Type.Str},p),s.opts.unevaluated&&f!==!0?e.assign((0,yi._)`${f}[${R}]`,!0):!P&&!s.allErrors&&e.if((0,yi.not)(p),()=>e.break())})})}}};ud.default=b0});var ly=M(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var w0=ue(),v0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,w0.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"}};pd.default=v0});var cy=M(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var _0=ct(),S0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:_0.validateUnion,error:{message:"must match a schema in anyOf"}};md.default=S0});var dy=M(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var bi=te(),k0=ue(),T0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,bi._)`{passingSchemas: ${t.passing}}`},x0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:T0,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),l=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((p,f)=>{let S;(0,k0.alwaysValidSchema)(o,p)?e.var(l,!0):S=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,bi._)`${l} && ${i}`).assign(i,!1).assign(a,(0,bi._)`[${a}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,f),S&&t.mergeEvaluated(S,bi.Name)})})}}};hd.default=x0});var uy=M(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var $0=ue(),R0={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,$0.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};fd.default=R0});var hy=M(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var wi=te(),my=ue(),E0={message:({params:t})=>(0,wi.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,wi._)`{failingKeyword: ${t.ifClause}}`},P0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:E0,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,my.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=py(n,"then"),s=py(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),o&&s){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,u("then",p),u("else",p))}else o?e.if(a,u("then")):e.if((0,wi.not)(a),u("else"));t.pass(i,()=>t.error(!0));function l(){let p=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(p)}function u(p,f){return()=>{let S=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(S,i),f?e.assign(f,(0,wi._)`${p}`):t.setParams({ifClause:p})}}}};function py(t,e){let r=t.schema[e];return r!==void 0&&!(0,my.alwaysValidSchema)(t,r)}gd.default=P0});var fy=M(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var A0=ue(),C0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,A0.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};yd.default=C0});var gy=M(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var I0=ed(),O0=Vg(),N0=td(),L0=Gg(),j0=Jg(),D0=Zg(),U0=ey(),M0=ld(),q0=ny(),z0=ay(),B0=ly(),F0=cy(),H0=dy(),K0=uy(),V0=hy(),W0=fy();function G0(t=!1){let e=[B0.default,F0.default,H0.default,K0.default,V0.default,W0.default,U0.default,M0.default,D0.default,q0.default,z0.default];return t?e.push(O0.default,L0.default):e.push(I0.default,N0.default),e.push(j0.default),e}bd.default=G0});var yy=M(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var ke=te(),J0={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},Y0={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:J0,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:f}=a;if(!l.validateFormats)return;o?S():y();function S(){let k=r.scopeValue("formats",{ref:f.formats,code:l.code.formats}),$=r.const("fDef",(0,ke._)`${k}[${i}]`),R=r.let("fType"),P=r.let("format");r.if((0,ke._)`typeof ${$} == "object" && !(${$} instanceof RegExp)`,()=>r.assign(R,(0,ke._)`${$}.type || "string"`).assign(P,(0,ke._)`${$}.validate`),()=>r.assign(R,(0,ke._)`"string"`).assign(P,$)),t.fail$data((0,ke.or)(O(),D()));function O(){return l.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${P}`}function D(){let Y=p.$async?(0,ke._)`(${$}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,ke._)`${P}(${n})`,K=(0,ke._)`(typeof ${P} == "function" ? ${Y} : ${P}.test(${n}))`;return(0,ke._)`${P} && ${P} !== true && ${R} === ${e} && !${K}`}}function y(){let k=f.formats[s];if(!k){O();return}if(k===!0)return;let[$,R,P]=D(k);$===e&&t.pass(Y());function O(){if(l.strictSchema===!1){f.logger.warn(K());return}throw new Error(K());function K(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function D(K){let Ae=K instanceof RegExp?(0,ke.regexpCode)(K):l.code.formats?(0,ke._)`${l.code.formats}${(0,ke.getProperty)(s)}`:void 0,De=r.scopeValue("formats",{key:s,ref:K,code:Ae});return typeof K=="object"&&!(K instanceof RegExp)?[K.type||"string",K.validate,(0,ke._)`${De}.validate`]:["string",K,De]}function Y(){if(typeof k=="object"&&!(k instanceof RegExp)&&k.async){if(!p.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${P}(${n})`}return typeof R=="function"?(0,ke._)`${P}(${n})`:(0,ke._)`${P}.test(${n})`}}}};wd.default=Y0});var by=M(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var X0=yy(),Z0=[X0.default];vd.default=Z0});var wy=M(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.contentVocabulary=an.metadataVocabulary=void 0;an.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];an.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var _y=M(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var Q0=Eg(),eP=Bg(),tP=gy(),rP=by(),vy=wy(),nP=[Q0.default,eP.default,(0,tP.default)(),rP.default,vy.metadataVocabulary,vy.contentVocabulary];_d.default=nP});var ky=M(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.DiscrError=void 0;var Sy;(function(t){t.Tag="tag",t.Mapping="mapping"})(Sy||(vi.DiscrError=Sy={}))});var xy=M(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var ln=te(),Sd=ky(),Ty=ti(),oP=oo(),sP=ue(),iP={message:({params:{discrError:t,tagName:e}})=>t===Sd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ln._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},aP={keyword:"discriminator",type:"object",schemaType:"object",error:iP,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 l=e.let("valid",!1),u=e.const("tag",(0,ln._)`${r}${(0,ln.getProperty)(a)}`);e.if((0,ln._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:Sd.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let y=S();e.if(!1);for(let k in y)e.elseIf((0,ln._)`${u} === ${k}`),e.assign(l,f(y[k]));e.else(),t.error(!1,{discrError:Sd.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function f(y){let k=e.name("valid"),$=t.subschema({keyword:"oneOf",schemaProp:y},k);return t.mergeEvaluated($,ln.Name),k}function S(){var y;let k={},$=P(o),R=!0;for(let Y=0;Y<i.length;Y++){let K=i[Y];if(K?.$ref&&!(0,sP.schemaHasRulesButRef)(K,s.self.RULES)){let De=K.$ref;if(K=Ty.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,De),K instanceof Ty.SchemaEnv&&(K=K.schema),K===void 0)throw new oP.default(s.opts.uriResolver,s.baseId,De)}let Ae=(y=K?.properties)===null||y===void 0?void 0:y[a];if(typeof Ae!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);R=R&&($||P(K)),O(Ae,Y)}if(!R)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:Y}){return Array.isArray(Y)&&Y.includes(a)}function O(Y,K){if(Y.const)D(Y.const,K);else if(Y.enum)for(let Ae of Y.enum)D(Ae,K);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(Y,K){if(typeof Y!="string"||Y in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[Y]=K}}}};kd.default=aP});var $y=M((T1,lP)=>{lP.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 xd=M((ve,Td)=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.MissingRefError=ve.ValidationError=ve.CodeGen=ve.Name=ve.nil=ve.stringify=ve.str=ve._=ve.KeywordCxt=ve.Ajv=void 0;var cP=Sg(),dP=_y(),uP=xy(),Ry=$y(),pP=["/properties"],_i="http://json-schema.org/draft-07/schema",cn=class extends cP.default{_addVocabularies(){super._addVocabularies(),dP.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(uP.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Ry,pP):Ry;this.addMetaSchema(e,_i,!1),this.refs["http://json-schema.org/schema"]=_i}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(_i)?_i:void 0)}};ve.Ajv=cn;Td.exports=ve=cn;Td.exports.Ajv=cn;Object.defineProperty(ve,"__esModule",{value:!0});ve.default=cn;var mP=no();Object.defineProperty(ve,"KeywordCxt",{enumerable:!0,get:function(){return mP.KeywordCxt}});var dn=te();Object.defineProperty(ve,"_",{enumerable:!0,get:function(){return dn._}});Object.defineProperty(ve,"str",{enumerable:!0,get:function(){return dn.str}});Object.defineProperty(ve,"stringify",{enumerable:!0,get:function(){return dn.stringify}});Object.defineProperty(ve,"nil",{enumerable:!0,get:function(){return dn.nil}});Object.defineProperty(ve,"Name",{enumerable:!0,get:function(){return dn.Name}});Object.defineProperty(ve,"CodeGen",{enumerable:!0,get:function(){return dn.CodeGen}});var hP=Qs();Object.defineProperty(ve,"ValidationError",{enumerable:!0,get:function(){return hP.default}});var fP=oo();Object.defineProperty(ve,"MissingRefError",{enumerable:!0,get:function(){return fP.default}})});var Ly=M(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.formatNames=Ct.fastFormats=Ct.fullFormats=void 0;function At(t,e){return{validate:t,compare:e}}Ct.fullFormats={date:At(Cy,Pd),time:At(Rd(!0),Ad),"date-time":At(Ey(!0),Oy),"iso-time":At(Rd(),Iy),"iso-date-time":At(Ey(),Ny),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_P,"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:EP,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:SP,int32:{type:"number",validate:xP},int64:{type:"number",validate:$P},float:{type:"number",validate:Ay},double:{type:"number",validate:Ay},password:!0,binary:!0};Ct.fastFormats={...Ct.fullFormats,date:At(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pd),time:At(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ad),"date-time":At(/^\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,Oy),"iso-time":At(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Iy),"iso-date-time":At(/^\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,Ny),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};Ct.formatNames=Object.keys(Ct.fullFormats);function gP(t){return t%4===0&&(t%100!==0||t%400===0)}var yP=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,bP=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Cy(t){let e=yP.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&&gP(r)?29:bP[n])}function Pd(t,e){if(t&&e)return t>e?1:t<e?-1:0}var $d=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Rd(t){return function(r){let n=$d.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,u=+(n[6]||0),p=+(n[7]||0);if(u>23||p>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let f=s-p*l,S=o-u*l-(f<0?1:0);return(S===23||S===-1)&&(f===59||f===-1)&&i<61}}function Ad(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 Iy(t,e){if(!(t&&e))return;let r=$d.exec(t),n=$d.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 Ed=/t|\s/i;function Ey(t){let e=Rd(t);return function(n){let o=n.split(Ed);return o.length===2&&Cy(o[0])&&e(o[1])}}function Oy(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Ny(t,e){if(!(t&&e))return;let[r,n]=t.split(Ed),[o,s]=e.split(Ed),i=Pd(r,o);if(i!==void 0)return i||Ad(n,s)}var wP=/\/|:/,vP=/^(?:[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 _P(t){return wP.test(t)&&vP.test(t)}var Py=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function SP(t){return Py.lastIndex=0,Py.test(t)}var kP=-(2**31),TP=2**31-1;function xP(t){return Number.isInteger(t)&&t<=TP&&t>=kP}function $P(t){return Number.isInteger(t)}function Ay(){return!0}var RP=/[^\\]\\Z/;function EP(t){if(RP.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var jy=M(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.formatLimitDefinition=void 0;var PP=xd(),St=te(),ar=St.operators,Si={formatMaximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},formatMinimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},formatExclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},formatExclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},AP={message:({keyword:t,schemaCode:e})=>(0,St.str)`should be ${Si[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,St._)`{comparison: ${Si[t].okStr}, limit: ${e}}`};un.formatLimitDefinition={keyword:Object.keys(Si),type:"string",schemaType:"string",$data:!0,error:AP,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let l=new PP.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let S=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=e.const("fmt",(0,St._)`${S}[${l.schemaCode}]`);t.fail$data((0,St.or)((0,St._)`typeof ${y} != "object"`,(0,St._)`${y} instanceof RegExp`,(0,St._)`typeof ${y}.compare != "function"`,f(y)))}function p(){let S=l.schema,y=a.formats[S];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${S}" does not define "compare" function`);let k=e.scopeValue("formats",{key:S,ref:y,code:i.code.formats?(0,St._)`${i.code.formats}${(0,St.getProperty)(S)}`:void 0});t.fail$data(f(k))}function f(S){return(0,St._)`${S}.compare(${r}, ${n}) ${Si[o].fail} 0`}},dependencies:["format"]};var CP=t=>(t.addKeyword(un.formatLimitDefinition),t);un.default=CP});var qy=M((wo,My)=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});var pn=Ly(),IP=jy(),Cd=te(),Dy=new Cd.Name("fullFormats"),OP=new Cd.Name("fastFormats"),Id=(t,e={keywords:!0})=>{if(Array.isArray(e))return Uy(t,e,pn.fullFormats,Dy),t;let[r,n]=e.mode==="fast"?[pn.fastFormats,OP]:[pn.fullFormats,Dy],o=e.formats||pn.formatNames;return Uy(t,o,r,n),e.keywords&&(0,IP.default)(t),t};Id.get=(t,e="full")=>{let n=(e==="fast"?pn.fastFormats:pn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Uy(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Cd._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}My.exports=wo=Id;Object.defineProperty(wo,"__esModule",{value:!0});wo.default=Id});function NP(){let t=new zy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,By.default)(t),t}var zy,By,ki,Fy=j(()=>{zy=Wd(xd(),1),By=Wd(qy(),1);ki=class{constructor(e){this._ajv=e??NP()}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 Ti,Hy=j(()=>{Gr();Ti=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(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],u=l.some(p=>p.type==="tool_use");if(i){if(s.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let p=new Set(l.filter(S=>S.type==="tool_use").map(S=>S.id)),f=new Set(s.filter(S=>S.type==="tool_result").map(S=>S.toolUseId));if(p.size!==f.size||![...p].every(S=>f.has(S)))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},zn,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},Wr,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 Ky(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 Vy(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 Wy=j(()=>{});var xi,Gy=j(()=>{Yh();Gr();Fy();Cn();Hy();Wy();xi=class extends qs{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(qn.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 ki,this.setRequestHandler(Va,n=>this._oninitialize(n)),this.setNotificationHandler(Wa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(el,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=qn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ti(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Jh(this._capabilities,e)}setRequestHandler(e,r){let o=Yt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Br(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(l,u)=>{let p=Jt(Vr,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new B(W.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:f}=p.data,S=await Promise.resolve(r(l,u));if(f.task){let k=Jt(Hr,S);if(!k.success){let $=k.error instanceof Error?k.error.message:String(k.error);throw new B(W.InvalidParams,`Invalid task creation result: ${$}`)}return k.data}let y=Jt(Es,S);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new B(W.InvalidParams,`Invalid tools/call result: ${k}`)}return y.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){Vy(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Ky(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:Gm.includes(r)?r:za,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"},ps)}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(u=>u.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]:[],l=a.some(u=>u.type==="tool_use");if(s){if(o.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(a.filter(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(o.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(u.size!==p.size||![...u].every(f=>p.has(f)))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},tl,r):this.request({method:"sampling/createMessage",params:e},zn,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},Wr,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},Wr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new B(W.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof B?i:new B(W.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},rl,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 Od(t){return!!t&&typeof t=="object"&&Yy in t}function Xy(t){return t[Yy]?.complete}var Yy,Jy,Zy=j(()=>{Yy=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Jy||(Jy={}))});var Qy=j(()=>{});function jP(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"),!LP.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 DP(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 Nd(t){let e=jP(t);return DP(t,e.warnings),e.isValid}var LP,eb=j(()=>{LP=/^[A-Za-z0-9._-]{1,128}$/});var $i,tb=j(()=>{$i=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)}}});import{ZodOptional as UP}from"zod";function ob(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function sb(t){return"_def"in t||"_zod"in t||ob(t)}function Ld(t){return typeof t!="object"||t===null||sb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(ob)}function rb(t){if(t){if(Ld(t))return gr(t);if(!sb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function qP(t){let e=Yt(t);return e?Object.entries(e).map(([r,n])=>{let o=Vm(n),s=Wm(n);return{name:r,description:o,required:!s}}):[]}function lr(t){let r=Yt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Br(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function nb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ri,MP,vo,ib=j(()=>{Gy();Cn();Ml();Gr();Zy();Qy();eb();tb();Ri=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 xi(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new $i(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(lr(Rs)),this.server.assertCanSetRequestHandler(lr(Vr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Rs,()=>({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=zr(r.inputSchema);return o?jl(o,{strictUnions:!0,pipeStrategy:"input"}):MP})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=zr(r.outputSchema);o&&(n.outputSchema=jl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Vr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B(W.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B(W.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 B(W.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new B(W.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),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof B&&n.code===W.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=zr(e.inputSchema)??e.inputSchema,i=await as(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=ls(a);throw new B(W.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(W.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=zr(e.outputSchema),s=await as(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ls(i);throw new B(W.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)),l=a.task.taskId,u=a.task,p=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(S=>setTimeout(S,p));let f=await n.taskStore.getTask(l);if(!f)throw new B(W.InternalError,`Task ${l} not found during polling`);u=f}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(lr(Ps)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ps,async e=>{switch(e.params.ref.type){case"ref/prompt":return dh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return uh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(W.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(W.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(W.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return vo;let s=Yt(n.argsSchema)?.[e.params.argument.name];if(!Od(s))return vo;let i=Xy(s);if(!i)return vo;let a=await i(e.params.argument.value,e.params.context);return nb(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 vo;throw new B(W.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return vo;let s=await o(e.params.argument.value,e.params.context);return nb(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(lr(Ss)),this.server.assertCanSetRequestHandler(lr(ks)),this.server.assertCanSetRequestHandler(lr(Ts)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ss,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(ks,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ts,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new B(W.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 B(W.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(lr(xs)),this.server.assertCanSetRequestHandler(lr($s)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(xs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?qP(r.argsSchema):void 0}))})),this.server.setRequestHandler($s,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B(W.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B(W.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=zr(n.argsSchema),s=await as(o,e.params.arguments);if(!s.success){let l="error"in s?s.error:"Unknown error",u=ls(l);throw new B(W.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}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:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:gr(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=gr(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(l=>{let u=l instanceof UP?l._def?.innerType:l;return Od(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,l,u){Nd(e);let p={title:r,description:n,inputSchema:rb(o),outputSchema:rb(s),annotations:i,execution:a,_meta:l,handler:u,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:f=>{typeof f.name<"u"&&f.name!==e&&(typeof f.name=="string"&&Nd(f.name),delete this._registeredTools[e],f.name&&(this._registeredTools[f.name]=p)),typeof f.title<"u"&&(p.title=f.title),typeof f.description<"u"&&(p.description=f.description),typeof f.paramsSchema<"u"&&(p.inputSchema=gr(f.paramsSchema)),typeof f.outputSchema<"u"&&(p.outputSchema=gr(f.outputSchema)),typeof f.callback<"u"&&(p.handler=f.callback),typeof f.annotations<"u"&&(p.annotations=f.annotations),typeof f._meta<"u"&&(p._meta=f._meta),typeof f.enabled<"u"&&(p.enabled=f.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}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 l=r[0];if(Ld(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Ld(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(u=>typeof u=="object"&&u!==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:l,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,l,{taskSupport:"forbidden"},u,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()}},MP={type:"object",properties:{}};vo={completion:{values:[],hasMore:!1}}});function BP(t){return rh.parse(JSON.parse(t))}function ab(t){return JSON.stringify(t)+`
2014
+ `}var zP,Ei,lb=j(()=>{Gr();zP=10*1024*1024,Ei=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??zP}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(`
2015
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),BP(r)}clear(){this._buffer=void 0}}});import cb from"node:process";var Pi,db=j(()=>{lb();Pi=class{constructor(e=cb.stdin,r=cb.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 Ei({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=ab(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var ub,pb=j(()=>{ub=[]});var _b={};Vd(_b,{AUTHORING_MCP_SERVER_NAME:()=>gb,AUTHORING_MCP_SERVER_VERSION:()=>yb,AUTHORING_RESOURCES:()=>JP,AUTHORING_TOOLS:()=>GP,AUTHORING_TOOLS_PUBLIC:()=>vb,buildAuthoringMcpServer:()=>wb,resolveSamplesDir:()=>bb,runAuthoringMcpServer:()=>YP});import{promises as FP}from"node:fs";import{isAbsolute as HP,resolve as Ai,sep as KP}from"node:path";import{z as q}from"zod";function fb(){return hb??=import("../mcp/grounding.js").then(e=>e,()=>null),hb}function bb(t,e){if(e===void 0)return Ai(process.cwd(),t??"samples");let r=Ai(e);if(t===void 0)return r;if(HP(t))return null;let n=Ai(r,t);return n===r||n.startsWith(r+KP)?n:null}function Se(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function WP(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 wb(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let y=await pt(t.baseUrl);if(!y)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:y.baseUrl,token:y.token}}let r=t.grounding??{},n=await fb(),o=null;if(n)try{let y=await e();o={surface:"mcp-authoring",baseUrl:y.baseUrl,token:y.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],l=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{l=(await n.listRecipesForSurface(o,i)).map(y=>({id:y.id,record_type:y.record_type,intent:y.intent}))}catch{l=[]}}let u=o?await WP(o,r):null,p=new Ri({name:gb,version:yb},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:l,promptNames:a.map(y=>y.id),deployedExtensions:u,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let y=o;for(let k of a)p.registerPrompt(k.id,{title:k.name,description:k.description},async()=>{let $=await n.getMcpPromptSkill(y,k.id,r);if(!$)throw new Error(`unknown prompt: ${k.id}`);return{description:$.description,messages:[{role:"user",content:{type:"text",text:($.prompts??[]).join(`
2016
+
2017
+ `)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await e(),$=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!$.ok)throw new Error(`catalog fetch failed: ${$.status}`);return Se(await $.json())}),p.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:q.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:q.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:y,source:k})=>{let{baseUrl:$,token:R}=await e(),P=k?`?source=${encodeURIComponent(k)}`:"",O=await fetch(`${$}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(O.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!O.ok)throw new Error(`record anatomy fetch failed: ${O.status}`);return Se(await O.json())}),p.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:q.array(q.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:q.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:y,source:k})=>{let{baseUrl:$,token:R}=await e(),P=new URLSearchParams({types:y.join(",")});k&&P.set("source",k);let O=await fetch(`${$}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(O.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!O.ok)throw new Error(`common columns fetch failed: ${O.status}`);return Se(await O.json())}),p.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:y,token:k}=await e(),$=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!$.ok)throw new Error(`catalog census failed: ${$.status}`);return Se(await $.json())}),p.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:q.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:q.enum(mb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:q.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:y,kind:k,limit:$})=>{let{baseUrl:R,token:P}=await e(),O=new URLSearchParams({q:y});k&&O.set("kind",k),$!==void 0&&O.set("limit",String($));let D=await fetch(`${R}/v1/catalog/objects?${O}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Se(await D.json())}),p.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:q.enum(mb),externalId:q.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:k})=>{let{baseUrl:$,token:R}=await e(),P=await fetch(`${$}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${k} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return Se(await P.json())}),p.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:q.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:q.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:y,limit:k})=>{let{baseUrl:$,token:R}=await e(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let O=await fetch(`${$}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!O.ok)throw new Error(`kb search failed: ${O.status}`);return Se(await O.json())}),p.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:q.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:k,token:$}=await e(),R=await fetch(`${k}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!R.ok&&R.status!==404)throw new Error(`kb document fetch failed: ${R.status}`);return Se(await R.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:q.boolean().optional()}},async({recordsOnly:y})=>{let{baseUrl:k,token:$}=await e();return{content:[{type:"text",text:await pr({baseUrl:k,token:$,recordsOnly:y})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:q.string(),event:q.string().optional(),template:q.enum(["require-field","enforce-format","blank"]).optional(),field:q.string().optional(),regex:q.string().optional(),source:q.string().optional(),id:q.string().optional()}},async y=>{let k=xt("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return Se({path:k.relativePath,content:k.content})}),p.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:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:q.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:q.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:q.string().optional().describe("Target record type (defaults to the trigger record type)."),event:q.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:q.string().optional()}},async y=>{let k=xt("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return Se({path:k.relativePath,content:k.content})}),p.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:q.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:q.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:q.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:q.string().optional()}},async y=>{let k=xt("process",{recordType:y.recordType,then:y.then,onFailure:y.onFailure,id:y.id});return Se({path:k.relativePath,content:k.content})}),p.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:q.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:q.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:q.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:q.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:q.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:q.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:q.array(q.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async y=>{let{baseUrl:k,token:$}=await e(),R=new z({baseUrl:k,token:$});return Se(await R.authorConduit({intent:y.intent,from:{source:y.fromSource,recordType:y.fromRecordType},to:{source:y.toSource,recordType:y.toRecordType},...y.intentId?{intentId:y.intentId}:{},...y.columns?.length?{columns:y.columns}:{}}))}),p.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:q.string().describe("The extension TS source."),samplesDir:q.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:k})=>{let $=bb(k,t.samplesRoot);if($===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:VP})}],isError:!0};let R;try{R=await wn($)}catch(D){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 D}let P=await Bo(y,R.map(D=>D.fixture)),O=P.filter(D=>!D.pass).length;return Se({total:P.length,passed:P.length-O,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:q.string(),recordType:q.string(),event:q.string(),source:q.string().describe('Adapter id or "standalone".'),sourceCode:q.string().describe("The verbatim extension TS."),extensionKind:q.string().optional()}},async y=>{let{baseUrl:k,token:$}=await e(),P=await new z({baseUrl:k,token:$}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.extensionKind});return Se(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:q.string(),limit:q.number().int().positive().optional()}},async({id:y,limit:k})=>{let{baseUrl:$,token:R}=await e(),P=new z({baseUrl:$,token:R});return Se({id:y,logs:await P.logs(y,k)})}),p.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:y,token:k}=await e(),$=new z({baseUrl:y,token:k});return Se(await $.appsList())}),p.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:q.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:q.string().optional().describe("Display name (defaults to the slug)."),description:q.string().optional().describe("Short description.")}},async({slug:y,name:k,description:$})=>{let{baseUrl:R,token:P}=await e(),O=new z({baseUrl:R,token:P});return Se(await O.appsCreate({slug:y,name:k,description:$}))}),p.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:q.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:k,token:$}=await e(),R=new z({baseUrl:k,token:$});return Se(await R.appsPull(y))}),p.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:q.string().describe("App slug or id."),files:q.record(q.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:q.string().optional().describe("Short note stored with the revision.")}},async({app:y,files:k,note:$})=>{let{baseUrl:R,token:P}=await e(),O=new z({baseUrl:R,token:P});return Se(await O.appsPush(y,k,{note:$}))});let f=q.object({name:q.string().describe("Field name (lowercase identifier)."),type:q.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:q.boolean().optional()}),S=q.object({slug:q.string().describe("Table slug; the physical table is cr_<slug>."),displayName:q.string().optional(),fields:q.array(f).describe("At least one field."),rowLevelOwner:q.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.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:y,token:k}=await e(),$=new z({baseUrl:y,token:k});return Se(await $.tablesList())}),p.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:q.array(S),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:$,token:R}=await e(),P=new z({baseUrl:$,token:R});return Se(await P.tablesPlan({tables:y,claimedBy:k}))}),p.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:q.array(S),claimedBy:q.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:$,token:R}=await e(),P=new z({baseUrl:$,token:R});return Se(await P.tablesApply({tables:y,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:k,token:$}=await e(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}})).text();return{contents:[{uri:y.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async y=>{let{baseUrl:k,token:$}=await e(),R=await pr({baseUrl:k,token:$});return{contents:[{uri:y.href,mimeType:"text/plain",text:R}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let k=Ai(process.cwd(),"samples"),$=[];try{$=(await FP.readdir(k)).filter(P=>P.endsWith(".json"))}catch{$=[]}let R=await wn(k);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:$,samples:R.map(P=>P.fixture)},null,2)}]}}),p.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 y=>{let k=await fb(),$=[];if(k){let{baseUrl:R,token:P}=await e();$=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:R,token:P},r)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:$})}]}}),p}async function YP(t={}){let e=await wb(t),r=new Pi;await e.connect(r)}var mb,hb,gb,yb,VP,vb,GP,JP,Sb=j(()=>{ib();db();Yi();gn();mt();aa();Wo();pb();mb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];gb="turbobase-authoring",yb="0.1.0";VP="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.";vb=["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"],GP=[...vb,...ub],JP=["catalog:///","types://all","samples:///","recipes:///"]});Yi();gn();mt();aa();import{spawn as zd}from"node:child_process";import{promises as se}from"node:fs";import{homedir as XP}from"node:os";import{basename as xb,dirname as qt,join as Qe,relative as Ii,resolve as oe,sep as qd}from"node:path";import{Command as ZP}from"commander";zo();import{promises as Ou}from"node:fs";var Rw=/^[a-z][a-z0-9_]+$/;function Eu(t,e){if(typeof t!="string"||!Rw.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 Ew="customrecord",Pw="customlist";function Aw(t){return t.startsWith("customrecord_")?t.slice(13):t}function Cw(t){return t.startsWith("customlist_")?t.slice(11):t}function Iw(t){return Eu(t,"custom_record scriptId"),`cr_${Aw(t)}`}function Ow(t){return Eu(t,"custom_list scriptId"),`cl_${Cw(t)}`}function Pu(t){return t.startsWith(Ew)?Iw(t):t.startsWith(Pw)?Ow(t):null}var Nw={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 Au(t,e){let r=e?jw[`${e}:${t}`]:void 0;if(r)return r;let n=Nw[t];if(n)return n;let o=Pu(t);return o?{table:o}:void 0}var Lw={accountingPeriod:"accounting_period"};var jw={...Object.fromEntries(Object.entries(Lw).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 Cu(t,e){let r=Au(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function Iu(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=Cu(t,n),i=Cu(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Nu=4;function la(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Ir(t,"id"),r=Ir(t,"on"),n=Ir(t,"source"),o=Ir(t,"recordType"),s=[];for(let l of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let u=Ir(l[1]??"","source"),p=Ir(l[1]??"","recordType");u&&p&&s.push({source:u,recordType:p})}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]):Nu}}function Ir(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Dw(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 Lu(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=la(t)}catch(u){return{fixtureName:o,conduit:Mw(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}let a=Dw(e),l=Object.entries(e.atlasLinks??{}).map(([u,p])=>({key:u,resolved:p}));try{let u=await qo(t,{resolveDir:n.resolveDir}),f=!!(await bn(u,a,{member:"when",timeoutMs:Mo})).whenResult;s.push({name:"from.when",status:f?"passed":"failed",detail:f?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let S=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${S} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!f)return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[]};let y=[],k=[],$=[];for(let P=0;P<i.targets.length;P+=1){let O=i.targets[P],D=await bn(u,{...a,materialized:$.map(Bt=>({...Bt}))},{member:"transform",stepIndex:P,timeoutMs:Mo});y.push(...D.effects.logs);let Y=D.effects.result;if(!Y||typeof Y!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${P+1})`:""} returned no result (expected { patch, createdFrom? })`);let K=Y,Ae=Iu(i.fromRecordType,O.recordType,{fromSource:i.fromSource,toSource:O.source}),{wouldWriteBindings:De,masterAction:zt}=Uw(i,O,Ae,e);k.push({to:O,transformResult:K,applyBranch:Ae,wouldWriteBindings:De,masterAction:zt}),$.push({source:O.source,recordType:O.recordType,masterTable:`<${O.recordType} master, dry-run>`,masterRowId:`<dry-run target ${P+1}>`,externalId:null})}let R=k[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:f,atlasResolutions:l,transformResult:R.transformResult,applyBranch:R.applyBranch,wouldWriteBindings:R.wouldWriteBindings,masterAction:R.masterAction,targets:k,logs:y}}catch(u){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:l,wouldWriteBindings:[],targets:[],logs:[],error:u instanceof Error?u.message:String(u)}}}function Uw(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 Mw(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Nu}}async function ju(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 Du(t){let e=await Ou.readFile(t,"utf8");return JSON.parse(e)}function Uu(t){return Ou.readFile(t,"utf8")}function Mu(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((l,u)=>l+u.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 l=a.status==="passed"?"\u2713":a.status==="failed"?"\u2717":"\u2298";o.push(` ${l} ${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(`
2018
+ `);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,l)=>{let u=n?` (target ${l+1}/${i.length}: ${a.to.source}.${a.to.recordType})`:"";o.push(""),o.push(`transform${u} \u2192 patch:`),o.push(qw(JSON.stringify(a.transformResult.patch??{},null,2)," ")),a.transformResult.createdFrom&&o.push(` createdFrom: ${JSON.stringify(a.transformResult.createdFrom)}`),o.push(""),o.push(`apply-branch${u}: ${a.applyBranch}`),o.push(` ${a.masterAction}`),o.push(""),o.push(`bindings that WOULD be written (txn_source_link)${u}:`);for(let p of a.wouldWriteBindings)o.push(` ${p.source} role=${p.role} external_id=${p.externalId??"null"} \u2014 ${p.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(`
2019
+ `)}function qw(t,e){return t.split(`
2020
+ `).map(r=>e+r).join(`
2021
+ `)}var zw="2026-01-01",qu="2026-01-01T00:00:00.000Z";function Bw(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"?zw:r.startsWith("timestamp")?qu: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:qu}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function Fw(t){let e={};for(let r of t.columns)e[r.name]=Bw(r.pgType,r.name);return e}function Hw(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:Fw(t)},expect:e.expect??"pass"}}function zu(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:Hw(r,e)}))}import{promises as Bu}from"node:fs";import{join as Fu,relative as Kw,sep as Vw}from"node:path";var Ww=67324752,Gw=33639248,Jw=101010256,Yw=(()=>{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 Xw(t){let e=4294967295;for(let r=0;r<t.length;r++)e=Yw[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function Zw(t){let e=[];async function r(n){let o=await Bu.readdir(n,{withFileTypes:!0});for(let s of o){let i=Fu(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(Kw(t,i).split(Vw).join("/"))}}return await r(t),e.sort(),e}async function Hu(t){let e=await Zw(t),r=[],n=[],o=0;for(let a of e){let l=Buffer.from(a,"utf8"),u=await Bu.readFile(Fu(t,a)),p=Xw(u),f=Buffer.alloc(30+l.length);f.writeUInt32LE(Ww,0),f.writeUInt16LE(20,4),f.writeUInt16LE(0,6),f.writeUInt16LE(0,8),f.writeUInt32LE(p,14),f.writeUInt32LE(u.length,18),f.writeUInt32LE(u.length,22),f.writeUInt16LE(l.length,26),l.copy(f,30),r.push(f,u);let S=Buffer.alloc(46+l.length);S.writeUInt32LE(Gw,0),S.writeUInt16LE(20,4),S.writeUInt16LE(20,6),S.writeUInt16LE(0,10),S.writeUInt32LE(p,16),S.writeUInt32LE(u.length,20),S.writeUInt32LE(u.length,24),S.writeUInt16LE(l.length,28),S.writeUInt32LE(o,42),l.copy(S,46),n.push(S),o+=f.length+u.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(Jw,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}}ra();function Qw(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function Fo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function ev(t){let e=tv(t,"from"),n=Ku(t,"to").map(o=>({source:Fo(o,"source"),recordType:Fo(o,"recordType")}));return{fromSource:e?Fo(e,"source"):void 0,fromRecordType:e?Fo(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function tv(t,e){return Ku(t,e)[0]??null}function Ku(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 l=t[a];if(l==="{")s+=1;else if(l==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function rv(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 l=t[s];if(o){l==="\\"?s+=1:l===o&&(o=null);continue}if(l==="'"||l==='"'||l==="`"){o=l;continue}if(l==="("||l==="{"||l==="[")n+=1;else if(l===")"||l==="}"||l==="]"){if(n===0)break;n-=1}else if(l===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function nv(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function ov(t){return/\bcreatedFrom\b/.test(t)}function Vu(t){let e=Qw(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,fromRecordType:o,toRecordType:s,targets:i}=ev(t);for(let p of i)if(n&&p.source&&n===p.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=rv(t);if(a!==null){let p=/\bexternalId\b/.test(a),f=/\bfromSource\b/.test(a);!p&&!f&&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 l=i.find(p=>p.recordType&&o&&p.recordType!==o)?.recordType??(o!==s?s:void 0);o&&l&&!ov(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${l}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${l} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let u=nv(t,"cycleBudget");return u!==void 0&&(u<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${u} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):u>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${u} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function Wu(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(`
2022
+ `);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(`
2023
+ lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
2024
+ `)}function Gu(t){return t.cases.filter(e=>e.status==="failed").length}function _n(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function sv(t){let e=Gu(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${_n(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${_n(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${_n(n.type)}"`:"";r.push(` <failure${i} message="${_n(s)}">${_n(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2012
2025
  `)}
2013
- `}function Vw(t){let e={suite:t.name,tests:t.cases.length,failures:Hu(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2014
- `}function Fs(t,e){return e==="junit"?Kw(t):Vw(t)}var Ve={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"},$e={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Nn=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],nt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Ku=/\x1b\[[0-9;]*m/g;function Ot(t){return t.replace(Ku,"").length}function ca(t,e){return e<=0?1:Math.max(1,Math.ceil(Ot(t)/e))}function Ww(){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 da=Ww();function Pe(){return da}function ua(t){da=t}function Ie(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function rt(t,e){return da?`${t}${e}${Ve.reset}`:e}var f={bold:t=>rt(Ve.bold,t),dim:t=>rt(Ve.dim,t),red:t=>rt(Ve.red,t),green:t=>rt(Ve.green,t),yellow:t=>rt(Ve.yellow,t),blue:t=>rt(Ve.blue,t),magenta:t=>rt(Ve.magenta,t),cyan:t=>rt(Ve.cyan,t),grey:t=>rt(Ve.grey,t)};var ye={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}`},Kt={add:t=>f.green(`+ ${t}`),change:t=>f.yellow(`~ ${t}`),destroy:t=>f.red(`- ${t}`)},Gw=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Jw=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),Yw=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Ln(t){let e=t.toLowerCase();return Gw.has(e)?f.green(t):Jw.has(e)?f.red(t):Yw.has(e)?f.yellow(t):t}function Vt(t,e=[]){let n=Math.max(Ot(t),...e.map(Ot),0),r=n+2,s=f.cyan(nt.v),o=a=>` ${a}${" ".repeat(n-Ot(a))} `,i=[f.cyan(`${nt.tl}${nt.h.repeat(r)}${nt.tr}`),`${s}${f.bold(o(t))}${s}`];if(e.length){i.push(`${f.cyan(nt.ml)}${f.dim(nt.h.repeat(r))}${f.cyan(nt.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(f.cyan(`${nt.bl}${nt.h.repeat(r)}${nt.br}`)),i.join(`
2015
- `)}function ft(t,e={}){let n=e.indent??" ",r=e.gap??" ",s=e.head?[e.head,...t]:t,o=Math.max(0,...s.map(u=>u.length)),i=[];for(let u=0;u<o;u+=1)i[u]=Math.max(0,...s.map(p=>Ot(p[u]??"")));let a=u=>{let p=u.map((m,S)=>{let b=m??"";return S===u.length-1?b:b+" ".repeat(Math.max(0,i[S]-Ot(b)))});return n+p.join(r)},l=[];e.head&&(l.push(a(e.head.map(u=>f.bold(u)))),l.push(a(e.head.map((u,p)=>f.dim("\u2500".repeat(i[p]??Ot(u)))))));for(let u of t)l.push(a(u));return l.join(`
2016
- `)}function pa(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`${Pe()?e.map(r=>rt(Ve.cyan,r)).join(`
2026
+ `}function iv(t){let e={suite:t.name,tests:t.cases.length,failures:Gu(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2027
+ `}function Ho(t,e){return e==="junit"?sv(t):iv(t)}var Ve={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"},xe={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Or=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],rt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Ju=/\x1b\[[0-9;]*m/g;function Ot(t){return t.replace(Ju,"").length}function ca(t,e){return e<=0?1:Math.max(1,Math.ceil(Ot(t)/e))}function av(){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 da=av();function Pe(){return da}function ua(t){da=t}function Ce(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function nt(t,e){return da?`${t}${e}${Ve.reset}`:e}var h={bold:t=>nt(Ve.bold,t),dim:t=>nt(Ve.dim,t),red:t=>nt(Ve.red,t),green:t=>nt(Ve.green,t),yellow:t=>nt(Ve.yellow,t),blue:t=>nt(Ve.blue,t),magenta:t=>nt(Ve.magenta,t),cyan:t=>nt(Ve.cyan,t),grey:t=>nt(Ve.grey,t)};var be={success:t=>`${h.green("\u2713")} ${t}`,error:t=>`${h.red("\u2716")} ${t}`,warn:t=>`${h.yellow("\u26A0")} ${t}`,info:t=>`${h.dim("\xB7")} ${t}`,step:t=>`${h.cyan("\u25B8")} ${t}`},Kt={add:t=>h.green(`+ ${t}`),change:t=>h.yellow(`~ ${t}`),destroy:t=>h.red(`- ${t}`)},lv=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),cv=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),dv=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Nr(t){let e=t.toLowerCase();return lv.has(e)?h.green(t):cv.has(e)?h.red(t):dv.has(e)?h.yellow(t):t}function Vt(t,e=[]){let r=Math.max(Ot(t),...e.map(Ot),0),n=r+2,o=h.cyan(rt.v),s=a=>` ${a}${" ".repeat(r-Ot(a))} `,i=[h.cyan(`${rt.tl}${rt.h.repeat(n)}${rt.tr}`),`${o}${h.bold(s(t))}${o}`];if(e.length){i.push(`${h.cyan(rt.ml)}${h.dim(rt.h.repeat(n))}${h.cyan(rt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(h.cyan(`${rt.bl}${rt.h.repeat(n)}${rt.br}`)),i.join(`
2028
+ `)}function ht(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(u=>u.length)),i=[];for(let u=0;u<s;u+=1)i[u]=Math.max(0,...o.map(p=>Ot(p[u]??"")));let a=u=>{let p=u.map((f,S)=>{let y=f??"";return S===u.length-1?y:y+" ".repeat(Math.max(0,i[S]-Ot(y)))});return r+p.join(n)},l=[];e.head&&(l.push(a(e.head.map(u=>h.bold(u)))),l.push(a(e.head.map((u,p)=>h.dim("\u2500".repeat(i[p]??Ot(u)))))));for(let u of t)l.push(a(u));return l.join(`
2029
+ `)}function pa(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`${Pe()?e.map(n=>nt(Ve.cyan,n)).join(`
2017
2030
  `):e.join(`
2018
2031
  `)}
2019
- ${f.dim(` ${t}`)}`}var st=t=>{process.stderr.write(t)};function Hs(){return Pe()&&process.stderr.isTTY===!0}function Vu(t,e=15){let n=Math.max(0,Math.min(100,t??0)),r=Math.round(n/100*e);return`${"\u2588".repeat(r)}${f.dim("\u2591".repeat(e-r))}`}async function J(t,e){let n=Hs(),r=0,s;n&&(st($e.hideCursor),s=setInterval(()=>{st(`${$e.col0}${$e.clearLine}${f.magenta(Nn[r++%Nn.length])} ${t}`)},80));let o=()=>{s&&clearInterval(s),n&&st(`${$e.col0}${$e.clearLine}${$e.showCursor}`)};try{let i=await e();return o(),n&&st(`${ye.success(t)}
2020
- `),i}catch(i){throw o(),n&&st(`${ye.error(t)}
2021
- `),i}}function ha(t){let e=0,n={stage:"queued"},r=!1,s=()=>{let l=f.magenta(Nn[e%Nn.length]),u=f.cyan(n.stage),p=n.runStatus?` ${f.dim(`(${n.runStatus})`)}`:"",m=`${String(Math.round(n.percent??0)).padStart(3)}%`;return`${l} ${t} ${f.dim("\u25B8")} ${u}${p} ${Vu(n.percent)} ${m}`},o=()=>{st(`${$e.col0}${$e.clearLine}${s()}`),r=!0},i=()=>{r&&st(`${$e.col0}${$e.clearLine}`),r=!1};st($e.hideCursor);let a=setInterval(()=>{e+=1,o()},80);return{log(l){i(),st(`${l}
2022
- `),o()},status(l){n=l,o()},done(l){clearInterval(a),i(),st($e.showCursor);let u=l.stage!=="failed",p=`${t} ${f.dim("\u25B8")} ${Xw(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;st(`${u?ye.success(p):ye.error(p)}
2023
- `)},stop(){clearInterval(a),i(),st($e.showCursor)}}}function Xw(t){return t==="completed"?f.green(t):t==="failed"?f.red(t):f.cyan(t)}function Ce(t,e,n={}){return new Promise((r,s)=>{let o=e.findIndex(R=>!R.disabled);if(o===-1){s(new Error("no selectable options"));return}let i=n.defaultIndex!==void 0&&!e[n.defaultIndex]?.disabled?n.defaultIndex:o,a=R=>{process.stderr.write(R)},l=process.stdin,u=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${f.bold(f.cyan("?"))} ${f.bold(t)}
2024
- `),a(`${f.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2025
- `),a($e.hideCursor);let p=0,m=()=>{let R=process.stderr.columns??process.stdout.columns??80;p>0&&(a($e.cursorUp(p)),a($e.clearToEnd));let T=0;for(let P=0;P<e.length;P+=1){let N=e[P],D=P===i,Y=D?f.cyan("\u25B6"):" ",K=N.disabled?f.grey(N.label):D?f.bold(f.cyan(N.label)):N.label,Ae=N.description?` ${f.dim(N.description)}`:"",De=` ${Y} ${K}${Ae}`;a(`\r${De}
2026
- `),T+=ca(De,R)}p=T},S=()=>{l.removeListener("data",_),l.setRawMode?.(u??!1),l.pause(),a($e.showCursor)},b=R=>{let T=i;for(let P=0;P<e.length;P+=1)if(T=(T+R+e.length)%e.length,!e[T].disabled){i=T;return}},_=R=>{let T=R.toString("utf8");if(T===""||T==="q"){S(),a(`
2027
- `),s(new Error("aborted"));return}if(T==="\r"||T===`
2028
- `){let N=e[i];if(N.disabled)return;S(),r(N.value);return}if(T==="\x1B[A"||T==="k"){b(-1),m();return}if(T==="\x1B[B"||T==="j"){b(1),m();return}let P=Number(T);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,m())};l.on("data",_),m()})}function Ks(t,e){return`${Ln(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Gu=t=>new Promise(e=>setTimeout(e,t));function Wu(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,n=t.reason?` reason="${t.reason}"`:"",r=t.fromExternalId?` ext=${t.fromExternalId}`:"",s=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Ks(t.state,9)} ${t.conduitId} \u2192 ${e}${r} hop=${t.hop}${s}${n}`}async function Ju(t,e,n={}){let r=n.sink??(p=>{process.stdout.write(`${p}
2029
- `)}),s=n.sleep??Gu,o=n.intervalMs??2e3,i=await t.conduitEvents(e,{limit:n.limit??100});if(i.length===0&&!n.follow)return r(`logs: no conduit_event rows for ${e}.`),0;let a=0,l="";for(let p of[...i].reverse())r(Wu(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!n.follow)return a;let u=n.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<u;p+=1){await s(o);let m=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let S of[...m].reverse())r(Wu(S)),a+=1,S.updatedAt>l&&(l=S.updatedAt)}return a}function Zw(t){let e=t.externalId??"\u2014",n=t.createdByConduit?` via=${t.createdByConduit}`:"",r=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Ks(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${n}${r}`}async function Yu(t,e={}){let n=e.sink??(s=>{process.stdout.write(`${s}
2030
- `)});if(e.retry){let s=await t.retryBinding(e.retry);return n(`binding: re-enqueued fan-out for ${s.id} \u2192 ${s.sourceSystem} (master ${s.masterTable}/${s.masterRowId}).`),{mode:"retry",id:s.id,retried:s.retried}}let r=await t.bindings({status:e.status,limit:e.limit});if(r.length===0)return n(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let s of r)n(Zw(s));return n(`
2031
- binding: ${r.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:r.length}}function Qw(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),n=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),r=t.occurrences>1?` x${t.occurrences}`:"",s=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",o=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Ks(t.severity,5)} ${Ks(t.outcome,8)} ${t.code}${r}${n?` ${n}`:""}${o}${e?` ${e}`:""}${s}`}async function Xu(t,e={}){let n=e.sink??(P=>{process.stdout.write(`${P}
2032
- `)}),r=e.sleep??Gu,s=e.intervalMs??2e3,{follow:o,maxPolls:i,json:a,sink:l,sleep:u,intervalMs:p,...m}=e,S=P=>{n(a?JSON.stringify(P):Qw(P))},b=await t.platformEvents({...m,limit:m.limit??100});if(b.length===0&&!o)return n("logs: no events matched."),0;let _=0,R="";for(let P of[...b].reverse())S(P),_+=1,P.ts>R&&(R=P.ts);if(!o)return _;let T=i??Number.POSITIVE_INFINITY;for(let P=0;P<T;P+=1){await r(s);let N=await t.platformEvents({...m,...R?{after:R,since:void 0}:{},limit:200});for(let D of[...N].reverse())S(D),_+=1,D.ts>R&&(R=D.ts)}return _}Vs();qs();function Qu(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 fa=".github/workflows/turbobase-release-deploy.yml",sv=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2032
+ ${h.dim(` ${t}`)}`}var ot=t=>{process.stderr.write(t)};function Ko(){return Pe()&&process.stderr.isTTY===!0}function Yu(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${h.dim("\u2591".repeat(e-n))}`}async function J(t,e){let r=Ko(),n=0,o;r&&(ot(xe.hideCursor),o=setInterval(()=>{ot(`${xe.col0}${xe.clearLine}${h.magenta(Or[n++%Or.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&ot(`${xe.col0}${xe.clearLine}${xe.showCursor}`)};try{let i=await e();return s(),r&&ot(`${be.success(t)}
2033
+ `),i}catch(i){throw s(),r&&ot(`${be.error(t)}
2034
+ `),i}}function ma(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let l=h.magenta(Or[e%Or.length]),u=h.cyan(r.stage),p=r.runStatus?` ${h.dim(`(${r.runStatus})`)}`:"",f=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${t} ${h.dim("\u25B8")} ${u}${p} ${Yu(r.percent)} ${f}`},s=()=>{ot(`${xe.col0}${xe.clearLine}${o()}`),n=!0},i=()=>{n&&ot(`${xe.col0}${xe.clearLine}`),n=!1};ot(xe.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(l){i(),ot(`${l}
2035
+ `),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),ot(xe.showCursor);let u=l.stage!=="failed",p=`${t} ${h.dim("\u25B8")} ${uv(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;ot(`${u?be.success(p):be.error(p)}
2036
+ `)},stop(){clearInterval(a),i(),ot(xe.showCursor)}}}function uv(t){return t==="completed"?h.green(t):t==="failed"?h.red(t):h.cyan(t)}function Ie(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex($=>!$.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=$=>{process.stderr.write($)},l=process.stdin,u=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${h.bold(h.cyan("?"))} ${h.bold(t)}
2037
+ `),a(`${h.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2038
+ `),a(xe.hideCursor);let p=0,f=()=>{let $=process.stderr.columns??process.stdout.columns??80;p>0&&(a(xe.cursorUp(p)),a(xe.clearToEnd));let R=0;for(let P=0;P<e.length;P+=1){let O=e[P],D=P===i,Y=D?h.cyan("\u25B6"):" ",K=O.disabled?h.grey(O.label):D?h.bold(h.cyan(O.label)):O.label,Ae=O.description?` ${h.dim(O.description)}`:"",De=` ${Y} ${K}${Ae}`;a(`\r${De}
2039
+ `),R+=ca(De,$)}p=R},S=()=>{l.removeListener("data",k),l.setRawMode?.(u??!1),l.pause(),a(xe.showCursor)},y=$=>{let R=i;for(let P=0;P<e.length;P+=1)if(R=(R+$+e.length)%e.length,!e[R].disabled){i=R;return}},k=$=>{let R=$.toString("utf8");if(R===""||R==="q"){S(),a(`
2040
+ `),o(new Error("aborted"));return}if(R==="\r"||R===`
2041
+ `){let O=e[i];if(O.disabled)return;S(),n(O.value);return}if(R==="\x1B[A"||R==="k"){y(-1),f();return}if(R==="\x1B[B"||R==="j"){y(1),f();return}let P=Number(R);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,f())};l.on("data",k),f()})}function Vo(t,e){return`${Nr(t)}${" ".repeat(Math.max(0,e-t.length))}`}var Zu=t=>new Promise(e=>setTimeout(e,t));function Xu(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}] ${Vo(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function Qu(t,e,r={}){let n=r.sink??(p=>{process.stdout.write(`${p}
2042
+ `)}),o=r.sleep??Zu,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,l="";for(let p of[...i].reverse())n(Xu(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!r.follow)return a;let u=r.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<u;p+=1){await o(s);let f=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let S of[...f].reverse())n(Xu(S)),a+=1,S.updatedAt>l&&(l=S.updatedAt)}return a}function pv(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Vo(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function ep(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2043
+ `)});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(pv(o));return r(`
2044
+ binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function mv(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}] ${Vo(t.severity,5)} ${Vo(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function tp(t,e={}){let r=e.sink??(P=>{process.stdout.write(`${P}
2045
+ `)}),n=e.sleep??Zu,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:l,sleep:u,intervalMs:p,...f}=e,S=P=>{r(a?JSON.stringify(P):mv(P))},y=await t.platformEvents({...f,limit:f.limit??100});if(y.length===0&&!s)return r("logs: no events matched."),0;let k=0,$="";for(let P of[...y].reverse())S(P),k+=1,P.ts>$&&($=P.ts);if(!s)return k;let R=i??Number.POSITIVE_INFINITY;for(let P=0;P<R;P+=1){await n(o);let O=await t.platformEvents({...f,...$?{after:$,since:void 0}:{},limit:200});for(let D of[...O].reverse())S(D),k+=1,D.ts>$&&($=D.ts)}return k}Wo();zo();function np(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 ha=".github/workflows/turbobase-release-deploy.yml",bv=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2033
2046
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
2034
2047
  #
2035
2048
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -2131,7 +2144,7 @@ jobs:
2131
2144
  --ref "\${{ github.sha }}" \\
2132
2145
  --project . \\
2133
2146
  --follow
2134
- `,ov=".github/workflows/turbobase-app-deploy.yml",iv=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2147
+ `,wv=".github/workflows/turbobase-app-deploy.yml",vv=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2135
2148
  # Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
2136
2149
  #
2137
2150
  # What ships from this repo, and when:
@@ -2349,14 +2362,14 @@ jobs:
2349
2362
  else
2350
2363
  echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
2351
2364
  fi
2352
- `;function ep(){return[{path:fa,content:sv}]}function tp(){return[{path:ov,content:iv}]}Vs();var av=[".mcp.json"];function sp(t,e=av){let n=i=>i.replace(/^\//,""),r=new Set(t.split(`
2353
- `).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(n)),s=e.filter(i=>!r.has(n(i)));return s.length===0?null:`${t===""||t.endsWith(`
2365
+ `;function op(){return[{path:ha,content:bv}]}function sp(){return[{path:wv,content:vv}]}Wo();var _v=[".mcp.json"];function lp(t,e=_v){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2366
+ `).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(`
2354
2367
  `)?t:`${t}
2355
2368
  `}
2356
2369
  # Added by the Turbobase scaffold.
2357
- ${s.join(`
2370
+ ${o.join(`
2358
2371
  `)}
2359
- `}var lv=`# Turbobase Extensions \u2014 extension project
2372
+ `}var Sv=`# Turbobase Extensions \u2014 extension project
2360
2373
 
2361
2374
  This directory authors **Turbobase extensions** (hooks today; conduits later)
2362
2375
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -2425,8 +2438,8 @@ order is the signal, and it is the part the product team reads first.
2425
2438
 
2426
2439
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
2427
2440
  updating a test. It is checked into the repo so the whole team sees it.
2428
- `,cv=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)+`
2429
- `;function dv(t){return`---
2441
+ `,kv=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)+`
2442
+ `;function Tv(t){return`---
2430
2443
  name: generate-types
2431
2444
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
2432
2445
  ---
@@ -2437,7 +2450,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
2437
2450
 
2438
2451
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
2439
2452
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
2440
- `}var uv=`---
2453
+ `}var xv=`---
2441
2454
  name: mock-test
2442
2455
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
2443
2456
  ---
@@ -2446,7 +2459,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
2446
2459
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
2447
2460
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
2448
2461
  fixture for each branch (a passing record and a rejecting record).
2449
- `,pv=`---
2462
+ `,$v=`---
2450
2463
  name: deploy
2451
2464
  description: Deploy a hook to your instance. Use only after mock-test is green.
2452
2465
  ---
@@ -2454,7 +2467,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
2454
2467
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
2455
2468
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
2456
2469
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
2457
- `;function hv(t){return`# ${t} \u2014 Turbobase app
2470
+ `;function Rv(t){return`# ${t} \u2014 Turbobase app
2458
2471
 
2459
2472
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
2460
2473
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -2793,7 +2806,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
2793
2806
  review, so what you write reaches the knowledge base and the product team instead
2794
2807
  of evaporating at the end of the session. Keep the section headings exactly as
2795
2808
  they are \u2014 the ingest finds entries by heading, not by filename.
2796
- `}var jn="customer",fn="email",fv="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",mv=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2809
+ `}var Lr="customer",mr="email",Ev="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",Pv=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2797
2810
  //
2798
2811
  // It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
2799
2812
  // the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
@@ -2812,8 +2825,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
2812
2825
  // Pure and credentials-free: no secrets, no network, no Node builtins, one
2813
2826
  // concern per file, nothing factored into a shared module (the sandbox fences
2814
2827
  // every import except the SDK).
2815
- `;function gv(){let t=$t("hook",{recordType:jn,event:"before_save",template:"enforce-format",field:fn,regex:fv,id:`app:${jn}:${fn}-format`,description:`Reject a ${jn} write whose ${fn} is not an address.`}),e=(n,r,s)=>JSON.stringify({name:s,context:{recordType:jn,event:"before_save",payload:n},expect:r},null,2)+`
2816
- `;return[{path:t.relativePath,content:`${mv}${t.content}`},{path:`samples/${jn}.${fn}-ok.json`,content:e({company_name:"Acme Supply",[fn]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${jn}.${fn}-malformed.json`,content:e({company_name:"Acme Supply",[fn]:"ada-at-example"},"reject","a malformed address is rejected")}]}var bv="---\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",yv=`---
2828
+ `;function Av(){let t=xt("hook",{recordType:Lr,event:"before_save",template:"enforce-format",field:mr,regex:Ev,id:`app:${Lr}:${mr}-format`,description:`Reject a ${Lr} write whose ${mr} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:Lr,event:"before_save",payload:r},expect:n},null,2)+`
2829
+ `;return[{path:t.relativePath,content:`${Pv}${t.content}`},{path:`samples/${Lr}.${mr}-ok.json`,content:e({company_name:"Acme Supply",[mr]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${Lr}.${mr}-malformed.json`,content:e({company_name:"Acme Supply",[mr]:"ada-at-example"},"reject","a malformed address is rejected")}]}var Cv="---\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",Iv=`---
2817
2830
  name: ship-app
2818
2831
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
2819
2832
  ---
@@ -2856,7 +2869,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
2856
2869
  non-text, so images and fonts belong in the build pipeline or object storage, not
2857
2870
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
2858
2871
  project root and DO travel \u2014 deploy reads them.
2859
- `,wv=`---
2872
+ `,Ov=`---
2860
2873
  name: business-rule-to-hook
2861
2874
  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.
2862
2875
  ---
@@ -2924,7 +2937,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
2924
2937
  standing rules for every agent on the instance \u2014 see the record-learning skill.
2925
2938
  A rule enforced in code and nowhere written down gets re-litigated by the next
2926
2939
  person.
2927
- `;function vv(t){return`---
2940
+ `;function Nv(t){return`---
2928
2941
  name: record-learning
2929
2942
  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.
2930
2943
  ---
@@ -2979,7 +2992,7 @@ earlier claim" and still publish.
2979
2992
 
2980
2993
  Do not reword the three headings. The deploy-side ingest recognises entries by
2981
2994
  heading, not by filename, so a renamed section is a finding nobody receives.
2982
- `}function kv(t){return`# What this instance's source system actually does
2995
+ `}function Lv(t){return`# What this instance's source system actually does
2983
2996
 
2984
2997
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
2985
2998
  Written for the knowledge base, and **everything here is verified against real
@@ -3110,7 +3123,7 @@ finding has not been handed to the knowledge base yet.
3110
3123
  and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
3111
3124
  already live, which is worth reading before adding another rule. -->
3112
3125
 
3113
- `}function Sv(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3126
+ `}function jv(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3114
3127
 
3115
3128
  Everything below cost time or produced a wrong result. Not speculation, and not
3116
3129
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -3190,7 +3203,7 @@ Expected / happened / cost / fix.
3190
3203
  and what it would replace. These are the highest-signal entries in the file:
3191
3204
  each one is a page downloading rows to fold that it could have asked for
3192
3205
  folded. -->
3193
- `}function _v(t,e){let n=e?`
3206
+ `}function Dv(t,e){let r=e?`
3194
3207
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
3195
3208
  # --records focus a previous run stamped into the file, so a refresh never
3196
3209
  # narrows what an agent deliberately widened.
@@ -3208,7 +3221,7 @@ turbobase project grounding \${records:+--records "$records"} --query ${JSON.str
3208
3221
  set -euo pipefail
3209
3222
  turbobase project types -o ${t} >/dev/null \\
3210
3223
  || echo "turbobase: \\\`turbobase project types\\\` failed (its error is above) \u2014 ${t} was NOT refreshed." >&2
3211
- ${n}
3224
+ ${r}
3212
3225
  # ADOPT.md \u2014 what changed in the PLATFORM that this project has to act on.
3213
3226
  #
3214
3227
  # Incremental and MERGING: it fetches only what is newer than the version already
@@ -3221,8 +3234,8 @@ ${n}
3221
3234
  # surface unticked items at the start of a session.
3222
3235
  turbobase project adopt -o ADOPT.md >/dev/null \\
3223
3236
  || echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
3224
- `}var op="Turbobase consultant",xv="turbobase-consultant",$v=`---
3225
- name: ${op}
3237
+ `}var cp="Turbobase consultant",Uv="turbobase-consultant",Mv=`---
3238
+ name: ${cp}
3226
3239
  description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
3227
3240
  keep-coding-instructions: true
3228
3241
  ---
@@ -3295,8 +3308,8 @@ exists on purpose.
3295
3308
  - Do not show a stack trace. Say what broke and what you are doing about it.
3296
3309
  - Do not apologise repeatedly or pad with "great question".
3297
3310
  - Do not use a table when a sentence works.
3298
- `,Rv=JSON.stringify({outputStyle:op,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)+`
3299
- `,Tv=`#!/usr/bin/env bash
3311
+ `,qv=JSON.stringify({outputStyle:cp,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)+`
3312
+ `,zv=`#!/usr/bin/env bash
3300
3313
  # PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
3301
3314
  #
3302
3315
  # Advisory only: exits 0 always, and adds a note for the agent when the edited
@@ -3313,7 +3326,7 @@ set -uo pipefail
3313
3326
  command -v node >/dev/null 2>&1 || exit 0
3314
3327
 
3315
3328
  exec node "$(dirname "$0")/check-rule-placement.mjs"
3316
- `,Ev=String.raw`/**
3329
+ `,Bv=String.raw`/**
3317
3330
  * Is the file that was just edited enforcing a business rule inside the SPA?
3318
3331
  *
3319
3332
  * Reads the PostToolUse payload on stdin, and when BOTH signals are present —
@@ -3382,7 +3395,7 @@ process.stdout.write(
3382
3395
  },
3383
3396
  }),
3384
3397
  );
3385
- `,Pv=`---
3398
+ `,Fv=`---
3386
3399
  name: roles-and-permissions
3387
3400
  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".
3388
3401
  ---
@@ -3533,7 +3546,7 @@ a denial look like emptiness.
3533
3546
  - Does every write catch \`TurbobasePermissionError\`?
3534
3547
  - Did you run \`turbobase apps plan\`?
3535
3548
  - Did you tell the user their administrator still has to ASSIGN the role?
3536
- `,Av=`---
3549
+ `,Hv=`---
3537
3550
  name: app-design
3538
3551
  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.
3539
3552
  ---
@@ -3626,7 +3639,7 @@ The design system covers the look. Two rules it does not:
3626
3639
  Load it in the browser and check: does it render with ZERO rows, with ONE row,
3627
3640
  and with several hundred? Does it survive the query failing? Does tab reach every
3628
3641
  control, with a visible focus ring? A green \`npm run build\` proves none of these.
3629
- `,Ws="",np=String.raw`{
3642
+ `,Go="",ip=String.raw`{
3630
3643
  "_comment": [
3631
3644
  "Declarative sync config — part of this repo's desired state.",
3632
3645
  " turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
@@ -3648,7 +3661,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3648
3661
  "fields": [],
3649
3662
  "tables": []
3650
3663
  }
3651
- `,rp=String.raw`{
3664
+ `,ap=String.raw`{
3652
3665
  "_comment": [
3653
3666
  "Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
3654
3667
  "Removing an entry does NOT remove the schedule unless you pass --prune.",
@@ -3664,93 +3677,93 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3664
3677
  ],
3665
3678
  "schedules": []
3666
3679
  }
3667
- `,Iv=t=>`node_modules/
3680
+ `,Kv=t=>`node_modules/
3668
3681
 
3669
3682
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
3670
3683
  .mcp.json
3671
3684
 
3672
3685
  .DS_Store
3673
- `;function ma(t={}){let e=cv.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),n=!!t.appSlug,r=n?"src/types.ts":"types.ts",s=n?{slug:t.appSlug}:void 0,o=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:Iv(n)},{path:"INSTANCE-LEARNINGS.md",content:kv(s)},{path:"TURBOBASE-FEEDBACK.md",content:Sv(s)},{path:".claude/settings.json",content:Rv},{path:`.claude/output-styles/${xv}.md`,content:$v},{path:".claude/skills/generate-types/SKILL.md",content:dv(r)},{path:".claude/skills/record-learning/SKILL.md",content:vv(s)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:wv},{path:".claude/hooks/session-start-refresh-types.sh",content:_v(r,s),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:Tv,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:Ev}];return n?[{path:"CLAUDE.md",content:hv(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:bv},{path:".claude/skills/ship-app/SKILL.md",content:yv},{path:".claude/skills/app-design/SKILL.md",content:Av},{path:".claude/skills/roles-and-permissions/SKILL.md",content:Pv},...gv(),{path:"conduits/.gitkeep",content:Ws},{path:"turbobase/sync.json",content:np},{path:"turbobase/schedules.json",content:rp},...tp()]:[{path:"CLAUDE.md",content:lv},...o,{path:".claude/skills/mock-test/SKILL.md",content:uv},{path:".claude/skills/deploy/SKILL.md",content:pv},{path:"hooks/.gitkeep",content:Ws},{path:"conduits/.gitkeep",content:Ws},{path:"samples/.gitkeep",content:Ws},{path:"turbobase/sync.json",content:np},{path:"turbobase/schedules.json",content:rp}]}import{promises as ba}from"node:fs";import{dirname as Cv,join as mt,resolve as dp}from"node:path";function ap(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var Sr="bundle.json",Gs="turbobase";function lp(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let n=e,r=typeof n.version=="number"?n.version:0;if(r!==1)throw new Error(`bundle.json version ${r} is unsupported (expected 1)`);let s=l=>Array.isArray(l)?l:[],o=n.sync??{},i=n.guardrails??{},a={version:1,...typeof n.tenant=="string"?{tenant:n.tenant}:{},hooks:s(n.hooks),conduits:s(n.conduits),sync:{fields:s(o.fields),tables:s(o.tables)},guardrails:{validationHooks:s(i.validationHooks),fieldRules:s(i.fieldRules),conduits:s(i.conduits)},schedules:s(n.schedules)};return ga(a)}function ga(t){let e=n=>(r,s)=>n(r)<n(s)?-1:n(r)>n(s)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(n=>n.id)),conduits:[...t.conduits].sort(e(n=>n.id)),sync:{fields:[...t.sync.fields].sort(e(ip)),tables:[...t.sync.tables].sort(e(n=>n.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(ip)),conduits:[...t.guardrails.conduits].sort(e(n=>n.conduitId))},schedules:[...t.schedules].sort(e(n=>n.name))}}function ip(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function cp(t,e){let n=(e??"").trim();if(!n)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let r=(t??"").trim();return r?r!==n?{ok:!1,reason:`--confirm "${r}" does not match the target instance "${n}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${n}")`}}var Ys="hooks",Xs="conduits",up="processes",Wt="turbobase/sync.json",Gt="turbobase/schedules.json";function ya(t){let e=u=>{let p=new RegExp(`${u}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return p?p[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(t),r=/\bdefineProcess\s*[<(]/.test(t),s=/\bdefineHook\s*[<(]/.test(t);if(!n&&!s&&!r)return null;let o=e("id"),i=e("recordType");if(r){let u=e("source")??"standalone";return!o||!i?null:{id:o,recordType:i,event:"invoke",source:u,extensionKind:"process"}}if(n){let u=e("on"),p=e("source");return!o||!i||!u||!p?null:{id:o,recordType:i,event:u,source:p,extensionKind:"conduit"}}let a=e("event"),l=e("source")??"standalone";return!o||!i||!a?null:{id:o,recordType:i,event:a,source:l,extensionKind:"hook"}}async function _r(t){let e;try{e=await ba.readdir(t,{withFileTypes:!0})}catch{return[]}let n=[];for(let r of e){if(r.isDirectory()){if(r.name.startsWith(".")||r.name==="node_modules")continue;for(let s of await _r(mt(t,r.name)))n.push(`${r.name}/${s}`);continue}r.name.endsWith(".ts")&&(r.name.endsWith(".test.ts")||r.name.endsWith(".d.ts")||n.push(r.name))}return n.sort()}async function Js(t,e){let n;try{n=await ba.readFile(t,"utf8")}catch{return}try{return JSON.parse(n)}catch(r){throw new Error(`${e} is not valid JSON: ${r instanceof Error?r.message:String(r)}`)}}function Ov(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function Nv(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function Lv(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 pp(t=process.cwd()){let e=dp(t),[n,r,s]=await Promise.all([_r(mt(e,Ys)),_r(mt(e,Xs)),_r(mt(e,up))]);if(n.length>0||r.length>0||s.length>0)return!0;let[o,i]=await Promise.all([Js(mt(e,Wt),Wt).catch(()=>{}),Js(mt(e,Gt),Gt).catch(()=>{})]);return o!==void 0||i!==void 0}async function hp(t=process.cwd(),e={}){let n=dp(t),r=ap(e.tenant),s=[],o=[];for(let l of[Ys,Xs,up])for(let u of await _r(mt(n,l))){let p=`${l}/${u}`,m=await ba.readFile(mt(n,l,u),"utf8"),S=e.inline?await e.inline(m,Cv(mt(n,l,u))):m,b=ya(S);if(!b){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(S)&&o.push({file:p,reason:"could not read id / recordType / event"});continue}let _={id:b.id,kind:b.extensionKind,recordType:b.recordType,event:b.event,source:b.source,sourceCode:S};b.extensionKind==="conduit"?r.conduits.push(_):r.hooks.push(_),s.push(p)}let i=await Js(mt(n,Wt),Wt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Wt} must be a JSON object with "fields" and/or "tables".`);let l=i;for(let u of Array.isArray(l.fields)?l.fields:[])r.sync.fields.push(Ov(u));for(let u of Array.isArray(l.tables)?l.tables:[])r.sync.tables.push(Nv(u));s.push(Wt)}let a=await Js(mt(n,Gt),Gt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Gt} must be a JSON array, or an object with a "schedules" array.`);for(let u of l)r.schedules.push(Lv(u));s.push(Gt)}return r.guardrails.fieldRules=[...r.sync.fields],r.guardrails.validationHooks=r.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:ga(r),contributed:s,unparsed:o}}import{promises as ka}from"node:fs";import{resolve as zv}from"node:path";var jv="For app developers \u2014 adopt these";function fp(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 mp(t,e){let n=fp(t),r=fp(e);if(!n&&!r)return 0;if(!n)return-1;if(!r)return 1;for(let s=0;s<3;s++){let o=(n.core[s]??0)-(r.core[s]??0);if(o!==0)return o}return n.prerelease===r.prerelease?0:n.prerelease?r.prerelease?n.prerelease<r.prerelease?-1:1:-1:1}function Dv(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var JI=Dv(jv);gr();ht();var Uv=t=>new Promise(e=>setTimeout(e,t));function gp(t){return t.stage==="completed"||t.stage==="failed"}function Mv(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function qv(t,e,n){let r=t.outputTail??"";if(r&&r!==e){let o=(r.startsWith(e)?r.slice(e.length):r).replace(/\n+$/,"");if(o)for(let i of o.split(`
3674
- `))n(i)}return r}async function wa(t,e={}){let n=e.sink??(S=>{process.stdout.write(`${S}
3675
- `)}),r=e.sleep??Uv,s=e.intervalMs??2e3,o=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(S=>n(Mv(S))),a=e.onPoll,l="",u="",p=S=>{a?.(S),S.stage!==u&&i(S),l=qv(S,l,n),u=S.stage},m=await t();if(p(m),gp(m))return m;for(let S=0;S<o;S+=1)if(await r(s),m=await t(),p(m),gp(m))return m;return m}var y=t=>{process.stdout.write(`${t}
3686
+ `;function fa(t={}){let e=kv.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:Kv(r)},{path:"INSTANCE-LEARNINGS.md",content:Lv(o)},{path:"TURBOBASE-FEEDBACK.md",content:jv(o)},{path:".claude/settings.json",content:qv},{path:`.claude/output-styles/${Uv}.md`,content:Mv},{path:".claude/skills/generate-types/SKILL.md",content:Tv(n)},{path:".claude/skills/record-learning/SKILL.md",content:Nv(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:Ov},{path:".claude/hooks/session-start-refresh-types.sh",content:Dv(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:zv,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:Bv}];return r?[{path:"CLAUDE.md",content:Rv(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:Cv},{path:".claude/skills/ship-app/SKILL.md",content:Iv},{path:".claude/skills/app-design/SKILL.md",content:Hv},{path:".claude/skills/roles-and-permissions/SKILL.md",content:Fv},...Av(),{path:"conduits/.gitkeep",content:Go},{path:"turbobase/sync.json",content:ip},{path:"turbobase/schedules.json",content:ap},...sp()]:[{path:"CLAUDE.md",content:Sv},...s,{path:".claude/skills/mock-test/SKILL.md",content:xv},{path:".claude/skills/deploy/SKILL.md",content:$v},{path:"hooks/.gitkeep",content:Go},{path:"conduits/.gitkeep",content:Go},{path:"samples/.gitkeep",content:Go},{path:"turbobase/sync.json",content:ip},{path:"turbobase/schedules.json",content:ap}]}import{promises as ya}from"node:fs";import{dirname as Vv,join as ft,resolve as hp}from"node:path";function up(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var Sn="bundle.json",Jo="turbobase";function pp(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}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=l=>Array.isArray(l)?l:[],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 ga(a)}function ga(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(dp)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(dp)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function dp(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function mp(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 Xo="hooks",Zo="conduits",fp="processes",Wt="turbobase/sync.json",Gt="turbobase/schedules.json";function ba(t){let e=u=>{let p=new RegExp(`${u}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return p?p[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 u=e("source")??"standalone";return!s||!i?null:{id:s,recordType:i,event:"invoke",source:u,extensionKind:"process"}}if(r){let u=e("on"),p=e("source");return!s||!i||!u||!p?null:{id:s,recordType:i,event:u,source:p,extensionKind:"conduit"}}let a=e("event"),l=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:l,extensionKind:"hook"}}async function kn(t){let e;try{e=await ya.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 kn(ft(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 Yo(t,e){let r;try{r=await ya.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 Wv(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function Gv(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function Jv(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 gp(t=process.cwd()){let e=hp(t),[r,n,o]=await Promise.all([kn(ft(e,Xo)),kn(ft(e,Zo)),kn(ft(e,fp))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([Yo(ft(e,Wt),Wt).catch(()=>{}),Yo(ft(e,Gt),Gt).catch(()=>{})]);return s!==void 0||i!==void 0}async function yp(t=process.cwd(),e={}){let r=hp(t),n=up(e.tenant),o=[],s=[];for(let l of[Xo,Zo,fp])for(let u of await kn(ft(r,l))){let p=`${l}/${u}`,f=await ya.readFile(ft(r,l,u),"utf8"),S=e.inline?await e.inline(f,Vv(ft(r,l,u))):f,y=ba(S);if(!y){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(S)&&s.push({file:p,reason:"could not read id / recordType / event"});continue}let k={id:y.id,kind:y.extensionKind,recordType:y.recordType,event:y.event,source:y.source,sourceCode:S};y.extensionKind==="conduit"?n.conduits.push(k):n.hooks.push(k),o.push(p)}let i=await Yo(ft(r,Wt),Wt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Wt} must be a JSON object with "fields" and/or "tables".`);let l=i;for(let u of Array.isArray(l.fields)?l.fields:[])n.sync.fields.push(Wv(u));for(let u of Array.isArray(l.tables)?l.tables:[])n.sync.tables.push(Gv(u));o.push(Wt)}let a=await Yo(ft(r,Gt),Gt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Gt} must be a JSON array, or an object with a "schedules" array.`);for(let u of l)n.schedules.push(Jv(u));o.push(Gt)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:ga(n),contributed:o,unparsed:s}}import{promises as _a}from"node:fs";import{resolve as t_}from"node:path";var Yv="For app developers \u2014 adopt these";function bp(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 wp(t,e){let r=bp(t),n=bp(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 Xv(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var yI=Xv(Yv);gn();mt();var Zv=t=>new Promise(e=>setTimeout(e,t));function vp(t){return t.stage==="completed"||t.stage==="failed"}function Qv(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function e_(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(`
3687
+ `))r(i)}return n}async function wa(t,e={}){let r=e.sink??(S=>{process.stdout.write(`${S}
3688
+ `)}),n=e.sleep??Zv,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(S=>r(Qv(S))),a=e.onPoll,l="",u="",p=S=>{a?.(S),S.stage!==u&&i(S),l=e_(S,l,r),u=S.stage},f=await t();if(p(f),vp(f))return f;for(let S=0;S<s;S+=1)if(await n(o),f=await t(),p(f),vp(f))return f;return f}var b=t=>{process.stdout.write(`${t}
3676
3689
  `)},L=t=>{process.stderr.write(`${t}
3677
- `)};function v(t){L(f.red(`turbobase: ${t}`)),process.exit(1)}var xr=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function bp(t,e){let n=e.json===!0||typeof e.reporter=="string";(t.color===!1||n)&&ua(!1)}async function V(t){let e=await pt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let n=await Ct();if(t){let r=n.length?` Stored instances: ${n.map(s=>s.baseUrl).join(", ")}.`:"";v(`not signed in to ${tt(t)}.${r} Run \`turbobase auth login --base-url ${tt(t)} --token tb_pat_\u2026\`.`)}if(n.length===0&&v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ie())try{let r=await Ce("Multiple instances stored \u2014 pick the active one:",n.map(o=>({value:o.baseUrl,label:o.baseUrl,description:`updated ${o.updatedAt}`})));await Os(r);let s=await pt();if(s)return{baseUrl:s.baseUrl,token:s.token}}catch{}v(`multiple instances stored (${n.map(r=>r.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function G(t,e,n){if(!(t instanceof Z)||t.status!==403)return;t.body?.error==="approval_required"&&v(`${n} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),v(`${n} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function va(t,e,n){let r=n?Number(n):void 0;if(Hs()){let o=ha(e),i;try{i=await wa(t,{intervalMs:r,sink:a=>o.log(a),onStage:()=>{},onPoll:a=>o.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){o.stop(),v(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}o.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let s;try{s=await wa(t,{sink:y,intervalMs:r})}catch(o){v(`${e} --follow failed: ${o instanceof Error?o.message:String(o)}`)}s.stage==="failed"&&v(`${e} failed${s.runStatus?` (${s.runStatus})`:""}.`),y(`${e} ${s.stage}.`)}var Bv=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function Fv(t){try{let e=await ka.readFile(t,"utf8");return Bv.exec(e)?.[1]??null}catch{return null}}var Hv=/GENERATED by `turbobase project adopt`/,wp=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,Kv=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function yp(t){let e=[],n=null;for(let r of t.split(`
3678
- `)){let s=wp.exec(r);if(s){n={version:s[1],items:[]},e.push(n);continue}if(/^#{1,6}[ \t]/.test(r)){n=null;continue}if(!n)continue;let o=Kv.exec(r);if(o){let a=o[2].trim();n.items.push({key:a.replace(/\s+/g," "),done:o[1]!==" ",text:a,extra:[]});continue}let i=n.items[n.items.length-1];i&&r.trim()!==""&&i.extra.push(r)}return e}function Vv(t){let e=t.items.map(n=>[`- [${n.done?"x":" "}] ${n.text}`,...n.extra].join(`
3690
+ `)};function v(t){L(h.red(`turbobase: ${t}`)),process.exit(1)}var Tn=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function _p(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&ua(!1)}async function V(t){let e=await pt(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await It();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";v(`not signed in to ${tt(t)}.${n} Run \`turbobase auth login --base-url ${tt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ce())try{let n=await Ie("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await No(n);let o=await pt();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 G(t,e,r){if(!(t instanceof Z)||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 va(t,e,r){let n=r?Number(r):void 0;if(Ko()){let s=ma(e),i;try{i=await wa(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 wa(t,{sink:b,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})`:""}.`),b(`${e} ${o.stage}.`)}var r_=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function n_(t){try{let e=await _a.readFile(t,"utf8");return r_.exec(e)?.[1]??null}catch{return null}}var o_=/GENERATED by `turbobase project adopt`/,kp=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,s_=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Sp(t){let e=[],r=null;for(let n of t.split(`
3691
+ `)){let o=kp.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=s_.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 i_(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
3679
3692
  `)).join(`
3680
3693
  `);return`## v${t.version}
3681
3694
 
3682
- ${e}`}function Wv(t,e){let n=yp(t);if(n.length===0&&!Hv.test(t))return null;let r=new Map(n.map(p=>[p.version,p])),s=[],o=0;for(let p of yp(e)){let m=r.get(p.version);r.delete(p.version);let S=new Set(p.items.map(_=>_.key)),b=p.items.map(_=>{let R=m?.items.find(T=>T.key===_.key);return R?{..._,done:R.done,extra:R.extra}:_});for(let _ of m?.items??[])S.has(_.key)||_.done||(b.push(_),o+=1);s.push({version:p.version,items:b})}for(let p of r.values()){let m=p.items.filter(S=>!S.done);m.length!==0&&(o+=m.length,s.push({version:p.version,items:m}))}s.sort((p,m)=>mp(m.version,p.version));let i=e.split(`
3683
- `),a=i.findIndex(p=>wp.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
3684
- `).replace(/\s+$/,"");return{markdown:s.length===0?`${l}
3695
+ ${e}`}function a_(t,e){let r=Sp(t);if(r.length===0&&!o_.test(t))return null;let n=new Map(r.map(p=>[p.version,p])),o=[],s=0;for(let p of Sp(e)){let f=n.get(p.version);n.delete(p.version);let S=new Set(p.items.map(k=>k.key)),y=p.items.map(k=>{let $=f?.items.find(R=>R.key===k.key);return $?{...k,done:$.done,extra:$.extra}:k});for(let k of f?.items??[])S.has(k.key)||k.done||(y.push(k),s+=1);o.push({version:p.version,items:y})}for(let p of n.values()){let f=p.items.filter(S=>!S.done);f.length!==0&&(s+=f.length,o.push({version:p.version,items:f}))}o.sort((p,f)=>wp(f.version,p.version));let i=e.split(`
3696
+ `),a=i.findIndex(p=>kp.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
3697
+ `).replace(/\s+$/,"");return{markdown:o.length===0?`${l}
3685
3698
  `:`${l}
3686
3699
 
3687
- ${s.map(Vv).join(`
3700
+ ${o.map(i_).join(`
3688
3701
 
3689
3702
  `)}
3690
- `,carried:o}}function vp(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:n,token:r}=await V(e.baseUrl),s=zv(process.cwd(),e.out),o=e.since?.trim()||await Fv(s),i=new URLSearchParams;o&&i.set("since",o);let a=i.toString(),l=await fetch(`${n}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});l.ok||v(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let u=await l.json();if(!u.available){y(`${n} ships no release notes to adopt from (nothing written).`);return}let p=u.releases.reduce((T,P)=>T+P.items.length,0);if(p===0){y(`up to date${o?` since v${o.replace(/^v/,"")}`:""}${u.currentVersion?` (instance is on v${u.currentVersion})`:""} \u2014 ${s} left untouched.`);return}let m=u.currentVersion??u.releases[0]?.version??"",S=`<!-- GENERATED by \`turbobase project adopt\` against ${n} \u2014 adopted-through=${m}. Re-run to refresh; delete this file once every line is done. -->
3691
-
3692
- `,b=await ka.readFile(s,"utf8").catch(()=>null),_=u.markdown,R=0;if(b!==null&&b.trim()!==""){let T=Wv(b,u.markdown);T||v(`${s} 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>\`.`),_=T.markdown,R=T.carried}await ka.writeFile(s,S+_,"utf8"),y(`wrote ${s} \u2014 ${p} item(s) across ${u.releases.length} release(s)${o?` since v${o.replace(/^v/,"")}`:""}${R>0?`, keeping ${R} unticked item(s) already in the file`:""}.`)})}ht();var $r=["suggested_kb_edit","kb_correction"];var Gv=[{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 Jv(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var lC=new Map(Gv.map(t=>[Jv(t.heading),t]));var cC=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 Yv(t){return t.diff??!!t.dryRun}var Xv={update_page:"append to the existing page",new_page:"create a NEW page"},Nt=(t,e)=>` ${f.dim(t.padEnd(11))}${e}`,_p=t=>t.ownerEmail??t.ownerId;function Dn(t){return!t.needsPageRef&&!t.blockedBy}var Zs=t=>f.green(t?` + ${t}`:" +"),Zv=t=>f.red(t?` - ${t}`:" -"),mn=t=>f.dim(` ${t}`),Qv=` ${f.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Sa=80;function ek(t){let e=[Qv];t.target?(e.push(mn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(Zv(`visibility: ${t.target.visibility}`)),e.push(Zs("visibility: admin"))):e.push(mn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(mn("title, slug, evidence: untouched")),e.push(mn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(mn("turbobase.document \xB7 new")),e.push(Zs(`title: ${t.pageTitle}`)),e.push(Zs("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(mn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(mn('appended under "## From app developers":'));let n=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3693
- `);for(let r of n.slice(0,Sa))e.push(Zs(r?` ${r}`:""));return n.length>Sa&&e.push(f.yellow(` \u2026 ${n.length-Sa} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function tk(t,e={}){let n=[];return t.forEach((r,s)=>{let{target:o,entries:i}=r;if(n.push(`${String(s+1).padStart(2)}. ${f.bold(r.pageTitle)}`),n.push(Nt("page",o?`${o.title} (${o.slug}) [${o.visibility}]`:f.dim("new \u2014 no existing page matches"))),n.push(Nt("action",Dn(r)?Xv[r.action]:f.red("SKIP \u2014 nothing is written"))),r.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];n.push(Nt("unresolved",f.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).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(n.push(Nt("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let l=a.verdict?` ${f.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${f.dim(`(${a.kb_page_ref})`)}`:"";n.push(` ${f.dim("\xB7")} ${a.title.trim()}${u}${l}`)}),n.push(Nt("confidence",r.withdraws?f.red("WITHDRAWN from readers (text untouched)"):f.dim("untouched"))),r.supersedes&&n.push(Nt("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"))),r.blockedBy&&n.push(Nt("blocked",f.red(`unpublished work on this page belongs to ${_p(r.blockedBy)} \u2014 this page will be SKIPPED`))),r.alsoMatched.length>0&&n.push(Nt("ambiguous",f.yellow(`${r.alsoMatched.length} other page(s) match this ref: ${r.alsoMatched.map(a=>a.slug).join(", ")}`))),(r.similarTo?.length??0)>0){let a=(r.similarTo??[]).map(l=>{let u=t.findIndex(m=>m.key===l),p=u>=0?t[u]:void 0;return p?`#${u+1} "${p.pageTitle}"`:l});n.push(Nt("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&&Dn(r)&&n.push(...ek(r)),n.push("")}),n}function nk(t){let e=u=>t.filter(u).length,n=t.reduce((u,p)=>u+p.entries.length,0),r=e(u=>u.withdraws),s=e(u=>u.blockedBy!=null),o=e(u=>u.needsPageRef),i=[`${n} finding${n===1?"":"s"}`,`${e(Dn)} page(s)`,`${e(u=>u.action==="update_page"&&Dn(u))} appended`,`${e(u=>u.action==="new_page"&&Dn(u))} created (unpublished)`,...o>0?[f.red(`${o} SKIPPED \u2014 correction with no page to correct`)]:[]],a=r>0?f.red(`${r} page(s) WITHDRAWN from readers`):f.dim("no page withdrawn"),l=s>0?` \xB7 ${f.red(`${s} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function rk(t,e){let n=new Map(e.map(s=>[s.key,s])),r=[];for(let s of t){let o=n.get(s.key),i=s.pageTitle||o?.pageTitle||s.key;if(s.skipped==="blocked_by_draft_owner"){r.push(`${f.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${s.blockedBy?_p(s.blockedBy):"another editor"}; its findings stay pending`);continue}if(s.skipped==="unresolved_page_ref"){let l=[...new Set((o?.entries??[]).map(u=>u.kb_page_ref?.trim()).filter(u=>!!u))];r.push(`${f.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(u=>`"${u}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(s.skipped){r.push(`${f.yellow("skipped")} ${i} \u2014 ${s.skipped.replace(/_/g," ")}`);continue}let a=s.created?f.green("created "):f.green("appended");r.push(`${a} ${i} \u2014 ${s.appliedEntryIds.length} finding(s) \u2192 page ${f.bold(s.documentId??"?")}`+(s.created?f.dim(" (unpublished)"):"")),s.confidence==="downgraded"?r.push(` ${f.red("withdrawn from readers:")} ${i}`):s.confidence==="already_withdrawn"?r.push(` ${f.dim("page was already unpublished \u2014 left as is")}`):s.confidence==="missing"&&r.push(` ${f.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return r}function kp(t){if(t instanceof Z){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.")}G(t,"extensions:deploy","learnings push-kb")}async function Rr(t,e){let n;try{n=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(s){return s instanceof Z&&s.status===404?L(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`.")):ku(s)?L(f.yellow(Sp(s))):L(f.yellow(`could not re-read the pushed markdown: ${Sp(s)} \u2014 planning anyway.`)),null}if(n.filesScanned===0)return L(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).")),n;let r=[`${n.filesScanned} file(s) scanned`];return n.docsIngested>0&&r.push(`${n.docsIngested} changed`),n.docsUnchanged>0&&r.push(`${n.docsUnchanged} unchanged`),r.push(`${n.entriesAdded} new finding(s)`),n.entriesDuplicate>0&&r.push(`${n.entriesDuplicate} already known`),n.parseSkipped>0&&r.push(f.yellow(`${n.parseSkipped} unparseable`)),L(f.dim(r.join(" \xB7 "))),n}function Sp(t){return t instanceof Error?t.message:String(t)}async function xp(t,e=n=>new z(n)){t.section&&!$r.includes(t.section.trim())&&v(`unknown --section "${t.section}" \u2014 expected one of ${$r.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let n=await V(t.baseUrl),r=e(n),s={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},o=await Rr(r,t.app),i;try{i=await J("reading the pending queue",()=>r.learningsPending(s))}catch(u){kp(u),v(`could not read the pending queue: ${u instanceof Error?u.message:String(u)}`)}if(i.items.length===0){if(i.pendingTotal===0&&o&&o.entriesDuplicate>0){L(`nothing pending \u2014 all ${o.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}L(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(y(tk(i.items,{diff:Yv(t)}).join(`
3694
- `)),y(nk(i.items)),t.dryRun){L(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(Dn);if(a.length===0){L(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 l=a.reduce((u,p)=>u+p.entries.length,0);if(!t.yes){if(!Ie()){L(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 Ce(`Push ${l} 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"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let u=await J("writing pages",()=>r.learningsPushKb(i.planToken,s));y(rk(u.applied,i.items).join(`
3695
- `))}catch(u){if(u instanceof Z&&u.status===409){L(f.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${xr} kb push\` to review the current plan.`),process.exitCode=2;return}kp(u),L(f.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}ht();var Un=t=>new z(t);async function Mn(t,e){let n=await V(t.baseUrl);return e(n)}async function Qs(t,e,n,r){return r.yes?!0:Ie()?await Ce(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function sk(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function $p(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function ok(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(o=>o.slug.length)),n=[];for(let o of t.items)n.push(`${$p(f.bold(o.slug),e)} ${$p(sk(o),10)} ${f.dim(o.path)}`);n.push("");let r=t.items.filter(o=>o.visibility==="published"&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return n.push(`${t.items.length} page(s) \xB7 ${r} readable \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),n}async function Rp(t,e=Un){let n={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),n.status=t.status);let r=await Mn(t,e),s;try{s=await J("reading the knowledge base",()=>r.docsList(n))}catch(o){G(o,"docs:publish","read the knowledge base"),v(`could not read the knowledge base: ${o instanceof Error?o.message:String(o)}`)}y(ok(s).join(`
3696
- `))}async function Tp(t,e,n=Un){let r=[...new Set(t.map(l=>l.trim()).filter(Boolean))];r.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let s=await Mn(e,n);if(!await Qs(`Publish ${r.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 J("publishing",()=>s.docsPublish(r))}catch(l){G(l,"docs:publish","publish a page"),v(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);y(f.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(f.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Ep(t,e,n=Un){let r=[...new Set(t.map(l=>l.trim()).filter(Boolean))];r.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let s=await Mn(e,n);if(!await Qs(`Hide ${r.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 J("unpublishing",()=>s.docsUnpublish(r))}catch(l){G(l,"docs:publish","unpublish a page"),v(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);y(f.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(f.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Pp(t,e=Un){let n=await Mn(t,e),r;try{r=await J("reading the releases",()=>n.docsVersions())}catch(s){G(s,"docs:publish","read the knowledge-base releases"),v(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){y("no releases yet \u2014 nothing has been published.");return}for(let s of r.items){let o=s.is_current?f.green("current"):f.dim(" ");y(`v${String(s.version_no).padEnd(4)} ${o} ${s.published_at} ${s.node_count} page(s)${s.published_by?` ${f.dim(s.published_by)}`:""}`),s.release_note&&y(` ${f.dim(s.release_note)}`)}}async function Ap(t,e,n=Un){let r=Number(t);(!Number.isInteger(r)||r<1)&&v(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let s=await Mn(e,n);if(await Qs(`Roll the knowledge base back to release v${r}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await J("rolling back",()=>s.docsRollback(r));y(f.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){G(i,"docs:publish","roll the knowledge base back"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Ip(t,e,n=Un){let r=(t??"").trim();r||v("name the page slug to delete. `turbobase kb list` shows them.");let s=await Mn(e,n);if(await Qs(`Delete "${r}"?`,"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 J("deleting",()=>s.docsDelete(r));y(f.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){G(i,"docs:publish","delete a page"),v(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}ht();function ik(t){return t.diff??!!t.dryRun}function ak(t,e){let n=[];return t.forEach((r,s)=>{let o=r.action==="new_rule"?f.green("new rule"):f.yellow("amend rule"),i=r.targetPublished?` ${f.yellow("[currently live]")}`:"";n.push(`${s+1}. ${o} ${f.bold(r.slug)}${i}`),n.push(` ${r.name}`),r.description&&n.push(` ${f.dim(r.description)}`);for(let a of r.entries)n.push(` ${f.dim("\xB7")} ${f.dim(a.app_slug)} ${a.title}`);if(e.diff){n.push("");for(let a of r.bodyMarkdown.split(`
3697
- `))n.push(` ${f.dim("|")} ${a}`)}n.push("")}),n}function lk(t){let e=t.reduce((s,o)=>s+o.entries.length,0),n=t.filter(s=>s.targetPublished).length,r=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return n>0&&r.push(f.yellow(`${n} amend a rule that is currently live`)),r.join(" \xB7 ")}async function Cp(t,e=n=>new z(n)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let n=await V(t.baseUrl),r=e(n),s={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},o=await Rr(r,t.app),i;try{i=await J("reading the pending rules",()=>r.rulesPending(s))}catch(l){G(l,"extensions:deploy","read the pending rules"),v(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&o&&o.entriesDuplicate>0){L(`nothing pending \u2014 all ${o.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}L(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(y(ak(i.items,{diff:ik(t)}).join(`
3698
- `)),y(lk(i.items)),t.dryRun){L(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!Ie()){L(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 Ce(`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"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await J("writing the rules",()=>r.rulesPush(i.planToken,s))}catch(l){l instanceof Z&&l.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: ${l instanceof Error?l.message:String(l)}`)}y(f.green(`wrote ${i.items.length} draft rule(s).`)),L(f.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as fk,readFile as mk,stat as gk}from"node:fs/promises";import{join as Lp,resolve as bk}from"node:path";var Lt=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},ck=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Op(t){let e=t.replace(/^/,""),n=ck.exec(e);if(!n)throw new Lt("SKILL.md must begin with a `---` YAML frontmatter block");let[,r,s]=n,o=dk(r??""),i=o.name,a=o.description;if(!i)throw new Lt("SKILL.md frontmatter is missing required `name`");if(!a)throw new Lt("SKILL.md frontmatter is missing required `description`");let l=new Set(["name","description","license","version"]),u=Object.entries(o).filter(([m])=>!l.has(m));return{frontmatter:{name:i,description:a,...o.license?{license:o.license}:{},...o.version?{version:o.version}:{},...u.length?{extra:Object.fromEntries(u)}:{}},body:(s??"").trim()}}function dk(t){let e={},n=t.split(/\r?\n/),r=0;for(;r<n.length;){let s=n[r]??"";if(!s.trim()||s.trim().startsWith("#")){r+=1;continue}if(/^\s/.test(s))throw new Lt(`SKILL.md frontmatter: indented line not allowed in this parser: "${s.trim()}"`);let o=s.indexOf(":");if(o===-1)throw new Lt(`SKILL.md frontmatter: expected "key: value", got "${s.trim()}"`);let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();if(a=pk(a),a===">"||a==="|"){let l=[];for(r+=1;r<n.length;){let u=n[r]??"";if(u.length===0||/^\s/.test(u))l.push(u.replace(/^\s{0,2}/,"")),r+=1;else break}e[i]=(a===">"?l.join(" "):l.join(`
3699
- `)).trim();continue}e[i]=uk(a),r+=1}return e}function uk(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function pk(t){let e=!1,n=!1;for(let r=0;r<t.length;r+=1){let s=t[r];if(s==="'"&&!n)e=!e;else if(s==='"'&&!e)n=!n;else if(s==="#"&&!e&&!n)return t.slice(0,r).trim()}return t}var hk=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function Np(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 n=new Set;for(let r of t){let s=r.slug||"(unnamed)";hk.test(r.slug??"")||e.push(`${s}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),n.has(r.slug)&&e.push(`${s}: two files share this slug`),n.add(r.slug),r.name?.trim()?r.name.length>200&&e.push(`${s}: \`name\` is over 200 characters`):e.push(`${s}: frontmatter \`name\` is empty`),r.description?.trim()?r.description.length>1024&&e.push(`${s}: \`description\` is over 1024 characters`):e.push(`${s}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),r.body?.trim()?Buffer.byteLength(r.body,"utf8")>65536&&e.push(`${s}: the body is over ${65536/1024} KB`):e.push(`${s}: the body after the frontmatter is empty`)}return e}ht();async function yk(t){let e=bk(t),n;try{n=(await fk(e)).sort()}catch{v(`--from ${t}: no such directory.`)}let r=[];for(let s of n){let o=Lp(e,s,"SKILL.md");if(await gk(o).then(a=>a.isFile()).catch(()=>!1))try{let a=Op(await mk(o,"utf8"));r.push({slug:s,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Lt&&v(`${Lp(t,s,"SKILL.md")}: ${a.message}`),a}}return r}var eo={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},wk={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 vk(t){let e=[];for(let n of t.items){let r=n.action==="refused"?f.red(eo.refused):n.action==="unchanged"?f.dim(eo.unchanged):n.action==="new"?f.green(eo.new):f.yellow(eo.update),s=n.targetPublished?` ${f.yellow("[currently live]")}`:"";e.push(`${r} ${f.bold(n.slug)}${s} \u2014 ${n.name}`),n.reason&&e.push(` ${f.red(wk[n.reason]??n.reason)}`)}for(let n of t.orphans)e.push(`${f.yellow("orphan")} ${f.bold(n)} \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 jp(t,e=n=>new z(n)){t.app||v("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let n=await yk(t.from),r=Np(n);r.length>0&&v(`nothing was sent:
3700
- ${r.join(`
3701
- `)}`);let s=await V(t.baseUrl),o=e(s),i=async S=>{try{return await J(S?"reading the plan":"writing the skills",()=>o.appSkillsPush(t.app,n,S))}catch(b){if(G(b,"extensions:deploy","push skill files"),b instanceof Z&&b.status===404){let _=b.body;v(_?.error==="app_not_found"?String(_.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}v(`push failed: ${b instanceof Error?b.message:String(b)}`)}},a=await i(!0);y(vk(a).join(`
3702
- `));let l=a.items.filter(S=>S.action==="new"||S.action==="update").length,u=a.items.filter(S=>S.action==="refused").length;if(t.dryRun){L(f.dim("dry run \u2014 nothing was written.")),u>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!t.yes){if(!Ie()){L(f.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await Ce(`Write ${l} 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"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}p=await i(!1)}let m=p.items.filter(S=>S.action==="new"||S.action==="update").map(S=>S.slug);if(y(`${m.length} written, ${p.items.filter(S=>S.action==="unchanged").length} unchanged, ${p.items.filter(S=>S.action==="refused").length} refused.`),t.publish&&m.length>0){let S;try{S=await J("publishing",()=>o.skillsPublish(m))}catch(b){G(b,"skills:publish","publish the pushed skills"),v(`the skills were written as drafts but publishing failed: ${b instanceof Error?b.message:String(b)}`)}y(f.green(`published ${S.published.join(", ")} \u2014 live as of release ${S.version.version_no}.`))}else t.publish?y(f.dim("nothing changed \u2014 nothing to publish.")):m.length>0&&L(f.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));p.items.some(S=>S.action==="refused")&&(L(f.red("one or more skill files were refused and not written.")),process.exitCode=1)}ht();var kk=["proposed","active","rejected"],Sk=["mechanic","operator","learning","code-baseline"],to=t=>new z(t);async function no(t,e){let n=await V(t.baseUrl);return e(n)}function Dp(t,e,n){if(!t)return;let r=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);if(r.length!==0){for(let s of r)e.includes(s)||v(`${n}: unknown value '${s}' \u2014 expected one of ${e.join(", ")}.`);return r}}function _k(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 qp(t){let e=Dp(t.status,kk,"--status"),n=Dp(t.provenance,Sk,"--provenance"),r=_k(t.limit);return{...e?{status:e}:{},...n?{provenance:n}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...r?{limit:r}:{}}}function Up(t){return!!(t.provenance?.length||t.recordType||t.source)}var zp=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function xk(t){return t.status==="active"?f.green("active"):t.status==="rejected"?f.dim("rejected"):f.yellow("proposed")}function $k(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 Bp(t){return[t.hookId,xk(t),t.provenance==="learning"?f.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),$k(t)]}async function Fp(t={},e=to){let n=await no(t,e),r=qp(t),s;try{s=await n.proposals(r)}catch(i){G(i,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return y(JSON.stringify(s,null,2));if(s.length===0){let i=r.status?.length?r.status.join("/"):"proposed";return y(`no ${i} hook proposals.
3703
- `+f.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}y(ft(s.map(Bp),{head:zp})),y(f.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let o=s.filter(i=>i.provenance==="learning"&&i.status==="proposed");o.length>0&&y(f.dim(` ${o.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function Rk(t,e,n){return n.yes?!0:Ie()?await Ce(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function Tk(t){return!(t instanceof Z)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function _a(t,e){Tk(t)&&G(t,"extensions:deploy",e)}function xa(t,e){let n=e instanceof Z?e.body:void 0,r=n?.error==="forbidden"?n.reason??n.error:n?.error,o=r?{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"}[r]??r:e instanceof Error?e.message:String(e);L(ye.error(`${f.bold(t)} \u2014 ${o}`))}async function Mp(t,e){try{let n=await t.proposalPromote(e);return y(ye.success(`${f.bold(e)} ${f.dim(`${n.previousStatus} \u2192`)} ${f.green(n.status)}`)),!0}catch(n){return _a(n,"promote a hook proposal"),xa(e,n),!1}}async function Hp(t,e={},n=to){!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 r=await no(e,n);if(!e.auto){let p=0;for(let m of t)await Mp(r,m)&&(p+=1);p>0&&y(f.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let s=qp({...e,status:e.status??"proposed"});s.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."),s.status?.some(p=>p!=="proposed")&&v("promote --auto: only `--status proposed` rows can be armed in bulk.");let o;try{o=await r.proposals(s)}catch(p){G(p,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=o.filter(p=>p.provenance==="learning"),a=o.filter(p=>p.provenance!=="learning");if(e.json&&(y(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(y(`nothing to promote${Up(s)?" for that filter":""}.`),i.length>0&&y(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(y(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):`),y(ft(a.map(Bp),{head:zp})),i.length>0&&y(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){y(""),y(ye.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Up(s)&&!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 Rk(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let u=0;for(let p of a)await Mp(r,p.hookId)&&(u+=1);y(f.dim(` ${u}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),u<a.length&&(process.exitCode=1)}async function Kp(t,e={},n=to){t.length===0&&v("retract: name at least one proposal id.");let r=await no(e,n),s=0;for(let o of t)try{let i=await r.proposalRetract(o);y(ye.success(`${f.bold(o)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.yellow(i.status)}`)),s+=1}catch(i){_a(i,"retract a hook proposal"),xa(o,i)}s>0&&y(f.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),s<t.length&&(process.exitCode=1)}async function Vp(t,e={},n=to){t.length===0&&v("reject: name at least one proposal id.");let r=await no(e,n),s=0;for(let o of t)try{let i=await r.proposalReject(o,e.reason);y(ye.success(`${f.bold(o)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.dim(i.status)}`)),s+=1}catch(i){_a(i,"reject a hook proposal"),xa(o,i)}s<t.length&&(process.exitCode=1)}ht();var $a=t=>new z(t);async function Ek(t,e){let n=await V(t.baseUrl);return e(n)}function Pk(t){return!(t instanceof Z)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Ak(t,e){let n=e instanceof Z?e.body:void 0,r=n?.error==="forbidden"?n.reason??n.error:n?.error,o=r?{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"}[r]??r:e instanceof Error?e.message:String(e);L(ye.error(`${f.bold(t)} \u2014 ${o}`))}async function Ra(t,e,n,r,s,o,i){e.length===0&&v(`${t}: name at least one extension id.`);let a=await Ek(n,r),l=[];for(let u of e)try{let p=await s(a,u);l.push(p),n.json||y(o(p))}catch(p){Pk(p)&&G(p,"extensions:deploy",`${t} an extension`),Ak(u,p)}if(n.json)y(JSON.stringify(l,null,2));else{let u=i(l.length);u&&y(f.dim(u))}l.length<e.length&&(process.exitCode=1)}async function Wp(t,e={},n=$a){await Ra("disable",t,e,n,(r,s)=>r.extensionDisable(s),r=>ye.success(`${f.bold(r.id)} ${f.dim(`${r.previousStatus} \u2192`)} ${f.yellow(r.status)}`),r=>r>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function Gp(t,e={},n=$a){await Ra("enable",t,e,n,(r,s)=>r.extensionEnable(s),r=>ye.success(`${f.bold(r.id)} ${f.dim(`${r.previousStatus} \u2192`)} ${f.green(r.status)}`),r=>r>0?" the loader compiles it on its next reload.":null)}async function Jp(t,e={},n=$a){await Ra("remove",t,e,n,(r,s)=>r.extensionRemove(s),r=>ye.success(`${f.bold(r.id)} ${f.dim(`${r.previousStatus} \u2192`)} ${f.dim(r.status)}`),r=>r>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}ht();var qn=t=>new z(t);async function zn(t,e){let n=await V(t.baseUrl);return e(n)}async function ro(t,e,n,r){return r.yes?!0:Ie()?await Ce(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function Ik(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function Yp(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function Ck(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(o=>o.slug.length)),n=[];for(let o of t.items)n.push(`${Yp(f.bold(o.slug),e)} ${Yp(Ik(o),10)} ${o.surfaces.join(",")||f.dim("none")}`),o.description&&n.push(` ${f.dim(o.description)}`);n.push("");let r=t.items.filter(o=>o.visibility==="published"&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return n.push(`${t.items.length} skill(s) \xB7 ${r} injected \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),n}async function Xp(t,e=qn){let n={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),n.status=t.status);let r=await zn(t,e),s;try{s=await J("reading the skills",()=>r.skillsList(n))}catch(o){G(o,"skills:publish","read the instance skills"),v(`could not read the skills: ${o instanceof Error?o.message:String(o)}`)}y(Ck(s).join(`
3704
- `))}async function Zp(t,e,n=qn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let s=await zn(e,n);if(!await ro(`Publish ${r.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 J("publishing",()=>s.skillsPublish(r))}catch(a){G(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(f.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Qp(t,e,n=qn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let s=await zn(e,n);if(!await ro(`Move ${r.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 J("unpublishing",()=>s.skillsUnpublish(r))}catch(a){G(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(f.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function eh(t,e,n=qn){let r=Number(t);(!Number.isInteger(r)||r<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await zn(e,n);if(await ro(`Roll the skills back to release v${r}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>s.skillsRollback(r));y(f.green(`rolled back to v${i.version.version_no}.`))}catch(i){G(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function th(t,e=qn){let n=await zn(t,e),r;try{r=await J("reading the releases",()=>n.skillsReleases())}catch(s){G(s,"skills:publish","read the skills releases"),v(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){L("no releases yet.");return}for(let s of r.items){let o=s.is_current?f.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";y(`${o} v${s.version_no} ${s.skill_count} skill(s) ${f.dim(s.published_at)}${s.published_by?f.dim(` by ${s.published_by}`):""}${f.dim(i)}`)}}async function nh(t,e,n=qn){let r=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];r.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await zn(e,n);if(!await ro(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
3705
- ${r.join(`
3706
- `)}`,"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 u of r)try{i.push(await J(`deleting ${u}`,()=>s.skillsDelete(u)))}catch(p){if(p instanceof Z&&p.status===404){a.push(u);continue}i.length>0&&L(f.dim(`deleted before the error: ${i.map(m=>m.slug).join(", ")}`)),G(p,"skills:publish","delete a skill"),v(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(f.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(f.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(f.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as rh}from"node:fs";import{join as Ok,relative as Nk,resolve as Lk,sep as jk}from"node:path";var Dk=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),Uk=new Set([".mcp.json",".env"]);function Mk(t){return Uk.has(t)||t.startsWith(".env.")&&t!==".env.example"}function qk(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function zk(t){return t.includes(0)}async function sh(t){let e=Lk(t),n={},r=[],s=[],o=[];async function i(a){let l=await rh.readdir(a,{withFileTypes:!0});for(let u of l){let p=Ok(a,u.name);if(Dk.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let m=Nk(e,p).split(jk).join("/");if(Mk(u.name)){s.push(m);continue}let S=await rh.readFile(p);if(!qk(S)){r.push(m);continue}zk(S)&&o.push(m),n[m]=S.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as Bk}from"node:crypto";var Fk="/_tb/app-assets",Hk=16,Kk=/^[0-9a-f]{32}$/;function oh(){return Bk(Hk).toString("hex")}function Vk(t){return Kk.test(t)}function ih(t){if(!Vk(t))throw new Error(`not a build id: ${t}`);return`${Fk}/${t}/`}var ah=7;Ea();var Pa=50*1024*1024;import so from"node:fs/promises";import Tr from"node:path";var Aa={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ia="@turbobase/isolated-vm-prebuilds";function Ca(t,e){return`${t}-${e}`}function Oa(t=process.versions){return`abi${t.modules}`}var lh=["darwin-x64","win32-arm64"];async function ch(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=Ca(e,n),s=Tr.join(t.home,"node_modules"),o=Tr.join(s,...Ia.split("/"),"prebuilds",r),i=Tr.join(s,"isolated-vm","prebuilds",r),a;try{a=await so.readdir(o)}catch{return[]}let l=[];await so.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=Tr.join(i,u);try{await so.copyFile(Tr.join(o,u),p,so.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as Wk}from"node:os";import{join as dh}from"node:path";import{promises as Na}from"node:fs";function ph(){let t=process.env.TURBOBASE_HOME??dh(Wk(),".turbobase");return{dir:t,file:dh(t,"sandboxes.json")}}var Gk={s:1e3,m:6e4,h:36e5,d:864e5};function Jk(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 n=Number(e[1]);if(!Number.isFinite(n)||n<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return n*Gk[e[2]]}function Yk(t,e=Date.now()){return new Date(e+Jk(t)).toISOString()}function Xk(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function Zk(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 n=Number(e[1]);if(!Number.isFinite(n)||n<0||n>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return n/100}function Qk(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let n=Math.max(1,Math.round(1/e)),r=[];for(let s=0;s<t.length;s+=n)r.push(t[s]);return r}var eS="[REDACTED]",Er=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},La=class extends Error{table;column;constructor(e,n,r){super(`Refusing to copy ${e}.${n} into a sandbox: ${r}. 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=n}};function tS(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new La(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:eS:r[s]=o}return r}function nS(t,e,n){return e.map(r=>tS(t,r,n))}var uh=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),rS=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function sS(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.hostname.toLowerCase()}catch{}let n=e.replace(/^[a-z]+:\/\//i,""),r=(n.split("/")[0]??n).split("@").pop()??n;return(r.split(":")[0]??r).toLowerCase()}function ja(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let r of rS)if(e.includes(r))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${r}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let n=sS(t);if(!uh.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...uh].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function oS(t,e=iS){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function iS(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function aS(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function lS(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Da(){let{file:t}=ph();try{let e=await Na.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function hh(t){let{dir:e,file:n}=ph();await Na.mkdir(e,{recursive:!0}),await Na.writeFile(n,`${JSON.stringify(t,null,2)}
3707
- `,{mode:384})}async function cS(t){let e=await Da();e.push(t),await hh(e)}async function fh(t){let e=await Da(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await hh(e),r??null}async function oo(){return Da()}function Ua(t,e=Date.now()){let n=[],r=[];for(let s of t)Xk(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function mh(t,e){ja(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new Er(n);let r=Zk(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>oS(u)))(e.fromTenant),i=aS(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=Qk(u.rows,r),m=nS(u.table,p,u.classification);m.length>0&&await t.copyRows(i,u.table,m)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:Yk(e.ttl,s),sampleFraction:r,url:lS(o,e.baseUrl)};return await cS(l),l}async function gh(t,e){ja(t.target());let r=(await oo()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await fh(e),r):null}async function Ma(t,e=Date.now()){ja(t.target());let n=await oo(),{expired:r}=Ua(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await fh(o.name),s.push(o)}return s}var Pr={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"}},yO=Object.keys(Pr).filter(t=>Pr[t].mintable);var kO=Pr.pat.prefix,dS=Object.entries(Pr).map(([t,e])=>[e.prefix,t]),uS=/^[A-Za-z0-9_-]{20,}$/;function pS(t){if(typeof t!="string")return null;for(let[e,n]of dS)if(t.startsWith(e)&&uS.test(t.slice(e.length)))return n;return null}function bh(t){return pS(t)==="pat"}gr();var hS=8e3,fS={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 mS(t){return fS[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function gS(t,e,n=fetch){let r;try{r=await n(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(hS)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(r.status===200||r.status===403)return{state:"accepted"};if(r.status===401){let o=await r.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(r.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${r.status} \u2014 this host does not serve the /v1 API`}}function yh(t){return t.state==="accepted"?Pe()?f.green("accepted"):"accepted":t.state==="rejected"?Pe()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Pe()?f.yellow("unreachable"):"unreachable"}async function wh(t={},e=fetch){let n=await Ct(),{file:r}=Cs();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${r}.`));return}let s=await pt(),o=await Promise.all(n.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await gS(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Pe())y(ft(o.map(i=>[i.active?f.green("*"):" ",f.bold(i.baseUrl),yh(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${yh(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${mS(i.check.reason)}.`)),L(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"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function MP(t){let e=await Ct();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ie()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Ce(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{v("cancelled.")}}async function qP(t,e){let n;try{n=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let r=(n.headers.get("content-type")??"").includes("application/json");return n.status===200||n.status===403?{ok:!0}:n.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${n.status}`}:r?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${n.status}`}}function zP(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function BP(t,e,n){let r=await gu({baseUrl:t,token:e}),s=(await Ct()).length-1;if(y(`signed in to ${r.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),zP(r.baseUrl),!n)return;let o=await qP(r.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${r.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${o.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):o.kind==="bad-token"?L(`warning: ${r.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${r.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function FP(t){let e=await oa(await vr(t),qt(t)),n=ya(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);v(r?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...n,sourceCode:e}}async function Pn(t,e,n,r){try{return await oe.access(t),"skipped"}catch{}return await oe.mkdir(qt(t),{recursive:!0}),await oe.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await oe.chmod(t,r),"wrote"}async function wy(t,e){if(ky(t)!==".gitignore")return Pn(t,e.content,e.executable,e.mode);let n=await oe.readFile(t,"utf8").catch(()=>null);if(n===null)return Pn(t,e.content,e.executable,e.mode);let r=sp(n);return r===null?"skipped":(await oe.writeFile(t,r,"utf8"),"merged")}function jd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ii(t){process.exit(t)}function HP(t){return{name:"turbobase ext test",cases:t.map(n=>{if(n.pass)return{name:n.name,status:"passed"};let r=n.error?"error":n.rejection?.code??"mismatch",s=n.error?`error: ${n.error}`:n.observed!==n.expected?`expected ${n.expected}, observed ${n.observed}`+(n.rejection?` (rejected: ${n.rejection.code??"rejected"}${n.rejection.message?` \u2014 ${n.rejection.message}`:""})`:""):`rejected: ${n.rejection?.code??"rejected"}${n.rejection?.message?` \u2014 ${n.rejection.message}`:""}`;return{name:n.name,status:"failed",detail:s,type:r}})}}function KP(t,e){let n=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(r=>({name:`${t}: ${r.rule}`,status:"failed",type:r.rule,detail:`${r.message} \u2192 fix: ${r.fix}`}));return{name:`turbobase ext lint ${t}`,cases:n}}function VP(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 n of t.guards)e.push(n.status==="failed"?{name:`guard: ${n.name}`,status:"failed",type:n.name,detail:n.detail}:{name:`guard: ${n.name}`,status:"passed",detail:n.status==="skipped-offline"?`skipped-offline: ${n.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 vy(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Bd({includeInternal:t=!0}={}){let e=new UP;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.30.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${pa()}
3708
- `),e.hook("preAction",(d,h)=>{bp(e.opts(),h.opts())});let n=e.command("auth").description("Sign in to an instance and manage stored credentials."),r=e.command("project").description("Set up the local project and the files an agent session reads."),s=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),o=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.");n.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=tt(d.baseUrl);d.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3709
- ${xr} auth login --base-url ${h} --token tb_pat_\u2026`),bh(d.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await BP(h,d.token,d.verify)}),n.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=>wh({probe:d.probe})),n.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let h=d??await MP("Pick the active instance:"),w=await Os(h);if(!w){let $=await Ct();v(`no stored sign-in for ${tt(h)}.`+($.length?` Stored: ${$.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${tt(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${w.baseUrl}.`)}),n.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 $=await Ct();for(let k of $)await Qi(k.baseUrl);y(`removed ${$.length} stored sign-in${$.length===1?"":"s"}.`);return}let h=await Qi(d.baseUrl);h||v(d.baseUrl?`no stored sign-in for ${tt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await pt();y(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),r.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$;try{$=await hn({baseUrl:h,token:w,recordsOnly:d.recordsOnly})}catch(g){let x=g instanceof Error?g.message:String(g);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(x)){L("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{$=await hn({baseUrl:h,token:w,recordsOnly:!0})}catch(E){v(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else v(`types generation failed: ${x}`)}let k=se(process.cwd(),d.out);await oe.writeFile(k,$,"utf8"),y(`wrote ${k} (${$.split(`
3710
- `).length} lines).`)}),vp(r),r.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$=new URLSearchParams;d.records&&$.set("records",d.records),d.query&&$.set("query",d.query);let k=$.toString(),g=await fetch(`${h}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});g.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let E=((await g.json()).markdown??"").trim(),A=se(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
3711
-
3712
- `;await oe.writeFile(A,O+(E?`${E}
3703
+ `,carried:s}}function Tp(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 V(e.baseUrl),o=t_(process.cwd(),e.out),s=e.since?.trim()||await n_(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),l=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});l.ok||v(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let u=await l.json();if(!u.available){b(`${r} ships no release notes to adopt from (nothing written).`);return}let p=u.releases.reduce((R,P)=>R+P.items.length,0);if(p===0){b(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${u.currentVersion?` (instance is on v${u.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let f=u.currentVersion??u.releases[0]?.version??"",S=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${f}. Re-run to refresh; delete this file once every line is done. -->
3704
+
3705
+ `,y=await _a.readFile(o,"utf8").catch(()=>null),k=u.markdown,$=0;if(y!==null&&y.trim()!==""){let R=a_(y,u.markdown);R||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>\`.`),k=R.markdown,$=R.carried}await _a.writeFile(o,S+k,"utf8"),b(`wrote ${o} \u2014 ${p} item(s) across ${u.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${$>0?`, keeping ${$} unticked item(s) already in the file`:""}.`)})}mt();var xn=["suggested_kb_edit","kb_correction"];var l_=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function c_(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var AI=new Map(l_.map(t=>[c_(t.heading),t]));var CI=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 d_(t){return t.diff??!!t.dryRun}var u_={update_page:"append to the existing page",new_page:"create a NEW page"},Nt=(t,e)=>` ${h.dim(t.padEnd(11))}${e}`,Rp=t=>t.ownerEmail??t.ownerId;function jr(t){return!t.needsPageRef&&!t.blockedBy}var Qo=t=>h.green(t?` + ${t}`:" +"),p_=t=>h.red(t?` - ${t}`:" -"),hr=t=>h.dim(` ${t}`),m_=` ${h.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Sa=80;function h_(t){let e=[m_];t.target?(e.push(hr(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(p_(`visibility: ${t.target.visibility}`)),e.push(Qo("visibility: admin"))):e.push(hr(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(hr("title, slug, evidence: untouched")),e.push(hr("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(hr("turbobase.document \xB7 new")),e.push(Qo(`title: ${t.pageTitle}`)),e.push(Qo("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(hr('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(hr('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3706
+ `);for(let n of r.slice(0,Sa))e.push(Qo(n?` ${n}`:""));return r.length>Sa&&e.push(h.yellow(` \u2026 ${r.length-Sa} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function f_(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${h.bold(n.pageTitle)}`),r.push(Nt("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:h.dim("new \u2014 no existing page matches"))),r.push(Nt("action",jr(n)?u_[n.action]:h.red("SKIP \u2014 nothing is written"))),n.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];r.push(Nt("unresolved",h.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).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(Nt("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let l=a.verdict?` ${h.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${h.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${h.dim("\xB7")} ${a.title.trim()}${u}${l}`)}),r.push(Nt("confidence",n.withdraws?h.red("WITHDRAWN from readers (text untouched)"):h.dim("untouched"))),n.supersedes&&r.push(Nt("supersedes",h.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(Nt("blocked",h.red(`unpublished work on this page belongs to ${Rp(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Nt("ambiguous",h.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(l=>{let u=t.findIndex(f=>f.key===l),p=u>=0?t[u]:void 0;return p?`#${u+1} "${p.pageTitle}"`:l});r.push(Nt("similar",h.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&&jr(n)&&r.push(...h_(n)),r.push("")}),r}function g_(t){let e=u=>t.filter(u).length,r=t.reduce((u,p)=>u+p.entries.length,0),n=e(u=>u.withdraws),o=e(u=>u.blockedBy!=null),s=e(u=>u.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(jr)} page(s)`,`${e(u=>u.action==="update_page"&&jr(u))} appended`,`${e(u=>u.action==="new_page"&&jr(u))} created (unpublished)`,...s>0?[h.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?h.red(`${n} page(s) WITHDRAWN from readers`):h.dim("no page withdrawn"),l=o>0?` \xB7 ${h.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function y_(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(`${h.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Rp(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let l=[...new Set((s?.entries??[]).map(u=>u.kb_page_ref?.trim()).filter(u=>!!u))];n.push(`${h.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(u=>`"${u}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${h.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?h.green("created "):h.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${h.bold(o.documentId??"?")}`+(o.created?h.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${h.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${h.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${h.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function xp(t){if(t instanceof Z){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.")}G(t,"extensions:deploy","learnings push-kb")}async function $n(t,e){let r;try{r=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof Z&&o.status===404?L(h.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`.")):_u(o)?L(h.yellow($p(o))):L(h.yellow(`could not re-read the pushed markdown: ${$p(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return L(h.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(h.yellow(`${r.parseSkipped} unparseable`)),L(h.dim(n.join(" \xB7 "))),r}function $p(t){return t instanceof Error?t.message:String(t)}async function Ep(t,e=r=>new z(r)){t.section&&!xn.includes(t.section.trim())&&v(`unknown --section "${t.section}" \u2014 expected one of ${xn.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await V(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 $n(n,t.app),i;try{i=await J("reading the pending queue",()=>n.learningsPending(o))}catch(u){xp(u),v(`could not read the pending queue: ${u instanceof Error?u.message:String(u)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){L(`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}L(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(b(f_(i.items,{diff:d_(t)}).join(`
3707
+ `)),b(g_(i.items)),t.dryRun){L(h.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(jr);if(a.length===0){L(h.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 l=a.reduce((u,p)=>u+p.entries.length,0);if(!t.yes){if(!Ce()){L(h.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 Ie(`Push ${l} 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"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let u=await J("writing pages",()=>n.learningsPushKb(i.planToken,o));b(y_(u.applied,i.items).join(`
3708
+ `))}catch(u){if(u instanceof Z&&u.status===409){L(h.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${Tn} kb push\` to review the current plan.`),process.exitCode=2;return}xp(u),L(h.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}mt();var Dr=t=>new z(t);async function Ur(t,e){let r=await V(t.baseUrl);return e(r)}async function es(t,e,r,n){return n.yes?!0:Ce()?await Ie(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function b_(t){return t.visibility!=="published"?h.dim("draft"):t.in_current_release?h.green("live"):h.yellow("unreleased")}function Pp(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function w_(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(`${Pp(h.bold(s.slug),e)} ${Pp(b_(s),10)} ${h.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 Ap(t,e=Dr){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 Ur(t,e),o;try{o=await J("reading the knowledge base",()=>n.docsList(r))}catch(s){G(s,"docs:publish","read the knowledge base"),v(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}b(w_(o).join(`
3709
+ `))}async function Cp(t,e,r=Dr){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Ur(e,r);if(!await es(`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 J("publishing",()=>o.docsPublish(n))}catch(l){G(l,"docs:publish","publish a page"),v(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);b(h.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(h.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(h.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Ip(t,e,r=Dr){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Ur(e,r);if(!await es(`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 J("unpublishing",()=>o.docsUnpublish(n))}catch(l){G(l,"docs:publish","unpublish a page"),v(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);b(h.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(h.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(h.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Op(t,e=Dr){let r=await Ur(t,e),n;try{n=await J("reading the releases",()=>r.docsVersions())}catch(o){G(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){b("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?h.green("current"):h.dim(" ");b(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${h.dim(o.published_by)}`:""}`),o.release_note&&b(` ${h.dim(o.release_note)}`)}}async function Np(t,e,r=Dr){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 Ur(e,r);if(await es(`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 J("rolling back",()=>o.docsRollback(n));b(h.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){G(i,"docs:publish","roll the knowledge base back"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Lp(t,e,r=Dr){let n=(t??"").trim();n||v("name the page slug to delete. `turbobase kb list` shows them.");let o=await Ur(e,r);if(await es(`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 J("deleting",()=>o.docsDelete(n));b(h.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){G(i,"docs:publish","delete a page"),v(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}mt();function v_(t){return t.diff??!!t.dryRun}function __(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?h.green("new rule"):h.yellow("amend rule"),i=n.targetPublished?` ${h.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${h.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${h.dim(n.description)}`);for(let a of n.entries)r.push(` ${h.dim("\xB7")} ${h.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
3710
+ `))r.push(` ${h.dim("|")} ${a}`)}r.push("")}),r}function S_(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(h.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function jp(t,e=r=>new z(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await V(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 $n(n,t.app),i;try{i=await J("reading the pending rules",()=>n.rulesPending(o))}catch(l){G(l,"extensions:deploy","read the pending rules"),v(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){L(`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}L(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(b(__(i.items,{diff:v_(t)}).join(`
3711
+ `)),b(S_(i.items)),t.dryRun){L(h.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!Ce()){L(h.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 Ie(`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"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await J("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(l){l instanceof Z&&l.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: ${l instanceof Error?l.message:String(l)}`)}b(h.green(`wrote ${i.items.length} draft rule(s).`)),L(h.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as E_,readFile as P_,stat as A_}from"node:fs/promises";import{join as Mp,resolve as C_}from"node:path";var Lt=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},k_=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Dp(t){let e=t.replace(/^/,""),r=k_.exec(e);if(!r)throw new Lt("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=T_(n??""),i=s.name,a=s.description;if(!i)throw new Lt("SKILL.md frontmatter is missing required `name`");if(!a)throw new Lt("SKILL.md frontmatter is missing required `description`");let l=new Set(["name","description","license","version"]),u=Object.entries(s).filter(([f])=>!l.has(f));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...u.length?{extra:Object.fromEntries(u)}:{}},body:(o??"").trim()}}function T_(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 Lt(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Lt(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=$_(a),a===">"||a==="|"){let l=[];for(n+=1;n<r.length;){let u=r[n]??"";if(u.length===0||/^\s/.test(u))l.push(u.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?l.join(" "):l.join(`
3712
+ `)).trim();continue}e[i]=x_(a),n+=1}return e}function x_(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function $_(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 R_=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function Up(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)";R_.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}mt();async function I_(t){let e=C_(t),r;try{r=(await E_(e)).sort()}catch{v(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=Mp(e,o,"SKILL.md");if(await A_(s).then(a=>a.isFile()).catch(()=>!1))try{let a=Dp(await P_(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Lt&&v(`${Mp(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var ts={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},O_={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 N_(t){let e=[];for(let r of t.items){let n=r.action==="refused"?h.red(ts.refused):r.action==="unchanged"?h.dim(ts.unchanged):r.action==="new"?h.green(ts.new):h.yellow(ts.update),o=r.targetPublished?` ${h.yellow("[currently live]")}`:"";e.push(`${n} ${h.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${h.red(O_[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${h.yellow("orphan")} ${h.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 qp(t,e=r=>new z(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 I_(t.from),n=Up(r);n.length>0&&v(`nothing was sent:
3713
+ ${n.join(`
3714
+ `)}`);let o=await V(t.baseUrl),s=e(o),i=async S=>{try{return await J(S?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,S))}catch(y){if(G(y,"extensions:deploy","push skill files"),y instanceof Z&&y.status===404){let k=y.body;v(k?.error==="app_not_found"?String(k.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}v(`push failed: ${y instanceof Error?y.message:String(y)}`)}},a=await i(!0);b(N_(a).join(`
3715
+ `));let l=a.items.filter(S=>S.action==="new"||S.action==="update").length,u=a.items.filter(S=>S.action==="refused").length;if(t.dryRun){L(h.dim("dry run \u2014 nothing was written.")),u>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!t.yes){if(!Ce()){L(h.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await Ie(`Write ${l} 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"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}p=await i(!1)}let f=p.items.filter(S=>S.action==="new"||S.action==="update").map(S=>S.slug);if(b(`${f.length} written, ${p.items.filter(S=>S.action==="unchanged").length} unchanged, ${p.items.filter(S=>S.action==="refused").length} refused.`),t.publish&&f.length>0){let S;try{S=await J("publishing",()=>s.skillsPublish(f))}catch(y){G(y,"skills:publish","publish the pushed skills"),v(`the skills were written as drafts but publishing failed: ${y instanceof Error?y.message:String(y)}`)}b(h.green(`published ${S.published.join(", ")} \u2014 live as of release ${S.version.version_no}.`))}else t.publish?b(h.dim("nothing changed \u2014 nothing to publish.")):f.length>0&&L(h.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));p.items.some(S=>S.action==="refused")&&(L(h.red("one or more skill files were refused and not written.")),process.exitCode=1)}mt();var L_=["proposed","active","rejected"],j_=["mechanic","operator","learning","code-baseline"],rs=t=>new z(t);async function ns(t,e){let r=await V(t.baseUrl);return e(r)}function zp(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 D_(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 Hp(t){let e=zp(t.status,L_,"--status"),r=zp(t.provenance,j_,"--provenance"),n=D_(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Bp(t){return!!(t.provenance?.length||t.recordType||t.source)}var Kp=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function U_(t){return t.status==="active"?h.green("active"):t.status==="rejected"?h.dim("rejected"):h.yellow("proposed")}function M_(t){return t.message?t.message:t.kind&&t.field?h.dim(`${t.kind} ${t.field}`):t.kind?h.dim(t.kind):h.dim("(no description)")}function Vp(t){return[t.hookId,U_(t),t.provenance==="learning"?h.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),M_(t)]}async function Wp(t={},e=rs){let r=await ns(t,e),n=Hp(t),o;try{o=await r.proposals(n)}catch(i){G(i,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return b(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return b(`no ${i} hook proposals.
3716
+ `+h.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}b(ht(o.map(Vp),{head:Kp})),b(h.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&&b(h.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function q_(t,e,r){return r.yes?!0:Ce()?await Ie(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function z_(t){return!(t instanceof Z)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function ka(t,e){z_(t)&&G(t,"extensions:deploy",e)}function Ta(t,e){let r=e instanceof Z?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);L(be.error(`${h.bold(t)} \u2014 ${s}`))}async function Fp(t,e){try{let r=await t.proposalPromote(e);return b(be.success(`${h.bold(e)} ${h.dim(`${r.previousStatus} \u2192`)} ${h.green(r.status)}`)),!0}catch(r){return ka(r,"promote a hook proposal"),Ta(e,r),!1}}async function Gp(t,e={},r=rs){!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 ns(e,r);if(!e.auto){let p=0;for(let f of t)await Fp(n,f)&&(p+=1);p>0&&b(h.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let o=Hp({...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(p=>p!=="proposed")&&v("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(p){G(p,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=s.filter(p=>p.provenance==="learning"),a=s.filter(p=>p.provenance!=="learning");if(e.json&&(b(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(b(`nothing to promote${Bp(o)?" for that filter":""}.`),i.length>0&&b(h.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(b(e.apply?`promoting ${h.bold(String(a.length))} hook proposal(s):`:`${h.bold("dry run")} \u2014 would promote ${h.bold(String(a.length))} hook proposal(s):`),b(ht(a.map(Vp),{head:Kp})),i.length>0&&b(h.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){b(""),b(be.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Bp(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 q_(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let u=0;for(let p of a)await Fp(n,p.hookId)&&(u+=1);b(h.dim(` ${u}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),u<a.length&&(process.exitCode=1)}async function Jp(t,e={},r=rs){t.length===0&&v("retract: name at least one proposal id.");let n=await ns(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);b(be.success(`${h.bold(s)} ${h.dim(`${i.previousStatus} \u2192`)} ${h.yellow(i.status)}`)),o+=1}catch(i){ka(i,"retract a hook proposal"),Ta(s,i)}o>0&&b(h.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function Yp(t,e={},r=rs){t.length===0&&v("reject: name at least one proposal id.");let n=await ns(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);b(be.success(`${h.bold(s)} ${h.dim(`${i.previousStatus} \u2192`)} ${h.dim(i.status)}`)),o+=1}catch(i){ka(i,"reject a hook proposal"),Ta(s,i)}o<t.length&&(process.exitCode=1)}mt();var xa=t=>new z(t);async function B_(t,e){let r=await V(t.baseUrl);return e(r)}function F_(t){return!(t instanceof Z)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function H_(t,e){let r=e instanceof Z?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);L(be.error(`${h.bold(t)} \u2014 ${s}`))}async function $a(t,e,r,n,o,s,i){e.length===0&&v(`${t}: name at least one extension id.`);let a=await B_(r,n),l=[];for(let u of e)try{let p=await o(a,u);l.push(p),r.json||b(s(p))}catch(p){F_(p)&&G(p,"extensions:deploy",`${t} an extension`),H_(u,p)}if(r.json)b(JSON.stringify(l,null,2));else{let u=i(l.length);u&&b(h.dim(u))}l.length<e.length&&(process.exitCode=1)}async function Xp(t,e={},r=xa){await $a("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>be.success(`${h.bold(n.id)} ${h.dim(`${n.previousStatus} \u2192`)} ${h.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 Zp(t,e={},r=xa){await $a("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>be.success(`${h.bold(n.id)} ${h.dim(`${n.previousStatus} \u2192`)} ${h.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function Qp(t,e={},r=xa){await $a("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>be.success(`${h.bold(n.id)} ${h.dim(`${n.previousStatus} \u2192`)} ${h.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}mt();var Mr=t=>new z(t);async function qr(t,e){let r=await V(t.baseUrl);return e(r)}async function os(t,e,r,n){return n.yes?!0:Ce()?await Ie(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(h.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function K_(t){return t.visibility!=="published"?h.dim("draft"):t.in_current_release?h.green("live"):h.yellow("unreleased")}function em(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function V_(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(`${em(h.bold(s.slug),e)} ${em(K_(s),10)} ${s.surfaces.join(",")||h.dim("none")}`),s.description&&r.push(` ${h.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 tm(t,e=Mr){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 qr(t,e),o;try{o=await J("reading the skills",()=>n.skillsList(r))}catch(s){G(s,"skills:publish","read the instance skills"),v(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}b(V_(o).join(`
3717
+ `))}async function rm(t,e,r=Mr){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 qr(e,r);if(!await os(`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 J("publishing",()=>o.skillsPublish(n))}catch(a){G(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}b(h.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(h.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(h.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function nm(t,e,r=Mr){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 qr(e,r);if(!await os(`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 J("unpublishing",()=>o.skillsUnpublish(n))}catch(a){G(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}b(h.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(h.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(h.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function om(t,e,r=Mr){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 qr(e,r);if(await os(`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 J("rolling back",()=>o.skillsRollback(n));b(h.green(`rolled back to v${i.version.version_no}.`))}catch(i){G(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function sm(t,e=Mr){let r=await qr(t,e),n;try{n=await J("reading the releases",()=>r.skillsReleases())}catch(o){G(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){L("no releases yet.");return}for(let o of n.items){let s=o.is_current?h.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";b(`${s} v${o.version_no} ${o.skill_count} skill(s) ${h.dim(o.published_at)}${o.published_by?h.dim(` by ${o.published_by}`):""}${h.dim(i)}`)}}async function im(t,e,r=Mr){let n=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await qr(e,r);if(!await os(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3718
+ ${n.join(`
3719
+ `)}`,"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 u of n)try{i.push(await J(`deleting ${u}`,()=>o.skillsDelete(u)))}catch(p){if(p instanceof Z&&p.status===404){a.push(u);continue}i.length>0&&L(h.dim(`deleted before the error: ${i.map(f=>f.slug).join(", ")}`)),G(p,"skills:publish","delete a skill"),v(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(h.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(h.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(h.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as am}from"node:fs";import{join as W_,relative as G_,resolve as J_,sep as Y_}from"node:path";var X_=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),Z_=new Set([".mcp.json",".env"]);function Q_(t){return Z_.has(t)||t.startsWith(".env.")&&t!==".env.example"}function eS(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function tS(t){return t.includes(0)}async function lm(t){let e=J_(t),r={},n=[],o=[],s=[];async function i(a){let l=await am.readdir(a,{withFileTypes:!0});for(let u of l){let p=W_(a,u.name);if(X_.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let f=G_(e,p).split(Y_).join("/");if(Q_(u.name)){o.push(f);continue}let S=await am.readFile(p);if(!eS(S)){n.push(f);continue}tS(S)&&s.push(f),r[f]=S.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as rS}from"node:crypto";var nS="/_tb/app-assets",oS=16,sS=/^[0-9a-f]{32}$/;function cm(){return rS(oS).toString("hex")}function iS(t){return sS.test(t)}function dm(t){if(!iS(t))throw new Error(`not a build id: ${t}`);return`${nS}/${t}/`}var um=7;Ea();var Pa=50*1024*1024;import ss from"node:fs/promises";import Rn from"node:path";var Aa={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ca="@turbobase/isolated-vm-prebuilds";function Ia(t,e){return`${t}-${e}`}function Oa(t=process.versions){return`abi${t.modules}`}var pm=["darwin-x64","win32-arm64"];async function mm(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Ia(e,r),o=Rn.join(t.home,"node_modules"),s=Rn.join(o,...Ca.split("/"),"prebuilds",n),i=Rn.join(o,"isolated-vm","prebuilds",n),a;try{a=await ss.readdir(s)}catch{return[]}let l=[];await ss.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=Rn.join(i,u);try{await ss.copyFile(Rn.join(s,u),p,ss.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as aS}from"node:os";import{join as hm}from"node:path";import{promises as Na}from"node:fs";function gm(){let t=process.env.TURBOBASE_HOME??hm(aS(),".turbobase");return{dir:t,file:hm(t,"sandboxes.json")}}var lS={s:1e3,m:6e4,h:36e5,d:864e5};function cS(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*lS[e[2]]}function dS(t,e=Date.now()){return new Date(e+cS(t)).toISOString()}function uS(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function pS(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 mS(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 hS="[REDACTED]",En=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},La=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 fS(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new La(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:hS:n[o]=s}return n}function gS(t,e,r){return e.map(n=>fS(t,n,r))}var fm=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),yS=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function bS(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 ja(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 yS)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=bS(t);if(!fm.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...fm].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function wS(t,e=vS){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function vS(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function _S(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function SS(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Da(){let{file:t}=gm();try{let e=await Na.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function ym(t){let{dir:e,file:r}=gm();await Na.mkdir(e,{recursive:!0}),await Na.writeFile(r,`${JSON.stringify(t,null,2)}
3720
+ `,{mode:384})}async function kS(t){let e=await Da();e.push(t),await ym(e)}async function bm(t){let e=await Da(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await ym(e),n??null}async function is(){return Da()}function Ua(t,e=Date.now()){let r=[],n=[];for(let o of t)uS(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function wm(t,e){ja(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new En(r);let n=pS(e.sample),o=e.now??Date.now(),s=(e.nameGen??(u=>wS(u)))(e.fromTenant),i=_S(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=mS(u.rows,n),f=gS(u.table,p,u.classification);f.length>0&&await t.copyRows(i,u.table,f)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:dS(e.ttl,o),sampleFraction:n,url:SS(s,e.baseUrl)};return await kS(l),l}async function vm(t,e){ja(t.target());let n=(await is()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await bm(e),n):null}async function Ma(t,e=Date.now()){ja(t.target());let r=await is(),{expired:n}=Ua(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await bm(s.name),o.push(s)}return o}var Pn={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"}},qO=Object.keys(Pn).filter(t=>Pn[t].mintable);var FO=Pn.pat.prefix,TS=Object.entries(Pn).map(([t,e])=>[e.prefix,t]),xS=/^[A-Za-z0-9_-]{20,}$/;function $S(t){if(typeof t!="string")return null;for(let[e,r]of TS)if(t.startsWith(e)&&xS.test(t.slice(e.length)))return r;return null}function _m(t){return $S(t)==="pat"}gn();var RS=8e3,ES={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 PS(t){return ES[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function AS(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(RS)})}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 Sm(t){return t.state==="accepted"?Pe()?h.green("accepted"):"accepted":t.state==="rejected"?Pe()?h.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Pe()?h.yellow("unreachable"):"unreachable"}async function km(t={},e=fetch){let r=await It(),{file:n}=Oo();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(h.dim(`no sign-ins stored in ${n}.`));return}let o=await pt(),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 AS(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Pe())b(ht(s.map(i=>[i.active?h.green("*"):" ",h.bold(i.baseUrl),Sm(i.check),h.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Sm(i.check)} (updated ${i.updatedAt})`);L(h.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(h.red(`${i.baseUrl}: ${PS(i.check.reason)}.`)),L(h.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"&&L(h.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function QP(t){let e=await It();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ce()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Ie(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function eA(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 tA(t){L(""),L("Sharing is ON. Two things reach the Turbobase product team from this instance:"),L(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),L(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),L(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),L(" about OUR platform, with instance name, user names and ids masked before they leave."),L(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),L("")}async function rA(t,e,r){let n=await gu({baseUrl:t,token:e}),o=(await It()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),tA(n.baseUrl),!r)return;let s=await eA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function nA(t){let e=await sa(await vn(t),qt(t)),r=ba(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);v(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function Er(t,e,r,n){try{return await se.access(t),"skipped"}catch{}return await se.mkdir(qt(t),{recursive:!0}),await se.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await se.chmod(t,n),"wrote"}async function kb(t,e){if(xb(t)!==".gitignore")return Er(t,e.content,e.executable,e.mode);let r=await se.readFile(t,"utf8").catch(()=>null);if(r===null)return Er(t,e.content,e.executable,e.mode);let n=lp(r);return n===null?"skipped":(await se.writeFile(t,n,"utf8"),"merged")}function jd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Ci(t){process.exit(t)}function oA(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 sA(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 iA(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 Tb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Bd({includeInternal:t=!0}={}){let e=new ZP;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.31.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${pa()}
3721
+ `),e.hook("preAction",(d,m)=>{_p(e.opts(),m.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let m=tt(d.baseUrl);d.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3722
+ ${Tn} auth login --base-url ${m} --token tb_pat_\u2026`),_m(d.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await rA(m,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=>km({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 m=d??await QP("Pick the active instance:"),w=await No(m);if(!w){let x=await It();v(`no stored sign-in for ${tt(m)}.`+(x.length?` Stored: ${x.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${tt(m)} --token tb_pat_\u2026\`.`)}b(`active instance \u2192 ${w.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let x=await It();for(let _ of x)await Qi(_.baseUrl);b(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let m=await Qi(d.baseUrl);m||v(d.baseUrl?`no stored sign-in for ${tt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await pt();b(`signed out of ${m}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:m,token:w}=await V(d.baseUrl),x;try{x=await pr({baseUrl:m,token:w,recordsOnly:d.recordsOnly})}catch(g){let T=g instanceof Error?g.message:String(g);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(T)){L("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{x=await pr({baseUrl:m,token:w,recordsOnly:!0})}catch(E){v(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else v(`types generation failed: ${T}`)}let _=oe(process.cwd(),d.out);await se.writeFile(_,x,"utf8"),b(`wrote ${_} (${x.split(`
3723
+ `).length} lines).`)}),Tp(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:m,token:w}=await V(d.baseUrl),x=new URLSearchParams;d.records&&x.set("records",d.records),d.query&&x.set("query",d.query);let _=x.toString(),g=await fetch(`${m}/v1/catalog/grounding${_?`?${_}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});g.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let E=((await g.json()).markdown??"").trim(),A=oe(process.cwd(),d.out),I=d.records?` records=${d.records}`:"",N=`<!-- GENERATED by \`turbobase project grounding\` against ${m}${I} \u2014 do not edit; re-run to refresh. -->
3724
+
3725
+ `;await se.writeFile(A,N+(E?`${E}
3713
3726
  `:`(no grounding available yet)
3714
- `),"utf8"),y(`wrote ${A}${E?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),o.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 (${$r.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=>xp(d)),o.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=>Rp(d)),o.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Tp(d,h)),o.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Ep(d,h)),o.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=>Pp(d)),o.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Ap(d,h)),o.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Ip(d,h)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>(d.publish&&!d.from&&v("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),d.from?jp({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):Cp(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=>Xp(d)),i.command("publish").argument("<slug...>","Skill slugs to approve (see `turbobase skills list`).").description("Publish skills \u2014 live by the time this returns. Sets visibility and cuts a release scoped to these skills.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Zp(d,h)),i.command("unpublish").argument("<slug...>","Skill slugs to move back to draft.").description("Move skills back to draft. Retracts them from every prompt immediately \u2014 no release needed \u2014 and keeps the text.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>Qp(d,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>th(d)),i.command("rollback").argument("<version>","Release number to restore (see `turbobase skills releases`).").description("Re-point the current skill release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>eh(d,h)),i.command("delete").argument("<slug...>","Skill slugs to delete (see `turbobase skills list`).").description("Delete skills. Permanent; prior releases keep their own copy of the text. Takes several slugs so cleaning up a bad push is one command.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>nh(d,h));let a=s.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async d=>{let h;try{h=$t("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 w=se(process.cwd(),h.relativePath);await Pn(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let h;try{h=$t("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 w=se(process.cwd(),h.relativePath);await Pn(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let h;try{h=$t("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(k){v(k instanceof Error?k.message:String(k))}let w=se(process.cwd(),h.relativePath);await Pn(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),s.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(d,h)=>{let w=jd(h.reporter),$=await vr(se(process.cwd(),d)),k=se(process.cwd(),h.samples),g=await wr(k);g.length===0&&!w&&y(`no samples found under ${k} \u2014 add JSON fixtures to dry-run against.`);let x;try{x=await zs($,g.map(C=>C.fixture),{resolveDir:qt(se(process.cwd(),d))})}catch(C){v(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(w){let C=HP(x);y(Fs(C,w)),Ii(C.cases.some(O=>O.status==="failed")?1:0)}let E=0;for(let C of x){let O=C.pass?f.green("PASS"):f.red("FAIL");C.pass||(E+=1);let U=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";y(` ${O} ${C.name}${U}`)}let A=`${x.length-E}/${x.length} sample(s) passed.`;y(`
3715
- ${E===0?f.green(A):f.yellow(A)}`),Ii(E>0?1:0)}),s.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,h)=>{if(h.to){let x=await Dd(),{baseUrl:E,token:A}=await V(h.baseUrl),C=new z({baseUrl:E,token:A});try{let O=await J(`applying bundle to ${h.to}`,()=>C.configApply(x,{prune:h.prune}));y(`applied bundle to ${h.to}: +${O.applied.add} ~${O.applied.change} -${O.applied.destroy}`+(O.backfillsQueued.length?` (${O.backfillsQueued.length} backfill(s) queued)`:""));let U=O.skippedDestroys??[];if(U.length>0){L(`${U.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let I of U)L(` ${I.kind} ${I.id}`);L("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(O){O instanceof Z&&O.status===403&&v("apply forbidden (403) \u2014 the stored PAT is not for an admin."),v(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}d||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:$}=await V(h.baseUrl),k=await FP(se(process.cwd(),d)),g=new z({baseUrl:w,token:$});try{let x=await J(`deploying ${ky(d)}`,()=>g.deploy(k));Pe()?y(Vt("Deployed",[`${f.bold(x.id)} ${Ln(x.status)} ${f.dim(x.outcome)}`])):y(`deployed ${x.id} \u2192 status=${x.status} (${x.outcome}).`)}catch(x){x instanceof Z&&x.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),v(`deploy failed: ${x instanceof Error?x.message:String(x)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.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,h,w)=>{let $=!!(w.preview||w.replace||w.replaceLabel);w.replace&&w.replaceLabel&&v("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let k=se(process.cwd(),h??".");await oe.mkdir(k,{recursive:!0});let g=w.proposal??await T(k),{baseUrl:x,token:E}=await V(w.baseUrl),A=new z({baseUrl:x,token:E}),C=!1;try{C=(await A.appsList()).some(de=>de.slug===d||de.id===d)}catch(de){G(de,"extensions:deploy","deploy"),v(`could not reach ${x}: ${de instanceof Error?de.message:String(de)}`)}if(!C){w.create||v(`no app "${d}" on ${x} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let de=await J(`creating app ${d}`,()=>m(x,E,{slug:d},{tolerateExisting:!0}));de.existed||y(`created ${de.slug??d}.`)}let O;if(w.replace)if(typeof w.replace=="string")O=w.replace;else{let{previews:de}=await K(x,E,d);if(de.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\`.`),de.length>1){for(let Ee of de)y(` ${Ee.previewId} v${Ee.version}${Ee.label?` ${Ee.label}`:""} ${Ee.url}`);v(`${d} has ${de.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${de[0].previewId}\`.`)}O=de[0].previewId}let U;if(w.replaceLabel){let de=w.replaceLabel,{previews:Ee}=await K(x,E,d),xt=Ee.filter(Li=>Li.label===de);xt.length>0?(O=xt[0].previewId,xt.length>1&&L(`${xt.length} open previews carry the label "${de}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):y(`no open preview labelled "${de}" \u2014 opening one.`),U=de}let I=de=>oe.stat(Qe(k,de)).then(()=>!0).catch(()=>!1),H=d,ae=k,me=w.build!==!1;if(me&&!await I("package.json"))if(await I("index.html"))y("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),me=!1;else if(w.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 de=await J(`pulling ${d}`,()=>S(x,E,d));H=de.slug??d,await b(k,de.files,!0),y(`pulled generated source (rev ${de.rev}).`)}let In;if(me){let de=oh();if(In={buildId:de,assetBase:ih(de)},w.install!==!1&&!await I("node_modules")){y("installing dependencies\u2026");try{await N(["install"],k)}catch(Ee){v(`npm install failed: ${Ee instanceof Error?Ee.message:String(Ee)}`)}}y("building\u2026");try{await N(["run","build"],k,{TURBOBASE_ASSET_BASE:In.assetBase})}catch(Ee){v(`build failed: ${Ee instanceof Error?Ee.message:String(Ee)}`)}await I("dist")||v(`no dist/ after build in ${k} \u2014 check the app's build script.`),ae=Qe(k,"dist")}$&&!In&&v(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${H}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let Ue=await Ae(x,E,H,ae,w.entry,g,In,$?{label:w.label??U,replacePreviewId:O}:void 0);if($){let de=Ue.previewUrl??"(no url returned)",Ee=Ue.expiresAt?new Date(Ue.expiresAt).toLocaleDateString():`${ah} days`,xt=Ue.replacedVersion==null?null:`replaced v${Ue.replacedVersion} \u2014 same URL`;if(Pe())y(Vt(xt?"Preview replaced":"Preview deployed",[`${f.bold(H)} ${f.green(`v${Ue.version??"?"}`)} ${f.dim("not live")}`,`${f.bold(de)}`,...xt?[f.dim(xt)]:[],f.dim(`expires ${Ee}`)]));else{let Li=xt?`; ${xt}`:"";y(`preview ${H} v${Ue.version??"?"} \u2192 ${de} (expires ${Ee}; /a/${H} unchanged${Li}).`)}y(`next: turbobase apps promote ${H} ${Ue.previewId??"<preview-id>"} # make it live`),y(` turbobase apps preview discard ${Ue.previewId??"<preview-id>"}`);return}Pe()?y(Vt("Deployed",[`${f.bold(H)} ${f.green(`v${Ue.version??"?"}`)} ${f.dim(Ue.url??`/a/${H}`)}`])):y(`deployed ${H} \u2192 v${Ue.version??"?"} (${Ue.url??`/a/${H}`}).`),De(Ue),zt(Ue),await Bt(Ue,k)}),l.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,h)=>{let w=await GP(d??".");w||v(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`);let $=Array.isArray(w.manifest.tables)?w.manifest.tables:[],k=Array.isArray(w.manifest.writes)?w.manifest.writes:[],g=Array.isArray(w.manifest.roles)?w.manifest.roles:[],x=Array.isArray(w.manifest.labels)?w.manifest.labels:[];if($.length===0&&k.length===0&&g.length===0&&x.length===0)return y(`${w.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);let{baseUrl:E,token:A}=await V(h.baseUrl),C=new z({baseUrl:E,token:A});if($.length>0){let O;try{O=await J("planning tables",()=>C.tablesPlan({claimedBy:h.as,tables:$}))}catch(U){G(U,"extensions:deploy","plan tables"),_s(U)}y(`claiming as ${f.bold(O.claimedBy)}`);for(let U of O.tables)Ss(U,{showClaimants:!0})}if(k.length>0||g.length>0||x.length>0){let O;try{O=await J("checking declared writes, roles and labels",()=>C.appsPlan({writes:k,roles:g,labels:x}))}catch(U){G(U,"extensions:deploy","plan writes"),v(`plan writes failed: ${U instanceof Error?U.message:String(U)}`)}if(O.roles&&O.roles.verdicts.length>0){y(""),y(f.bold("roles"));let U=Math.max(...O.roles.verdicts.map(I=>I.name.length));for(let I of O.roles.verdicts){let H=I.name.padEnd(U);if(I.action==="error")L(` ${f.bold("ERROR")} ${H} \u2014 ${I.message??"cannot be created"}`);else if(I.action==="create"){let ae=I.addCapabilities?.length??0;y(` create ${H} ${f.dim(`${ae} capabilit${ae===1?"y":"ies"}`)}`)}else if(I.action==="add_capabilities"){let ae=(I.addCapabilities??[]).map(me=>`+${me}`).join(", ");y(` add ${H} ${f.dim(ae)}`)}else y(` ${f.dim("ok")} ${H} ${f.dim("already up to date")}`)}O.roles.verdicts.some(I=>I.action!=="error")&&y(f.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}if(O.labels&&O.labels.verdicts.length>0){y(""),y(f.bold("labels"));let U=Math.max(...O.labels.verdicts.map(I=>I.name.length));for(let I of O.labels.verdicts){let H=I.name.padEnd(U);if(I.action==="create")y(` create ${H} ${f.dim(I.color)}`);else{let ae=I.declaredColor?`${I.color} \u2014 declared ${I.declaredColor}, the instance's colour is kept`:I.color;y(` ${f.dim("ok")} ${H} ${f.dim(ae)}`)}}y(f.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}k.length>0&&y("");for(let U of O.verdicts){let I=`${U.source} ${U.recordType}.${U.op}`;U.allowed?U.heldForApproval?y(`${f.dim("HELD")} ${I} \u2014 allowed, but each write waits for operator approval.`):y(`${f.dim("ok")} ${I}`):L(`${f.bold("DENIED")} ${I}${U.rule?` \u2014 guardrail "${U.rule}"`:""} (${U.reason})`)}O.ok||(y(""),v(O.message??(O.roles&&!O.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.")))}y(""),y(f.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,w)=>{let{baseUrl:$,token:k}=await V(w.baseUrl),g=await J(`promoting ${h}`,()=>Y($,k,d,"promote",{previewId:h}));Pe()?y(Vt("Promoted",[`${f.bold(d)} ${f.green(`v${g.version??"?"}`)} ${f.dim(g.url??`/a/${d}`)}`])):y(`promoted ${d} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${d}`}.`),zt({labels:g.labels?{applied:!0,verdicts:g.labels}:null}),await Bt(g)});let u=l.command("preview").description("Inspect and manage an app's open previews.");u.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=await K(w,$,d);if(h.json)return y(JSON.stringify(k.previews,null,2));if(k.previews.length===0){y(`no open previews for ${d}.`);return}for(let g of k.previews){let x=g.label?` ${g.label}`:"",E=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";y(`v${g.version} ${g.previewId}${x} ${g.url} (expires ${E})`)}}),u.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,w)=>{let{baseUrl:$,token:k}=await V(w.baseUrl);await J(`discarding ${h}`,()=>Y($,k,d,"discard",{previewId:h})),y(`discarded ${h}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=await J(`creating ${d}`,()=>m(w,$,{slug:d,name:h.name,description:h.description})),g=k.slug??d;Pe()?y(Vt("Created",[`${f.bold(g)} ${f.dim(k.url??`/a/${g}`)}`])):y(`created ${g} (${k.url??`/a/${g}`}).`),y(`next: turbobase apps push ${g} . # store the source`),y(` turbobase apps deploy ${g} # build + go live`)});let p=Ns(fetch);async function m(d,h,w,$={}){let k=`${d.replace(/\/+$/,"")}/v1/apps`,g;try{g=await p(k,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:w.slug,name:w.name??w.slug,description:w.description})})}catch(x){v(`create request failed: ${x instanceof Error?x.message:String(x)}`)}if(g.status===401&&v("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&v("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if($.tolerateExisting)return{slug:w.slug,existed:!0};v(`an app with slug "${w.slug}" already exists.`)}return g.ok||v(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function S(d,h,w){let $=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,k;try{k=await p($,{headers:{Authorization:`Bearer ${h}`}})}catch(g){v(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}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 "${w}" \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 b(d,h,w){let $=se(d),k=0;for(let[g,x]of Object.entries(h)){let E=se($,g);E!==$&&!E.startsWith($+qd)&&v(`refusing to write outside ${$}: ${g}`),w||await oe.stat(E).then(()=>!0).catch(()=>!1)&&v(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await oe.mkdir(qt(E),{recursive:!0}),await oe.writeFile(E,x,"utf8"),k+=1}return k}function _(d){let h=d.indexOf(","),w=d.startsWith("data:")?h>=0?d.slice(h+1):"":d;if(!w)return null;try{let $=Buffer.from(w,"base64");return $.length>0?new Uint8Array($):null}catch{return null}}async function R(d,h,w){let $=se(d),k=async(x,E)=>{let A=se($,x);A!==$&&!A.startsWith($+qd)&&v(`refusing to write outside ${$}: ${x}`),w||await oe.stat(A).then(()=>!0).catch(()=>!1)&&v(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await oe.mkdir(qt(A),{recursive:!0}),await oe.writeFile(A,E)},g=`# ${h.title||"App change request"}
3727
+ `),"utf8"),b(`wrote ${A}${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 (${xn.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=>Ep(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=>Ap(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,m)=>Cp(d,m)),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,m)=>Ip(d,m)),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=>Op(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,m)=>Np(d,m)),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,m)=>Lp(d,m)),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?qp({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):jp(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=>tm(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,m)=>rm(d,m)),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,m)=>nm(d,m)),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=>sm(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,m)=>om(d,m)),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,m)=>im(d,m));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 m;try{m=xt("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),m.relativePath);await Er(w,m.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`wrote ${w}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let m;try{m=xt("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),m.relativePath);await Er(w,m.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`wrote ${w}`)}),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 m;try{m=xt("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),m.relativePath);await Er(w,m.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`wrote ${w}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(d,m)=>{let w=jd(m.reporter),x=await vn(oe(process.cwd(),d)),_=oe(process.cwd(),m.samples),g=await wn(_);g.length===0&&!w&&b(`no samples found under ${_} \u2014 add JSON fixtures to dry-run against.`);let T;try{T=await Bo(x,g.map(I=>I.fixture),{resolveDir:qt(oe(process.cwd(),d))})}catch(I){v(`bundle failed: ${I instanceof Error?I.message:String(I)}`)}if(w){let I=oA(T);b(Ho(I,w)),Ci(I.cases.some(N=>N.status==="failed")?1:0)}let E=0;for(let I of T){let N=I.pass?h.green("PASS"):h.red("FAIL");I.pass||(E+=1);let U=I.error?` (error: ${I.error})`:I.observed!==I.expected?` (expected ${I.expected}, observed ${I.observed})`:I.rejection?` (rejected: ${I.rejection.code??"rejected"})`:"";b(` ${N} ${I.name}${U}`)}let A=`${T.length-E}/${T.length} sample(s) passed.`;b(`
3728
+ ${E===0?h.green(A):h.yellow(A)}`),Ci(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,m)=>{if(m.to){let T=await Dd(),{baseUrl:E,token:A}=await V(m.baseUrl),I=new z({baseUrl:E,token:A});try{let N=await J(`applying bundle to ${m.to}`,()=>I.configApply(T,{prune:m.prune}));b(`applied bundle to ${m.to}: +${N.applied.add} ~${N.applied.change} -${N.applied.destroy}`+(N.backfillsQueued.length?` (${N.backfillsQueued.length} backfill(s) queued)`:""));let U=N.skippedDestroys??[];if(U.length>0){L(`${U.length} resource(s) exist on ${m.to} but are not declared by this project \u2014 NOT removed:`);for(let C of U)L(` ${C.kind} ${C.id}`);L("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(N){N instanceof Z&&N.status===403&&v("apply forbidden (403) \u2014 the stored PAT is not for an admin."),v(`bundle apply failed: ${N instanceof Error?N.message:String(N)}`)}return}d||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:x}=await V(m.baseUrl),_=await nA(oe(process.cwd(),d)),g=new z({baseUrl:w,token:x});try{let T=await J(`deploying ${xb(d)}`,()=>g.deploy(_));Pe()?b(Vt("Deployed",[`${h.bold(T.id)} ${Nr(T.status)} ${h.dim(T.outcome)}`])):b(`deployed ${T.id} \u2192 status=${T.status} (${T.outcome}).`)}catch(T){T instanceof Z&&T.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),v(`deploy failed: ${T instanceof Error?T.message:String(T)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.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,m,w)=>{let x=!!(w.preview||w.replace||w.replaceLabel);w.replace&&w.replaceLabel&&v("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let _=oe(process.cwd(),m??".");await se.mkdir(_,{recursive:!0});let g=w.proposal??await R(_),{baseUrl:T,token:E}=await V(w.baseUrl),A=new z({baseUrl:T,token:E}),I=!1;try{I=(await A.appsList()).some(de=>de.slug===d||de.id===d)}catch(de){G(de,"extensions:deploy","deploy"),v(`could not reach ${T}: ${de instanceof Error?de.message:String(de)}`)}if(!I){w.create||v(`no app "${d}" on ${T} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let de=await J(`creating app ${d}`,()=>f(T,E,{slug:d},{tolerateExisting:!0}));de.existed||b(`created ${de.slug??d}.`)}let N;if(w.replace)if(typeof w.replace=="string")N=w.replace;else{let{previews:de}=await K(T,E,d);if(de.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\`.`),de.length>1){for(let Ee of de)b(` ${Ee.previewId} v${Ee.version}${Ee.label?` ${Ee.label}`:""} ${Ee.url}`);v(`${d} has ${de.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${de[0].previewId}\`.`)}N=de[0].previewId}let U;if(w.replaceLabel){let de=w.replaceLabel,{previews:Ee}=await K(T,E,d),Tt=Ee.filter(Li=>Li.label===de);Tt.length>0?(N=Tt[0].previewId,Tt.length>1&&L(`${Tt.length} open previews carry the label "${de}"; replacing the newest (${N}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${de}" \u2014 opening one.`),U=de}let C=de=>se.stat(Qe(_,de)).then(()=>!0).catch(()=>!1),H=d,ae=_,fe=w.build!==!1;if(fe&&!await C("package.json"))if(await C("index.html"))b("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),fe=!1;else if(w.pull===!1)v(`${_} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let de=await J(`pulling ${d}`,()=>S(T,E,d));H=de.slug??d,await y(_,de.files,!0),b(`pulled generated source (rev ${de.rev}).`)}let Ar;if(fe){let de=cm();if(Ar={buildId:de,assetBase:dm(de)},w.install!==!1&&!await C("node_modules")){b("installing dependencies\u2026");try{await O(["install"],_)}catch(Ee){v(`npm install failed: ${Ee instanceof Error?Ee.message:String(Ee)}`)}}b("building\u2026");try{await O(["run","build"],_,{TURBOBASE_ASSET_BASE:Ar.assetBase})}catch(Ee){v(`build failed: ${Ee instanceof Error?Ee.message:String(Ee)}`)}await C("dist")||v(`no dist/ after build in ${_} \u2014 check the app's build script.`),ae=Qe(_,"dist")}x&&!Ar&&v(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${H}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let Ue=await Ae(T,E,H,ae,w.entry,g,Ar,x?{label:w.label??U,replacePreviewId:N}:void 0);if(x){let de=Ue.previewUrl??"(no url returned)",Ee=Ue.expiresAt?new Date(Ue.expiresAt).toLocaleDateString():`${um} days`,Tt=Ue.replacedVersion==null?null:`replaced v${Ue.replacedVersion} \u2014 same URL`;if(Pe())b(Vt(Tt?"Preview replaced":"Preview deployed",[`${h.bold(H)} ${h.green(`v${Ue.version??"?"}`)} ${h.dim("not live")}`,`${h.bold(de)}`,...Tt?[h.dim(Tt)]:[],h.dim(`expires ${Ee}`)]));else{let Li=Tt?`; ${Tt}`:"";b(`preview ${H} v${Ue.version??"?"} \u2192 ${de} (expires ${Ee}; /a/${H} unchanged${Li}).`)}b(`next: turbobase apps promote ${H} ${Ue.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${Ue.previewId??"<preview-id>"}`);return}Pe()?b(Vt("Deployed",[`${h.bold(H)} ${h.green(`v${Ue.version??"?"}`)} ${h.dim(Ue.url??`/a/${H}`)}`])):b(`deployed ${H} \u2192 v${Ue.version??"?"} (${Ue.url??`/a/${H}`}).`),De(Ue),zt(Ue),await Bt(Ue,_)}),l.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,m)=>{let w=await lA(d??".");w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`);let x=Array.isArray(w.manifest.tables)?w.manifest.tables:[],_=Array.isArray(w.manifest.writes)?w.manifest.writes:[],g=Array.isArray(w.manifest.roles)?w.manifest.roles:[],T=Array.isArray(w.manifest.labels)?w.manifest.labels:[];if(x.length===0&&_.length===0&&g.length===0&&T.length===0)return b(`${w.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);let{baseUrl:E,token:A}=await V(m.baseUrl),I=new z({baseUrl:E,token:A});if(x.length>0){let N;try{N=await J("planning tables",()=>I.tablesPlan({claimedBy:m.as,tables:x}))}catch(U){G(U,"extensions:deploy","plan tables"),To(U)}b(`claiming as ${h.bold(N.claimedBy)}`);for(let U of N.tables)ko(U,{showClaimants:!0})}if(_.length>0||g.length>0||T.length>0){let N;try{N=await J("checking declared writes, roles and labels",()=>I.appsPlan({writes:_,roles:g,labels:T}))}catch(U){G(U,"extensions:deploy","plan writes"),v(`plan writes failed: ${U instanceof Error?U.message:String(U)}`)}if(N.roles&&N.roles.verdicts.length>0){b(""),b(h.bold("roles"));let U=Math.max(...N.roles.verdicts.map(C=>C.name.length));for(let C of N.roles.verdicts){let H=C.name.padEnd(U);if(C.action==="error")L(` ${h.bold("ERROR")} ${H} \u2014 ${C.message??"cannot be created"}`);else if(C.action==="create"){let ae=C.addCapabilities?.length??0;b(` create ${H} ${h.dim(`${ae} capabilit${ae===1?"y":"ies"}`)}`)}else if(C.action==="add_capabilities"){let ae=(C.addCapabilities??[]).map(fe=>`+${fe}`).join(", ");b(` add ${H} ${h.dim(ae)}`)}else b(` ${h.dim("ok")} ${H} ${h.dim("already up to date")}`)}N.roles.verdicts.some(C=>C.action!=="error")&&b(h.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}if(N.labels&&N.labels.verdicts.length>0){b(""),b(h.bold("labels"));let U=Math.max(...N.labels.verdicts.map(C=>C.name.length));for(let C of N.labels.verdicts){let H=C.name.padEnd(U);if(C.action==="create")b(` create ${H} ${h.dim(C.color)}`);else{let ae=C.declaredColor?`${C.color} \u2014 declared ${C.declaredColor}, the instance's colour is kept`:C.color;b(` ${h.dim("ok")} ${H} ${h.dim(ae)}`)}}b(h.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}_.length>0&&b("");for(let U of N.verdicts){let C=`${U.source} ${U.recordType}.${U.op}`;U.allowed?U.heldForApproval?b(`${h.dim("HELD")} ${C} \u2014 allowed, but each write waits for operator approval.`):b(`${h.dim("ok")} ${C}`):L(`${h.bold("DENIED")} ${C}${U.rule?` \u2014 guardrail "${U.rule}"`:""} (${U.reason})`)}N.ok||(b(""),v(N.message??(N.roles&&!N.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}b(""),b(h.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),l.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,m,w)=>{let{baseUrl:x,token:_}=await V(w.baseUrl),g=await J(`promoting ${m}`,()=>Y(x,_,d,"promote",{previewId:m}));Pe()?b(Vt("Promoted",[`${h.bold(d)} ${h.green(`v${g.version??"?"}`)} ${h.dim(g.url??`/a/${d}`)}`])):b(`promoted ${d} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${d}`}.`),zt({labels:g.labels?{applied:!0,verdicts:g.labels}:null}),await Bt(g)});let u=l.command("preview").description("Inspect and manage an app's open previews.");u.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=await K(w,x,d);if(m.json)return b(JSON.stringify(_.previews,null,2));if(_.previews.length===0){b(`no open previews for ${d}.`);return}for(let g of _.previews){let T=g.label?` ${g.label}`:"",E=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";b(`v${g.version} ${g.previewId}${T} ${g.url} (expires ${E})`)}}),u.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,m,w)=>{let{baseUrl:x,token:_}=await V(w.baseUrl);await J(`discarding ${m}`,()=>Y(x,_,d,"discard",{previewId:m})),b(`discarded ${m}.`)}),l.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=await J(`creating ${d}`,()=>f(w,x,{slug:d,name:m.name,description:m.description})),g=_.slug??d;Pe()?b(Vt("Created",[`${h.bold(g)} ${h.dim(_.url??`/a/${g}`)}`])):b(`created ${g} (${_.url??`/a/${g}`}).`),b(`next: turbobase apps push ${g} . # store the source`),b(` turbobase apps deploy ${g} # build + go live`)});let p=Lo(fetch);async function f(d,m,w,x={}){let _=`${d.replace(/\/+$/,"")}/v1/apps`,g;try{g=await p(_,{method:"POST",headers:{Authorization:`Bearer ${m}`,"content-type":"application/json"},body:JSON.stringify({slug:w.slug,name:w.name??w.slug,description:w.description})})}catch(T){v(`create request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&v("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&v("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(x.tolerateExisting)return{slug:w.slug,existed:!0};v(`an app with slug "${w.slug}" already exists.`)}return g.ok||v(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function S(d,m,w){let x=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,_;try{_=await p(x,{headers:{Authorization:`Bearer ${m}`}})}catch(g){v(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return _.status===401&&v("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),_.status===403&&v("pull forbidden (403) \u2014 the PAT is not for an admin."),_.status===404&&v(`no generated source for "${w}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),_.ok||v(`pull failed: HTTP ${_.status} ${(await _.text().catch(()=>"")).slice(0,200)}`),await _.json()}async function y(d,m,w){let x=oe(d),_=0;for(let[g,T]of Object.entries(m)){let E=oe(x,g);E!==x&&!E.startsWith(x+qd)&&v(`refusing to write outside ${x}: ${g}`),w||await se.stat(E).then(()=>!0).catch(()=>!1)&&v(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await se.mkdir(qt(E),{recursive:!0}),await se.writeFile(E,T,"utf8"),_+=1}return _}function k(d){let m=d.indexOf(","),w=d.startsWith("data:")?m>=0?d.slice(m+1):"":d;if(!w)return null;try{let x=Buffer.from(w,"base64");return x.length>0?new Uint8Array(x):null}catch{return null}}async function $(d,m,w){let x=oe(d),_=async(T,E)=>{let A=oe(x,T);A!==x&&!A.startsWith(x+qd)&&v(`refusing to write outside ${x}: ${T}`),w||await se.stat(A).then(()=>!0).catch(()=>!1)&&v(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await se.mkdir(qt(A),{recursive:!0}),await se.writeFile(A,E)},g=`# ${m.title||"App change request"}
3716
3729
 
3717
- > Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
3718
- > \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
3730
+ > Widget proposal \`${m.proposalId}\` \u2014 build this change, then ship it with
3731
+ > \`turbobase apps deploy ${m.appSlug}\`. The deploy stamps this proposal complete.
3719
3732
 
3720
- ${h.bodyMarkdown||"_No description provided._"}
3733
+ ${m.bodyMarkdown||"_No description provided._"}
3721
3734
 
3722
3735
  ## Screen context
3723
3736
 
3724
- `+(h.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
3725
- `);if(await k("PROPOSAL.md",g),h.screenshot){let x=_(h.screenshot);x&&await k("proposal-screenshot.png",x)}await k(Qe(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
3726
- `)}async function T(d){try{let h=await oe.readFile(Qe(d,".turbobase","proposal.json"),"utf8"),w=JSON.parse(h);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function P(d,h,w,$,k,g){let x=new z({baseUrl:d,token:h});try{return await x.appsPush(w,$,{note:k,proposalId:g})}catch(E){if(E instanceof Z){let A=E.body;if(E.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&G(E,"extensions:deploy","push app source"),E.status===404&&v(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";v(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}v(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function N(d,h,w){return new Promise(($,k)=>{let g=zd("npm",d,{cwd:h,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});g.on("error",k),g.on("exit",x=>x===0?$():k(new Error(`npm ${d.join(" ")} exited ${x??"?"}`)))})}async function D(d,h,w,$){let k=`${d.replace(/\/+$/,"")}${w}`,g;try{g=await p(k,{method:$.method,headers:{Authorization:`Bearer ${h}`,...$.body?{"content-type":"application/json"}:{}},...$.body?{body:JSON.stringify($.body)}:{}})}catch(x){v(`request failed: ${x instanceof Error?x.message:String(x)}`)}if(g.status===401&&v("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&v("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let x=await g.text().catch(()=>""),E=x.slice(0,300);try{let A=JSON.parse(x);E=A.message??A.error??E}catch{}v(`failed: HTTP ${g.status} ${E}`)}return await g.json().catch(()=>({}))}async function Y(d,h,w,$,k){return await D(d,h,`/v1/apps/${encodeURIComponent(w)}/preview/${$}`,{method:"POST",body:k})}async function K(d,h,w){return{previews:(await D(d,h,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function Ae(d,h,w,$,k,g,x,E){let A;try{A=await J(`zipping ${$}`,()=>qu($))}catch(I){v(`could not zip ${$}: ${I instanceof Error?I.message:String(I)}`)}A.fileCount===0&&v(`${$} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>Pa&&v(`${$} zips to ${vy(A.buffer.byteLength)} \u2014 over the ${vy(Pa)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let C={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};k&&(C["x-app-entry"]=k),g&&(C["x-proposal-id"]=g),x&&(C["x-app-build-id"]=x.buildId,C["x-app-asset-base"]=x.assetBase),E&&(C["x-app-channel"]="preview",E.label&&(C["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(C["x-app-preview-replace"]=E.replacePreviewId));let O=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,U;try{U=await J(`deploying ${w} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(I){v(`deploy request failed: ${I instanceof Error?I.message:String(I)}`)}if(U.status===401&&v("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),U.status===403&&v("deploy forbidden (403) \u2014 the PAT is not for an admin."),U.status===404){let I=await U.text().catch(()=>""),H={};try{H=JSON.parse(I)}catch{}H.error==="no_preview"&&v(`${H.message??`no open preview to replace on ${w}`} \u2014 list them with \`turbobase apps preview list ${w}\`.`),v(`no app "${w}" on ${d} \u2014 create it with \`turbobase apps create ${w}\`.`)}if(!U.ok){let I=await U.text().catch(()=>""),H=I.slice(0,300);try{let ae=JSON.parse(I);H=ae.message??ae.error??H}catch{}v(`deploy failed: HTTP ${U.status} ${H}`)}return await U.json().catch(()=>({}))}function De(d){let h=d.roles;if(!h||h.verdicts.length===0)return;let w=h.verdicts.filter(k=>k.action!=="noop");if(w.length===0)return;y(""),y(f.bold(h.applied?"roles":"roles (preview \u2014 not applied)"));let $=Math.max(...w.map(k=>k.name.length));for(let k of w){let g=k.name.padEnd($);if(k.action==="create"){let x=k.addCapabilities?.length??0;y(` created ${g} ${f.dim(`${x} capabilit${x===1?"y":"ies"}`)}`)}else if(k.action==="add_capabilities"){let x=(k.addCapabilities??[]).map(A=>`+${A}`).join(", "),E=k.holdersRestamped?f.dim(` (${k.holdersRestamped} holder${k.holdersRestamped===1?"":"s"} re-stamped)`):"";y(` updated ${g} ${f.dim(x)}${E}`)}}y(f.dim(h.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 zt(d){let h=d.labels;if(!h||h.verdicts.length===0)return;let w=h.verdicts.filter(k=>k.action!=="noop");if(w.length===0)return;y(""),y(f.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let $=Math.max(...w.map(k=>k.name.length));for(let k of w){let g=k.name.padEnd($);if(k.action==="detach")y(` removed ${g} ${f.dim("no longer declared in the manifest")}`);else if(k.action==="create")y(` created ${g} ${f.dim(k.color)}`);else{let x=k.declaredColor?`${k.color} \u2014 declared ${k.declaredColor}, the instance's colour is kept`:k.color;y(` added ${g} ${f.dim(x)}`)}}y(f.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Bt(d,h){let w=Qu(d,{localDocsModifiedAt:await dn(h)});w&&y(w.level==="warn"?f.yellow(w.message):f.dim(w.message))}async function dn(d){if(!d)return null;let h=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let $=await oe.stat(Qe(d,w));(h===null||$.mtimeMs>h)&&(h=$.mtimeMs)}catch{}return h===null?null:new Date(h)}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(d,h,w)=>{let{baseUrl:$,token:k}=await V(w.baseUrl);if(w.proposal){let A=new z({baseUrl:$,token:k}),C;try{C=await J(`fetching proposal ${w.proposal}`,()=>A.appPullContext(w.proposal))}catch(ae){G(ae,"extensions:deploy","pull proposal"),ae instanceof Z&&ae.status===404&&v(`no widget proposal "${w.proposal}" on ${$}.`),v(`could not fetch proposal ${w.proposal}: ${ae instanceof Error?ae.message:String(ae)}`)}let O=await J(`pulling ${C.appSlug}`,()=>S($,k,C.appSlug)),U=h??d,I=se(process.cwd(),U??C.appSlug);await oe.mkdir(I,{recursive:!0});let H=await b(I,O.files,!!w.force);await R(I,C,!!w.force),y(`pulled ${H} file${H===1?"":"s"} \u2192 ${I} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),y(`next: cd ${Ci(process.cwd(),I)||"."} && turbobase apps deploy ${C.appSlug}`);return}d||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await J(`pulling ${d}`,()=>S($,k,d)),x=se(process.cwd(),h??g.slug??d);await oe.mkdir(x,{recursive:!0});let E=await b(x,g.files,!!w.force);y(`pulled ${E} file${E===1?"":"s"} \u2192 ${x} (rev ${g.rev}).`),y(`next: cd ${Ci(process.cwd(),x)||"."} && turbobase apps deploy ${g.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(d,h,w)=>{let $=se(process.cwd(),h??d),k=await pt(w.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:x}=await Promise.resolve().then(()=>(qh(),Mh)),E=w.title??d,A=g({slug:d,title:E,appTsx:x(E),instanceOrigin:k?.baseUrl});await oe.mkdir($,{recursive:!0});let C=await b($,A,!!w.force);if(y(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${$}`),w.claude!==!1){let U=ma({baseUrl:k?.baseUrl,token:k?.token,appSlug:d}),I=0;for(let H of U){let ae=await wy(Qe($,H.path),H);(ae==="wrote"||ae==="merged")&&(I+=1)}y(`wired Claude Code: ${I} file${I===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),k||L("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 O=Ci(process.cwd(),$)||".";y(`next: cd ${O} && npm install && npm run dev`),y(` turbobase apps create ${d}`),y(` turbobase apps push ${d} .`),y(` turbobase apps deploy ${d} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$=new z({baseUrl:h,token:w}),k;try{k=await $.appsList()}catch(g){G(g,"extensions:deploy","list apps"),v(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");y(ft(k.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(d,h,w)=>{let $=se(process.cwd(),h??".");await oe.stat($).then(me=>me.isDirectory()).catch(()=>!1)||v(`${$} is not a directory.`);let{baseUrl:g,token:x}=await V(w.baseUrl),E=w.proposal??await T($),{files:A,skipped:C,secrets:O,unstorable:U}=await sh($),I=Object.keys(A).length;if(I===0&&v(`no source files found under ${$} (build output and node_modules are skipped).`),U.length>0){for(let me of U)L(`${me} contains a NUL byte (U+0000), which cannot be stored.`);v(`push aborted: ${U.length} ${U.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let me of C)L(f.dim(`skipped binary file ${me}`));for(let me of O)L(f.dim(`skipped ${me} (holds credentials \u2014 never pushed)`));let H=await J(`pushing ${I} file${I===1?"":"s"}`,()=>P(g,x,d,A,w.note,E));y(`pushed ${H.files} file${H.files===1?"":"s"} \u2192 ${H.slug} rev ${H.rev} (source only, nothing deployed).`);let ae=await Rr(new z({baseUrl:g,token:x}),H.slug);ae&&ae.entriesAdded>0&&y(`${ae.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),y(`next: turbobase apps deploy ${H.slug}`)}),s.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let h=await Dd(),{baseUrl:w,token:$}=await V(d.baseUrl),k=new z({baseUrl:w,token:$}),g;try{g=await J(`planning against ${d.to??w}`,()=>k.configPlan(h))}catch(x){v(`plan failed: ${x instanceof Error?x.message:String(x)}`)}YP(g,d.to??w)}),s.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let h=await Dd(),{baseUrl:w,token:$}=await V(d.baseUrl),k=h.tenant??XP(w),g=cp(d.confirm,k);g.ok||v(`promote refused (fail-closed): ${g.reason}`);let x=new z({baseUrl:w,token:$});try{let E=await J(`promoting ${d.from} \u2192 ${d.to} (${k})`,()=>x.configApply(h,{prune:d.prune}));if(Pe()){let C=[`${f.bold(`${d.from} \u2192 ${d.to}`)} ${f.dim(k??"")}`,`${Kt.add(String(E.applied.add))} ${Kt.change(String(E.applied.change))} ${Kt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&C.push(f.dim(`${E.backfillsQueued.length} backfill(s) queued`)),y(Vt("Promoted",C))}else y(`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 A=E.skippedDestroys??[];if(A.length>0){L(`${A.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let C of A)L(` ${C.kind} ${C.id}`);L("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof Z&&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)}`)}}),s.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,h)=>{let w=jd(h.reporter),$=se(process.cwd(),d),k=await vr($),g=Bu(k);w?y(Fs(KP(d,g),w)):y(Fu(d,g,{warn:f.yellow,ok:f.green,dim:f.dim})),h.ci&&g.warnings.length>0&&process.exit(1)}),s.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(d,h)=>{let w=jd(h.reporter),$=await Nu(se(process.cwd(),d));if(h.against){h.against!=="sandbox"&&v(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Cu(la($))}catch(x){v(x instanceof Error?x.message:String(x))}return}h.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await Ou(se(process.cwd(),h.fixture))}catch(x){v(`could not read fixture ${h.fixture}: ${x instanceof Error?x.message:String(x)}`)}let g=await Iu($,k,h.fixture,{resolveDir:qt(se(process.cwd(),d))});if(w){let x=VP(g);y(Fs(x,w)),Ii(x.cases.some(E=>E.status==="failed")?1:0)}y(Lu(g,!!h.trace)),Ii(g.error?1:0)}),s.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$=new z({baseUrl:h,token:w});try{await Yu($,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:y})}catch(k){k instanceof Z&&k.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof Z&&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 Ft=s.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Ft.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 Fp(d)}),Ft.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,h)=>{await Hp(d??[],h)}),Ft.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{await Kp(d,h)}),Ft.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,h)=>{await Vp(d,h)}),s.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Wp(d,h)}),s.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Gp(d,h)}),s.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Jp(d,h)}),s.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(d,h)=>{let w=d.lastIndexOf("@"),$=w>0?d.slice(0,w):d,k=w>0?d.slice(w+1):void 0,g=ra();g||v(`marketplace not configured \u2014 set ${Cn} and ${Ls}.
3727
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=sa(g.registryUrl);x&&v(x);let{baseUrl:E,token:A}=await V(h.baseUrl),C=new br(g),O;try{O=await J(`fetching ${d}`,()=>C.fetchBundle($,k))}catch(me){v(`marketplace fetch failed for ${d}: ${me instanceof Error?me.message:String(me)}`)}let U=$s(O.manifest),I=null;if(U.length>0){if(!h.connection){let me=U.map(In=>In.source_system).join(", ");v(`${O.name}@${O.version} declares a connection input (source: ${me}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}I=h.connection}let H=WP(O.bundle,O.name,O.kind),ae=new z({baseUrl:E,token:A});try{let me=await J(`installing ${O.name}@${O.version}`,()=>ae.deploy({...H,provenance:"marketplace",...I?{connectionId:I}:{}}));y(`installed ${O.name}@${O.version} \u2192 ${me.id} (status=${me.status}, ${me.outcome})`+(I?` bound to connection ${I}.`:"."))}catch(me){me instanceof Z&&me.status===403&&v("install forbidden (403) \u2014 the stored PAT is not for an admin."),v(`install failed: ${me instanceof Error?me.message:String(me)}`)}}),s.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(d,h)=>{let w=ra();w||v(`marketplace not configured \u2014 set ${Cn} and ${Ls}.
3728
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let $=sa(w.registryUrl);$&&v($);let k=se(process.cwd(),d),g=await vr(k),x=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",E={};if(h.manifest){let O=se(process.cwd(),h.manifest),U;try{U=await oe.readFile(O,"utf8")}catch{v(`manifest not found at ${h.manifest}.`)}let I;try{I=JSON.parse(U)}catch{v(`manifest is not valid JSON: ${h.manifest}.`)}(typeof I!="object"||I===null||Array.isArray(I))&&v("manifest must be a JSON object."),E=I}try{Ui(E,g)}catch(O){O instanceof Ht&&v(O.message),v(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new br(w);try{await J(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:x,bundle:g,manifest:E}))}catch(O){O instanceof Z&&O.status===403&&v("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof Z&&O.status===409&&v(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),v(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let C=$s(E);y(`published ${h.name}@${h.pkgVersion} (kind=${x}) to the marketplace.`),C.length>0&&y(` declares ${C.length} connection input(s): ${C.map(O=>O.source_system).join(", ")} \u2014 bound at install.`)}),r.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let h=await pt(d.baseUrl).catch(()=>null),w=ma({baseUrl:h?.baseUrl,token:h?.token}),$=0,k=0,g=0;for(let x of w){let E=se(process.cwd(),x.path),A=await wy(E,x);A==="wrote"?($+=1,y(` wrote ${x.path}`)):A==="merged"?(g+=1,y(` merged ${x.path} (added the .mcp.json rule)`)):(k+=1,y(` skipped ${x.path} (exists)`))}y(`
3729
- project init: ${$} written, ${g} merged, ${k} skipped.`)}),r.command("ci").description(`Write the reusable release-deploy GitHub Action to ${fa} (non-destructive).`).action(async()=>{let d=ep(),h=0,w=0;for(let $ of d){let k=se(process.cwd(),$.path);await Pn(k,$.content,$.executable)==="wrote"?(h+=1,y(` wrote ${$.path}`)):(w+=1,y(` skipped ${$.path} (exists)`))}y(`
3730
- project ci: ${h} written, ${w} skipped.`),h>0&&(y(`
3731
- Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),y("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),y("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),r.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$=new z({baseUrl:h,token:w}),k;try{k=await $.catalogRecords()}catch(C){C instanceof Z&&(C.status===401||C.status===403)&&v("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),v(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(k.length===0){y("no records in the instance catalog \u2014 nothing to generate.");return}let g=se(process.cwd(),d.out),x=Du(k,{event:d.event}),E=0,A=0;for(let{recordType:C,fixture:O}of x){let U=Qe(g,`${C}.json`),I=`${JSON.stringify(O,null,2)}
3732
- `;d.force?(await oe.mkdir(qt(U),{recursive:!0}),await oe.writeFile(U,I,{mode:420}),E+=1,y(` wrote ${d.out}/${C}.json`)):await Pn(U,I)==="wrote"?(E+=1,y(` wrote ${d.out}/${C}.json`)):(A+=1,y(` skipped ${d.out}/${C}.json (exists \u2014 use --force to overwrite)`))}y(`
3733
- samples init: ${E} written, ${A} skipped.`)});let _t=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),ks=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??""],Oi=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];_t.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$=new z({baseUrl:h,token:w}),k;try{k=await $.guardrailsList()}catch(g){G(g,"extensions:deploy","list guardrails"),v(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3734
- `+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(ft(k.map(ks),{head:Oi})),y(f.dim(" first match wins; lower PRIO is evaluated first."))}),_t.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$}),g;try{g=await k.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(x){G(x,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${x instanceof Error?x.message:String(x)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(g.name??g.id)} created${g.status==="active"?"":f.dim(` (${g.status} \u2014 activate it to take effect)`)}`),y(f.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),y(f.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),_t.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$}),g;try{g=await k.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(x){G(x,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${x instanceof Error?x.message:String(x)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(g.name??g.id)} updated`),y(f.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[d,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])_t.command(`${d} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async($,k)=>{let{baseUrl:g,token:x}=await V(k.baseUrl),E=new z({baseUrl:g,token:x});try{await E.guardrailUpdate($,{status:h})}catch(A){G(A,"extensions:deploy",`${d} a guardrail`),v(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail ${f.bold($)} ${w}`),h==="inactive"&&y(f.dim(" writes it was gating now fall through to the other rules."))});_t.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$});try{await k.guardrailDelete(d)}catch(g){G(g,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),_t.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await k.guardrailPostureGet()}catch(C){G(C,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}y(`guardrail posture: ${f.bold(g(A.mode))}`),y(f.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let x=d.trim().toLowerCase();x!=="allow"&&x!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await k.guardrailPostureSet(x)}catch(A){G(A,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail posture set to ${f.bold(g(E.mode))}`),E.mode==="deny"&&y(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),_t.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let h;if(d.fields)try{h=JSON.parse(d.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:$}=await V(d.baseUrl),k=new z({baseUrl:w,token:$}),g;try{g=await k.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){G(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return y(JSON.stringify(g,null,2));let x=`${d.source}/${g.op??d.record}`;g.degraded?(y(`${f.red("\u2717")} ${x} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(f.dim(` ${g.reason}`))):g.allowed?y(`${f.green("\u2713")} ${x} \u2014 ${g.decision}`+(g.blockedBy?f.dim(` (rule ${g.blockedBy})`):f.dim(" (no rule matched)"))):(y(`${f.red("\u2717")} ${x} \u2014 ${g.decision} by ${f.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&y(f.dim(` ${g.message}`))),g.decision==="require_confirm"&&y(f.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let hr=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Ss=(d,h={})=>{let w=`${f.bold(d.table)} ${f.dim(d.displayName)}`;y(d.exists===!1?`${w} ${f.dim("(new)")}`:w);for(let $ of d.fields){let k=[$.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&$.claimedBy?.length?` ${f.dim(`\u2190 ${$.claimedBy.join(", ")}`)}`:"";y(` ${$.column.padEnd(28)} ${$.type}${k?` (${k})`:""}${g}`)}h.showClaimants&&d.claimants.length>1&&y(f.dim(` claimed by ${d.claimants.join(", ")}`))};function _s(d){if(d instanceof Z&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}v(`tables: ${d instanceof Error?d.message:String(d)}`)}let Fd=async d=>{let h=Qe(se(process.cwd(),d),"public","turbobase.json"),w=await oe.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let $;try{$=JSON.parse(w)}catch(g){v(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let k=$.tables;return k===void 0?{tables:[],manifestPath:h}:(Array.isArray(k)||v(`${h}: "tables" must be an array.`),{tables:k,manifestPath:h})};hr.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$=new z({baseUrl:h,token:w}),k;try{k=await $.tablesList()}catch(g){G(g,"extensions:deploy","list tables"),v(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(ft(k.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),hr.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,h)=>{let w=await Fd(d??".");if(w||v(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:$,token:k}=await V(h.baseUrl),g=new z({baseUrl:$,token:k}),x;try{x=await J("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(E){G(E,"extensions:deploy","plan tables"),_s(E)}y(`claiming as ${f.bold(x.claimedBy)}`);for(let E of x.tables)Ss(E,{showClaimants:!0});y(""),y(f.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),hr.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,h)=>{let w=await Fd(d??".");if(w||v(`no public/turbobase.json under ${se(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:$,token:k}=await V(h.baseUrl),g=new z({baseUrl:$,token:k}),x;try{x=await J("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(E){G(E,"extensions:deploy","apply tables"),_s(E)}for(let E of x.tables)Ss(E,{showClaimants:!0});y(`applied ${x.tables.length} table${x.tables.length===1?"":"s"} as ${x.claimedBy}.`)}),hr.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let w=h.field.map(E=>{let[A,C,O]=E.split(":");return(!A||!C)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:$,token:k}=await V(h.baseUrl),g=new z({baseUrl:$,token:k}),x;try{x=await J(`creating cr_${d}`,()=>g.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){G(E,"extensions:deploy","create a table"),_s(E)}for(let E of x.tables)Ss(E);y(""),y(f.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),hr.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.confirm!==d&&v(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$}),g;try{g=await J(`dropping cr_${d}`,()=>k.tablesDrop(d,h.confirm))}catch(x){G(x,"extensions:deploy","drop a table"),v(`drop failed: ${x instanceof Error?x.message:String(x)}`)}if(!g.removed)return y(`no table named "${d}" on this instance \u2014 nothing dropped.`);y(`dropped ${g.table} and every row in it.`)});let Ni=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ni.command("create").description("Stand up a fresh local sandbox seeded with a sampled+redacted slice of an instance.").requiredOption("--from <instance>","Source instance to clone the data slice from.").option("--ttl <duration>","Time-to-live before reaping (e.g. 72h, 30m, 7d).","72h").option("--sample <pct>","Percent of each table to copy (e.g. 2%).","2%").option("--base-url <url>","Local base URL the sandbox is reachable at.").action(async d=>{process.env.TURBOBASE_SANDBOX="1";let h=Ud(),w;try{w=await mh(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch($){$ instanceof Er&&v($.message),v(`sandbox create failed: ${$ instanceof Error?$.message:String($)}`)}y(`sandbox ${w.name} ready.`),y(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),y(` url: ${w.url}`),y(` expires: ${w.expiresAt}`)}),Ni.command("destroy").argument("<name>","The sandbox name to tear down.").description("Drop a sandbox database and remove it from the registry.").action(async d=>{let h=Ud();await Ma(h).catch(()=>[]);let w;try{w=await gh(h,d)}catch($){v(`sandbox destroy failed: ${$ instanceof Error?$.message:String($)}`)}w||v(`no sandbox named '${d}'.`),y(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Ni.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Ud(),h=await Ma(d).catch(()=>[]),w=await oo(),{active:$}=Ua(w);if($.length===0)y("no active sandboxes.");else{for(let k of $)y(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);y(`
3735
- ${$.length} active sandbox(es).`)}h.length>0&&y(`(reaped ${h.length} expired sandbox(es).)`)}),s.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.",Gs).action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$=new z({baseUrl:h,token:w}),k;try{k=await J("exporting instance config",()=>$.configExport())}catch(E){E instanceof Z&&(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 g=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
3736
- `,x=se(process.cwd(),d.out,Sr);await oe.mkdir(qt(x),{recursive:!0}),await oe.writeFile(x,g,"utf8"),y(`wrote ${d.out}/${Sr} (${g.split(`
3737
- `).length} lines).`)});let Hd=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Sy=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Kd=()=>process.env.TURBOBASE_HOME?.trim()||Qe(DP(),".turbobase"),_y=()=>"1.30.0",xs=async()=>Promise.all(Sy.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Hd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await xs();for(let h of d)y(`${h.present?ye.success("installed"):ye.warn("missing")} ${f.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3738
- run \`${xr} ext extras install\` to fetch them into ${Kd()}.`)}),Hd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await xs();if(d.every(A=>A.present)){y(ye.success("extras already installed \u2014 nothing to do."));return}let h=Kd();await oe.mkdir(h,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),$=Ca(process.platform,process.arch),k=async(A,C)=>{let{code:O,stderr:U}=await vs("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&v(`extras install failed while installing ${C} (npm exited ${O}).
3737
+ `+(m.screenshot?"A screenshot of the screen this request was filed from is saved beside this file as `proposal-screenshot.png`.\n":`No screenshot was captured with this request.
3738
+ `);if(await _("PROPOSAL.md",g),m.screenshot){let T=k(m.screenshot);T&&await _("proposal-screenshot.png",T)}await _(Qe(".turbobase","proposal.json"),`${JSON.stringify({proposalId:m.proposalId},null,2)}
3739
+ `)}async function R(d){try{let m=await se.readFile(Qe(d,".turbobase","proposal.json"),"utf8"),w=JSON.parse(m);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function P(d,m,w,x,_,g){let T=new z({baseUrl:d,token:m});try{return await T.appsPush(w,x,{note:_,proposalId:g})}catch(E){if(E instanceof Z){let A=E.body;if(E.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&G(E,"extensions:deploy","push app source"),E.status===404&&v(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let I=A?.path?` in ${A.path}`:"",N=A?.reason?` (${A.reason})`:"";v(`push rejected: ${A?.error??"bad request"}${N}${I}.`)}}v(`push failed: ${E instanceof Error?E.message:String(E)}`)}}function O(d,m,w){return new Promise((x,_)=>{let g=zd("npm",d,{cwd:m,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});g.on("error",_),g.on("exit",T=>T===0?x():_(new Error(`npm ${d.join(" ")} exited ${T??"?"}`)))})}async function D(d,m,w,x){let _=`${d.replace(/\/+$/,"")}${w}`,g;try{g=await p(_,{method:x.method,headers:{Authorization:`Bearer ${m}`,...x.body?{"content-type":"application/json"}:{}},...x.body?{body:JSON.stringify(x.body)}:{}})}catch(T){v(`request failed: ${T instanceof Error?T.message:String(T)}`)}if(g.status===401&&v("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&v("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let T=await g.text().catch(()=>""),E=T.slice(0,300);try{let A=JSON.parse(T);E=A.message??A.error??E}catch{}v(`failed: HTTP ${g.status} ${E}`)}return await g.json().catch(()=>({}))}async function Y(d,m,w,x,_){return await D(d,m,`/v1/apps/${encodeURIComponent(w)}/preview/${x}`,{method:"POST",body:_})}async function K(d,m,w){return{previews:(await D(d,m,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function Ae(d,m,w,x,_,g,T,E){let A;try{A=await J(`zipping ${x}`,()=>Hu(x))}catch(C){v(`could not zip ${x}: ${C instanceof Error?C.message:String(C)}`)}A.fileCount===0&&v(`${x} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>Pa&&v(`${x} zips to ${Tb(A.buffer.byteLength)} \u2014 over the ${Tb(Pa)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let I={Authorization:`Bearer ${m}`,"Content-Type":"application/zip"};_&&(I["x-app-entry"]=_),g&&(I["x-proposal-id"]=g),T&&(I["x-app-build-id"]=T.buildId,I["x-app-asset-base"]=T.assetBase),E&&(I["x-app-channel"]="preview",E.label&&(I["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(I["x-app-preview-replace"]=E.replacePreviewId));let N=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,U;try{U=await J(`deploying ${w} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(N,{method:"POST",headers:I,body:new Uint8Array(A.buffer)}))}catch(C){v(`deploy request failed: ${C instanceof Error?C.message:String(C)}`)}if(U.status===401&&v("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),U.status===403&&v("deploy forbidden (403) \u2014 the PAT is not for an admin."),U.status===404){let C=await U.text().catch(()=>""),H={};try{H=JSON.parse(C)}catch{}H.error==="no_preview"&&v(`${H.message??`no open preview to replace on ${w}`} \u2014 list them with \`turbobase apps preview list ${w}\`.`),v(`no app "${w}" on ${d} \u2014 create it with \`turbobase apps create ${w}\`.`)}if(!U.ok){let C=await U.text().catch(()=>""),H=C.slice(0,300);try{let ae=JSON.parse(C);H=ae.message??ae.error??H}catch{}v(`deploy failed: HTTP ${U.status} ${H}`)}return await U.json().catch(()=>({}))}function De(d){let m=d.roles;if(!m||m.verdicts.length===0)return;let w=m.verdicts.filter(_=>_.action!=="noop");if(w.length===0)return;b(""),b(h.bold(m.applied?"roles":"roles (preview \u2014 not applied)"));let x=Math.max(...w.map(_=>_.name.length));for(let _ of w){let g=_.name.padEnd(x);if(_.action==="create"){let T=_.addCapabilities?.length??0;b(` created ${g} ${h.dim(`${T} capabilit${T===1?"y":"ies"}`)}`)}else if(_.action==="add_capabilities"){let T=(_.addCapabilities??[]).map(A=>`+${A}`).join(", "),E=_.holdersRestamped?h.dim(` (${_.holdersRestamped} holder${_.holdersRestamped===1?"":"s"} re-stamped)`):"";b(` updated ${g} ${h.dim(T)}${E}`)}}b(h.dim(m.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 zt(d){let m=d.labels;if(!m||m.verdicts.length===0)return;let w=m.verdicts.filter(_=>_.action!=="noop");if(w.length===0)return;b(""),b(h.bold(m.applied?"labels":"labels (preview \u2014 not applied)"));let x=Math.max(...w.map(_=>_.name.length));for(let _ of w){let g=_.name.padEnd(x);if(_.action==="detach")b(` removed ${g} ${h.dim("no longer declared in the manifest")}`);else if(_.action==="create")b(` created ${g} ${h.dim(_.color)}`);else{let T=_.declaredColor?`${_.color} \u2014 declared ${_.declaredColor}, the instance's colour is kept`:_.color;b(` added ${g} ${h.dim(T)}`)}}b(h.dim(m.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 Bt(d,m){let w=np(d,{localDocsModifiedAt:await cr(m)});w&&b(w.level==="warn"?h.yellow(w.message):h.dim(w.message))}async function cr(d){if(!d)return null;let m=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let x=await se.stat(Qe(d,w));(m===null||x.mtimeMs>m)&&(m=x.mtimeMs)}catch{}return m===null?null:new Date(m)}l.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,m,w)=>{let{baseUrl:x,token:_}=await V(w.baseUrl);if(w.proposal){let A=new z({baseUrl:x,token:_}),I;try{I=await J(`fetching proposal ${w.proposal}`,()=>A.appPullContext(w.proposal))}catch(ae){G(ae,"extensions:deploy","pull proposal"),ae instanceof Z&&ae.status===404&&v(`no widget proposal "${w.proposal}" on ${x}.`),v(`could not fetch proposal ${w.proposal}: ${ae instanceof Error?ae.message:String(ae)}`)}let N=await J(`pulling ${I.appSlug}`,()=>S(x,_,I.appSlug)),U=m??d,C=oe(process.cwd(),U??I.appSlug);await se.mkdir(C,{recursive:!0});let H=await y(C,N.files,!!w.force);await $(C,I,!!w.force),b(`pulled ${H} file${H===1?"":"s"} \u2192 ${C} (rev ${N.rev}), linked to proposal ${I.proposalId}.`),b(`next: cd ${Ii(process.cwd(),C)||"."} && turbobase apps deploy ${I.appSlug}`);return}d||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await J(`pulling ${d}`,()=>S(x,_,d)),T=oe(process.cwd(),m??g.slug??d);await se.mkdir(T,{recursive:!0});let E=await y(T,g.files,!!w.force);b(`pulled ${E} file${E===1?"":"s"} \u2192 ${T} (rev ${g.rev}).`),b(`next: cd ${Ii(process.cwd(),T)||"."} && turbobase apps deploy ${g.slug}`)}),l.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,m,w)=>{let x=oe(process.cwd(),m??d),_=await pt(w.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:T}=await Promise.resolve().then(()=>(Hm(),Fm)),E=w.title??d,A=g({slug:d,title:E,appTsx:T(E),instanceOrigin:_?.baseUrl});await se.mkdir(x,{recursive:!0});let I=await y(x,A,!!w.force);if(b(`scaffolded ${I} file${I===1?"":"s"} \u2192 ${x}`),w.claude!==!1){let U=fa({baseUrl:_?.baseUrl,token:_?.token,appSlug:d}),C=0;for(let H of U){let ae=await kb(Qe(x,H.path),H);(ae==="wrote"||ae==="merged")&&(C+=1)}b(`wired Claude Code: ${C} file${C===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),_||L("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 N=Ii(process.cwd(),x)||".";b(`next: cd ${N} && npm install && npm run dev`),b(` turbobase apps create ${d}`),b(` turbobase apps push ${d} .`),b(` turbobase apps deploy ${d} .`)}),l.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:m,token:w}=await V(d.baseUrl),x=new z({baseUrl:m,token:w}),_;try{_=await x.appsList()}catch(g){G(g,"extensions:deploy","list apps"),v(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");b(ht(_.map(g=>[g.slug,g.name,g.deployed?"yes":"no",g.sourceRev===null?"\u2014":`rev ${g.sourceRev}`,g.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.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,m,w)=>{let x=oe(process.cwd(),m??".");await se.stat(x).then(fe=>fe.isDirectory()).catch(()=>!1)||v(`${x} is not a directory.`);let{baseUrl:g,token:T}=await V(w.baseUrl),E=w.proposal??await R(x),{files:A,skipped:I,secrets:N,unstorable:U}=await lm(x),C=Object.keys(A).length;if(C===0&&v(`no source files found under ${x} (build output and node_modules are skipped).`),U.length>0){for(let fe of U)L(`${fe} contains a NUL byte (U+0000), which cannot be stored.`);v(`push aborted: ${U.length} ${U.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let fe of I)L(h.dim(`skipped binary file ${fe}`));for(let fe of N)L(h.dim(`skipped ${fe} (holds credentials \u2014 never pushed)`));let H=await J(`pushing ${C} file${C===1?"":"s"}`,()=>P(g,T,d,A,w.note,E));b(`pushed ${H.files} file${H.files===1?"":"s"} \u2192 ${H.slug} rev ${H.rev} (source only, nothing deployed).`);let ae=await $n(new z({baseUrl:g,token:T}),H.slug);ae&&ae.entriesAdded>0&&b(`${ae.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),b(`next: turbobase apps deploy ${H.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 m=await Dd(),{baseUrl:w,token:x}=await V(d.baseUrl),_=new z({baseUrl:w,token:x}),g;try{g=await J(`planning against ${d.to??w}`,()=>_.configPlan(m))}catch(T){v(`plan failed: ${T instanceof Error?T.message:String(T)}`)}dA(g,d.to??w)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let m=await Dd(),{baseUrl:w,token:x}=await V(d.baseUrl),_=m.tenant??uA(w),g=mp(d.confirm,_);g.ok||v(`promote refused (fail-closed): ${g.reason}`);let T=new z({baseUrl:w,token:x});try{let E=await J(`promoting ${d.from} \u2192 ${d.to} (${_})`,()=>T.configApply(m,{prune:d.prune}));if(Pe()){let I=[`${h.bold(`${d.from} \u2192 ${d.to}`)} ${h.dim(_??"")}`,`${Kt.add(String(E.applied.add))} ${Kt.change(String(E.applied.change))} ${Kt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&I.push(h.dim(`${E.backfillsQueued.length} backfill(s) queued`)),b(Vt("Promoted",I))}else b(`promoted ${d.from} \u2192 ${d.to} (${_}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let A=E.skippedDestroys??[];if(A.length>0){L(`${A.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let I of A)L(` ${I.kind} ${I.id}`);L("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof Z&&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,m)=>{let w=jd(m.reporter),x=oe(process.cwd(),d),_=await vn(x),g=Vu(_);w?b(Ho(sA(d,g),w)):b(Wu(d,g,{warn:h.yellow,ok:h.green,dim:h.dim})),m.ci&&g.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(d,m)=>{let w=jd(m.reporter),x=await Uu(oe(process.cwd(),d));if(m.against){m.against!=="sandbox"&&v(`unknown --against target '${m.against}' (only 'sandbox' is supported).`);try{await ju(la(x))}catch(T){v(T instanceof Error?T.message:String(T))}return}m.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let _;try{_=await Du(oe(process.cwd(),m.fixture))}catch(T){v(`could not read fixture ${m.fixture}: ${T instanceof Error?T.message:String(T)}`)}let g=await Lu(x,_,m.fixture,{resolveDir:qt(oe(process.cwd(),d))});if(w){let T=iA(g);b(Ho(T,w)),Ci(T.cases.some(E=>E.status==="failed")?1:0)}b(Mu(g,!!m.trace)),Ci(g.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:m,token:w}=await V(d.baseUrl),x=new z({baseUrl:m,token:w});try{await ep(x,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:b})}catch(_){_ instanceof Z&&_.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),_ instanceof Z&&_.status===409&&v("binding is not retryable (only divergent/blocked bindings can be retried)."),v(`ext binding failed: ${_ instanceof Error?_.message:String(_)}`)}});let Ft=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");Ft.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 Wp(d)}),Ft.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,m)=>{await Gp(d??[],m)}),Ft.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,m)=>{await Jp(d,m)}),Ft.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,m)=>{await Yp(d,m)}),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,m)=>{await Xp(d,m)}),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,m)=>{await Zp(d,m)}),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,m)=>{await Qp(d,m)}),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,m)=>{let w=d.lastIndexOf("@"),x=w>0?d.slice(0,w):d,_=w>0?d.slice(w+1):void 0,g=na();g||v(`marketplace not configured \u2014 set ${Cr} and ${jo}.
3740
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=oa(g.registryUrl);T&&v(T);let{baseUrl:E,token:A}=await V(m.baseUrl),I=new yn(g),N;try{N=await J(`fetching ${d}`,()=>I.fetchBundle(x,_))}catch(fe){v(`marketplace fetch failed for ${d}: ${fe instanceof Error?fe.message:String(fe)}`)}let U=$o(N.manifest),C=null;if(U.length>0){if(!m.connection){let fe=U.map(Ar=>Ar.source_system).join(", ");v(`${N.name}@${N.version} declares a connection input (source: ${fe}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}C=m.connection}let H=aA(N.bundle,N.name,N.kind),ae=new z({baseUrl:E,token:A});try{let fe=await J(`installing ${N.name}@${N.version}`,()=>ae.deploy({...H,provenance:"marketplace",...C?{connectionId:C}:{}}));b(`installed ${N.name}@${N.version} \u2192 ${fe.id} (status=${fe.status}, ${fe.outcome})`+(C?` bound to connection ${C}.`:"."))}catch(fe){fe instanceof Z&&fe.status===403&&v("install forbidden (403) \u2014 the stored PAT is not for an admin."),v(`install failed: ${fe instanceof Error?fe.message:String(fe)}`)}}),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,m)=>{let w=na();w||v(`marketplace not configured \u2014 set ${Cr} and ${jo}.
3741
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=oa(w.registryUrl);x&&v(x);let _=oe(process.cwd(),d),g=await vn(_),T=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",E={};if(m.manifest){let N=oe(process.cwd(),m.manifest),U;try{U=await se.readFile(N,"utf8")}catch{v(`manifest not found at ${m.manifest}.`)}let C;try{C=JSON.parse(U)}catch{v(`manifest is not valid JSON: ${m.manifest}.`)}(typeof C!="object"||C===null||Array.isArray(C))&&v("manifest must be a JSON object."),E=C}try{Ui(E,g)}catch(N){N instanceof Ht&&v(N.message),v(`manifest validation failed: ${N instanceof Error?N.message:String(N)}`)}let A=new yn(w);try{await J(`publishing ${m.name}@${m.pkgVersion}`,()=>A.publish({name:m.name,version:m.pkgVersion,kind:T,bundle:g,manifest:E}))}catch(N){N instanceof Z&&N.status===403&&v("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),N instanceof Z&&N.status===409&&v(`version already published \u2014 ${m.name}@${m.pkgVersion} exists. Bump the version.`),v(`publish failed: ${N instanceof Error?N.message:String(N)}`)}let I=$o(E);b(`published ${m.name}@${m.pkgVersion} (kind=${T}) to the marketplace.`),I.length>0&&b(` declares ${I.length} connection input(s): ${I.map(N=>N.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 m=await pt(d.baseUrl).catch(()=>null),w=fa({baseUrl:m?.baseUrl,token:m?.token}),x=0,_=0,g=0;for(let T of w){let E=oe(process.cwd(),T.path),A=await kb(E,T);A==="wrote"?(x+=1,b(` wrote ${T.path}`)):A==="merged"?(g+=1,b(` merged ${T.path} (added the .mcp.json rule)`)):(_+=1,b(` skipped ${T.path} (exists)`))}b(`
3742
+ project init: ${x} written, ${g} merged, ${_} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${ha} (non-destructive).`).action(async()=>{let d=op(),m=0,w=0;for(let x of d){let _=oe(process.cwd(),x.path);await Er(_,x.content,x.executable)==="wrote"?(m+=1,b(` wrote ${x.path}`)):(w+=1,b(` skipped ${x.path} (exists)`))}b(`
3743
+ project ci: ${m} written, ${w} skipped.`),m>0&&(b(`
3744
+ Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),b("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),b("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:m,token:w}=await V(d.baseUrl),x=new z({baseUrl:m,token:w}),_;try{_=await x.catalogRecords()}catch(I){I instanceof Z&&(I.status===401||I.status===403)&&v("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),v(`catalog fetch failed: ${I instanceof Error?I.message:String(I)}`)}if(_.length===0){b("no records in the instance catalog \u2014 nothing to generate.");return}let g=oe(process.cwd(),d.out),T=zu(_,{event:d.event}),E=0,A=0;for(let{recordType:I,fixture:N}of T){let U=Qe(g,`${I}.json`),C=`${JSON.stringify(N,null,2)}
3745
+ `;d.force?(await se.mkdir(qt(U),{recursive:!0}),await se.writeFile(U,C,{mode:420}),E+=1,b(` wrote ${d.out}/${I}.json`)):await Er(U,C)==="wrote"?(E+=1,b(` wrote ${d.out}/${I}.json`)):(A+=1,b(` skipped ${d.out}/${I}.json (exists \u2014 use --force to overwrite)`))}b(`
3746
+ samples init: ${E} written, ${A} skipped.`)});let kt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),So=d=>[d.name??h.dim(d.id.slice(0,8)),d.status==="active"?h.green("active"):d.status==="proposed"?h.yellow("proposed"):h.dim("inactive"),d.decision==="deny"?h.red(d.decision):d.decision==="require_confirm"?h.yellow(d.decision):h.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??h.dim("any"),d.when||h.dim("(always)"),d.reason??""],Oi=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];kt.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:m,token:w}=await V(d.baseUrl),x=new z({baseUrl:m,token:w}),_;try{_=await x.guardrailsList()}catch(g){G(g,"extensions:deploy","list guardrails"),v(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3747
+ `+h.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ht(_.map(So),{head:Oi})),b(h.dim(" first match wins; lower PRIO is evaluated first."))}),kt.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x}),g;try{g=await _.guardrailCreate({name:d,source:m.source,record:m.record,decision:m.decision,...m.op?{op:m.op}:{},...m.target?{target:m.target}:{},...m.actor?{actor:m.actor}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when?{when:m.when}:{},...m.reason?{reason:m.reason}:{},...m.disabled?{enabled:!1}:{},...m.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(T){G(T,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(g.name??g.id)} created${g.status==="active"?"":h.dim(` (${g.status} \u2014 activate it to take effect)`)}`),b(h.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),b(h.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),kt.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,m)=>{m.decision===void 0&&m.priority===void 0&&m.when===void 0&&m.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x}),g;try{g=await _.guardrailUpdate(d,{...m.decision!==void 0?{decision:m.decision}:{},...Number.isFinite(m.priority)?{priority:Number(m.priority)}:{},...m.when!==void 0?{when:m.when}:{},...m.reason!==void 0?{reason:m.reason}:{}})}catch(T){G(T,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${T instanceof Error?T.message:String(T)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(g.name??g.id)} updated`),b(h.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[d,m,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])kt.command(`${d} <name>`).description(m==="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(x,_)=>{let{baseUrl:g,token:T}=await V(_.baseUrl),E=new z({baseUrl:g,token:T});try{await E.guardrailUpdate(x,{status:m})}catch(A){G(A,"extensions:deploy",`${d} a guardrail`),v(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(x)} ${w}`),m==="inactive"&&b(h.dim(" writes it was gating now fall through to the other rules."))});kt.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x});try{await _.guardrailDelete(d)}catch(g){G(g,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}b(`${h.green("\u2713")} guardrail ${h.bold(d)} deleted`)}),kt.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await _.guardrailPostureGet()}catch(I){G(I,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}b(`guardrail posture: ${h.bold(g(A.mode))}`),b(h.dim(A.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 T=d.trim().toLowerCase();T!=="allow"&&T!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await _.guardrailPostureSet(T)}catch(A){G(A,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${h.green("\u2713")} guardrail posture set to ${h.bold(g(E.mode))}`),E.mode==="deny"&&b(h.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),kt.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 m;if(d.fields)try{m=JSON.parse(d.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:x}=await V(d.baseUrl),_=new z({baseUrl:w,token:x}),g;try{g=await _.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...m?{fields:m}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(E){G(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return b(JSON.stringify(g,null,2));let T=`${d.source}/${g.op??d.record}`;g.degraded?(b(`${h.red("\u2717")} ${T} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(h.dim(` ${g.reason}`))):g.allowed?b(`${h.green("\u2713")} ${T} \u2014 ${g.decision}`+(g.blockedBy?h.dim(` (rule ${g.blockedBy})`):h.dim(" (no rule matched)"))):(b(`${h.red("\u2717")} ${T} \u2014 ${g.decision} by ${h.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&b(h.dim(` ${g.message}`))),g.decision==="require_confirm"&&b(h.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let mn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),ko=(d,m={})=>{let w=`${h.bold(d.table)} ${h.dim(d.displayName)}`;b(d.exists===!1?`${w} ${h.dim("(new)")}`:w);for(let x of d.fields){let _=[x.required?"required":null].filter(Boolean).join(", "),g=m.showClaimants&&x.claimedBy?.length?` ${h.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";b(` ${x.column.padEnd(28)} ${x.type}${_?` (${_})`:""}${g}`)}m.showClaimants&&d.claimants.length>1&&b(h.dim(` claimed by ${d.claimants.join(", ")}`))};function To(d){if(d instanceof Z&&d.status===409){let m=d.body;m?.error==="table_conflict"&&m.message&&(L(m.message),process.exit(1))}v(`tables: ${d instanceof Error?d.message:String(d)}`)}let Fd=async d=>{let m=Qe(oe(process.cwd(),d),"public","turbobase.json"),w=await se.readFile(m,"utf8").catch(()=>null);if(w===null)return null;let x;try{x=JSON.parse(w)}catch(g){v(`${m} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let _=x.tables;return _===void 0?{tables:[],manifestPath:m}:(Array.isArray(_)||v(`${m}: "tables" must be an array.`),{tables:_,manifestPath:m})};mn.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:m,token:w}=await V(d.baseUrl),x=new z({baseUrl:m,token:w}),_;try{_=await x.tablesList()}catch(g){G(g,"extensions:deploy","list tables"),v(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ht(_.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),mn.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,m)=>{let w=await Fd(d??".");if(w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:_}=await V(m.baseUrl),g=new z({baseUrl:x,token:_}),T;try{T=await J("planning tables",()=>g.tablesPlan({claimedBy:m.as,tables:w.tables}))}catch(E){G(E,"extensions:deploy","plan tables"),To(E)}b(`claiming as ${h.bold(T.claimedBy)}`);for(let E of T.tables)ko(E,{showClaimants:!0});b(""),b(h.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),mn.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,m)=>{let w=await Fd(d??".");if(w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:_}=await V(m.baseUrl),g=new z({baseUrl:x,token:_}),T;try{T=await J("applying tables",()=>g.tablesApply({claimedBy:m.as,tables:w.tables}))}catch(E){G(E,"extensions:deploy","apply tables"),To(E)}for(let E of T.tables)ko(E,{showClaimants:!0});b(`applied ${T.tables.length} table${T.tables.length===1?"":"s"} as ${T.claimedBy}.`)}),mn.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,m)=>[...m??[],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,m)=>{let w=m.field.map(E=>{let[A,I,N]=E.split(":");return(!A||!I)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:A,type:I,...N==="required"?{required:!0}:{}}}),{baseUrl:x,token:_}=await V(m.baseUrl),g=new z({baseUrl:x,token:_}),T;try{T=await J(`creating cr_${d}`,()=>g.tablesApply({tables:[{slug:d,displayName:m.name??d,fields:w,...m.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){G(E,"extensions:deploy","create a table"),To(E)}for(let E of T.tables)ko(E);b(""),b(h.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),mn.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,m)=>{m.confirm!==d&&v(`drop refused: --confirm "${m.confirm}" does not match "${d}".`);let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x}),g;try{g=await J(`dropping cr_${d}`,()=>_.tablesDrop(d,m.confirm))}catch(T){G(T,"extensions:deploy","drop a table"),v(`drop failed: ${T instanceof Error?T.message:String(T)}`)}if(!g.removed)return b(`no table named "${d}" on this instance \u2014 nothing dropped.`);b(`dropped ${g.table} and every row in it.`)});let Ni=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Ni.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 m=Ud(),w;try{w=await wm(m,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(x){x instanceof En&&v(x.message),v(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}b(`sandbox ${w.name} ready.`),b(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),b(` url: ${w.url}`),b(` expires: ${w.expiresAt}`)}),Ni.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 m=Ud();await Ma(m).catch(()=>[]);let w;try{w=await vm(m,d)}catch(x){v(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}w||v(`no sandbox named '${d}'.`),b(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Ni.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Ud(),m=await Ma(d).catch(()=>[]),w=await is(),{active:x}=Ua(w);if(x.length===0)b("no active sandboxes.");else{for(let _ of x)b(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);b(`
3748
+ ${x.length} active sandbox(es).`)}m.length>0&&b(`(reaped ${m.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.",Jo).action(async d=>{let{baseUrl:m,token:w}=await V(d.baseUrl),x=new z({baseUrl:m,token:w}),_;try{_=await J("exporting instance config",()=>x.configExport())}catch(E){E instanceof Z&&(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 g=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
3749
+ `,T=oe(process.cwd(),d.out,Sn);await se.mkdir(qt(T),{recursive:!0}),await se.writeFile(T,g,"utf8"),b(`wrote ${d.out}/${Sn} (${g.split(`
3750
+ `).length} lines).`)});let Hd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),$b=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Kd=()=>process.env.TURBOBASE_HOME?.trim()||Qe(XP(),".turbobase"),Rb=()=>"1.31.0",xo=async()=>Promise.all($b.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Hd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await xo();for(let m of d)b(`${m.present?be.success("installed"):be.warn("missing")} ${h.bold(m.name)} \u2014 ${m.needs}`);d.some(m=>!m.present)&&b(`
3751
+ run \`${Tn} ext extras install\` to fetch them into ${Kd()}.`)}),Hd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await xo();if(d.every(A=>A.present)){b(be.success("extras already installed \u2014 nothing to do."));return}let m=Kd();await se.mkdir(m,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),x=Ia(process.platform,process.arch),_=async(A,I)=>{let{code:N,stderr:U}=await _o("npm",["install","--prefix",m,"--no-audit","--no-fund",...A]);N!==0&&v(`extras install failed while installing ${I} (npm exited ${N}).
3739
3752
  ${U.trim()}
3740
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=w.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(C=>`${C}@${Aa[C]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await k(A,g.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Aa["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await k(["--ignore-scripts",A],"isolated-vm"),lh.includes($)){let O=`${Ia}@${_y()}`;y(`fetching ${O} (no upstream binary for ${$}) \u2026`);let{code:U}=await vs("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);U!==0&&y(ye.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await ch({home:h});C.length>0&&y(` ${ye.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${$}`)}let x=await xs(),E=x.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){y(ye.warn(`no prebuilt isolated-vm for ${$} / Node ${process.versions.node} (${Oa()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await vs("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(x=await xs(),E=x.filter(C=>!C.present).map(C=>C.name))}E.length>0&&v(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${$} / Node ${process.versions.node} (${Oa()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),y(ye.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let An=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return An.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||v(`--target must be 'auto' or 'approved' (got '${d.target}').`);let w=await ZP(se(process.cwd(),d.project??".")),$=Object.keys(w).length;!d.solution&&$===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(d.ref?await Md(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Md(["rev-parse","HEAD"]),x=d.gitRepo??process.env.GITHUB_REPOSITORY??await Md(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await V(d.baseUrl),U=new z({baseUrl:C,token:O}),I;try{I=await U.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:$>0?w:null,gitRepo:x,gitRef:E,gitSha:g,prUrl:A})}catch(H){G(H,"releases:write","release deploy"),H instanceof Z&&H.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${H instanceof Error?H.message:String(H)}`)}y(`release ${I.releaseId} enqueued \u2192 taskId=${I.taskId} (target=${h}`+($>0?`, uploaded ${$} bundle file(s)`:", live-fetch")+")."),d.follow&&await va(()=>U.releaseStatus(I.releaseId),`release ${I.releaseId}`,d.intervalMs)}),An.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$}),g;try{g=await k.releaseFiles(d)}catch(A){A instanceof Z&&A.status===404&&v(`release ${d} not found.`),A instanceof Z&&A.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.`),G(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let x=se(process.cwd(),h.dir),E=0;for(let[A,C]of[["owned",g.owned],["context",g.context]])for(let[O,U]of Object.entries(C)){let I=Qe(x,A,O);await oe.mkdir(qt(I),{recursive:!0}),await oe.writeFile(I,U,"utf8"),E++}await oe.writeFile(Qe(x,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),y(`pulled release ${g.releaseId} (${g.status}) \u2192 ${x}
3753
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=w.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(I=>`${I}@${Aa[I]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${m}/node_modules \u2026`),await _(A,g.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Aa["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${m}/node_modules \u2026`),await _(["--ignore-scripts",A],"isolated-vm"),pm.includes(x)){let N=`${Ca}@${Rb()}`;b(`fetching ${N} (no upstream binary for ${x}) \u2026`);let{code:U}=await _o("npm",["install","--prefix",m,"--no-audit","--no-fund","--ignore-scripts",N]);U!==0&&b(be.warn(`could not fetch ${N} \u2014 falling back to a source build.`))}let I=await mm({home:m});I.length>0&&b(` ${be.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let T=await xo(),E=T.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){b(be.warn(`no prebuilt isolated-vm for ${x} / Node ${process.versions.node} (${Oa()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await _o("npm",["rebuild","--prefix",m,"isolated-vm"]);A===0&&(T=await xo(),E=T.filter(I=>!I.present).map(I=>I.name))}E.length>0&&v(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${x} / Node ${process.versions.node} (${Oa()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(be.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Pr=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Pr.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 m=d.target==="approved"?"approved":d.target==="auto"?"auto":null;m||v(`--target must be 'auto' or 'approved' (got '${d.target}').`);let w=await pA(oe(process.cwd(),d.project??".")),x=Object.keys(w).length;!d.solution&&x===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let g=(d.ref?await Md(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Md(["rev-parse","HEAD"]),T=d.gitRepo??process.env.GITHUB_REPOSITORY??await Md(["remote","get-url","origin"]),E=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:I,token:N}=await V(d.baseUrl),U=new z({baseUrl:I,token:N}),C;try{C=await U.releaseDeploy({solutionId:d.solution??null,target:m,approvedBy:d.approvedBy??null,files:x>0?w:null,gitRepo:T,gitRef:E,gitSha:g,prUrl:A})}catch(H){G(H,"releases:write","release deploy"),H instanceof Z&&H.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${H instanceof Error?H.message:String(H)}`)}b(`release ${C.releaseId} enqueued \u2192 taskId=${C.taskId} (target=${m}`+(x>0?`, uploaded ${x} bundle file(s)`:", live-fetch")+")."),d.follow&&await va(()=>U.releaseStatus(C.releaseId),`release ${C.releaseId}`,d.intervalMs)}),Pr.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x}),g;try{g=await _.releaseFiles(d)}catch(A){A instanceof Z&&A.status===404&&v(`release ${d} not found.`),A instanceof Z&&A.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.`),G(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let T=oe(process.cwd(),m.dir),E=0;for(let[A,I]of[["owned",g.owned],["context",g.context]])for(let[N,U]of Object.entries(I)){let C=Qe(T,A,N);await se.mkdir(qt(C),{recursive:!0}),await se.writeFile(C,U,"utf8"),E++}await se.writeFile(Qe(T,".turbobase-release.json"),JSON.stringify({releaseId:g.releaseId,version:g.version,contentDigest:g.contentDigest},null,2),"utf8"),b(`pulled release ${g.releaseId} (${g.status}) \u2192 ${T}
3741
3754
  ${Object.keys(g.owned).length} owned file(s), ${Object.keys(g.context).length} context file(s), ${E} total
3742
3755
  `+(g.logTail?`
3743
3756
  the failure these bytes produced:
3744
3757
  ${g.logTail.trim()}
3745
3758
  `:"")+`
3746
3759
  edit the files under owned/, then:
3747
- turbobase release push ${g.releaseId} --dir ${h.dir}`)}),An.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$}),g=se(process.cwd(),h.dir),x;try{x=await k.releaseFiles(d)}catch(I){I instanceof Z&&I.status===404&&v(`release ${d} not found.`),G(I,"releases:write","push a release"),v(`release push failed: ${I instanceof Error?I.message:String(I)}`)}let E=async(I,H)=>{try{return await oe.readFile(Qe(g,I,H),"utf8")}catch{return null}},A=[];for(let[I,H]of Object.entries(x.context)){let ae=await E("context",I);ae!==null&&ae!==H&&A.push(I)}A.length>0&&v(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
3748
- `+A.map(I=>` context/${I}`).join(`
3749
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...x.context},O=0;for(let[I,H]of Object.entries(x.owned)){let ae=await E("owned",I);C[I]=ae??H,ae!==null&&ae!==H&&O++}O===0&&y("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let U=h.target==="approved"?"approved":"auto";try{let I=await k.releasePush(d,{files:C,target:U,...h.approvedBy?{approvedBy:h.approvedBy}:{}});y(`pushed ${Object.keys(C).length} file(s) (${O} edited) \u2192 release ${I.releaseId} (task ${I.taskId}).
3760
+ turbobase release push ${g.releaseId} --dir ${m.dir}`)}),Pr.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x}),g=oe(process.cwd(),m.dir),T;try{T=await _.releaseFiles(d)}catch(C){C instanceof Z&&C.status===404&&v(`release ${d} not found.`),G(C,"releases:write","push a release"),v(`release push failed: ${C instanceof Error?C.message:String(C)}`)}let E=async(C,H)=>{try{return await se.readFile(Qe(g,C,H),"utf8")}catch{return null}},A=[];for(let[C,H]of Object.entries(T.context)){let ae=await E("context",C);ae!==null&&ae!==H&&A.push(C)}A.length>0&&v(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
3761
+ `+A.map(C=>` context/${C}`).join(`
3762
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let I={...T.context},N=0;for(let[C,H]of Object.entries(T.owned)){let ae=await E("owned",C);I[C]=ae??H,ae!==null&&ae!==H&&N++}N===0&&b("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let U=m.target==="approved"?"approved":"auto";try{let C=await _.releasePush(d,{files:I,target:U,...m.approvedBy?{approvedBy:m.approvedBy}:{}});b(`pushed ${Object.keys(I).length} file(s) (${N} edited) \u2192 release ${C.releaseId} (task ${C.taskId}).
3750
3763
  follow it with:
3751
- turbobase release status ${I.releaseId} --follow`)}catch(I){I instanceof Z&&I.status===403&&v("an approved target needs --approved-by (the deploy gate fails closed)."),I instanceof Z&&I.status===409&&v("that solution already has an active release \u2014 roll it back or wait for it."),G(I,"releases:write","push a release"),v(`release push failed: ${I instanceof Error?I.message:String(I)}`)}}),An.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$});if(h.follow){await va(()=>k.releaseStatus(d),`release ${d}`,h.intervalMs);return}let g;try{g=await k.releaseStatus(d)}catch(x){G(x,"releases:write","release status"),x instanceof Z&&x.status===404&&v(`release ${d} not found.`),v(`release status failed: ${x instanceof Error?x.message:String(x)}`)}y(`release ${d}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&y(g.outputTail.replace(/\n+$/,""))}),An.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:$}=await V(h.baseUrl),k=new z({baseUrl:w,token:$}),g;try{g=await k.releaseRollback(d)}catch(x){G(x,"releases:write","release rollback"),x instanceof Z&&x.status===404&&v(`release ${d} not found.`),x instanceof Z&&x.status===409&&v(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),v(`release rollback failed: ${x instanceof Error?x.message:String(x)}`)}y(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),An.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:h,token:w}=await V(d.baseUrl),$=new z({baseUrl:h,token:w}),k;try{k=await $.releaseList()}catch(g){G(g,"releases:write","release list"),v(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(k.length===0){y("no releases.");return}if(Pe())y(ft(k.map(g=>[g.id,Ln(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(x=>`"${x}"`).join(", "):f.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of k){let x=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";y(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${x}`)}y(`
3752
- ${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:h,token:w}=await V(d.baseUrl),$=new z({baseUrl:h,token:w}),k=d.limit?Number(d.limit):void 0,g=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await Ju($,d.conduit,{...d.follow?{follow:!0}:{},...k!==void 0?{limit:k}:{},...g!==void 0?{intervalMs:g}:{},sink:y})}catch(x){v(`logs --conduit failed: ${x instanceof Error?x.message:String(x)}`)}return}if(d.extension){try{let x=await $.logs(d.extension,k);x.length===0&&y(`no logs for ${d.extension}.`);for(let E of x)y(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(x){v(`logs --extension failed: ${x instanceof Error?x.message:String(x)}`)}return}try{await Xu($,{...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}:{},...g!==void 0?{intervalMs:g}:{},sink:y})}catch(x){v(`logs failed: ${x instanceof Error?x.message:String(x)}`)}}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(yy(),by));await h({baseUrl:d.baseUrl})}),e.addHelpText("after",["","Common flows:"," turbobase auth login --base-url https://acme.turbobase.app --token tb_pat_\u2026"," turbobase project init && turbobase project types"," turbobase ext new hook --record salesOrder && turbobase ext test hooks/\u2026"," turbobase ext deploy --to prod"," turbobase apps deploy my-app ./app","","Run `turbobase <group> --help` for a group (auth, project, ext, apps, kb, sandbox, mcp).","Docs: https://docs.turbobase.io/cli/overview/"].join(`
3753
- `)),t&&void 0,e}function WP(t,e,n){let r=s=>{let o=new RegExp(`${s}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return o?o[2]:void 0};return{id:r("id")??`marketplace:${e}`,recordType:r("recordType")??"*",event:r("event")??"before_save",source:r("source")??"standalone",sourceCode:t,extensionKind:n||"hook"}}async function GP(t){let e=Qe(se(process.cwd(),t),"public","turbobase.json"),n=await oe.readFile(e,"utf8").catch(()=>null);if(n===null)return null;let r;try{r=JSON.parse(n)}catch(s){v(`${e} is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}return(typeof r!="object"||r===null||Array.isArray(r))&&v(`${e} must be a JSON object.`),{manifest:r,manifestPath:e}}async function JP(){let t=se(process.cwd(),Gs,Sr),e;try{e=await oe.readFile(t,"utf8")}catch{v(`no config found \u2014 this project authors none (no ${Ys}/, ${Xs}/, ${Wt} or ${Gt}) and there is no ${Gs}/${Sr}.
3754
- Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return lp(e)}catch(n){v(`bundle is invalid: ${n instanceof Error?n.message:String(n)}`)}}async function Dd(){let t=process.cwd();if(!await pp(t))return JP();let e;try{e=await hp(t,{inline:oa})}catch(n){v(`could not build the config bundle from this project: ${n instanceof Error?n.message:String(n)}`)}for(let n of e.unparsed)L(`${n.file}: ${n.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 YP(t,e){y(`plan against ${e}:`);for(let n of t.add)y(` ${Kt.add(`${n.kind} ${n.id}`)}`);for(let n of t.change)y(` ${Kt.change(`${n.kind} ${n.id}`)}`);for(let n of t.destroy)y(` ${Kt.destroy(`${n.kind} ${n.id}`)}`);y(`
3755
- ${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 XP(t){try{let n=new URL(t).hostname.split(".")[0];return n&&n!=="localhost"?n:void 0}catch{return}}function vs(t,e,n){return new Promise(r=>{let s=zd(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...n}}),o="";s.stderr?.on("data",i=>{let a=i.toString();o+=a,process.stderr.write(a)}),s.on("error",i=>r({code:-1,stderr:i.message})),s.on("exit",i=>r({code:i??-1,stderr:o}))})}function Ud(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(n,r)=>{let s=r?t.replace(/\/[^/]*$/,`/${r}`):t,o=await vs("psql",[s,"-v","ON_ERROR_STOP=1","-c",n]);if(o.code!==0)throw new Error(`psql failed (exit ${o.code}): ${o.stderr.trim()}`)};return{target:()=>t,createDatabase:async n=>{await e(`CREATE DATABASE ${n};`)},replayMigrations:async n=>{let r=t.replace(/\/[^/]*$/,`/${n}`),s=await vs("supabase",["migration","up","--db-url",r]);if(s.code!==0)throw new Error(`supabase migration up failed (exit ${s.code}): ${s.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 n=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(n,r,s)=>{let o=Object.keys(s[0]??{});if(o.length===0)return;let i=s.map(a=>`(${o.map(l=>a[l]===null||a[l]===void 0?"NULL":`'${String(a[l]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${r} (${o.join(", ")}) VALUES ${i};`,n)},dropDatabase:async n=>{await e(`DROP DATABASE IF EXISTS ${n} WITH (FORCE);`)}}}async function ZP(t){let e=se(t,"src"),n={},r=async s=>{let o;try{o=await oe.readdir(s,{withFileTypes:!0})}catch{return}for(let i of o){let a=Qe(s,i.name);if(i.isDirectory())await r(a);else if(i.isFile()){let l=Ci(e,a).split(qd).join("/");n[l]=await oe.readFile(a,"utf8")}}};return await r(e),n}function Md(t){return new Promise(e=>{let n=zd("git",t,{stdio:["ignore","pipe","ignore"]}),r="";n.stdout?.on("data",s=>{r+=s.toString()}),n.on("error",()=>e(null)),n.on("exit",s=>e(s===0&&r.trim()?r.trim():null))})}var QP=!1;QP&&Bd().parseAsync(process.argv).catch(t=>v(t instanceof Error?t.message:String(t)));Bd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3764
+ turbobase release status ${C.releaseId} --follow`)}catch(C){C instanceof Z&&C.status===403&&v("an approved target needs --approved-by (the deploy gate fails closed)."),C instanceof Z&&C.status===409&&v("that solution already has an active release \u2014 roll it back or wait for it."),G(C,"releases:write","push a release"),v(`release push failed: ${C instanceof Error?C.message:String(C)}`)}}),Pr.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x});if(m.follow){await va(()=>_.releaseStatus(d),`release ${d}`,m.intervalMs);return}let g;try{g=await _.releaseStatus(d)}catch(T){G(T,"releases:write","release status"),T instanceof Z&&T.status===404&&v(`release ${d} not found.`),v(`release status failed: ${T instanceof Error?T.message:String(T)}`)}b(`release ${d}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&b(g.outputTail.replace(/\n+$/,""))}),Pr.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,m)=>{let{baseUrl:w,token:x}=await V(m.baseUrl),_=new z({baseUrl:w,token:x}),g;try{g=await _.releaseRollback(d)}catch(T){G(T,"releases:write","release rollback"),T instanceof Z&&T.status===404&&v(`release ${d} not found.`),T instanceof Z&&T.status===409&&v(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),v(`release rollback failed: ${T instanceof Error?T.message:String(T)}`)}b(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),Pr.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:m,token:w}=await V(d.baseUrl),x=new z({baseUrl:m,token:w}),_;try{_=await x.releaseList()}catch(g){G(g,"releases:write","release list"),v(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(_.length===0){b("no releases.");return}if(Pe())b(ht(_.map(g=>[g.id,Nr(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(T=>`"${T}"`).join(", "):h.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of _){let T=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";b(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${T}`)}b(`
3765
+ ${_.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:m,token:w}=await V(d.baseUrl),x=new z({baseUrl:m,token:w}),_=d.limit?Number(d.limit):void 0,g=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await Qu(x,d.conduit,{...d.follow?{follow:!0}:{},..._!==void 0?{limit:_}:{},...g!==void 0?{intervalMs:g}:{},sink:b})}catch(T){v(`logs --conduit failed: ${T instanceof Error?T.message:String(T)}`)}return}if(d.extension){try{let T=await x.logs(d.extension,_);T.length===0&&b(`no logs for ${d.extension}.`);for(let E of T)b(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(T){v(`logs --extension failed: ${T instanceof Error?T.message:String(T)}`)}return}try{await tp(x,{...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}:{},..._!==void 0?{limit:_}:{},...g!==void 0?{intervalMs:g}:{},sink:b})}catch(T){v(`logs failed: ${T instanceof Error?T.message:String(T)}`)}}),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:m}=await Promise.resolve().then(()=>(Sb(),_b));await m({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(`
3766
+ `)),t&&void 0,e}function aA(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 lA(t){let e=Qe(oe(process.cwd(),t),"public","turbobase.json"),r=await se.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 cA(){let t=oe(process.cwd(),Jo,Sn),e;try{e=await se.readFile(t,"utf8")}catch{v(`no config found \u2014 this project authors none (no ${Xo}/, ${Zo}/, ${Wt} or ${Gt}) and there is no ${Jo}/${Sn}.
3767
+ Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return pp(e)}catch(r){v(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function Dd(){let t=process.cwd();if(!await gp(t))return cA();let e;try{e=await yp(t,{inline:sa})}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)L(`${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 dA(t,e){b(`plan against ${e}:`);for(let r of t.add)b(` ${Kt.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)b(` ${Kt.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)b(` ${Kt.destroy(`${r.kind} ${r.id}`)}`);b(`
3768
+ ${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 uA(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function _o(t,e,r){return new Promise(n=>{let o=zd(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 Ud(){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 _o("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 _o("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(l=>a[l]===null||a[l]===void 0?"NULL":`'${String(a[l]).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 pA(t){let e=oe(t,"src"),r={},n=async o=>{let s;try{s=await se.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=Qe(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let l=Ii(e,a).split(qd).join("/");r[l]=await se.readFile(a,"utf8")}}};return await n(e),r}function Md(t){return new Promise(e=>{let r=zd("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 mA=!1;mA&&Bd().parseAsync(process.argv).catch(t=>v(t instanceof Error?t.message:String(t)));Bd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3756
3769
  `),process.exit(1)});