@turbobase/cli 1.4.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/turbobase.js CHANGED
@@ -1,7 +1,7 @@
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 Lb=Object.create;var Si=Object.defineProperty;var jb=Object.getOwnPropertyDescriptor;var Ub=Object.getOwnPropertyNames;var Db=Object.getPrototypeOf,qb=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$d=(t,e)=>{for(var n in e)Si(t,n,{get:e[n],enumerable:!0})},zb=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ub(e))!qb.call(t,s)&&s!==n&&Si(t,s,{get:()=>e[s],enumerable:!(r=jb(e,s))||r.enumerable});return t};var xd=(t,e,n)=>(n=t!=null?Lb(Db(t)):{},zb(e||!t||!t.__esModule?Si(n,"default",{value:t,enumerable:!0}):n,t));function pr(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ws=j(()=>{});import{z as cn}from"zod";function vs(t){let e=_i.safeParse(t);return e.success?(e.data.inputs??[]).filter(n=>n.type==="connection"):[]}function $i(t,e){let n=_i.safeParse(t);if(!n.success)throw new Dt(`invalid manifest: ${n.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(Td.test(e))throw new Dt('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(Td.test(r))throw new Dt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Rd,Ed,_i,Dt,Td,Pd=j(()=>{Rd=cn.object({type:cn.literal("connection"),source_system:cn.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:cn.string().min(1).max(200).optional()}),Ed=cn.discriminatedUnion("type",[Rd]),_i=cn.object({inputs:cn.array(Ed).optional()}).passthrough(),Dt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Td=/\bconnection[_-]?id\b["']?\s*[:=]/i});var ks,xi=j(()=>{ks=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Ue}from"zod";var Ti,Ad,Id=j(()=>{ws();xi();Ti=Ue.object({id:Ue.string().min(1,"hook id must be non-empty"),recordType:Ue.union([Ue.string().min(1),Ue.array(Ue.string().min(1)).min(1),Ue.literal("*")]),event:Ue.enum(ks),source:Ue.string().min(1).optional(),when:Ue.unknown().optional(),run:Ue.unknown(),failClosed:Ue.boolean().optional(),timeoutMs:Ue.number().int().positive().optional(),description:Ue.string().optional(),systemReserved:Ue.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"})}),Ad=pr({kind:"hook",schema:Ti,factoryName:"defineHook"})});var Cd=j(()=>{Id();xi()});var Ss,Ri=j(()=>{Ss=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as Re}from"zod";var Ei,Od,Nd=j(()=>{ws();Ri();Ei=Re.object({id:Re.string().min(1,"conduit id must be non-empty"),on:Re.enum(Ss),from:Re.object({source:Re.string().min(1,"from.source must be non-empty"),recordType:Re.string().min(1,"from.recordType must be non-empty"),when:Re.unknown().optional()}),to:Re.object({source:Re.string().min(1,"to.source must be non-empty"),recordType:Re.string().min(1,"to.recordType must be non-empty")}),mode:Re.enum(["dual-bind","one-shot"]).optional(),transform:Re.unknown(),idempotencyKey:Re.unknown().optional(),cycleBudget:Re.number().int().positive().optional(),conflictStrategy:Re.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:Re.number().int().positive().optional(),description:Re.string().optional(),systemReserved:Re.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let n=t.from?.when;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let r=t.idempotencyKey;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let s=t.from,o=t.to;s?.source&&o?.source&&s.source===o.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"})}),Od=pr({kind:"conduit",schema:Ei,factoryName:"defineConduit"})});var Ld=j(()=>{Nd();Ri()});async function Kb(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 _s(t,e={}){return(e.transform??Kb)(t)}var Pi=j(()=>{});function Ai(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 jd(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Ii(t){return`${jd(t.source)}${jd(t.recordType)}`}function Vb(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.description&&e.push(t.description),e.join(" \xB7 ")}function Ci(t){let e=Ii(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]} */`:`/**
4
+ var Lb=Object.create;var Si=Object.defineProperty;var jb=Object.getOwnPropertyDescriptor;var Ub=Object.getOwnPropertyNames;var Db=Object.getPrototypeOf,qb=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var U=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),$d=(t,e)=>{for(var n in e)Si(t,n,{get:e[n],enumerable:!0})},zb=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ub(e))!qb.call(t,s)&&s!==n&&Si(t,s,{get:()=>e[s],enumerable:!(r=jb(e,s))||r.enumerable});return t};var xd=(t,e,n)=>(n=t!=null?Lb(Db(t)):{},zb(e||!t||!t.__esModule?Si(n,"default",{value:t,enumerable:!0}):n,t));function pr(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var ws=j(()=>{});import{z as ln}from"zod";function vs(t){let e=_i.safeParse(t);return e.success?(e.data.inputs??[]).filter(n=>n.type==="connection"):[]}function $i(t,e){let n=_i.safeParse(t);if(!n.success)throw new Dt(`invalid manifest: ${n.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(Td.test(e))throw new Dt('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(Td.test(r))throw new Dt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Rd,Ed,_i,Dt,Td,Pd=j(()=>{Rd=ln.object({type:ln.literal("connection"),source_system:ln.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:ln.string().min(1).max(200).optional()}),Ed=ln.discriminatedUnion("type",[Rd]),_i=ln.object({inputs:ln.array(Ed).optional()}).passthrough(),Dt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Td=/\bconnection[_-]?id\b["']?\s*[:=]/i});var ks,xi=j(()=>{ks=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Ue}from"zod";var Ti,Ad,Id=j(()=>{ws();xi();Ti=Ue.object({id:Ue.string().min(1,"hook id must be non-empty"),recordType:Ue.union([Ue.string().min(1),Ue.array(Ue.string().min(1)).min(1),Ue.literal("*")]),event:Ue.enum(ks),source:Ue.string().min(1).optional(),when:Ue.unknown().optional(),run:Ue.unknown(),failClosed:Ue.boolean().optional(),timeoutMs:Ue.number().int().positive().optional(),description:Ue.string().optional(),systemReserved:Ue.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"})}),Ad=pr({kind:"hook",schema:Ti,factoryName:"defineHook"})});var Cd=j(()=>{Id();xi()});var Ss,Ri=j(()=>{Ss=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as Re}from"zod";var Ei,Od,Nd=j(()=>{ws();Ri();Ei=Re.object({id:Re.string().min(1,"conduit id must be non-empty"),on:Re.enum(Ss),from:Re.object({source:Re.string().min(1,"from.source must be non-empty"),recordType:Re.string().min(1,"from.recordType must be non-empty"),when:Re.unknown().optional()}),to:Re.object({source:Re.string().min(1,"to.source must be non-empty"),recordType:Re.string().min(1,"to.recordType must be non-empty")}),mode:Re.enum(["dual-bind","one-shot"]).optional(),transform:Re.unknown(),idempotencyKey:Re.unknown().optional(),cycleBudget:Re.number().int().positive().optional(),conflictStrategy:Re.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:Re.number().int().positive().optional(),description:Re.string().optional(),systemReserved:Re.boolean().optional()}).superRefine((t,e)=>{typeof t.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"});let n=t.from?.when;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let r=t.idempotencyKey;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let s=t.from,o=t.to;s?.source&&o?.source&&s.source===o.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"})}),Od=pr({kind:"conduit",schema:Ei,factoryName:"defineConduit"})});var Ld=j(()=>{Nd();Ri()});async function Kb(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 _s(t,e={}){return(e.transform??Kb)(t)}var Pi=j(()=>{});function Ai(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 jd(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Ii(t){return`${jd(t.source)}${jd(t.recordType)}`}function Vb(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.description&&e.push(t.description),e.join(" \xB7 ")}function Ci(t){let e=Ii(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
5
  * ${n.join(`
6
6
  * `)}
7
7
  */`;if(t.columns.length===0)return`${r}
@@ -16,7 +16,7 @@ ${s.join(`
16
16
  }`}function $s(t){return[...t.records].sort((r,s)=>`${r.source}:${r.recordType}`.localeCompare(`${s.source}:${s.recordType}`)).map(Ci).join(`
17
17
 
18
18
  `)}function Ud(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 Wb(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Oi(t){let e=Ud(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` ${Wb(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 Ni=j(()=>{});function Jb(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Dd(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 qt(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let n=Jb(t.baseUrl),r=await Dd(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=$s(r),o=[Yb,"// ----- Record shapes (from /v1/catalog/records) -----",s,"// ----- Keyset seek keys (derived from column nullability) -----",Oi(r)];if(!t.recordsOnly){let i=await Dd(n.openapi,t.token,e),a=await _s(i,t.openApi);o.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return o.join(`
19
+ `)}var Ni=j(()=>{});function Jb(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Dd(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 cn(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let n=Jb(t.baseUrl),r=await Dd(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=$s(r),o=[Yb,"// ----- Record shapes (from /v1/catalog/records) -----",s,"// ----- Keyset seek keys (derived from column nullability) -----",Oi(r)];if(!t.recordsOnly){let i=await Dd(n.openapi,t.token,e),a=await _s(i,t.openApi);o.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return o.join(`
20
20
 
21
21
  `)+`
22
22
  `}var Yb,qd=j(()=>{Pi();Ni();Ni();Pi();Yb=["/**"," * 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(`
@@ -94,7 +94,7 @@ ${s.join(`
94
94
  export const defineHook = (def) => def;
95
95
  export const defineConduit = (def) => def;
96
96
  export default defineHook;
97
- `,Mi=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};ry=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 Fi}from"node:fs";import{join as cy}from"node:path";function dy(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 uy(t,e,n){let r=e.name??n,s=e.expect??"pass";try{let{effects:o}=await gr(t,dy(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 Ps(t,e){let n=await Es(t),r=[];for(let s=0;s<e.length;s+=1)r.push(await uy(n,e[s],`sample[${s}]`));return r}async function br(t){let e;try{e=await Fi.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 Fi.readFile(cy(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 yr(t){return Fi.readFile(t,"utf8")}var Hi=j(()=>{Bi()});function Bt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function By(t){let e=t.recordType;if(!e)throw new nt("record type is required (e.g. --record=salesOrder)");let n=t.event??"before_save",r=t.template??"require-field",s=t.source,o=s?`
97
+ `,Mi=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};ry=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 Fi}from"node:fs";import{join as cy}from"node:path";function dy(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 uy(t,e,n){let r=e.name??n,s=e.expect??"pass";try{let{effects:o}=await gr(t,dy(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 Ps(t,e){let n=await Es(t),r=[];for(let s=0;s<e.length;s+=1)r.push(await uy(n,e[s],`sample[${s}]`));return r}async function br(t){let e;try{e=await Fi.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 Fi.readFile(cy(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 yr(t){return Fi.readFile(t,"utf8")}var Hi=j(()=>{Bi()});function Mt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function By(t){let e=t.recordType;if(!e)throw new nt("record type is required (e.g. --record=salesOrder)");let n=t.event??"before_save",r=t.template??"require-field",s=t.source,o=s?`
98
98
  source: ${JSON.stringify(s)},`:"",i,a;if(r==="blank")i=`
99
99
  run: (ctx) => {
100
100
  // Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
@@ -119,7 +119,7 @@ export default defineHook;
119
119
  message: ${JSON.stringify(`${_} does not match expected format`)},
120
120
  });
121
121
  }
122
- },`,a=`enforce-format-${_}`}else throw new nt(`unsupported template: ${r}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${Bt(t.regex).slice(0,24)}`:""}`,p=`/**
122
+ },`,a=`enforce-format-${_}`}else throw new nt(`unsupported template: ${r}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${Mt(t.regex).slice(0,24)}`:""}`,p=`/**
123
123
  * ${t.description??`${a} on ${e}.${n}`}
124
124
  *
125
125
  * Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
@@ -132,7 +132,7 @@ export default defineHook<Record<string, unknown>>({
132
132
  recordType: ${JSON.stringify(e)},
133
133
  event: ${JSON.stringify(n)},${o}${i}
134
134
  });
135
- `;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:p}}function Fy(t){let e=t.recordType;if(!e)throw new nt("record type is required (e.g. --record=order)");let n=t.source;if(!n)throw new nt("--source is required (the origin source, e.g. --source=shopify)");let r=t.to;if(!r)throw new nt("--to is required (the target source, e.g. --to=netsuite)");if(n===r)throw new nt(`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??`${Bt(n)}2${Bt(r)}:${Bt(e)}`,l=`/**
135
+ `;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:p}}function Fy(t){let e=t.recordType;if(!e)throw new nt("record type is required (e.g. --record=order)");let n=t.source;if(!n)throw new nt("--source is required (the origin source, e.g. --source=shopify)");let r=t.to;if(!r)throw new nt("--to is required (the target source, e.g. --to=netsuite)");if(n===r)throw new nt(`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??`${Mt(n)}2${Mt(r)}:${Mt(e)}`,l=`/**
136
136
  * ${t.description??`Bridge ${n} ${e} \u2192 ${r} ${s} (${o}).`}
137
137
  *
138
138
  * Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
@@ -175,7 +175,7 @@ export default defineConduit<Record<string, unknown>>({
175
175
  },
176
176
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
177
177
  });
178
- `;return{relativePath:`conduits/${Bt(n)}-${Bt(e)}-to-${Bt(r)}-${Bt(s)}.ts`,content:l}}function Ft(t,e){let n=Hy[t];if(!n)throw new nt(`unknown extension kind '${t}'. Scaffoldable kinds: ${bu.join(", ")}.`);return n(e)}var bu,nt,Hy,Ns=j(()=>{bu=["hook","conduit"];nt=class extends Error{};Hy={hook:By,conduit:Fy}});function Bv(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 Fv(t){return Ap[Bv(t)%Ap.length]}function Hv(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 Ip(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Cp(t,e){let[n,r]=Fv(t),s=Ip(Hv(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Ip(e)}">
178
+ `;return{relativePath:`conduits/${Mt(n)}-${Mt(e)}-to-${Mt(r)}-${Mt(s)}.ts`,content:l}}function Bt(t,e){let n=Hy[t];if(!n)throw new nt(`unknown extension kind '${t}'. Scaffoldable kinds: ${bu.join(", ")}.`);return n(e)}var bu,nt,Hy,Ns=j(()=>{bu=["hook","conduit"];nt=class extends Error{};Hy={hook:By,conduit:Fy}});function Bv(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 Fv(t){return Ap[Bv(t)%Ap.length]}function Hv(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 Ip(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Cp(t,e){let[n,r]=Fv(t),s=Ip(Hv(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Ip(e)}">
179
179
  <defs>
180
180
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
181
181
  <stop offset="0" stop-color="${n}"/>
@@ -1762,23 +1762,23 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
1762
1762
  Label.displayName = 'Label';
1763
1763
 
1764
1764
  export { Label };
1765
- `});import*as Xp from"zod/v3";import*as pn from"zod/v4-mini";function kt(t){return!!t._zod}function hn(t){let e=Object.values(t);if(e.length===0)return pn.object({});let n=e.every(kt),r=e.every(s=>!kt(s));if(n)return pn.object(t);if(r)return Xp.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Vt(t,e){return kt(t)?pn.safeParse(t,e):t.safeParse(e)}async function Ws(t,e){return kt(t)?await pn.safeParseAsync(t,e):await t.safeParseAsync(e)}function Gt(t){if(!t)return;let e;if(kt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Dn(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 hn(t)}}if(kt(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 tk(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function Js(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 ${tk(e.path)}`:e.message).join(`
1766
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function eh(t){return t.description}function th(t){if(kt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function qn(t){if(kt(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 Er=j(()=>{});import*as c from"zod/v4";function yh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function wh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var wa,nh,Wt,Zs,xe,rh,sh,mI,nk,rk,va,Ze,Pr,oh,Pe,rt,st,Ae,Qs,ih,ka,ah,lh,Sa,Ar,F,_a,ch,dh,gI,Xs,sk,eo,ok,Ir,zn,uh,ik,ak,lk,ck,dk,uk,$a,pk,hk,xa,to,fk,mk,no,gk,Cr,Or,bk,Nr,Mn,yk,Lr,ro,so,oo,bI,io,ao,lo,ph,hh,fh,Ta,mh,jr,Bn,gh,wk,co,vk,uo,kk,Ra,Sk,po,_k,$k,xk,Tk,Rk,Ek,Pk,Ak,Ik,Ck,ho,Ok,Nk,fo,Ea,Pa,Aa,Lk,jk,Uk,Ia,Dk,qk,zk,Mk,Bk,bh,mo,Fk,go,yI,Hk,Fn,Kk,wI,Ur,Vk,Ca,Gk,Wk,Jk,Yk,Zk,Qk,Xk,Ys,eS,tS,nS,Dr,Oa,rS,sS,oS,iS,aS,lS,cS,dS,uS,pS,hS,fS,mS,gS,bS,yS,wS,vS,Hn,kS,SS,_S,bo,$S,xS,TS,Na,RS,vI,kI,SI,_I,$I,xI,q,ya,Kn=j(()=>{wa="2025-11-25",nh=[wa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Wt="io.modelcontextprotocol/related-task",Zs="2.0",xe=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),rh=c.union([c.string(),c.number().int()]),sh=c.string(),mI=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),nk=c.object({ttl:c.number().optional()}),rk=c.object({taskId:c.string()}),va=c.looseObject({progressToken:rh.optional(),[Wt]:rk.optional()}),Ze=c.object({_meta:va.optional()}),Pr=Ze.extend({task:nk.optional()}),oh=t=>Pr.safeParse(t).success,Pe=c.object({method:c.string(),params:Ze.loose().optional()}),rt=c.object({_meta:va.optional()}),st=c.object({method:c.string(),params:rt.loose().optional()}),Ae=c.looseObject({_meta:va.optional()}),Qs=c.union([c.string(),c.number().int()]),ih=c.object({jsonrpc:c.literal(Zs),id:Qs,...Pe.shape}).strict(),ka=t=>ih.safeParse(t).success,ah=c.object({jsonrpc:c.literal(Zs),...st.shape}).strict(),lh=t=>ah.safeParse(t).success,Sa=c.object({jsonrpc:c.literal(Zs),id:Qs,result:Ae}).strict(),Ar=t=>Sa.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"})(F||(F={}));_a=c.object({jsonrpc:c.literal(Zs),id:Qs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),ch=t=>_a.safeParse(t).success,dh=c.union([ih,ah,Sa,_a]),gI=c.union([Sa,_a]),Xs=Ae.strict(),sk=rt.extend({requestId:Qs.optional(),reason:c.string().optional()}),eo=st.extend({method:c.literal("notifications/cancelled"),params:sk}),ok=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Ir=c.object({icons:c.array(ok).optional()}),zn=c.object({name:c.string(),title:c.string().optional()}),uh=zn.extend({...zn.shape,...Ir.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),ik=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),ak=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:ik.optional(),url:xe.optional()}),c.record(c.string(),c.unknown()).optional())),lk=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:xe.optional()}).optional(),elicitation:c.looseObject({create:xe.optional()}).optional()}).optional()}),ck=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({tools:c.looseObject({call:xe.optional()}).optional()}).optional()}),dk=c.object({experimental:c.record(c.string(),xe).optional(),sampling:c.object({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:ak.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:lk.optional(),extensions:c.record(c.string(),xe).optional()}),uk=Ze.extend({protocolVersion:c.string(),capabilities:dk,clientInfo:uh}),$a=Pe.extend({method:c.literal("initialize"),params:uk}),pk=c.object({experimental:c.record(c.string(),xe).optional(),logging:xe.optional(),completions:xe.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:ck.optional(),extensions:c.record(c.string(),xe).optional()}),hk=Ae.extend({protocolVersion:c.string(),capabilities:pk,serverInfo:uh,instructions:c.string().optional()}),xa=st.extend({method:c.literal("notifications/initialized"),params:rt.optional()}),to=Pe.extend({method:c.literal("ping"),params:Ze.optional()}),fk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),mk=c.object({...rt.shape,...fk.shape,progressToken:rh}),no=st.extend({method:c.literal("notifications/progress"),params:mk}),gk=Ze.extend({cursor:sh.optional()}),Cr=Pe.extend({params:gk.optional()}),Or=Ae.extend({nextCursor:sh.optional()}),bk=c.enum(["working","input_required","completed","failed","cancelled"]),Nr=c.object({taskId:c.string(),status:bk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Mn=Ae.extend({task:Nr}),yk=rt.merge(Nr),Lr=st.extend({method:c.literal("notifications/tasks/status"),params:yk}),ro=Pe.extend({method:c.literal("tasks/get"),params:Ze.extend({taskId:c.string()})}),so=Ae.merge(Nr),oo=Pe.extend({method:c.literal("tasks/result"),params:Ze.extend({taskId:c.string()})}),bI=Ae.loose(),io=Cr.extend({method:c.literal("tasks/list")}),ao=Or.extend({tasks:c.array(Nr)}),lo=Pe.extend({method:c.literal("tasks/cancel"),params:Ze.extend({taskId:c.string()})}),ph=Ae.merge(Nr),hh=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),fh=hh.extend({text:c.string()}),Ta=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),mh=hh.extend({blob:Ta}),jr=c.enum(["user","assistant"]),Bn=c.object({audience:c.array(jr).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),gh=c.object({...zn.shape,...Ir.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Bn.optional(),_meta:c.optional(c.looseObject({}))}),wk=c.object({...zn.shape,...Ir.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Bn.optional(),_meta:c.optional(c.looseObject({}))}),co=Cr.extend({method:c.literal("resources/list")}),vk=Or.extend({resources:c.array(gh)}),uo=Cr.extend({method:c.literal("resources/templates/list")}),kk=Or.extend({resourceTemplates:c.array(wk)}),Ra=Ze.extend({uri:c.string()}),Sk=Ra,po=Pe.extend({method:c.literal("resources/read"),params:Sk}),_k=Ae.extend({contents:c.array(c.union([fh,mh]))}),$k=st.extend({method:c.literal("notifications/resources/list_changed"),params:rt.optional()}),xk=Ra,Tk=Pe.extend({method:c.literal("resources/subscribe"),params:xk}),Rk=Ra,Ek=Pe.extend({method:c.literal("resources/unsubscribe"),params:Rk}),Pk=rt.extend({uri:c.string()}),Ak=st.extend({method:c.literal("notifications/resources/updated"),params:Pk}),Ik=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),Ck=c.object({...zn.shape,...Ir.shape,description:c.optional(c.string()),arguments:c.optional(c.array(Ik)),_meta:c.optional(c.looseObject({}))}),ho=Cr.extend({method:c.literal("prompts/list")}),Ok=Or.extend({prompts:c.array(Ck)}),Nk=Ze.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),fo=Pe.extend({method:c.literal("prompts/get"),params:Nk}),Ea=c.object({type:c.literal("text"),text:c.string(),annotations:Bn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Pa=c.object({type:c.literal("image"),data:Ta,mimeType:c.string(),annotations:Bn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Aa=c.object({type:c.literal("audio"),data:Ta,mimeType:c.string(),annotations:Bn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Lk=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()}),jk=c.object({type:c.literal("resource"),resource:c.union([fh,mh]),annotations:Bn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Uk=gh.extend({type:c.literal("resource_link")}),Ia=c.union([Ea,Pa,Aa,Uk,jk]),Dk=c.object({role:jr,content:Ia}),qk=Ae.extend({description:c.string().optional(),messages:c.array(Dk)}),zk=st.extend({method:c.literal("notifications/prompts/list_changed"),params:rt.optional()}),Mk=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Bk=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),bh=c.object({...zn.shape,...Ir.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),xe).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),xe).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:Mk.optional(),execution:Bk.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),mo=Cr.extend({method:c.literal("tools/list")}),Fk=Or.extend({tools:c.array(bh)}),go=Ae.extend({content:c.array(Ia).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),yI=go.or(Ae.extend({toolResult:c.unknown()})),Hk=Pr.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Fn=Pe.extend({method:c.literal("tools/call"),params:Hk}),Kk=st.extend({method:c.literal("notifications/tools/list_changed"),params:rt.optional()}),wI=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Ur=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Vk=Ze.extend({level:Ur}),Ca=Pe.extend({method:c.literal("logging/setLevel"),params:Vk}),Gk=rt.extend({level:Ur,logger:c.string().optional(),data:c.unknown()}),Wk=st.extend({method:c.literal("notifications/message"),params:Gk}),Jk=c.object({name:c.string().optional()}),Yk=c.object({hints:c.array(Jk).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()}),Zk=c.object({mode:c.enum(["auto","required","none"]).optional()}),Qk=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Ia).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Xk=c.discriminatedUnion("type",[Ea,Pa,Aa]),Ys=c.discriminatedUnion("type",[Ea,Pa,Aa,Lk,Qk]),eS=c.object({role:jr,content:c.union([Ys,c.array(Ys)]),_meta:c.record(c.string(),c.unknown()).optional()}),tS=Pr.extend({messages:c.array(eS),modelPreferences:Yk.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:xe.optional(),tools:c.array(bh).optional(),toolChoice:Zk.optional()}),nS=Pe.extend({method:c.literal("sampling/createMessage"),params:tS}),Dr=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:jr,content:Xk}),Oa=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:jr,content:c.union([Ys,c.array(Ys)])}),rS=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),sS=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()}),oS=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()}),iS=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),aS=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()}),lS=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()}),cS=c.union([iS,aS]),dS=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()}),uS=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()}),pS=c.union([dS,uS]),hS=c.union([lS,cS,pS]),fS=c.union([hS,rS,sS,oS]),mS=Pr.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),fS),required:c.array(c.string()).optional()})}),gS=Pr.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),bS=c.union([mS,gS]),yS=Pe.extend({method:c.literal("elicitation/create"),params:bS}),wS=rt.extend({elicitationId:c.string()}),vS=st.extend({method:c.literal("notifications/elicitation/complete"),params:wS}),Hn=Ae.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())}),kS=c.object({type:c.literal("ref/resource"),uri:c.string()}),SS=c.object({type:c.literal("ref/prompt"),name:c.string()}),_S=Ze.extend({ref:c.union([SS,kS]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),bo=Pe.extend({method:c.literal("completion/complete"),params:_S});$S=Ae.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),xS=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),TS=Pe.extend({method:c.literal("roots/list"),params:Ze.optional()}),Na=Ae.extend({roots:c.array(xS)}),RS=st.extend({method:c.literal("notifications/roots/list_changed"),params:rt.optional()}),vI=c.union([to,$a,bo,Ca,fo,ho,co,uo,po,Tk,Ek,Fn,mo,ro,oo,io,lo]),kI=c.union([eo,no,xa,RS,Lr]),SI=c.union([Xs,Dr,Oa,Hn,Na,so,ao,Mn]),_I=c.union([to,nS,yS,TS,ro,oo,io,lo]),$I=c.union([eo,no,Wk,Ak,$k,Kk,zk,Lr,vS]),xI=c.union([Xs,hk,$S,qk,Ok,vk,kk,_k,go,Fk,so,ao,Mn]),q=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===F.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new ya(s.elicitations,n)}return new t(e,n,r)}},ya=class extends q{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(F.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Jt(t){return t==="completed"||t==="failed"||t==="cancelled"}var vh=j(()=>{});var Sh,kh,_h,yo=j(()=>{Sh=Symbol("Let zodToJsonSchema decide on which parser to use"),kh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},_h=t=>typeof t=="string"?{...kh,name:t}:{...kh,...t}});var $h,La=j(()=>{yo();$h=t=>{let e=_h(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 ja(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ae(t,e,n,r,s){t[e]=n,ja(t,e,r,s)}var Yt=j(()=>{});var wo,vo=j(()=>{wo=(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 we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?wo(e,t.currentPath):e.join("/")}}var ot=j(()=>{vo()});import{ZodFirstPartyTypeKind as ES}from"zod/v3";function xh(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ES.ZodAny&&(n.items=G(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(n,"minItems",t.exactLength.value,t.exactLength.message,e),ae(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var Ua=j(()=>{Yt();$e()});function Th(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?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}var Da=j(()=>{Yt()});function Rh(){return{type:"boolean"}}var qa=j(()=>{});function ko(t,e){return G(t.type._def,e)}var So=j(()=>{$e()});var Eh,za=j(()=>{$e();Eh=(t,e)=>G(t.innerType._def,e)});function Ma(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>Ma(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 PS(t,e)}}var PS,Ba=j(()=>{Yt();PS=(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":ae(n,"minimum",r.value,r.message,e);break;case"max":ae(n,"maximum",r.value,r.message,e);break}return n}});function Ph(t,e){return{...G(t.innerType._def,e),default:t.defaultValue()}}var Fa=j(()=>{$e()});function Ah(t,e){return e.effectStrategy==="input"?G(t.schema._def,e):we(e)}var Ha=j(()=>{$e();ot()});function Ih(t){return{type:"string",enum:Array.from(t.values)}}var Ka=j(()=>{});function Ch(t,e){let n=[G(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),G(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(AS(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 AS,Va=j(()=>{$e();AS=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Oh(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 Ga=j(()=>{});function _o(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ae(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":ft(n,"email",r.message,e);break;case"format:idn-email":ft(n,"idn-email",r.message,e);break;case"pattern:zod":ze(n,ht.email,r.message,e);break}break;case"url":ft(n,"uri",r.message,e);break;case"uuid":ft(n,"uuid",r.message,e);break;case"regex":ze(n,r.regex,r.message,e);break;case"cuid":ze(n,ht.cuid,r.message,e);break;case"cuid2":ze(n,ht.cuid2,r.message,e);break;case"startsWith":ze(n,RegExp(`^${Ja(r.value,e)}`),r.message,e);break;case"endsWith":ze(n,RegExp(`${Ja(r.value,e)}$`),r.message,e);break;case"datetime":ft(n,"date-time",r.message,e);break;case"date":ft(n,"date",r.message,e);break;case"time":ft(n,"time",r.message,e);break;case"duration":ft(n,"duration",r.message,e);break;case"length":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{ze(n,RegExp(Ja(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&ft(n,"ipv4",r.message,e),r.version!=="v4"&&ft(n,"ipv6",r.message,e);break}case"base64url":ze(n,ht.base64url,r.message,e);break;case"jwt":ze(n,ht.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&ze(n,ht.ipv4Cidr,r.message,e),r.version!=="v4"&&ze(n,ht.ipv6Cidr,r.message,e);break}case"emoji":ze(n,ht.emoji(),r.message,e);break;case"ulid":{ze(n,ht.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ft(n,"binary",r.message,e);break}case"contentEncoding:base64":{ae(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{ze(n,ht.base64,r.message,e);break}}break}case"nanoid":ze(n,ht.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Ja(t,e){return e.patternStrategy==="escape"?CS(t):t}function CS(t){let e="";for(let n=0;n<t.length;n++)IS.has(t[n])||(e+="\\"),e+=t[n];return e}function ft(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}}})):ae(t,"format",e,n,r)}function ze(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:Nh(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(t,"pattern",Nh(e,r),n,r)}function Nh(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
1765
+ `});import*as Xp from"zod/v3";import*as pn from"zod/v4-mini";function kt(t){return!!t._zod}function hn(t){let e=Object.values(t);if(e.length===0)return pn.object({});let n=e.every(kt),r=e.every(s=>!kt(s));if(n)return pn.object(t);if(r)return Xp.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Kt(t,e){return kt(t)?pn.safeParse(t,e):t.safeParse(e)}async function Ws(t,e){return kt(t)?await pn.safeParseAsync(t,e):await t.safeParseAsync(e)}function Vt(t){if(!t)return;let e;if(kt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Dn(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 hn(t)}}if(kt(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 tk(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function Js(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 ${tk(e.path)}`:e.message).join(`
1766
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function eh(t){return t.description}function th(t){if(kt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function qn(t){if(kt(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 Er=j(()=>{});import*as c from"zod/v4";function yh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function wh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var wa,nh,Gt,Zs,xe,rh,sh,fI,nk,rk,va,Ze,Pr,oh,Pe,rt,st,Ae,Qs,ih,ka,ah,lh,Sa,Ar,F,_a,ch,dh,mI,Xs,sk,eo,ok,Ir,zn,uh,ik,ak,lk,ck,dk,uk,$a,pk,hk,xa,to,fk,mk,no,gk,Cr,Or,bk,Nr,Mn,yk,Lr,ro,so,oo,gI,io,ao,lo,ph,hh,fh,Ta,mh,jr,Bn,gh,wk,co,vk,uo,kk,Ra,Sk,po,_k,$k,xk,Tk,Rk,Ek,Pk,Ak,Ik,Ck,ho,Ok,Nk,fo,Ea,Pa,Aa,Lk,jk,Uk,Ia,Dk,qk,zk,Mk,Bk,bh,mo,Fk,go,bI,Hk,Fn,Kk,yI,Ur,Vk,Ca,Gk,Wk,Jk,Yk,Zk,Qk,Xk,Ys,eS,tS,nS,Dr,Oa,rS,sS,oS,iS,aS,lS,cS,dS,uS,pS,hS,fS,mS,gS,bS,yS,wS,vS,Hn,kS,SS,_S,bo,$S,xS,TS,Na,RS,wI,vI,kI,SI,_I,$I,q,ya,Kn=j(()=>{wa="2025-11-25",nh=[wa,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Gt="io.modelcontextprotocol/related-task",Zs="2.0",xe=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),rh=c.union([c.string(),c.number().int()]),sh=c.string(),fI=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),nk=c.object({ttl:c.number().optional()}),rk=c.object({taskId:c.string()}),va=c.looseObject({progressToken:rh.optional(),[Gt]:rk.optional()}),Ze=c.object({_meta:va.optional()}),Pr=Ze.extend({task:nk.optional()}),oh=t=>Pr.safeParse(t).success,Pe=c.object({method:c.string(),params:Ze.loose().optional()}),rt=c.object({_meta:va.optional()}),st=c.object({method:c.string(),params:rt.loose().optional()}),Ae=c.looseObject({_meta:va.optional()}),Qs=c.union([c.string(),c.number().int()]),ih=c.object({jsonrpc:c.literal(Zs),id:Qs,...Pe.shape}).strict(),ka=t=>ih.safeParse(t).success,ah=c.object({jsonrpc:c.literal(Zs),...st.shape}).strict(),lh=t=>ah.safeParse(t).success,Sa=c.object({jsonrpc:c.literal(Zs),id:Qs,result:Ae}).strict(),Ar=t=>Sa.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"})(F||(F={}));_a=c.object({jsonrpc:c.literal(Zs),id:Qs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),ch=t=>_a.safeParse(t).success,dh=c.union([ih,ah,Sa,_a]),mI=c.union([Sa,_a]),Xs=Ae.strict(),sk=rt.extend({requestId:Qs.optional(),reason:c.string().optional()}),eo=st.extend({method:c.literal("notifications/cancelled"),params:sk}),ok=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Ir=c.object({icons:c.array(ok).optional()}),zn=c.object({name:c.string(),title:c.string().optional()}),uh=zn.extend({...zn.shape,...Ir.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),ik=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),ak=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:ik.optional(),url:xe.optional()}),c.record(c.string(),c.unknown()).optional())),lk=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:xe.optional()}).optional(),elicitation:c.looseObject({create:xe.optional()}).optional()}).optional()}),ck=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({tools:c.looseObject({call:xe.optional()}).optional()}).optional()}),dk=c.object({experimental:c.record(c.string(),xe).optional(),sampling:c.object({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:ak.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:lk.optional(),extensions:c.record(c.string(),xe).optional()}),uk=Ze.extend({protocolVersion:c.string(),capabilities:dk,clientInfo:uh}),$a=Pe.extend({method:c.literal("initialize"),params:uk}),pk=c.object({experimental:c.record(c.string(),xe).optional(),logging:xe.optional(),completions:xe.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:ck.optional(),extensions:c.record(c.string(),xe).optional()}),hk=Ae.extend({protocolVersion:c.string(),capabilities:pk,serverInfo:uh,instructions:c.string().optional()}),xa=st.extend({method:c.literal("notifications/initialized"),params:rt.optional()}),to=Pe.extend({method:c.literal("ping"),params:Ze.optional()}),fk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),mk=c.object({...rt.shape,...fk.shape,progressToken:rh}),no=st.extend({method:c.literal("notifications/progress"),params:mk}),gk=Ze.extend({cursor:sh.optional()}),Cr=Pe.extend({params:gk.optional()}),Or=Ae.extend({nextCursor:sh.optional()}),bk=c.enum(["working","input_required","completed","failed","cancelled"]),Nr=c.object({taskId:c.string(),status:bk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Mn=Ae.extend({task:Nr}),yk=rt.merge(Nr),Lr=st.extend({method:c.literal("notifications/tasks/status"),params:yk}),ro=Pe.extend({method:c.literal("tasks/get"),params:Ze.extend({taskId:c.string()})}),so=Ae.merge(Nr),oo=Pe.extend({method:c.literal("tasks/result"),params:Ze.extend({taskId:c.string()})}),gI=Ae.loose(),io=Cr.extend({method:c.literal("tasks/list")}),ao=Or.extend({tasks:c.array(Nr)}),lo=Pe.extend({method:c.literal("tasks/cancel"),params:Ze.extend({taskId:c.string()})}),ph=Ae.merge(Nr),hh=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),fh=hh.extend({text:c.string()}),Ta=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),mh=hh.extend({blob:Ta}),jr=c.enum(["user","assistant"]),Bn=c.object({audience:c.array(jr).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),gh=c.object({...zn.shape,...Ir.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Bn.optional(),_meta:c.optional(c.looseObject({}))}),wk=c.object({...zn.shape,...Ir.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Bn.optional(),_meta:c.optional(c.looseObject({}))}),co=Cr.extend({method:c.literal("resources/list")}),vk=Or.extend({resources:c.array(gh)}),uo=Cr.extend({method:c.literal("resources/templates/list")}),kk=Or.extend({resourceTemplates:c.array(wk)}),Ra=Ze.extend({uri:c.string()}),Sk=Ra,po=Pe.extend({method:c.literal("resources/read"),params:Sk}),_k=Ae.extend({contents:c.array(c.union([fh,mh]))}),$k=st.extend({method:c.literal("notifications/resources/list_changed"),params:rt.optional()}),xk=Ra,Tk=Pe.extend({method:c.literal("resources/subscribe"),params:xk}),Rk=Ra,Ek=Pe.extend({method:c.literal("resources/unsubscribe"),params:Rk}),Pk=rt.extend({uri:c.string()}),Ak=st.extend({method:c.literal("notifications/resources/updated"),params:Pk}),Ik=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),Ck=c.object({...zn.shape,...Ir.shape,description:c.optional(c.string()),arguments:c.optional(c.array(Ik)),_meta:c.optional(c.looseObject({}))}),ho=Cr.extend({method:c.literal("prompts/list")}),Ok=Or.extend({prompts:c.array(Ck)}),Nk=Ze.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),fo=Pe.extend({method:c.literal("prompts/get"),params:Nk}),Ea=c.object({type:c.literal("text"),text:c.string(),annotations:Bn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Pa=c.object({type:c.literal("image"),data:Ta,mimeType:c.string(),annotations:Bn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Aa=c.object({type:c.literal("audio"),data:Ta,mimeType:c.string(),annotations:Bn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Lk=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()}),jk=c.object({type:c.literal("resource"),resource:c.union([fh,mh]),annotations:Bn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Uk=gh.extend({type:c.literal("resource_link")}),Ia=c.union([Ea,Pa,Aa,Uk,jk]),Dk=c.object({role:jr,content:Ia}),qk=Ae.extend({description:c.string().optional(),messages:c.array(Dk)}),zk=st.extend({method:c.literal("notifications/prompts/list_changed"),params:rt.optional()}),Mk=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Bk=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),bh=c.object({...zn.shape,...Ir.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),xe).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),xe).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:Mk.optional(),execution:Bk.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),mo=Cr.extend({method:c.literal("tools/list")}),Fk=Or.extend({tools:c.array(bh)}),go=Ae.extend({content:c.array(Ia).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),bI=go.or(Ae.extend({toolResult:c.unknown()})),Hk=Pr.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Fn=Pe.extend({method:c.literal("tools/call"),params:Hk}),Kk=st.extend({method:c.literal("notifications/tools/list_changed"),params:rt.optional()}),yI=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Ur=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Vk=Ze.extend({level:Ur}),Ca=Pe.extend({method:c.literal("logging/setLevel"),params:Vk}),Gk=rt.extend({level:Ur,logger:c.string().optional(),data:c.unknown()}),Wk=st.extend({method:c.literal("notifications/message"),params:Gk}),Jk=c.object({name:c.string().optional()}),Yk=c.object({hints:c.array(Jk).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()}),Zk=c.object({mode:c.enum(["auto","required","none"]).optional()}),Qk=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Ia).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Xk=c.discriminatedUnion("type",[Ea,Pa,Aa]),Ys=c.discriminatedUnion("type",[Ea,Pa,Aa,Lk,Qk]),eS=c.object({role:jr,content:c.union([Ys,c.array(Ys)]),_meta:c.record(c.string(),c.unknown()).optional()}),tS=Pr.extend({messages:c.array(eS),modelPreferences:Yk.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:xe.optional(),tools:c.array(bh).optional(),toolChoice:Zk.optional()}),nS=Pe.extend({method:c.literal("sampling/createMessage"),params:tS}),Dr=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:jr,content:Xk}),Oa=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:jr,content:c.union([Ys,c.array(Ys)])}),rS=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),sS=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()}),oS=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()}),iS=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),aS=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()}),lS=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()}),cS=c.union([iS,aS]),dS=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()}),uS=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()}),pS=c.union([dS,uS]),hS=c.union([lS,cS,pS]),fS=c.union([hS,rS,sS,oS]),mS=Pr.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),fS),required:c.array(c.string()).optional()})}),gS=Pr.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),bS=c.union([mS,gS]),yS=Pe.extend({method:c.literal("elicitation/create"),params:bS}),wS=rt.extend({elicitationId:c.string()}),vS=st.extend({method:c.literal("notifications/elicitation/complete"),params:wS}),Hn=Ae.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())}),kS=c.object({type:c.literal("ref/resource"),uri:c.string()}),SS=c.object({type:c.literal("ref/prompt"),name:c.string()}),_S=Ze.extend({ref:c.union([SS,kS]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),bo=Pe.extend({method:c.literal("completion/complete"),params:_S});$S=Ae.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),xS=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),TS=Pe.extend({method:c.literal("roots/list"),params:Ze.optional()}),Na=Ae.extend({roots:c.array(xS)}),RS=st.extend({method:c.literal("notifications/roots/list_changed"),params:rt.optional()}),wI=c.union([to,$a,bo,Ca,fo,ho,co,uo,po,Tk,Ek,Fn,mo,ro,oo,io,lo]),vI=c.union([eo,no,xa,RS,Lr]),kI=c.union([Xs,Dr,Oa,Hn,Na,so,ao,Mn]),SI=c.union([to,nS,yS,TS,ro,oo,io,lo]),_I=c.union([eo,no,Wk,Ak,$k,Kk,zk,Lr,vS]),$I=c.union([Xs,hk,$S,qk,Ok,vk,kk,_k,go,Fk,so,ao,Mn]),q=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===F.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new ya(s.elicitations,n)}return new t(e,n,r)}},ya=class extends q{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(F.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Wt(t){return t==="completed"||t==="failed"||t==="cancelled"}var vh=j(()=>{});var Sh,kh,_h,yo=j(()=>{Sh=Symbol("Let zodToJsonSchema decide on which parser to use"),kh={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},_h=t=>typeof t=="string"?{...kh,name:t}:{...kh,...t}});var $h,La=j(()=>{yo();$h=t=>{let e=_h(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 ja(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ie(t,e,n,r,s){t[e]=n,ja(t,e,r,s)}var Jt=j(()=>{});var wo,vo=j(()=>{wo=(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 we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?wo(e,t.currentPath):e.join("/")}}var ot=j(()=>{vo()});import{ZodFirstPartyTypeKind as ES}from"zod/v3";function xh(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==ES.ZodAny&&(n.items=G(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ie(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ie(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ie(n,"minItems",t.exactLength.value,t.exactLength.message,e),ie(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}var Ua=j(()=>{Jt();$e()});function Th(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?ie(n,"minimum",r.value,r.message,e):ie(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ie(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ie(n,"maximum",r.value,r.message,e):ie(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ie(n,"maximum",r.value,r.message,e));break;case"multipleOf":ie(n,"multipleOf",r.value,r.message,e);break}return n}var Da=j(()=>{Jt()});function Rh(){return{type:"boolean"}}var qa=j(()=>{});function ko(t,e){return G(t.type._def,e)}var So=j(()=>{$e()});var Eh,za=j(()=>{$e();Eh=(t,e)=>G(t.innerType._def,e)});function Ma(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>Ma(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 PS(t,e)}}var PS,Ba=j(()=>{Jt();PS=(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":ie(n,"minimum",r.value,r.message,e);break;case"max":ie(n,"maximum",r.value,r.message,e);break}return n}});function Ph(t,e){return{...G(t.innerType._def,e),default:t.defaultValue()}}var Fa=j(()=>{$e()});function Ah(t,e){return e.effectStrategy==="input"?G(t.schema._def,e):we(e)}var Ha=j(()=>{$e();ot()});function Ih(t){return{type:"string",enum:Array.from(t.values)}}var Ka=j(()=>{});function Ch(t,e){let n=[G(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),G(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(AS(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 AS,Va=j(()=>{$e();AS=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Oh(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 Ga=j(()=>{});function _o(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ie(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ie(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":ft(n,"email",r.message,e);break;case"format:idn-email":ft(n,"idn-email",r.message,e);break;case"pattern:zod":ze(n,ht.email,r.message,e);break}break;case"url":ft(n,"uri",r.message,e);break;case"uuid":ft(n,"uuid",r.message,e);break;case"regex":ze(n,r.regex,r.message,e);break;case"cuid":ze(n,ht.cuid,r.message,e);break;case"cuid2":ze(n,ht.cuid2,r.message,e);break;case"startsWith":ze(n,RegExp(`^${Ja(r.value,e)}`),r.message,e);break;case"endsWith":ze(n,RegExp(`${Ja(r.value,e)}$`),r.message,e);break;case"datetime":ft(n,"date-time",r.message,e);break;case"date":ft(n,"date",r.message,e);break;case"time":ft(n,"time",r.message,e);break;case"duration":ft(n,"duration",r.message,e);break;case"length":ie(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ie(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{ze(n,RegExp(Ja(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&ft(n,"ipv4",r.message,e),r.version!=="v4"&&ft(n,"ipv6",r.message,e);break}case"base64url":ze(n,ht.base64url,r.message,e);break;case"jwt":ze(n,ht.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&ze(n,ht.ipv4Cidr,r.message,e),r.version!=="v4"&&ze(n,ht.ipv6Cidr,r.message,e);break}case"emoji":ze(n,ht.emoji(),r.message,e);break;case"ulid":{ze(n,ht.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ft(n,"binary",r.message,e);break}case"contentEncoding:base64":{ie(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{ze(n,ht.base64,r.message,e);break}}break}case"nanoid":ze(n,ht.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Ja(t,e){return e.patternStrategy==="escape"?CS(t):t}function CS(t){let e="";for(let n=0;n<t.length;n++)IS.has(t[n])||(e+="\\"),e+=t[n];return e}function ft(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}}})):ie(t,"format",e,n,r)}function ze(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:Nh(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ie(t,"pattern",Nh(e,r),n,r)}function Nh(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
1767
1767
  ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
1768
1768
  ]))`;continue}}if(n.s&&r[l]==="."){s+=i?`${r[l]}\r
1769
1769
  `:`[${r[l]}\r
1770
- ]`;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 Wa,ht,IS,$o=j(()=>{Yt();ht={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:()=>(Wa===void 0&&(Wa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wa),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-_]*$/};IS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as qr}from"zod/v3";function xo(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===qr.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===qr.ZodString&&t.keyType._def.checks?.length){let{type:r,...s}=_o(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===qr.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===qr.ZodBranded&&t.keyType._def.type._def.typeName===qr.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=ko(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var To=j(()=>{$e();$o();So();ot()});function Lh(t,e){if(e.mapStrategy==="record")return xo(t,e);let n=G(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),r=G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Ya=j(()=>{$e();To();ot()});function jh(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 Za=j(()=>{});function Uh(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}var Qa=j(()=>{ot()});function Dh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Xa=j(()=>{});function zh(t,e){if(e.target==="openApi3")return qh(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in zr&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=zr[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 qh(t,e)}var zr,qh,Ro=j(()=>{$e();zr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};qh=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>G(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 Mh(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:zr[t.innerType._def.typeName],nullable:!0}:{type:[zr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=G(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var el=j(()=>{$e();Ro()});function Bh(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",ja(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}var tl=j(()=>{Yt()});function Fh(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=NS(l);u&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=G(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=OS(t,e);return i!==void 0&&(r.additionalProperties=i),r}function OS(t,e){if(t.catchall._def.typeName!=="ZodNever")return G(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 NS(t){try{return t.isOptional()}catch{return!0}}var nl=j(()=>{$e()});var Hh,rl=j(()=>{$e();ot();Hh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return G(t.innerType._def,e);let n=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:we(e)},n]}:we(e)}});var Kh,sl=j(()=>{$e();Kh=(t,e)=>{if(e.pipeStrategy==="input")return G(t.in._def,e);if(e.pipeStrategy==="output")return G(t.out._def,e);let n=G(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=G(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function Vh(t,e){return G(t.type._def,e)}var ol=j(()=>{$e()});function Gh(t,e){let r={type:"array",uniqueItems:!0,items:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var il=j(()=>{Yt();$e()});function Wh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>G(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:G(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>G(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var al=j(()=>{$e()});function Jh(t){return{not:we(t)}}var ll=j(()=>{ot()});function Yh(t){return we(t)}var cl=j(()=>{ot()});var Zh,dl=j(()=>{$e();Zh=(t,e)=>G(t.innerType._def,e)});import{ZodFirstPartyTypeKind as oe}from"zod/v3";var Qh,ul=j(()=>{ot();Ua();Da();qa();So();za();Ba();Fa();Ha();Ka();Va();Ga();Ya();Za();Qa();Xa();el();tl();nl();rl();sl();ol();To();il();$o();al();ll();Ro();cl();dl();Qh=(t,e,n)=>{switch(e){case oe.ZodString:return _o(t,n);case oe.ZodNumber:return Bh(t,n);case oe.ZodObject:return Fh(t,n);case oe.ZodBigInt:return Th(t,n);case oe.ZodBoolean:return Rh();case oe.ZodDate:return Ma(t,n);case oe.ZodUndefined:return Jh(n);case oe.ZodNull:return Dh(n);case oe.ZodArray:return xh(t,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return zh(t,n);case oe.ZodIntersection:return Ch(t,n);case oe.ZodTuple:return Wh(t,n);case oe.ZodRecord:return xo(t,n);case oe.ZodLiteral:return Oh(t,n);case oe.ZodEnum:return Ih(t);case oe.ZodNativeEnum:return jh(t);case oe.ZodNullable:return Mh(t,n);case oe.ZodOptional:return Hh(t,n);case oe.ZodMap:return Lh(t,n);case oe.ZodSet:return Gh(t,n);case oe.ZodLazy:return()=>t.getter()._def;case oe.ZodPromise:return Vh(t,n);case oe.ZodNaN:case oe.ZodNever:return Uh(n);case oe.ZodEffects:return Ah(t,n);case oe.ZodAny:return we(n);case oe.ZodUnknown:return Yh(n);case oe.ZodDefault:return Ph(t,n);case oe.ZodBranded:return ko(t,n);case oe.ZodReadonly:return Zh(t,n);case oe.ZodCatch:return Eh(t,n);case oe.ZodPipeline:return Kh(t,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(r=>{})(e)}}});function G(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==Sh)return a}if(r&&!n){let a=LS(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=Qh(t,t.typeName,e),i=typeof o=="function"?G(o(),e):o;if(i&&jS(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var LS,jS,$e=j(()=>{yo();ul();vo();ot();LS=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:wo(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`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},jS=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var Xh=j(()=>{});var pl,hl=j(()=>{$e();La();ot();pl=(t,e)=>{let n=$h(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:G(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??we(n)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=G(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??we(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 ef=j(()=>{yo();La();Yt();vo();$e();Xh();ot();Ua();Da();qa();So();za();Ba();Fa();Ha();Ka();Va();Ga();Ya();Za();Qa();Xa();el();tl();nl();rl();sl();ol();dl();To();il();$o();al();ll();Ro();cl();ul();hl();hl()});import*as tf from"zod/v4-mini";function US(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function fl(t,e){return kt(t)?tf.toJSONSchema(t,{target:US(e?.target),io:e?.pipeStrategy??"input"}):pl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function ml(t){let n=Gt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=qn(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function gl(t,e){let n=Vt(t,e);if(!n.success)throw n.error;return n.data}var bl=j(()=>{Er();ef()});function nf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rf(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];nf(i)&&nf(o)?n[s]={...i,...o}:n[s]=o}return n}var DS,Eo,sf=j(()=>{Er();Kn();vh();bl();DS=6e4,Eo=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(eo,n=>{this._oncancel(n)}),this.setNotificationHandler(no,n=>{this._onprogress(n)}),this.setRequestHandler(to,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ro,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new q(F.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(oo,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 f=l,_=new q(f.error.code,f.error.message,f.error.data);p(_)}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:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new q(F.InvalidParams,`Task not found: ${o}`);if(!Jt(i.status))return await this._waitForTaskUpdate(o,r.signal),await s();if(Jt(i.status)){let a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Wt]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(io,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 q(F.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(lo,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new q(F.InvalidParams,`Task not found: ${n.params.taskId}`);if(Jt(s.status))throw new q(F.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 q(F.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof q?s:new q(F.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),q.fromError(F.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),Ar(o)||ch(o)?this._onresponse(o):ka(o)?this._onrequest(o,i):lh(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=q.fromError(F.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?.[Wt]?.taskId;if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:F.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):s?.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=oh(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 f={relatedRequestId:e.id};o&&(f.relatedTask={taskId:o}),await this.notification(p,f)},sendRequest:async(p,f,_)=>{if(i.signal.aborted)throw new q(F.ConnectionClosed,"Request was cancelled");let v={..._,relatedRequestId:e.id};o&&!v.relatedTask&&(v.relatedTask={taskId:o});let k=v.relatedTask?.taskId??o;return k&&l&&await l.updateTaskStatus(k,"input_required"),await this.request(p,f,v)},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 f={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:f,timestamp:Date.now()},s?.sessionId):await s?.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:F.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:f,timestamp:Date.now()},s?.sessionId):await s?.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: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),Ar(e))r(e);else{let i=new q(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(Ar(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),Ar(e))s(e);else{let i=q.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 q?i:new q(F.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Mn,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new q(F.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Jt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)}:a.status==="failed"?yield{type:"error",error:new q(F.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(F.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 q?i:new q(F.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 f=C=>{p(C)};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(C){f(C);return}r?.signal?.throwIfAborted();let _=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:_};r?.onprogress&&(this._progressHandlers.set(_,r.onprogress),v.params={...e.params,_meta:{...e.params?._meta||{},progressToken:_}}),a&&(v.params={...v.params,task:a}),l&&(v.params={...v.params,_meta:{...v.params?._meta||{},[Wt]:l}});let k=C=>{this._responseHandlers.delete(_),this._progressHandlers.delete(_),this._cleanupTimeout(_),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(C)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(se=>this._onerror(new Error(`Failed to send cancellation: ${se}`)));let D=C instanceof q?C:new q(F.RequestTimeout,String(C));p(D)};this._responseHandlers.set(_,C=>{if(!r?.signal?.aborted){if(C instanceof Error)return p(C);try{let D=Vt(n,C.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),r?.signal?.addEventListener("abort",()=>{k(r?.signal?.reason)});let T=r?.timeout??DS,E=()=>k(q.fromError(F.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(_,T,r?.maxTotalTimeout,E,r?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let C=D=>{let se=this._responseHandlers.get(_);se?se(D):this._onerror(new Error(`Response handler missing for side-channeled request ${_}`))};this._requestResolvers.set(_,C),this._enqueueTaskMessage(P,{type:"request",message:v,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(_),p(D)})}else this._transport.send(v,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(C=>{this._cleanupTimeout(_),p(C)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},so,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},ao,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},ph,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||{},[Wt]: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||{},[Wt]: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||{},[Wt]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=ml(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,o)=>{let i=gl(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=ml(e);this._notificationHandlers.set(r,s=>{let o=gl(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"&&ka(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new q(F.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 q(F.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new q(F.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 q(F.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=Lr.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Jt(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 q(F.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Jt(a.status))throw new q(F.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=Lr.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Jt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var Fr=U(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.regexpCode=pe.getEsmExportName=pe.getProperty=pe.safeStringify=pe.stringify=pe.strConcat=pe.addCodeArg=pe.str=pe._=pe.nil=pe._Code=pe.Name=pe.IDENTIFIER=pe._CodeOrName=void 0;var Mr=class{};pe._CodeOrName=Mr;pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var fn=class extends Mr{constructor(e){if(super(),!pe.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}}};pe.Name=fn;var it=class extends Mr{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 fn&&(n[r.str]=(n[r.str]||0)+1),n),{})}};pe._Code=it;pe.nil=new it("");function of(t,...e){let n=[t[0]],r=0;for(;r<e.length;)wl(n,e[r]),n.push(t[++r]);return new it(n)}pe._=of;var yl=new it("+");function af(t,...e){let n=[Br(t[0])],r=0;for(;r<e.length;)n.push(yl),wl(n,e[r]),n.push(yl,Br(t[++r]));return qS(n),new it(n)}pe.str=af;function wl(t,e){e instanceof it?t.push(...e._items):e instanceof fn?t.push(e):t.push(BS(e))}pe.addCodeArg=wl;function qS(t){let e=1;for(;e<t.length-1;){if(t[e]===yl){let n=zS(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function zS(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof fn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof fn))return`"${t}${e.slice(1)}`}function MS(t,e){return e.emptyStr()?t:t.emptyStr()?e:af`${t}${e}`}pe.strConcat=MS;function BS(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Br(Array.isArray(t)?t.join(","):t)}function FS(t){return new it(Br(t))}pe.stringify=FS;function Br(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}pe.safeStringify=Br;function HS(t){return typeof t=="string"&&pe.IDENTIFIER.test(t)?new it(`.${t}`):of`[${t}]`}pe.getProperty=HS;function KS(t){if(typeof t=="string"&&pe.IDENTIFIER.test(t))return new it(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}pe.getEsmExportName=KS;function VS(t){return new it(t.toString())}pe.regexpCode=VS});var Sl=U(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var Ve=Fr(),vl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Po;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Po||(Ge.UsedValueState=Po={}));Ge.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var Ao=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Ve.Name?e:this.name(e)}name(e){return new Ve.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}}};Ge.Scope=Ao;var Io=class extends Ve.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Ve._)`.${new Ve.Name(n)}[${r}]`}};Ge.ValueScopeName=Io;var GS=(0,Ve._)`\n`,kl=class extends Ao{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?GS:Ve.nil}}get(){return this._scope}name(e){return new Io(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,Ve._)`${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=Ve.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,Po.Started);let p=n(u);if(p){let f=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;o=(0,Ve._)`${o}${f} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,Ve._)`${o}${p}${this.opts._n}`;else throw new vl(u);l.set(u,Po.Completed)})}return o}};Ge.ValueScope=kl});var ee=U(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.or=te.and=te.not=te.CodeGen=te.operators=te.varKinds=te.ValueScopeName=te.ValueScope=te.Scope=te.Name=te.regexpCode=te.stringify=te.getProperty=te.nil=te.strConcat=te.str=te._=void 0;var le=Fr(),mt=Sl(),Zt=Fr();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return Zt._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return Zt.str}});Object.defineProperty(te,"strConcat",{enumerable:!0,get:function(){return Zt.strConcat}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return Zt.nil}});Object.defineProperty(te,"getProperty",{enumerable:!0,get:function(){return Zt.getProperty}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return Zt.stringify}});Object.defineProperty(te,"regexpCode",{enumerable:!0,get:function(){return Zt.regexpCode}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return Zt.Name}});var Lo=Sl();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return Lo.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return Lo.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return Lo.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return Lo.varKinds}});te.operators={GT:new le._Code(">"),GTE:new le._Code(">="),LT:new le._Code("<"),LTE:new le._Code("<="),EQ:new le._Code("==="),NEQ:new le._Code("!=="),NOT:new le._Code("!"),OR:new le._Code("||"),AND:new le._Code("&&"),ADD:new le._Code("+")};var Ct=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},_l=class extends Ct{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?mt.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=Gn(this.rhs,e,n)),this}get names(){return this.rhs instanceof le._CodeOrName?this.rhs.names:{}}},Co=class extends Ct{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 le.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Gn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof le.Name?{}:{...this.lhs.names};return No(e,this.rhs)}},$l=class extends Co{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},xl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Tl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Rl=class extends Ct{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},El=class extends Ct{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=Gn(this.code,e,n),this}get names(){return this.code instanceof le._CodeOrName?this.code.names:{}}},Hr=class extends Ct{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)||(WS(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>bn(e,n.names),{})}},Ot=class extends Hr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Pl=class extends Hr{},Vn=class extends Ot{};Vn.kind="else";var mn=class t extends Ot{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 Vn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(lf(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=Gn(this.condition,e,n),this}get names(){let e=super.names;return No(e,this.condition),this.else&&bn(e,this.else.names),e}};mn.kind="if";var gn=class extends Ot{};gn.kind="for";var Al=class extends gn{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=Gn(this.iteration,e,n),this}get names(){return bn(super.names,this.iteration.names)}},Il=class extends gn{constructor(e,n,r,s){super(),this.varKind=e,this.name=n,this.from=r,this.to=s}render(e){let n=e.es5?mt.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=No(super.names,this.from);return No(e,this.to)}},Oo=class extends gn{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=Gn(this.iterable,e,n),this}get names(){return bn(super.names,this.iterable.names)}},Kr=class extends Ot{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)}};Kr.kind="func";var Vr=class extends Hr{render(e){return"return "+super.render(e)}};Vr.kind="return";var Cl=class extends Ot{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&&bn(e,this.catch.names),this.finally&&bn(e,this.finally.names),e}},Gr=class extends Ot{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Gr.kind="catch";var Wr=class extends Ot{render(e){return"finally"+super.render(e)}};Wr.kind="finally";var Ol=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
1771
- `:""},this._extScope=e,this._scope=new mt.Scope({parent:e}),this._nodes=[new Pl]}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 _l(e,o,r)),o}const(e,n,r){return this._def(mt.varKinds.const,e,n,r)}let(e,n,r){return this._def(mt.varKinds.let,e,n,r)}var(e,n,r){return this._def(mt.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new Co(e,n,r))}add(e,n){return this._leafNode(new $l(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==le.nil&&this._leafNode(new El(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,le.addCodeArg)(n,s));return n.push("}"),new le._Code(n)}if(e,n,r){if(this._blockNode(new mn(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 mn(e))}else(){return this._elseNode(new Vn)}endIf(){return this._endBlockNode(mn,Vn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Al(e),n)}forRange(e,n,r,s,o=this.opts.es5?mt.varKinds.var:mt.varKinds.let){let i=this._scope.toName(e);return this._for(new Il(o,i,n,r),()=>s(i))}forOf(e,n,r,s=mt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=n instanceof le.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,le._)`${i}.length`,a=>{this.var(o,(0,le._)`${i}[${a}]`),r(o)})}return this._for(new Oo("of",s,o,n),()=>r(o))}forIn(e,n,r,s=this.opts.es5?mt.varKinds.var:mt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,le._)`Object.keys(${n})`,r);let o=this._scope.toName(e);return this._for(new Oo("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(gn)}label(e){return this._leafNode(new xl(e))}break(e){return this._leafNode(new Tl(e))}return(e){let n=new Vr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Cl;if(this._blockNode(s),this.code(e),n){let o=this.name("e");this._currNode=s.catch=new Gr(o),n(o)}return r&&(this._currNode=s.finally=new Wr,this.code(r)),this._endBlockNode(Gr,Wr)}throw(e){return this._leafNode(new Rl(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=le.nil,r,s){return this._blockNode(new Kr(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Kr)}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 mn))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}};te.CodeGen=Ol;function bn(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function No(t,e){return e instanceof le._CodeOrName?bn(t,e.names):t}function Gn(t,e,n){if(t instanceof le.Name)return r(t);if(!s(t))return t;return new le._Code(t._items.reduce((o,i)=>(i instanceof le.Name&&(i=r(i)),i instanceof le._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 le._Code&&o._items.some(i=>i instanceof le.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function WS(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function lf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,le._)`!${Nl(t)}`}te.not=lf;var JS=cf(te.operators.AND);function YS(...t){return t.reduce(JS)}te.and=YS;var ZS=cf(te.operators.OR);function QS(...t){return t.reduce(ZS)}te.or=QS;function cf(t){return(e,n)=>e===le.nil?n:n===le.nil?e:(0,le._)`${Nl(e)} ${t} ${Nl(n)}`}function Nl(t){return t instanceof le.Name?t:(0,le._)`(${t})`}});var de=U(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 ge=ee(),XS=Fr();function e_(t){let e={};for(let n of t)e[n]=!0;return e}ne.toHash=e_;function t_(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(pf(t,e),!hf(e,t.self.RULES.all))}ne.alwaysValidSchema=t_;function pf(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]||gf(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=pf;function hf(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ne.schemaHasRules=hf;function n_(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ne.schemaHasRulesButRef=n_;function r_({topSchemaRef:t,schemaPath:e},n,r,s){if(!s){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,ge._)`${n}`}return(0,ge._)`${t}${e}${(0,ge.getProperty)(r)}`}ne.schemaRefOrVal=r_;function s_(t){return ff(decodeURIComponent(t))}ne.unescapeFragment=s_;function o_(t){return encodeURIComponent(jl(t))}ne.escapeFragment=o_;function jl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=jl;function ff(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=ff;function i_(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ne.eachItem=i_;function df({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(s,o,i,a)=>{let l=i===void 0?o:i instanceof ge.Name?(o instanceof ge.Name?t(s,o,i):e(s,o,i),i):o instanceof ge.Name?(e(s,i,o),o):n(o,i);return a===ge.Name&&!(l instanceof ge.Name)?r(s,l):l}}ne.mergeEvaluated={props:df({mergeNames:(t,e,n)=>t.if((0,ge._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,ge._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,ge._)`${n} || {}`).code((0,ge._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,ge._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,ge._)`${n} || {}`),Ul(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:mf}),items:df({mergeNames:(t,e,n)=>t.if((0,ge._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,ge._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,ge._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,ge._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function mf(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,ge._)`{}`);return e!==void 0&&Ul(t,n,e),n}ne.evaluatedPropsToName=mf;function Ul(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(r)}`,!0))}ne.setEvaluated=Ul;var uf={};function a_(t,e){return t.scopeValue("func",{ref:e,code:uf[e.code]||(uf[e.code]=new XS._Code(e.code))})}ne.useFunc=a_;var Ll;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ll||(ne.Type=Ll={}));function l_(t,e,n){if(t instanceof ge.Name){let r=e===Ll.Num;return n?r?(0,ge._)`"[" + ${t} + "]"`:(0,ge._)`"['" + ${t} + "']"`:r?(0,ge._)`"/" + ${t}`:(0,ge._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,ge.getProperty)(t).toString():"/"+jl(t)}ne.getErrorPath=l_;function gf(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=gf});var Nt=U(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var Oe=ee(),c_={data:new Oe.Name("data"),valCxt:new Oe.Name("valCxt"),instancePath:new Oe.Name("instancePath"),parentData:new Oe.Name("parentData"),parentDataProperty:new Oe.Name("parentDataProperty"),rootData:new Oe.Name("rootData"),dynamicAnchors:new Oe.Name("dynamicAnchors"),vErrors:new Oe.Name("vErrors"),errors:new Oe.Name("errors"),this:new Oe.Name("this"),self:new Oe.Name("self"),scope:new Oe.Name("scope"),json:new Oe.Name("json"),jsonPos:new Oe.Name("jsonPos"),jsonLen:new Oe.Name("jsonLen"),jsonPart:new Oe.Name("jsonPart")};Dl.default=c_});var Jr=U(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.extendErrors=Ne.resetErrorsCount=Ne.reportExtraError=Ne.reportError=Ne.keyword$DataError=Ne.keywordError=void 0;var ue=ee(),jo=de(),Me=Nt();Ne.keywordError={message:({keyword:t})=>(0,ue.str)`must pass "${t}" keyword validation`};Ne.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ue.str)`"${t}" keyword must be ${e} ($data)`:(0,ue.str)`"${t}" keyword is invalid ($data)`};function d_(t,e=Ne.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=wf(t,e,n);r??(i||a)?bf(o,l):yf(s,(0,ue._)`[${l}]`)}Ne.reportError=d_;function u_(t,e=Ne.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=wf(t,e,n);bf(s,a),o||i||yf(r,Me.default.vErrors)}Ne.reportExtraError=u_;function p_(t,e){t.assign(Me.default.errors,e),t.if((0,ue._)`${Me.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ue._)`${Me.default.vErrors}.length`,e),()=>t.assign(Me.default.vErrors,null)))}Ne.resetErrorsCount=p_;function h_({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,Me.default.errors,a=>{t.const(i,(0,ue._)`${Me.default.vErrors}[${a}]`),t.if((0,ue._)`${i}.instancePath === undefined`,()=>t.assign((0,ue._)`${i}.instancePath`,(0,ue.strConcat)(Me.default.instancePath,o.errorPath))),t.assign((0,ue._)`${i}.schemaPath`,(0,ue.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,ue._)`${i}.schema`,n),t.assign((0,ue._)`${i}.data`,r))})}Ne.extendErrors=h_;function bf(t,e){let n=t.const("err",e);t.if((0,ue._)`${Me.default.vErrors} === null`,()=>t.assign(Me.default.vErrors,(0,ue._)`[${n}]`),(0,ue._)`${Me.default.vErrors}.push(${n})`),t.code((0,ue._)`${Me.default.errors}++`)}function yf(t,e){let{gen:n,validateName:r,schemaEnv:s}=t;s.$async?n.throw((0,ue._)`new ${t.ValidationError}(${e})`):(n.assign((0,ue._)`${r}.errors`,e),n.return(!1))}var yn={keyword:new ue.Name("keyword"),schemaPath:new ue.Name("schemaPath"),params:new ue.Name("params"),propertyName:new ue.Name("propertyName"),message:new ue.Name("message"),schema:new ue.Name("schema"),parentSchema:new ue.Name("parentSchema")};function wf(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,ue._)`{}`:f_(t,e,n)}function f_(t,e,n={}){let{gen:r,it:s}=t,o=[m_(s,n),g_(t,n)];return b_(t,e,o),r.object(...o)}function m_({errorPath:t},{instancePath:e}){let n=e?(0,ue.str)`${t}${(0,jo.getErrorPath)(e,jo.Type.Str)}`:t;return[Me.default.instancePath,(0,ue.strConcat)(Me.default.instancePath,n)]}function g_({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let s=r?e:(0,ue.str)`${e}/${t}`;return n&&(s=(0,ue.str)`${s}${(0,jo.getErrorPath)(n,jo.Type.Str)}`),[yn.schemaPath,s]}function b_(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:f}=a;r.push([yn.keyword,s],[yn.params,typeof e=="function"?e(t):e||(0,ue._)`{}`]),l.messages&&r.push([yn.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([yn.schema,i],[yn.parentSchema,(0,ue._)`${p}${f}`],[Me.default.data,o]),u&&r.push([yn.propertyName,u])}});var kf=U(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.boolOrEmptySchema=Wn.topBoolOrEmptySchema=void 0;var y_=Jr(),w_=ee(),v_=Nt(),k_={message:"boolean schema is false"};function S_(t){let{gen:e,schema:n,validateName:r}=t;n===!1?vf(t,!1):typeof n=="object"&&n.$async===!0?e.return(v_.default.data):(e.assign((0,w_._)`${r}.errors`,null),e.return(!0))}Wn.topBoolOrEmptySchema=S_;function __(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),vf(t)):n.var(e,!0)}Wn.boolOrEmptySchema=__;function vf(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,y_.reportError)(s,k_,void 0,e)}});var ql=U(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.getRules=Jn.isJSONType=void 0;var $_=["string","number","integer","boolean","null","object","array"],x_=new Set($_);function T_(t){return typeof t=="string"&&x_.has(t)}Jn.isJSONType=T_;function R_(){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:{}}}Jn.getRules=R_});var zl=U(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.shouldUseRule=Qt.shouldUseGroup=Qt.schemaHasRulesForType=void 0;function E_({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&Sf(t,r)}Qt.schemaHasRulesForType=E_;function Sf(t,e){return e.rules.some(n=>_f(t,n))}Qt.shouldUseGroup=Sf;function _f(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))}Qt.shouldUseRule=_f});var Yr=U(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var P_=ql(),A_=zl(),I_=Jr(),Q=ee(),$f=de(),Yn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Yn||(Le.DataType=Yn={}));function C_(t){let e=xf(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}Le.getSchemaTypes=C_;function xf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(P_.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=xf;function O_(t,e){let{gen:n,data:r,opts:s}=t,o=N_(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,A_.schemaHasRulesForType)(t,e[0]));if(i){let a=Bl(e,r,s.strictNumbers,Yn.Wrong);n.if(a,()=>{o.length?L_(t,e,o):Fl(t)})}return i}Le.coerceAndCheckDataType=O_;var Tf=new Set(["string","number","integer","boolean","null"]);function N_(t,e){return e?t.filter(n=>Tf.has(n)||e==="array"&&n==="array"):[]}function L_(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,Q._)`typeof ${s}`),a=r.let("coerced",(0,Q._)`undefined`);o.coerceTypes==="array"&&r.if((0,Q._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,Q._)`${s}[0]`).assign(i,(0,Q._)`typeof ${s}`).if(Bl(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,Q._)`${a} !== undefined`);for(let u of n)(Tf.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);r.else(),Fl(t),r.endIf(),r.if((0,Q._)`${a} !== undefined`,()=>{r.assign(s,a),j_(t,a)});function l(u){switch(u){case"string":r.elseIf((0,Q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Q._)`"" + ${s}`).elseIf((0,Q._)`${s} === null`).assign(a,(0,Q._)`""`);return;case"number":r.elseIf((0,Q._)`${i} == "boolean" || ${s} === null
1770
+ ]`;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 Wa,ht,IS,$o=j(()=>{Jt();ht={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:()=>(Wa===void 0&&(Wa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Wa),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-_]*$/};IS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as qr}from"zod/v3";function xo(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===qr.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===qr.ZodString&&t.keyType._def.checks?.length){let{type:r,...s}=_o(t.keyType._def,e);return{...n,propertyNames:s}}else{if(t.keyType?._def.typeName===qr.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===qr.ZodBranded&&t.keyType._def.type._def.typeName===qr.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=ko(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var To=j(()=>{$e();$o();So();ot()});function Lh(t,e){if(e.mapStrategy==="record")return xo(t,e);let n=G(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),r=G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}var Ya=j(()=>{$e();To();ot()});function jh(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 Za=j(()=>{});function Uh(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}var Qa=j(()=>{ot()});function Dh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Xa=j(()=>{});function zh(t,e){if(e.target==="openApi3")return qh(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in zr&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=zr[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 qh(t,e)}var zr,qh,Ro=j(()=>{$e();zr={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};qh=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,s)=>G(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 Mh(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:zr[t.innerType._def.typeName],nullable:!0}:{type:[zr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=G(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var el=j(()=>{$e();Ro()});function Bh(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",ja(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ie(n,"minimum",r.value,r.message,e):ie(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ie(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ie(n,"maximum",r.value,r.message,e):ie(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ie(n,"maximum",r.value,r.message,e));break;case"multipleOf":ie(n,"multipleOf",r.value,r.message,e);break}return n}var tl=j(()=>{Jt()});function Fh(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=NS(l);u&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=G(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=OS(t,e);return i!==void 0&&(r.additionalProperties=i),r}function OS(t,e){if(t.catchall._def.typeName!=="ZodNever")return G(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 NS(t){try{return t.isOptional()}catch{return!0}}var nl=j(()=>{$e()});var Hh,rl=j(()=>{$e();ot();Hh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return G(t.innerType._def,e);let n=G(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:we(e)},n]}:we(e)}});var Kh,sl=j(()=>{$e();Kh=(t,e)=>{if(e.pipeStrategy==="input")return G(t.in._def,e);if(e.pipeStrategy==="output")return G(t.out._def,e);let n=G(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=G(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function Vh(t,e){return G(t.type._def,e)}var ol=j(()=>{$e()});function Gh(t,e){let r={type:"array",uniqueItems:!0,items:G(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}var il=j(()=>{Jt();$e()});function Wh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>G(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:G(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>G(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var al=j(()=>{$e()});function Jh(t){return{not:we(t)}}var ll=j(()=>{ot()});function Yh(t){return we(t)}var cl=j(()=>{ot()});var Zh,dl=j(()=>{$e();Zh=(t,e)=>G(t.innerType._def,e)});import{ZodFirstPartyTypeKind as oe}from"zod/v3";var Qh,ul=j(()=>{ot();Ua();Da();qa();So();za();Ba();Fa();Ha();Ka();Va();Ga();Ya();Za();Qa();Xa();el();tl();nl();rl();sl();ol();To();il();$o();al();ll();Ro();cl();dl();Qh=(t,e,n)=>{switch(e){case oe.ZodString:return _o(t,n);case oe.ZodNumber:return Bh(t,n);case oe.ZodObject:return Fh(t,n);case oe.ZodBigInt:return Th(t,n);case oe.ZodBoolean:return Rh();case oe.ZodDate:return Ma(t,n);case oe.ZodUndefined:return Jh(n);case oe.ZodNull:return Dh(n);case oe.ZodArray:return xh(t,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return zh(t,n);case oe.ZodIntersection:return Ch(t,n);case oe.ZodTuple:return Wh(t,n);case oe.ZodRecord:return xo(t,n);case oe.ZodLiteral:return Oh(t,n);case oe.ZodEnum:return Ih(t);case oe.ZodNativeEnum:return jh(t);case oe.ZodNullable:return Mh(t,n);case oe.ZodOptional:return Hh(t,n);case oe.ZodMap:return Lh(t,n);case oe.ZodSet:return Gh(t,n);case oe.ZodLazy:return()=>t.getter()._def;case oe.ZodPromise:return Vh(t,n);case oe.ZodNaN:case oe.ZodNever:return Uh(n);case oe.ZodEffects:return Ah(t,n);case oe.ZodAny:return we(n);case oe.ZodUnknown:return Yh(n);case oe.ZodDefault:return Ph(t,n);case oe.ZodBranded:return ko(t,n);case oe.ZodReadonly:return Zh(t,n);case oe.ZodCatch:return Eh(t,n);case oe.ZodPipeline:return Kh(t,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(r=>{})(e)}}});function G(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==Sh)return a}if(r&&!n){let a=LS(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=Qh(t,t.typeName,e),i=typeof o=="function"?G(o(),e):o;if(i&&jS(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var LS,jS,$e=j(()=>{yo();ul();vo();ot();LS=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:wo(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`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},jS=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var Xh=j(()=>{});var pl,hl=j(()=>{$e();La();ot();pl=(t,e)=>{let n=$h(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:G(p._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??we(n)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=G(t._def,s===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,s]},!1)??we(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 ef=j(()=>{yo();La();Jt();vo();$e();Xh();ot();Ua();Da();qa();So();za();Ba();Fa();Ha();Ka();Va();Ga();Ya();Za();Qa();Xa();el();tl();nl();rl();sl();ol();dl();To();il();$o();al();ll();Ro();cl();ul();hl();hl()});import*as tf from"zod/v4-mini";function US(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function fl(t,e){return kt(t)?tf.toJSONSchema(t,{target:US(e?.target),io:e?.pipeStrategy??"input"}):pl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function ml(t){let n=Vt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=qn(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function gl(t,e){let n=Kt(t,e);if(!n.success)throw n.error;return n.data}var bl=j(()=>{Er();ef()});function nf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function rf(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];nf(i)&&nf(o)?n[s]={...i,...o}:n[s]=o}return n}var DS,Eo,sf=j(()=>{Er();Kn();vh();bl();DS=6e4,Eo=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(eo,n=>{this._oncancel(n)}),this.setNotificationHandler(no,n=>{this._onprogress(n)}),this.setRequestHandler(to,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ro,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new q(F.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(oo,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 f=l,_=new q(f.error.code,f.error.message,f.error.data);p(_)}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:r.requestId})}}let i=await this._taskStore.getTask(o,r.sessionId);if(!i)throw new q(F.InvalidParams,`Task not found: ${o}`);if(!Wt(i.status))return await this._waitForTaskUpdate(o,r.signal),await s();if(Wt(i.status)){let a=await this._taskStore.getTaskResult(o,r.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Gt]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(io,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 q(F.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(lo,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new q(F.InvalidParams,`Task not found: ${n.params.taskId}`);if(Wt(s.status))throw new q(F.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 q(F.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof q?s:new q(F.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),q.fromError(F.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),Ar(o)||ch(o)?this._onresponse(o):ka(o)?this._onrequest(o,i):lh(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=q.fromError(F.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?.[Gt]?.taskId;if(r===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:F.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(f=>this._onerror(new Error(`Failed to enqueue error response: ${f}`))):s?.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=oh(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 f={relatedRequestId:e.id};o&&(f.relatedTask={taskId:o}),await this.notification(p,f)},sendRequest:async(p,f,_)=>{if(i.signal.aborted)throw new q(F.ConnectionClosed,"Request was cancelled");let v={..._,relatedRequestId:e.id};o&&!v.relatedTask&&(v.relatedTask={taskId:o});let k=v.relatedTask?.taskId??o;return k&&l&&await l.updateTaskStatus(k,"input_required"),await this.request(p,f,v)},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 f={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:f,timestamp:Date.now()},s?.sessionId):await s?.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:F.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:f,timestamp:Date.now()},s?.sessionId):await s?.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: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),Ar(e))r(e);else{let i=new q(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(Ar(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),Ar(e))s(e);else{let i=q.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 q?i:new q(F.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Mn,r);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new q(F.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},r);if(yield{type:"taskStatus",task:a},Wt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},n,r)}:a.status==="failed"?yield{type:"error",error:new q(F.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(F.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 q?i:new q(F.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 f=C=>{p(C)};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(C){f(C);return}r?.signal?.throwIfAborted();let _=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:_};r?.onprogress&&(this._progressHandlers.set(_,r.onprogress),v.params={...e.params,_meta:{...e.params?._meta||{},progressToken:_}}),a&&(v.params={...v.params,task:a}),l&&(v.params={...v.params,_meta:{...v.params?._meta||{},[Gt]:l}});let k=C=>{this._responseHandlers.delete(_),this._progressHandlers.delete(_),this._cleanupTimeout(_),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:_,reason:String(C)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(re=>this._onerror(new Error(`Failed to send cancellation: ${re}`)));let D=C instanceof q?C:new q(F.RequestTimeout,String(C));p(D)};this._responseHandlers.set(_,C=>{if(!r?.signal?.aborted){if(C instanceof Error)return p(C);try{let D=Kt(n,C.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),r?.signal?.addEventListener("abort",()=>{k(r?.signal?.reason)});let T=r?.timeout??DS,E=()=>k(q.fromError(F.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(_,T,r?.maxTotalTimeout,E,r?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let C=D=>{let re=this._responseHandlers.get(_);re?re(D):this._onerror(new Error(`Response handler missing for side-channeled request ${_}`))};this._requestResolvers.set(_,C),this._enqueueTaskMessage(P,{type:"request",message:v,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(_),p(D)})}else this._transport.send(v,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(C=>{this._cleanupTimeout(_),p(C)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},so,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},ao,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},ph,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||{},[Gt]: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||{},[Gt]: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||{},[Gt]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=ml(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,o)=>{let i=gl(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=ml(e);this._notificationHandlers.set(r,s=>{let o=gl(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"&&ka(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new q(F.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 q(F.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new q(F.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 q(F.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=Lr.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Wt(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 q(F.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Wt(a.status))throw new q(F.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=Lr.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Wt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var Fr=U(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.regexpCode=pe.getEsmExportName=pe.getProperty=pe.safeStringify=pe.stringify=pe.strConcat=pe.addCodeArg=pe.str=pe._=pe.nil=pe._Code=pe.Name=pe.IDENTIFIER=pe._CodeOrName=void 0;var Mr=class{};pe._CodeOrName=Mr;pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var fn=class extends Mr{constructor(e){if(super(),!pe.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}}};pe.Name=fn;var it=class extends Mr{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 fn&&(n[r.str]=(n[r.str]||0)+1),n),{})}};pe._Code=it;pe.nil=new it("");function of(t,...e){let n=[t[0]],r=0;for(;r<e.length;)wl(n,e[r]),n.push(t[++r]);return new it(n)}pe._=of;var yl=new it("+");function af(t,...e){let n=[Br(t[0])],r=0;for(;r<e.length;)n.push(yl),wl(n,e[r]),n.push(yl,Br(t[++r]));return qS(n),new it(n)}pe.str=af;function wl(t,e){e instanceof it?t.push(...e._items):e instanceof fn?t.push(e):t.push(BS(e))}pe.addCodeArg=wl;function qS(t){let e=1;for(;e<t.length-1;){if(t[e]===yl){let n=zS(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function zS(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof fn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof fn))return`"${t}${e.slice(1)}`}function MS(t,e){return e.emptyStr()?t:t.emptyStr()?e:af`${t}${e}`}pe.strConcat=MS;function BS(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Br(Array.isArray(t)?t.join(","):t)}function FS(t){return new it(Br(t))}pe.stringify=FS;function Br(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}pe.safeStringify=Br;function HS(t){return typeof t=="string"&&pe.IDENTIFIER.test(t)?new it(`.${t}`):of`[${t}]`}pe.getProperty=HS;function KS(t){if(typeof t=="string"&&pe.IDENTIFIER.test(t))return new it(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}pe.getEsmExportName=KS;function VS(t){return new it(t.toString())}pe.regexpCode=VS});var Sl=U(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var Ve=Fr(),vl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Po;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Po||(Ge.UsedValueState=Po={}));Ge.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var Ao=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof Ve.Name?e:this.name(e)}name(e){return new Ve.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}}};Ge.Scope=Ao;var Io=class extends Ve.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,Ve._)`.${new Ve.Name(n)}[${r}]`}};Ge.ValueScopeName=Io;var GS=(0,Ve._)`\n`,kl=class extends Ao{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?GS:Ve.nil}}get(){return this._scope}name(e){return new Io(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,Ve._)`${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=Ve.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,Po.Started);let p=n(u);if(p){let f=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;o=(0,Ve._)`${o}${f} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,Ve._)`${o}${p}${this.opts._n}`;else throw new vl(u);l.set(u,Po.Completed)})}return o}};Ge.ValueScope=kl});var ee=U(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.or=te.and=te.not=te.CodeGen=te.operators=te.varKinds=te.ValueScopeName=te.ValueScope=te.Scope=te.Name=te.regexpCode=te.stringify=te.getProperty=te.nil=te.strConcat=te.str=te._=void 0;var ae=Fr(),mt=Sl(),Yt=Fr();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return Yt._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return Yt.str}});Object.defineProperty(te,"strConcat",{enumerable:!0,get:function(){return Yt.strConcat}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return Yt.nil}});Object.defineProperty(te,"getProperty",{enumerable:!0,get:function(){return Yt.getProperty}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return Yt.stringify}});Object.defineProperty(te,"regexpCode",{enumerable:!0,get:function(){return Yt.regexpCode}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return Yt.Name}});var Lo=Sl();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return Lo.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return Lo.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return Lo.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return Lo.varKinds}});te.operators={GT:new ae._Code(">"),GTE:new ae._Code(">="),LT:new ae._Code("<"),LTE:new ae._Code("<="),EQ:new ae._Code("==="),NEQ:new ae._Code("!=="),NOT:new ae._Code("!"),OR:new ae._Code("||"),AND:new ae._Code("&&"),ADD:new ae._Code("+")};var Ct=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},_l=class extends Ct{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?mt.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=Gn(this.rhs,e,n)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},Co=class extends Ct{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 ae.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Gn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return No(e,this.rhs)}},$l=class extends Co{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},xl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Tl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Rl=class extends Ct{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},El=class extends Ct{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=Gn(this.code,e,n),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},Hr=class extends Ct{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)||(WS(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>bn(e,n.names),{})}},Ot=class extends Hr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Pl=class extends Hr{},Vn=class extends Ot{};Vn.kind="else";var mn=class t extends Ot{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 Vn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(lf(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=Gn(this.condition,e,n),this}get names(){let e=super.names;return No(e,this.condition),this.else&&bn(e,this.else.names),e}};mn.kind="if";var gn=class extends Ot{};gn.kind="for";var Al=class extends gn{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=Gn(this.iteration,e,n),this}get names(){return bn(super.names,this.iteration.names)}},Il=class extends gn{constructor(e,n,r,s){super(),this.varKind=e,this.name=n,this.from=r,this.to=s}render(e){let n=e.es5?mt.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=No(super.names,this.from);return No(e,this.to)}},Oo=class extends gn{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=Gn(this.iterable,e,n),this}get names(){return bn(super.names,this.iterable.names)}},Kr=class extends Ot{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)}};Kr.kind="func";var Vr=class extends Hr{render(e){return"return "+super.render(e)}};Vr.kind="return";var Cl=class extends Ot{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&&bn(e,this.catch.names),this.finally&&bn(e,this.finally.names),e}},Gr=class extends Ot{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Gr.kind="catch";var Wr=class extends Ot{render(e){return"finally"+super.render(e)}};Wr.kind="finally";var Ol=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
1771
+ `:""},this._extScope=e,this._scope=new mt.Scope({parent:e}),this._nodes=[new Pl]}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 _l(e,o,r)),o}const(e,n,r){return this._def(mt.varKinds.const,e,n,r)}let(e,n,r){return this._def(mt.varKinds.let,e,n,r)}var(e,n,r){return this._def(mt.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new Co(e,n,r))}add(e,n){return this._leafNode(new $l(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new El(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,ae.addCodeArg)(n,s));return n.push("}"),new ae._Code(n)}if(e,n,r){if(this._blockNode(new mn(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 mn(e))}else(){return this._elseNode(new Vn)}endIf(){return this._endBlockNode(mn,Vn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Al(e),n)}forRange(e,n,r,s,o=this.opts.es5?mt.varKinds.var:mt.varKinds.let){let i=this._scope.toName(e);return this._for(new Il(o,i,n,r),()=>s(i))}forOf(e,n,r,s=mt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=n instanceof ae.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ae._)`${i}.length`,a=>{this.var(o,(0,ae._)`${i}[${a}]`),r(o)})}return this._for(new Oo("of",s,o,n),()=>r(o))}forIn(e,n,r,s=this.opts.es5?mt.varKinds.var:mt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ae._)`Object.keys(${n})`,r);let o=this._scope.toName(e);return this._for(new Oo("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(gn)}label(e){return this._leafNode(new xl(e))}break(e){return this._leafNode(new Tl(e))}return(e){let n=new Vr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Cl;if(this._blockNode(s),this.code(e),n){let o=this.name("e");this._currNode=s.catch=new Gr(o),n(o)}return r&&(this._currNode=s.finally=new Wr,this.code(r)),this._endBlockNode(Gr,Wr)}throw(e){return this._leafNode(new Rl(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=ae.nil,r,s){return this._blockNode(new Kr(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Kr)}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 mn))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}};te.CodeGen=Ol;function bn(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function No(t,e){return e instanceof ae._CodeOrName?bn(t,e.names):t}function Gn(t,e,n){if(t instanceof ae.Name)return r(t);if(!s(t))return t;return new ae._Code(t._items.reduce((o,i)=>(i instanceof ae.Name&&(i=r(i)),i instanceof ae._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 ae._Code&&o._items.some(i=>i instanceof ae.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function WS(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function lf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${Nl(t)}`}te.not=lf;var JS=cf(te.operators.AND);function YS(...t){return t.reduce(JS)}te.and=YS;var ZS=cf(te.operators.OR);function QS(...t){return t.reduce(ZS)}te.or=QS;function cf(t){return(e,n)=>e===ae.nil?n:n===ae.nil?e:(0,ae._)`${Nl(e)} ${t} ${Nl(n)}`}function Nl(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var de=U(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 ge=ee(),XS=Fr();function e_(t){let e={};for(let n of t)e[n]=!0;return e}ne.toHash=e_;function t_(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(pf(t,e),!hf(e,t.self.RULES.all))}ne.alwaysValidSchema=t_;function pf(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]||gf(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=pf;function hf(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ne.schemaHasRules=hf;function n_(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}ne.schemaHasRulesButRef=n_;function r_({topSchemaRef:t,schemaPath:e},n,r,s){if(!s){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,ge._)`${n}`}return(0,ge._)`${t}${e}${(0,ge.getProperty)(r)}`}ne.schemaRefOrVal=r_;function s_(t){return ff(decodeURIComponent(t))}ne.unescapeFragment=s_;function o_(t){return encodeURIComponent(jl(t))}ne.escapeFragment=o_;function jl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=jl;function ff(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=ff;function i_(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ne.eachItem=i_;function df({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(s,o,i,a)=>{let l=i===void 0?o:i instanceof ge.Name?(o instanceof ge.Name?t(s,o,i):e(s,o,i),i):o instanceof ge.Name?(e(s,i,o),o):n(o,i);return a===ge.Name&&!(l instanceof ge.Name)?r(s,l):l}}ne.mergeEvaluated={props:df({mergeNames:(t,e,n)=>t.if((0,ge._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,ge._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,ge._)`${n} || {}`).code((0,ge._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,ge._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,ge._)`${n} || {}`),Ul(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:mf}),items:df({mergeNames:(t,e,n)=>t.if((0,ge._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,ge._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,ge._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,ge._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function mf(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,ge._)`{}`);return e!==void 0&&Ul(t,n,e),n}ne.evaluatedPropsToName=mf;function Ul(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(r)}`,!0))}ne.setEvaluated=Ul;var uf={};function a_(t,e){return t.scopeValue("func",{ref:e,code:uf[e.code]||(uf[e.code]=new XS._Code(e.code))})}ne.useFunc=a_;var Ll;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ll||(ne.Type=Ll={}));function l_(t,e,n){if(t instanceof ge.Name){let r=e===Ll.Num;return n?r?(0,ge._)`"[" + ${t} + "]"`:(0,ge._)`"['" + ${t} + "']"`:r?(0,ge._)`"/" + ${t}`:(0,ge._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,ge.getProperty)(t).toString():"/"+jl(t)}ne.getErrorPath=l_;function gf(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=gf});var Nt=U(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var Oe=ee(),c_={data:new Oe.Name("data"),valCxt:new Oe.Name("valCxt"),instancePath:new Oe.Name("instancePath"),parentData:new Oe.Name("parentData"),parentDataProperty:new Oe.Name("parentDataProperty"),rootData:new Oe.Name("rootData"),dynamicAnchors:new Oe.Name("dynamicAnchors"),vErrors:new Oe.Name("vErrors"),errors:new Oe.Name("errors"),this:new Oe.Name("this"),self:new Oe.Name("self"),scope:new Oe.Name("scope"),json:new Oe.Name("json"),jsonPos:new Oe.Name("jsonPos"),jsonLen:new Oe.Name("jsonLen"),jsonPart:new Oe.Name("jsonPart")};Dl.default=c_});var Jr=U(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.extendErrors=Ne.resetErrorsCount=Ne.reportExtraError=Ne.reportError=Ne.keyword$DataError=Ne.keywordError=void 0;var ue=ee(),jo=de(),Me=Nt();Ne.keywordError={message:({keyword:t})=>(0,ue.str)`must pass "${t}" keyword validation`};Ne.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ue.str)`"${t}" keyword must be ${e} ($data)`:(0,ue.str)`"${t}" keyword is invalid ($data)`};function d_(t,e=Ne.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=wf(t,e,n);r??(i||a)?bf(o,l):yf(s,(0,ue._)`[${l}]`)}Ne.reportError=d_;function u_(t,e=Ne.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=wf(t,e,n);bf(s,a),o||i||yf(r,Me.default.vErrors)}Ne.reportExtraError=u_;function p_(t,e){t.assign(Me.default.errors,e),t.if((0,ue._)`${Me.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ue._)`${Me.default.vErrors}.length`,e),()=>t.assign(Me.default.vErrors,null)))}Ne.resetErrorsCount=p_;function h_({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,Me.default.errors,a=>{t.const(i,(0,ue._)`${Me.default.vErrors}[${a}]`),t.if((0,ue._)`${i}.instancePath === undefined`,()=>t.assign((0,ue._)`${i}.instancePath`,(0,ue.strConcat)(Me.default.instancePath,o.errorPath))),t.assign((0,ue._)`${i}.schemaPath`,(0,ue.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,ue._)`${i}.schema`,n),t.assign((0,ue._)`${i}.data`,r))})}Ne.extendErrors=h_;function bf(t,e){let n=t.const("err",e);t.if((0,ue._)`${Me.default.vErrors} === null`,()=>t.assign(Me.default.vErrors,(0,ue._)`[${n}]`),(0,ue._)`${Me.default.vErrors}.push(${n})`),t.code((0,ue._)`${Me.default.errors}++`)}function yf(t,e){let{gen:n,validateName:r,schemaEnv:s}=t;s.$async?n.throw((0,ue._)`new ${t.ValidationError}(${e})`):(n.assign((0,ue._)`${r}.errors`,e),n.return(!1))}var yn={keyword:new ue.Name("keyword"),schemaPath:new ue.Name("schemaPath"),params:new ue.Name("params"),propertyName:new ue.Name("propertyName"),message:new ue.Name("message"),schema:new ue.Name("schema"),parentSchema:new ue.Name("parentSchema")};function wf(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,ue._)`{}`:f_(t,e,n)}function f_(t,e,n={}){let{gen:r,it:s}=t,o=[m_(s,n),g_(t,n)];return b_(t,e,o),r.object(...o)}function m_({errorPath:t},{instancePath:e}){let n=e?(0,ue.str)`${t}${(0,jo.getErrorPath)(e,jo.Type.Str)}`:t;return[Me.default.instancePath,(0,ue.strConcat)(Me.default.instancePath,n)]}function g_({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let s=r?e:(0,ue.str)`${e}/${t}`;return n&&(s=(0,ue.str)`${s}${(0,jo.getErrorPath)(n,jo.Type.Str)}`),[yn.schemaPath,s]}function b_(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:f}=a;r.push([yn.keyword,s],[yn.params,typeof e=="function"?e(t):e||(0,ue._)`{}`]),l.messages&&r.push([yn.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([yn.schema,i],[yn.parentSchema,(0,ue._)`${p}${f}`],[Me.default.data,o]),u&&r.push([yn.propertyName,u])}});var kf=U(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.boolOrEmptySchema=Wn.topBoolOrEmptySchema=void 0;var y_=Jr(),w_=ee(),v_=Nt(),k_={message:"boolean schema is false"};function S_(t){let{gen:e,schema:n,validateName:r}=t;n===!1?vf(t,!1):typeof n=="object"&&n.$async===!0?e.return(v_.default.data):(e.assign((0,w_._)`${r}.errors`,null),e.return(!0))}Wn.topBoolOrEmptySchema=S_;function __(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),vf(t)):n.var(e,!0)}Wn.boolOrEmptySchema=__;function vf(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,y_.reportError)(s,k_,void 0,e)}});var ql=U(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.getRules=Jn.isJSONType=void 0;var $_=["string","number","integer","boolean","null","object","array"],x_=new Set($_);function T_(t){return typeof t=="string"&&x_.has(t)}Jn.isJSONType=T_;function R_(){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:{}}}Jn.getRules=R_});var zl=U(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.shouldUseRule=Zt.shouldUseGroup=Zt.schemaHasRulesForType=void 0;function E_({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&Sf(t,r)}Zt.schemaHasRulesForType=E_;function Sf(t,e){return e.rules.some(n=>_f(t,n))}Zt.shouldUseGroup=Sf;function _f(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))}Zt.shouldUseRule=_f});var Yr=U(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var P_=ql(),A_=zl(),I_=Jr(),Q=ee(),$f=de(),Yn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Yn||(Le.DataType=Yn={}));function C_(t){let e=xf(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}Le.getSchemaTypes=C_;function xf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(P_.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=xf;function O_(t,e){let{gen:n,data:r,opts:s}=t,o=N_(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,A_.schemaHasRulesForType)(t,e[0]));if(i){let a=Bl(e,r,s.strictNumbers,Yn.Wrong);n.if(a,()=>{o.length?L_(t,e,o):Fl(t)})}return i}Le.coerceAndCheckDataType=O_;var Tf=new Set(["string","number","integer","boolean","null"]);function N_(t,e){return e?t.filter(n=>Tf.has(n)||e==="array"&&n==="array"):[]}function L_(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,Q._)`typeof ${s}`),a=r.let("coerced",(0,Q._)`undefined`);o.coerceTypes==="array"&&r.if((0,Q._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,Q._)`${s}[0]`).assign(i,(0,Q._)`typeof ${s}`).if(Bl(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,Q._)`${a} !== undefined`);for(let u of n)(Tf.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);r.else(),Fl(t),r.endIf(),r.if((0,Q._)`${a} !== undefined`,()=>{r.assign(s,a),j_(t,a)});function l(u){switch(u){case"string":r.elseIf((0,Q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Q._)`"" + ${s}`).elseIf((0,Q._)`${s} === null`).assign(a,(0,Q._)`""`);return;case"number":r.elseIf((0,Q._)`${i} == "boolean" || ${s} === null
1772
1772
  || (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,Q._)`+${s}`);return;case"integer":r.elseIf((0,Q._)`${i} === "boolean" || ${s} === null
1773
1773
  || (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,Q._)`+${s}`);return;case"boolean":r.elseIf((0,Q._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,Q._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":r.elseIf((0,Q._)`${s} === "" || ${s} === 0 || ${s} === false`),r.assign(a,null);return;case"array":r.elseIf((0,Q._)`${i} === "string" || ${i} === "number"
1774
- || ${i} === "boolean" || ${s} === null`).assign(a,(0,Q._)`[${s}]`)}}}function j_({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Q._)`${e} !== undefined`,()=>t.assign((0,Q._)`${e}[${n}]`,r))}function Ml(t,e,n,r=Yn.Correct){let s=r===Yn.Correct?Q.operators.EQ:Q.operators.NEQ,o;switch(t){case"null":return(0,Q._)`${e} ${s} null`;case"array":o=(0,Q._)`Array.isArray(${e})`;break;case"object":o=(0,Q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,Q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,Q._)`typeof ${e} ${s} ${t}`}return r===Yn.Correct?o:(0,Q.not)(o);function i(a=Q.nil){return(0,Q.and)((0,Q._)`typeof ${e} == "number"`,a,n?(0,Q._)`isFinite(${e})`:Q.nil)}}Le.checkDataType=Ml;function Bl(t,e,n,r){if(t.length===1)return Ml(t[0],e,n,r);let s,o=(0,$f.toHash)(t);if(o.array&&o.object){let i=(0,Q._)`typeof ${e} != "object"`;s=o.null?i:(0,Q._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=Q.nil;o.number&&delete o.integer;for(let i in o)s=(0,Q.and)(s,Ml(i,e,n,r));return s}Le.checkDataTypes=Bl;var U_={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Q._)`{type: ${t}}`:(0,Q._)`{type: ${e}}`};function Fl(t){let e=D_(t);(0,I_.reportError)(e,U_)}Le.reportTypeError=Fl;function D_(t){let{gen:e,data:n,schema:r}=t,s=(0,$f.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var Ef=U(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.assignDefaults=void 0;var Zn=ee(),q_=de();function z_(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)Rf(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>Rf(t,o,s.default))}Uo.assignDefaults=z_;function Rf(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,Zn._)`${o}${(0,Zn.getProperty)(e)}`;if(s){(0,q_.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Zn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Zn._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,Zn._)`${a} = ${(0,Zn.stringify)(n)}`)}});var at=U(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.validateUnion=fe.validateArray=fe.usePattern=fe.callValidateCode=fe.schemaProperties=fe.allSchemaProperties=fe.noPropertyInData=fe.propertyInData=fe.isOwnProperty=fe.hasPropFunc=fe.reportMissingProp=fe.checkMissingProp=fe.checkReportMissingProp=void 0;var be=ee(),Hl=de(),Xt=Nt(),M_=de();function B_(t,e){let{gen:n,data:r,it:s}=t;n.if(Vl(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,be._)`${e}`},!0),t.error()})}fe.checkReportMissingProp=B_;function F_({gen:t,data:e,it:{opts:n}},r,s){return(0,be.or)(...r.map(o=>(0,be.and)(Vl(t,e,o,n.ownProperties),(0,be._)`${s} = ${o}`)))}fe.checkMissingProp=F_;function H_(t,e){t.setParams({missingProperty:e},!0),t.error()}fe.reportMissingProp=H_;function Pf(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,be._)`Object.prototype.hasOwnProperty`})}fe.hasPropFunc=Pf;function Kl(t,e,n){return(0,be._)`${Pf(t)}.call(${e}, ${n})`}fe.isOwnProperty=Kl;function K_(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} !== undefined`;return r?(0,be._)`${s} && ${Kl(t,e,n)}`:s}fe.propertyInData=K_;function Vl(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} === undefined`;return r?(0,be.or)(s,(0,be.not)(Kl(t,e,n))):s}fe.noPropertyInData=Vl;function Af(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}fe.allSchemaProperties=Af;function V_(t,e){return Af(e).filter(n=>!(0,Hl.alwaysValidSchema)(t,e[n]))}fe.schemaProperties=V_;function G_({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,l,u){let p=u?(0,be._)`${t}, ${e}, ${r}${s}`:e,f=[[Xt.default.instancePath,(0,be.strConcat)(Xt.default.instancePath,o)],[Xt.default.parentData,i.parentData],[Xt.default.parentDataProperty,i.parentDataProperty],[Xt.default.rootData,Xt.default.rootData]];i.opts.dynamicRef&&f.push([Xt.default.dynamicAnchors,Xt.default.dynamicAnchors]);let _=(0,be._)`${p}, ${n.object(...f)}`;return l!==be.nil?(0,be._)`${a}.call(${l}, ${_})`:(0,be._)`${a}(${_})`}fe.callValidateCode=G_;var W_=(0,be._)`new RegExp`;function J_({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,be._)`${s.code==="new RegExp"?W_:(0,M_.useFunc)(t,s)}(${n}, ${r})`})}fe.usePattern=J_;function Y_(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,be._)`${n}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Hl.Type.Num},o),e.if((0,be.not)(o),a)})}}fe.validateArray=Y_;function Z_(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,Hl.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,be._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,be.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}fe.validateUnion=Z_});var Of=U(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateKeywordUsage=St.validSchemaType=St.funcKeywordCode=St.macroKeywordCode=void 0;var Be=ee(),wn=Nt(),Q_=at(),X_=Jr();function e$(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=Cf(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:Be.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}St.macroKeywordCode=e$;function t$(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;r$(l,e);let u=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=Cf(r,s,u),f=r.let("valid");t.block$data(f,_),t.ok((n=e.valid)!==null&&n!==void 0?n:f);function _(){if(e.errors===!1)T(),e.modifying&&If(t),E(()=>t.error());else{let P=e.async?v():k();e.modifying&&If(t),E(()=>n$(t,P))}}function v(){let P=r.let("ruleErrs",null);return r.try(()=>T((0,Be._)`await `),C=>r.assign(f,!1).if((0,Be._)`${C} instanceof ${l.ValidationError}`,()=>r.assign(P,(0,Be._)`${C}.errors`),()=>r.throw(C))),P}function k(){let P=(0,Be._)`${p}.errors`;return r.assign(P,null),T(Be.nil),P}function T(P=e.async?(0,Be._)`await `:Be.nil){let C=l.opts.passContext?wn.default.this:wn.default.self,D=!("compile"in e&&!a||e.schema===!1);r.assign(f,(0,Be._)`${P}${(0,Q_.callValidateCode)(t,p,C,D)}`,e.modifying)}function E(P){var C;r.if((0,Be.not)((C=e.valid)!==null&&C!==void 0?C:f),P)}}St.funcKeywordCode=t$;function If(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Be._)`${r.parentData}[${r.parentDataProperty}]`))}function n$(t,e){let{gen:n}=t;n.if((0,Be._)`Array.isArray(${e})`,()=>{n.assign(wn.default.vErrors,(0,Be._)`${wn.default.vErrors} === null ? ${e} : ${wn.default.vErrors}.concat(${e})`).assign(wn.default.errors,(0,Be._)`${wn.default.vErrors}.length`),(0,X_.extendErrors)(t)},()=>t.error())}function r$({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Cf(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,Be.stringify)(n)})}function s$(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")}St.validSchemaType=s$;function o$({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)}}St.validateKeywordUsage=o$});var Lf=U(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.extendSubschemaMode=en.extendSubschemaData=en.getSubschema=void 0;var _t=ee(),Nf=de();function i$(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,_t._)`${t.schemaPath}${(0,_t.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,_t._)`${t.schemaPath}${(0,_t.getProperty)(e)}${(0,_t.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Nf.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')}en.getSubschema=i$;function a$(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:f}=e,_=a.let("data",(0,_t._)`${e.data}${(0,_t.getProperty)(n)}`,!0);l(_),t.errorPath=(0,_t.str)`${u}${(0,Nf.getErrorPath)(n,r,f.jsPropertySyntax)}`,t.parentDataProperty=(0,_t._)`${n}`,t.dataPathArr=[...p,t.parentDataProperty]}if(s!==void 0){let u=s instanceof _t.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]}}en.extendSubschemaData=a$;function l$(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}en.extendSubschemaMode=l$});var Gl=U((MN,jf)=>{"use strict";jf.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 Df=U((BN,Uf)=>{"use strict";var tn=Uf.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(){};Do(e,r,s,t,"",t)};tn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};tn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};tn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};tn.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 Do(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 f=r[p];if(Array.isArray(f)){if(p in tn.arrayKeywords)for(var _=0;_<f.length;_++)Do(t,e,n,f[_],s+"/"+p+"/"+_,o,s,p,r,_)}else if(p in tn.propsKeywords){if(f&&typeof f=="object")for(var v in f)Do(t,e,n,f[v],s+"/"+p+"/"+c$(v),o,s,p,r,v)}else(p in tn.keywords||t.allKeys&&!(p in tn.skipKeywords))&&Do(t,e,n,f,s+"/"+p,o,s,p,r)}n(r,s,o,i,a,l,u)}}function c$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Zr=U(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.getSchemaRefs=We.resolveUrl=We.normalizeId=We._getFullPath=We.getFullPath=We.inlineRef=void 0;var d$=de(),u$=Gl(),p$=Df(),h$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function f$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Wl(t):e?qf(t)<=e:!1}We.inlineRef=f$;var m$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Wl(t){for(let e in t){if(m$.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Wl)||typeof n=="object"&&Wl(n))return!0}return!1}function qf(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,d$.eachItem)(t[n],r=>e+=qf(r)),e===1/0))return 1/0}return e}function zf(t,e="",n){n!==!1&&(e=Qn(e));let r=t.parse(e);return Mf(t,r)}We.getFullPath=zf;function Mf(t,e){return t.serialize(e).split("#")[0]+"#"}We._getFullPath=Mf;var g$=/#\/?$/;function Qn(t){return t?t.replace(g$,""):""}We.normalizeId=Qn;function b$(t,e,n){return n=Qn(n),t.resolve(e,n)}We.resolveUrl=b$;var y$=/^[a-z_][-a-z0-9._]*$/i;function w$(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=Qn(t[n]||e),o={"":s},i=zf(r,s,!1),a={},l=new Set;return p$(t,{allKeys:!0},(f,_,v,k)=>{if(k===void 0)return;let T=i+_,E=o[k];typeof f[n]=="string"&&(E=P.call(this,f[n])),C.call(this,f.$anchor),C.call(this,f.$dynamicAnchor),o[_]=E;function P(D){let se=this.opts.uriResolver.resolve;if(D=Qn(E?se(E,D):D),l.has(D))throw p(D);l.add(D);let Y=this.refs[D];return typeof Y=="string"&&(Y=this.refs[Y]),typeof Y=="object"?u(f,Y.schema,D):D!==Qn(T)&&(D[0]==="#"?(u(f,a[D],D),a[D]=f):this.refs[D]=T),D}function C(D){if(typeof D=="string"){if(!y$.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(f,_,v){if(_!==void 0&&!u$(f,_))throw p(v)}function p(f){return new Error(`reference "${f}" resolves to more than one schema`)}}We.getSchemaRefs=w$});var es=U(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.getData=nn.KeywordCxt=nn.validateFunctionCode=void 0;var Vf=kf(),Bf=Yr(),Yl=zl(),qo=Yr(),v$=Ef(),Xr=Of(),Jl=Lf(),z=ee(),Z=Nt(),k$=Zr(),Lt=de(),Qr=Jr();function S$(t){if(Jf(t)&&(Yf(t),Wf(t))){x$(t);return}Gf(t,()=>(0,Vf.topBoolOrEmptySchema)(t))}nn.validateFunctionCode=S$;function Gf({gen:t,validateName:e,schema:n,schemaEnv:r,opts:s},o){s.code.es5?t.func(e,(0,z._)`${Z.default.data}, ${Z.default.valCxt}`,r.$async,()=>{t.code((0,z._)`"use strict"; ${Ff(n,s)}`),$$(t,s),t.code(o)}):t.func(e,(0,z._)`${Z.default.data}, ${_$(s)}`,r.$async,()=>t.code(Ff(n,s)).code(o))}function _$(t){return(0,z._)`{${Z.default.instancePath}="", ${Z.default.parentData}, ${Z.default.parentDataProperty}, ${Z.default.rootData}=${Z.default.data}${t.dynamicRef?(0,z._)`, ${Z.default.dynamicAnchors}={}`:z.nil}}={}`}function $$(t,e){t.if(Z.default.valCxt,()=>{t.var(Z.default.instancePath,(0,z._)`${Z.default.valCxt}.${Z.default.instancePath}`),t.var(Z.default.parentData,(0,z._)`${Z.default.valCxt}.${Z.default.parentData}`),t.var(Z.default.parentDataProperty,(0,z._)`${Z.default.valCxt}.${Z.default.parentDataProperty}`),t.var(Z.default.rootData,(0,z._)`${Z.default.valCxt}.${Z.default.rootData}`),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,z._)`${Z.default.valCxt}.${Z.default.dynamicAnchors}`)},()=>{t.var(Z.default.instancePath,(0,z._)`""`),t.var(Z.default.parentData,(0,z._)`undefined`),t.var(Z.default.parentDataProperty,(0,z._)`undefined`),t.var(Z.default.rootData,Z.default.data),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,z._)`{}`)})}function x$(t){let{schema:e,opts:n,gen:r}=t;Gf(t,()=>{n.$comment&&e.$comment&&Qf(t),A$(t),r.let(Z.default.vErrors,null),r.let(Z.default.errors,0),n.unevaluated&&T$(t),Zf(t),O$(t)})}function T$(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,z._)`${n}.evaluated`),e.if((0,z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,z._)`${t.evaluated}.props`,(0,z._)`undefined`)),e.if((0,z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,z._)`${t.evaluated}.items`,(0,z._)`undefined`))}function Ff(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,z._)`/*# sourceURL=${n} */`:z.nil}function R$(t,e){if(Jf(t)&&(Yf(t),Wf(t))){E$(t,e);return}(0,Vf.boolOrEmptySchema)(t,e)}function Wf({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 Jf(t){return typeof t.schema!="boolean"}function E$(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&Qf(t),I$(t),C$(t);let o=r.const("_errs",Z.default.errors);Zf(t,o),r.var(e,(0,z._)`${o} === ${Z.default.errors}`)}function Yf(t){(0,Lt.checkUnknownRules)(t),P$(t)}function Zf(t,e){if(t.opts.jtd)return Hf(t,[],!1,e);let n=(0,Bf.getSchemaTypes)(t.schema),r=(0,Bf.coerceAndCheckDataType)(t,n);Hf(t,n,!r,e)}function P$(t){let{schema:e,errSchemaPath:n,opts:r,self:s}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Lt.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function A$(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Lt.checkStrictMode)(t,"default is ignored in the schema root")}function I$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,k$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function C$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Qf({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:s}){let o=n.$comment;if(s.$comment===!0)t.code((0,z._)`${Z.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,z.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${Z.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function O$(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=t;n.$async?e.if((0,z._)`${Z.default.errors} === 0`,()=>e.return(Z.default.data),()=>e.throw((0,z._)`new ${s}(${Z.default.vErrors})`)):(e.assign((0,z._)`${r}.errors`,Z.default.vErrors),o.unevaluated&&N$(t),e.return((0,z._)`${Z.default.errors} === 0`))}function N$({gen:t,evaluated:e,props:n,items:r}){n instanceof z.Name&&t.assign((0,z._)`${e}.props`,n),r instanceof z.Name&&t.assign((0,z._)`${e}.items`,r)}function Hf(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,Lt.schemaHasRulesButRef)(o,p))){s.block(()=>em(t,"$ref",p.all.$ref.definition));return}l.jtd||L$(t,e),s.block(()=>{for(let _ of p.rules)f(_);f(p.post)});function f(_){(0,Yl.shouldUseGroup)(o,_)&&(_.type?(s.if((0,qo.checkDataType)(_.type,i,l.strictNumbers)),Kf(t,_),e.length===1&&e[0]===_.type&&n&&(s.else(),(0,qo.reportTypeError)(t)),s.endIf()):Kf(t,_),a||s.if((0,z._)`${Z.default.errors} === ${r||0}`))}}function Kf(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,v$.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,Yl.shouldUseRule)(r,o)&&em(t,o.keyword,o.definition,e.type)})}function L$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(j$(t,e),t.opts.allowUnionTypes||U$(t,e),D$(t,t.dataTypes))}function j$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Xf(t.dataTypes,n)||Zl(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),z$(t,e)}}function U$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Zl(t,"use allowUnionTypes to allow union type keyword")}function D$(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,Yl.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>q$(e,i))&&Zl(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function q$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Xf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function z$(t,e){let n=[];for(let r of t.dataTypes)Xf(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Zl(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Lt.checkStrictMode)(t,e,t.opts.strictTypes)}var zo=class{constructor(e,n,r){if((0,Xr.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,Lt.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",tm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Xr.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",Z.default.errors))}result(e,n,r){this.failResult((0,z.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,z.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,z._)`${n} !== undefined && (${(0,z.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?Qr.reportExtraError:Qr.reportError)(this,this.def.error,n)}$dataError(){(0,Qr.reportError)(this,this.def.$dataError||Qr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Qr.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=z.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=z.nil,n=z.nil){if(!this.$data)return;let{gen:r,schemaCode:s,schemaType:o,def:i}=this;r.if((0,z.or)((0,z._)`${s} === undefined`,n)),e!==z.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==z.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:s,it:o}=this;return(0,z.or)(i(),a());function i(){if(r.length){if(!(n instanceof z.Name))throw new Error("ajv implementation error");let l=Array.isArray(r)?r:[r];return(0,z._)`${(0,qo.checkDataTypes)(l,n,o.opts.strictNumbers,qo.DataType.Wrong)}`}return z.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,z._)`!${l}(${n})`}return z.nil}}subschema(e,n){let r=(0,Jl.getSubschema)(this.it,e);(0,Jl.extendSubschemaData)(r,this.it,e),(0,Jl.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return R$(s,n),s}mergeEvaluated(e,n){let{it:r,gen:s}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Lt.mergeEvaluated.props(s,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Lt.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,z.Name)),!0}};nn.KeywordCxt=zo;function em(t,e,n,r){let s=new zo(t,n,e);"code"in n?n.code(s,r):s.$data&&n.validate?(0,Xr.funcKeywordCode)(s,n):"macro"in n?(0,Xr.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,Xr.funcKeywordCode)(s,n)}var M$=/^\/(?:[^~]|~0|~1)*$/,B$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function tm(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return Z.default.rootData;if(t[0]==="/"){if(!M$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Z.default.rootData}else{let u=B$.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,z._)`${o}${(0,z.getProperty)((0,Lt.unescapeJsonPointer)(u))}`,i=(0,z._)`${i} && ${o}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}nn.getData=tm});var Mo=U(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var Ql=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Xl.default=Ql});var ts=U(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var ec=Zr(),tc=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,ec.resolveUrl)(e,n,r),this.missingSchema=(0,ec.normalizeId)((0,ec.getFullPath)(e,this.missingRef))}};nc.default=tc});var Fo=U(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var gt=ee(),F$=Mo(),vn=Nt(),bt=Zr(),nm=de(),H$=es(),Xn=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,bt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};lt.SchemaEnv=Xn;function sc(t){let e=rm.call(this,t);if(e)return e;let n=(0,bt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new gt.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:F$.default,code:(0,gt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:vn.default.data,parentData:vn.default.parentData,parentDataProperty:vn.default.parentDataProperty,dataNames:[vn.default.data],dataPathArr:[gt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,gt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:gt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,gt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,H$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let f=i.toString();p=`${i.scopeRefs(vn.default.scope)}return ${f}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let v=new Function(`${vn.default.self}`,`${vn.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:v}),v.errors=null,v.schema=t.schema,v.schemaEnv=t,t.$async&&(v.$async=!0),this.opts.code.source===!0&&(v.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:T}=u;v.evaluated={props:k instanceof gt.Name?void 0:k,items:T instanceof gt.Name?void 0:T,dynamicProps:k instanceof gt.Name,dynamicItems:T instanceof gt.Name},v.source&&(v.source.evaluated=(0,gt.stringify)(v.evaluated))}return t.validate=v,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)}}lt.compileSchema=sc;function K$(t,e,n){var r;n=(0,bt.resolveUrl)(this.opts.uriResolver,e,n);let s=t.refs[n];if(s)return s;let o=W$.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 Xn({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=V$.call(this,o)}lt.resolveRef=K$;function V$(t){return(0,bt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:sc.call(this,t)}function rm(t){for(let e of this._compilations)if(G$(e,t))return e}lt.getCompilingSchema=rm;function G$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function W$(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Bo.call(this,t,e)}function Bo(t,e){let n=this.opts.uriResolver.parse(e),r=(0,bt._getFullPath)(this.opts.uriResolver,n),s=(0,bt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===s)return rc.call(this,n,t);let o=(0,bt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Bo.call(this,t,i);return typeof a?.schema!="object"?void 0:rc.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||sc.call(this,i),o===(0,bt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(s=(0,bt.resolveUrl)(this.opts.uriResolver,s,u)),new Xn({schema:a,schemaId:l,root:t,baseId:s})}return rc.call(this,n,i)}}lt.resolveSchema=Bo;var J$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function rc(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,nm.unescapeFragment)(a)];if(l===void 0)return;n=l;let u=typeof n=="object"&&n[this.opts.schemaId];!J$.has(a)&&u&&(e=(0,bt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,nm.schemaHasRulesButRef)(n,this.RULES)){let a=(0,bt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=Bo.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new Xn({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var sm=U((WN,Y$)=>{Y$.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 ac=U((JN,dm)=>{"use strict";var Z$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),im=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),oc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),am=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Q$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function ic(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 X$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function om(t){return t.length=0,!0}function ex(t,e,n){if(t.length){let r=ic(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function tx(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=ex;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=om}else{s.push(u);continue}}return s.length&&(a===om?n.zone=s.join(""):i?r.push(s.join("")):r.push(ic(s))),n.address=r.join(""),n}function lm(t){if(nx(t,":")<2)return{host:t,isIPV6:!1};let e=tx(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 nx(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function rx(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 sx={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ox=/[@/?#:]/g,ix=/[@/?#]/g;function cm(t,e){let n=e?ix:ox;return n.lastIndex=0,t.replace(n,r=>sx[r])}function ax(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(oc(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&am(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function lx(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(oc(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&am(o)?e+=o:e+="%"+s,n+=2;continue}}Q$(t[n])?e+=t[n]:e+=escape(t[n])}return e}function cx(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(oc(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function dx(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!im(n)){let r=lm(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=cm(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}dm.exports={nonSimpleDomain:X$,recomposeAuthority:dx,reescapeHostDelimiters:cm,normalizePercentEncoding:ax,normalizePathEncoding:lx,escapePreservingEscapes:cx,removeDotSegments:rx,isIPv4:im,isUUID:Z$,normalizeIPv6:lm,stringArrayToHexStripped:ic}});var mm=U((YN,fm)=>{"use strict";var{isUUID:ux}=ac(),px=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,hx=["http","https","ws","wss","urn","urn:uuid"];function fx(t){return hx.indexOf(t)!==-1}function lc(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 um(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function pm(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 mx(t){return t.secure=lc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function gx(t){if((t.port===(lc(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 bx(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(px);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=cc(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function yx(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=cc(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 wx(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!ux(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function vx(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var hm={scheme:"http",domainHost:!0,parse:um,serialize:pm},kx={scheme:"https",domainHost:hm.domainHost,parse:um,serialize:pm},Ho={scheme:"ws",domainHost:!0,parse:mx,serialize:gx},Sx={scheme:"wss",domainHost:Ho.domainHost,parse:Ho.parse,serialize:Ho.serialize},_x={scheme:"urn",parse:bx,serialize:yx,skipNormalize:!0},$x={scheme:"urn:uuid",parse:wx,serialize:vx,skipNormalize:!0},Ko={http:hm,https:kx,ws:Ho,wss:Sx,urn:_x,"urn:uuid":$x};Object.setPrototypeOf(Ko,null);function cc(t){return t&&(Ko[t]||Ko[t.toLowerCase()])||void 0}fm.exports={wsIsSecure:lc,SCHEMES:Ko,isValidSchemeName:fx,getSchemeHandler:cc}});var vm=U((ZN,Wo)=>{"use strict";var{normalizeIPv6:xx,removeDotSegments:ns,recomposeAuthority:Tx,normalizePercentEncoding:Rx,normalizePathEncoding:Ex,escapePreservingEscapes:Px,reescapeHostDelimiters:Ax,isIPv4:Ix,nonSimpleDomain:Cx}=ac(),{SCHEMES:Ox,getSchemeHandler:bm}=mm();function Nx(t,e){return typeof t=="string"?t=Mx(t,e):typeof t=="object"&&(t=Go(kn(t,e),e)),t}function Lx(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=Vo(t,r),{parsed:i,malformedAuthorityOrPort:a}=Vo(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=ym(s,i,r,!0);return r.skipEscape=!0,kn(l,r)}function ym(t,e,n,r){let s={};return r||(t=Go(kn(t,n),n),e=Go(kn(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=ns(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=ns(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=ns(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=ns(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 jx(t,e,n){let r=gm(t,n),s=gm(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function kn(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=bm(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=Rx(n.path):(n.path=Px(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=Tx(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=ns(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 Ux=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Dx=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,qx=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function zx(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 Vo(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(Dx);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(qx);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(Ux);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=zx(r,l);if(u!==void 0&&(r.error=r.error||u,s=!0),r.host)if(Ix(r.host)===!1){let _=xx(r.host);r.host=_.host.toLowerCase(),o=_.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=bm(n.scheme||r.scheme);if(!n.unicodeSupport&&(!p||!p.unicodeSupport)&&r.host&&(n.domainHost||p&&p.domainHost)&&o===!1&&Cx(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(f){r.error=r.error||"Host's domain name can not be converted to ASCII: "+f}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Ax(unescape(r.host),o))),r.path&&(r.path=Ex(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 Go(t,e){return Vo(t,e).parsed}function Mx(t,e){return wm(t,e).normalized}function wm(t,e){let{parsed:n,malformedAuthorityOrPort:r}=Vo(t,e);return{normalized:r?t:kn(n,e),malformedAuthorityOrPort:r}}function gm(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=wm(t,e);return r?void 0:n}if(typeof t=="object")return kn(t,e)}var dc={SCHEMES:Ox,normalize:Nx,resolve:Lx,resolveComponent:ym,equal:jx,serialize:kn,parse:Go};Wo.exports=dc;Wo.exports.default=dc;Wo.exports.fastUri=dc});var Sm=U(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var km=vm();km.code='require("ajv/dist/runtime/uri").default';uc.default=km});var Am=U(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=void 0;var Bx=es();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return Bx.KeywordCxt}});var er=ee();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return er._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return er.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return er.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return er.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return er.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return er.CodeGen}});var Fx=Mo(),Rm=ts(),Hx=ql(),rs=Fo(),Kx=ee(),ss=Zr(),Jo=Yr(),hc=de(),_m=sm(),Vx=Sm(),Em=(t,e)=>new RegExp(t,e);Em.code="new RegExp";var Gx=["removeAdditional","useDefaults","coerceTypes"],Wx=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Jx={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."},Yx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$m=200;function Zx(t){var e,n,r,s,o,i,a,l,u,p,f,_,v,k,T,E,P,C,D,se,Y,je,Fe,jt,dt;let an=t.strict,ur=(e=t.code)===null||e===void 0?void 0:e.optimize,Ut=ur===!0||ur===void 0?1:ur||0,ln=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Em,xn=(s=t.uriResolver)!==null&&s!==void 0?s:Vx.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:an)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:an)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:an)!==null&&p!==void 0?p:"log",strictTuples:(_=(f=t.strictTuples)!==null&&f!==void 0?f:an)!==null&&_!==void 0?_:"log",strictRequired:(k=(v=t.strictRequired)!==null&&v!==void 0?v:an)!==null&&k!==void 0?k:!1,code:t.code?{...t.code,optimize:Ut,regExp:ln}:{optimize:Ut,regExp:ln},loopRequired:(T=t.loopRequired)!==null&&T!==void 0?T:$m,loopEnum:(E=t.loopEnum)!==null&&E!==void 0?E:$m,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(C=t.messages)!==null&&C!==void 0?C:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(se=t.schemaId)!==null&&se!==void 0?se:"$id",addUsedSchema:(Y=t.addUsedSchema)!==null&&Y!==void 0?Y:!0,validateSchema:(je=t.validateSchema)!==null&&je!==void 0?je:!0,validateFormats:(Fe=t.validateFormats)!==null&&Fe!==void 0?Fe:!0,unicodeRegExp:(jt=t.unicodeRegExp)!==null&&jt!==void 0?jt:!0,int32range:(dt=t.int32range)!==null&&dt!==void 0?dt:!0,uriResolver:xn}}var os=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,...Zx(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Kx.ValueScope({scope:{},prefixes:Wx,es5:n,lines:r}),this.logger=rT(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Hx.getRules)(),xm.call(this,Jx,e,"NOT SUPPORTED"),xm.call(this,Yx,e,"DEPRECATED","warn"),this._metaOpts=tT.call(this),e.formats&&Xx.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&eT.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Qx.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=_m;r==="id"&&(s={..._m},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,f){await o.call(this,p.$schema);let _=this._addSchema(p,f);return _.validate||i.call(this,_)}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(f){if(!(f instanceof Rm.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 o.call(this,f.$schema),this.refs[p]||this.addSchema(f,p,n)}async function u(p){let f=this._loading[p];if(f)return f;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,ss.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=Tm.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new rs.SchemaEnv({schema:{},schemaId:r});if(n=rs.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=Tm.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,ss.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(oT.call(this,r,n),!n)return(0,hc.eachItem)(r,o=>pc.call(this,o)),this;aT.call(this,n);let s={...n,type:(0,Jo.getJSONTypes)(n.type),schemaType:(0,Jo.getJSONTypes)(n.schemaType)};return(0,hc.eachItem)(r,s.type.length===0?o=>pc.call(this,o,s):o=>s.type.forEach(i=>pc.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]=Pm(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,ss.normalizeId)(i||r);let u=ss.getSchemaRefs.call(this,e,r);return l=new rs.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):rs.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{rs.compileSchema.call(this,e)}finally{this.opts=n}}};os.ValidationError=Fx.default;os.MissingRefError=Rm.default;Ie.default=os;function xm(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 Tm(t){return t=(0,ss.normalizeId)(t),this.schemas[t]||this.refs[t]}function Qx(){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 Xx(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function eT(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 tT(){let t={...this.opts};for(let e of Gx)delete t[e];return t}var nT={log(){},warn(){},error(){}};function rT(t){if(t===!1)return nT;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 sT=/^[a-z_$][a-z0-9_$:-]*$/i;function oT(t,e){let{RULES:n}=this;if((0,hc.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!sT.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 pc(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,Jo.getJSONTypes)(e.type),schemaType:(0,Jo.getJSONTypes)(e.schemaType)}};e.before?iT.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 iT(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 aT(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Pm(e)),t.validateSchema=this.compile(e,!0))}var lT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Pm(t){return{anyOf:[t,lT]}}});var Im=U(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var cT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};fc.default=cT});var Lm=U(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.callRef=Sn.getValidate=void 0;var dT=ts(),Cm=at(),Je=ee(),tr=Nt(),Om=Fo(),Yo=de(),uT={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 f();let p=Om.resolveRef.call(l,u,s,n);if(p===void 0)throw new dT.default(r.opts.uriResolver,s,n);if(p instanceof Om.SchemaEnv)return _(p);return v(p);function f(){if(o===u)return Zo(t,i,o,o.$async);let k=e.scopeValue("root",{ref:u});return Zo(t,(0,Je._)`${k}.validate`,u,u.$async)}function _(k){let T=Nm(t,k);Zo(t,T,k,k.$async)}function v(k){let T=e.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,Je.stringify)(k)}:{ref:k}),E=e.name("valid"),P=t.subschema({schema:k,dataTypes:[],schemaPath:Je.nil,topSchemaRef:T,errSchemaPath:n},E);t.mergeEvaluated(P),t.ok(E)}}};function Nm(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Je._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Sn.getValidate=Nm;function Zo(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,u=l.passContext?tr.default.this:Je.nil;r?p():f();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=s.let("valid");s.try(()=>{s.code((0,Je._)`await ${(0,Cm.callValidateCode)(t,e,u)}`),v(e),i||s.assign(k,!0)},T=>{s.if((0,Je._)`!(${T} instanceof ${o.ValidationError})`,()=>s.throw(T)),_(T),i||s.assign(k,!1)}),t.ok(k)}function f(){t.result((0,Cm.callValidateCode)(t,e,u),()=>v(e),()=>_(e))}function _(k){let T=(0,Je._)`${k}.errors`;s.assign(tr.default.vErrors,(0,Je._)`${tr.default.vErrors} === null ? ${T} : ${tr.default.vErrors}.concat(${T})`),s.assign(tr.default.errors,(0,Je._)`${tr.default.vErrors}.length`)}function v(k){var T;if(!o.opts.unevaluated)return;let E=(T=n?.validate)===null||T===void 0?void 0:T.evaluated;if(o.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(o.props=Yo.mergeEvaluated.props(s,E.props,o.props));else{let P=s.var("props",(0,Je._)`${k}.evaluated.props`);o.props=Yo.mergeEvaluated.props(s,P,o.props,Je.Name)}if(o.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(o.items=Yo.mergeEvaluated.items(s,E.items,o.items));else{let P=s.var("items",(0,Je._)`${k}.evaluated.items`);o.items=Yo.mergeEvaluated.items(s,P,o.items,Je.Name)}}}Sn.callRef=Zo;Sn.default=uT});var jm=U(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var pT=Im(),hT=Lm(),fT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",pT.default,hT.default];mc.default=fT});var Um=U(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var Qo=ee(),rn=Qo.operators,Xo={maximum:{okStr:"<=",ok:rn.LTE,fail:rn.GT},minimum:{okStr:">=",ok:rn.GTE,fail:rn.LT},exclusiveMaximum:{okStr:"<",ok:rn.LT,fail:rn.GTE},exclusiveMinimum:{okStr:">",ok:rn.GT,fail:rn.LTE}},mT={message:({keyword:t,schemaCode:e})=>(0,Qo.str)`must be ${Xo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Qo._)`{comparison: ${Xo[t].okStr}, limit: ${e}}`},gT={keyword:Object.keys(Xo),type:"number",schemaType:"number",$data:!0,error:mT,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Qo._)`${n} ${Xo[e].fail} ${r} || isNaN(${n})`)}};gc.default=gT});var Dm=U(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var is=ee(),bT={message:({schemaCode:t})=>(0,is.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,is._)`{multipleOf: ${t}}`},yT={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:bT,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,is._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,is._)`${i} !== parseInt(${i})`;t.fail$data((0,is._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};bc.default=yT});var zm=U(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});function qm(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}yc.default=qm;qm.code='require("ajv/dist/runtime/ucs2length").default'});var Mm=U(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var _n=ee(),wT=de(),vT=zm(),kT={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,_n.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,_n._)`{limit: ${t}}`},ST={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:kT,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?_n.operators.GT:_n.operators.LT,i=s.opts.unicode===!1?(0,_n._)`${n}.length`:(0,_n._)`${(0,wT.useFunc)(t.gen,vT.default)}(${n})`;t.fail$data((0,_n._)`${i} ${o} ${r}`)}};wc.default=ST});var Bm=U(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var _T=at(),$T=de(),nr=ee(),xT={message:({schemaCode:t})=>(0,nr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,nr._)`{pattern: ${t}}`},TT={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:xT,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,nr._)`new RegExp`:(0,$T.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,nr._)`${u}(${o}, ${a}).test(${n})`),()=>e.assign(p,!1)),t.fail$data((0,nr._)`!${p}`)}else{let l=(0,_T.usePattern)(t,s);t.fail$data((0,nr._)`!${l}.test(${n})`)}}};vc.default=TT});var Fm=U(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var as=ee(),RT={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,as.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,as._)`{limit: ${t}}`},ET={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:RT,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?as.operators.GT:as.operators.LT;t.fail$data((0,as._)`Object.keys(${n}).length ${s} ${r}`)}};kc.default=ET});var Hm=U(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var ls=at(),cs=ee(),PT=de(),AT={message:({params:{missingProperty:t}})=>(0,cs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,cs._)`{missingProperty: ${t}}`},IT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:AT,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 v=t.parentSchema.properties,{definedProperties:k}=t.it;for(let T of n)if(v?.[T]===void 0&&!k.has(T)){let E=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${T}" is not defined at "${E}" (strictRequired)`;(0,PT.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(cs.nil,f);else for(let v of n)(0,ls.checkReportMissingProp)(t,v)}function p(){let v=e.let("missing");if(l||o){let k=e.let("valid",!0);t.block$data(k,()=>_(v,k)),t.ok(k)}else e.if((0,ls.checkMissingProp)(t,n,v)),(0,ls.reportMissingProp)(t,v),e.else()}function f(){e.forOf("prop",r,v=>{t.setParams({missingProperty:v}),e.if((0,ls.noPropertyInData)(e,s,v,a.ownProperties),()=>t.error())})}function _(v,k){t.setParams({missingProperty:v}),e.forOf(v,r,()=>{e.assign(k,(0,ls.propertyInData)(e,s,v,a.ownProperties)),e.if((0,cs.not)(k),()=>{t.error(),e.break()})},cs.nil)}}};Sc.default=IT});var Km=U(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var ds=ee(),CT={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,ds.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,ds._)`{limit: ${t}}`},OT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:CT,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?ds.operators.GT:ds.operators.LT;t.fail$data((0,ds._)`${n}.length ${s} ${r}`)}};_c.default=OT});var ei=U($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var Vm=Gl();Vm.code='require("ajv/dist/runtime/equal").default';$c.default=Vm});var Gm=U(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var xc=Yr(),Ce=ee(),NT=de(),LT=ei(),jT={message:({params:{i:t,j:e}})=>(0,Ce.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ce._)`{i: ${t}, j: ${e}}`},UT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:jT,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,xc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,Ce._)`${i} === false`),t.ok(l);function p(){let k=e.let("i",(0,Ce._)`${n}.length`),T=e.let("j");t.setParams({i:k,j:T}),e.assign(l,!0),e.if((0,Ce._)`${k} > 1`,()=>(f()?_:v)(k,T))}function f(){return u.length>0&&!u.some(k=>k==="object"||k==="array")}function _(k,T){let E=e.name("item"),P=(0,xc.checkDataTypes)(u,E,a.opts.strictNumbers,xc.DataType.Wrong),C=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${k}--;`,()=>{e.let(E,(0,Ce._)`${n}[${k}]`),e.if(P,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${E} == "string"`,(0,Ce._)`${E} += "_"`),e.if((0,Ce._)`typeof ${C}[${E}] == "number"`,()=>{e.assign(T,(0,Ce._)`${C}[${E}]`),t.error(),e.assign(l,!1).break()}).code((0,Ce._)`${C}[${E}] = ${k}`)})}function v(k,T){let E=(0,NT.useFunc)(e,LT.default),P=e.name("outer");e.label(P).for((0,Ce._)`;${k}--;`,()=>e.for((0,Ce._)`${T} = ${k}; ${T}--;`,()=>e.if((0,Ce._)`${E}(${n}[${k}], ${n}[${T}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Tc.default=UT});var Wm=U(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Rc=ee(),DT=de(),qT=ei(),zT={message:"must be equal to constant",params:({schemaCode:t})=>(0,Rc._)`{allowedValue: ${t}}`},MT={keyword:"const",$data:!0,error:zT,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,Rc._)`!${(0,DT.useFunc)(e,qT.default)}(${n}, ${s})`):t.fail((0,Rc._)`${o} !== ${n}`)}};Ec.default=MT});var Jm=U(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var us=ee(),BT=de(),FT=ei(),HT={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,us._)`{allowedValues: ${t}}`},KT={keyword:"enum",schemaType:"array",$data:!0,error:HT,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,BT.useFunc)(e,FT.default)),p;if(a||r)p=e.let("valid"),t.block$data(p,f);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let v=e.const("vSchema",o);p=(0,us.or)(...s.map((k,T)=>_(v,T)))}t.pass(p);function f(){e.assign(p,!1),e.forOf("v",o,v=>e.if((0,us._)`${u()}(${n}, ${v})`,()=>e.assign(p,!0).break()))}function _(v,k){let T=s[k];return typeof T=="object"&&T!==null?(0,us._)`${u()}(${n}, ${v}[${k}])`:(0,us._)`${n} === ${T}`}}};Pc.default=KT});var Ym=U(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var VT=Um(),GT=Dm(),WT=Mm(),JT=Bm(),YT=Fm(),ZT=Hm(),QT=Km(),XT=Gm(),eR=Wm(),tR=Jm(),nR=[VT.default,GT.default,WT.default,JT.default,YT.default,ZT.default,QT.default,XT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},eR.default,tR.default];Ac.default=nR});var Cc=U(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.validateAdditionalItems=void 0;var $n=ee(),Ic=de(),rR={message:({params:{len:t}})=>(0,$n.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,$n._)`{limit: ${t}}`},sR={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:rR,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Ic.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Zm(t,r)}};function Zm(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,$n._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,$n._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Ic.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,$n._)`${a} <= ${e.length}`);n.if((0,$n.not)(u),()=>l(u)),t.ok(u)}function l(u){n.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Ic.Type.Num},u),i.allErrors||n.if((0,$n.not)(u),()=>n.break())})}}ps.validateAdditionalItems=Zm;ps.default=sR});var Oc=U(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.validateTuple=void 0;var Qm=ee(),ti=de(),oR=at(),iR={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Xm(t,"additionalItems",e);n.items=!0,!(0,ti.alwaysValidSchema)(n,e)&&t.ok((0,oR.validateArray)(t))}};function Xm(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=ti.mergeEvaluated.items(r,n.length,a.items));let l=r.name("valid"),u=r.const("len",(0,Qm._)`${o}.length`);n.forEach((f,_)=>{(0,ti.alwaysValidSchema)(a,f)||(r.if((0,Qm._)`${u} > ${_}`,()=>t.subschema({keyword:i,schemaProp:_,dataProp:_},l)),t.ok(l))});function p(f){let{opts:_,errSchemaPath:v}=a,k=n.length,T=k===f.minItems&&(k===f.maxItems||f[e]===!1);if(_.strictTuples&&!T){let E=`"${i}" is ${k}-tuple, but minItems or maxItems/${e} are not specified or different at path "${v}"`;(0,ti.checkStrictMode)(a,E,_.strictTuples)}}}hs.validateTuple=Xm;hs.default=iR});var eg=U(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var aR=Oc(),lR={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,aR.validateTuple)(t,"items")};Nc.default=lR});var ng=U(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var tg=ee(),cR=de(),dR=at(),uR=Cc(),pR={message:({params:{len:t}})=>(0,tg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,tg._)`{limit: ${t}}`},hR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:pR,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,cR.alwaysValidSchema)(r,e)&&(s?(0,uR.validateAdditionalItems)(t,s):t.ok((0,dR.validateArray)(t)))}};Lc.default=hR});var rg=U(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var ct=ee(),ni=de(),fR={message:({params:{min:t,max:e}})=>e===void 0?(0,ct.str)`must contain at least ${t} valid item(s)`:(0,ct.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ct._)`{minContains: ${t}}`:(0,ct._)`{minContains: ${t}, maxContains: ${e}}`},mR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:fR,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,ct._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ni.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ni.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ni.alwaysValidSchema)(o,n)){let T=(0,ct._)`${p} >= ${i}`;a!==void 0&&(T=(0,ct._)`${T} && ${p} <= ${a}`),t.pass(T);return}o.items=!0;let f=e.name("valid");a===void 0&&i===1?v(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),a!==void 0&&e.if((0,ct._)`${s}.length > 0`,_)):(e.let(f,!1),_()),t.result(f,()=>t.reset());function _(){let T=e.name("_valid"),E=e.let("count",0);v(T,()=>e.if(T,()=>k(E)))}function v(T,E){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:ni.Type.Num,compositeRule:!0},T),E()})}function k(T){e.code((0,ct._)`${T}++`),a===void 0?e.if((0,ct._)`${T} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,ct._)`${T} > ${a}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,ct._)`${T} >= ${i}`,()=>e.assign(f,!0)))}}};jc.default=mR});var ig=U($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.validateSchemaDeps=$t.validatePropertyDeps=$t.error=void 0;var Uc=ee(),gR=de(),fs=at();$t.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Uc.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Uc._)`{property: ${t},
1774
+ || ${i} === "boolean" || ${s} === null`).assign(a,(0,Q._)`[${s}]`)}}}function j_({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Q._)`${e} !== undefined`,()=>t.assign((0,Q._)`${e}[${n}]`,r))}function Ml(t,e,n,r=Yn.Correct){let s=r===Yn.Correct?Q.operators.EQ:Q.operators.NEQ,o;switch(t){case"null":return(0,Q._)`${e} ${s} null`;case"array":o=(0,Q._)`Array.isArray(${e})`;break;case"object":o=(0,Q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,Q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,Q._)`typeof ${e} ${s} ${t}`}return r===Yn.Correct?o:(0,Q.not)(o);function i(a=Q.nil){return(0,Q.and)((0,Q._)`typeof ${e} == "number"`,a,n?(0,Q._)`isFinite(${e})`:Q.nil)}}Le.checkDataType=Ml;function Bl(t,e,n,r){if(t.length===1)return Ml(t[0],e,n,r);let s,o=(0,$f.toHash)(t);if(o.array&&o.object){let i=(0,Q._)`typeof ${e} != "object"`;s=o.null?i:(0,Q._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=Q.nil;o.number&&delete o.integer;for(let i in o)s=(0,Q.and)(s,Ml(i,e,n,r));return s}Le.checkDataTypes=Bl;var U_={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Q._)`{type: ${t}}`:(0,Q._)`{type: ${e}}`};function Fl(t){let e=D_(t);(0,I_.reportError)(e,U_)}Le.reportTypeError=Fl;function D_(t){let{gen:e,data:n,schema:r}=t,s=(0,$f.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var Ef=U(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.assignDefaults=void 0;var Zn=ee(),q_=de();function z_(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)Rf(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>Rf(t,o,s.default))}Uo.assignDefaults=z_;function Rf(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,Zn._)`${o}${(0,Zn.getProperty)(e)}`;if(s){(0,q_.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Zn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Zn._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,Zn._)`${a} = ${(0,Zn.stringify)(n)}`)}});var at=U(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.validateUnion=fe.validateArray=fe.usePattern=fe.callValidateCode=fe.schemaProperties=fe.allSchemaProperties=fe.noPropertyInData=fe.propertyInData=fe.isOwnProperty=fe.hasPropFunc=fe.reportMissingProp=fe.checkMissingProp=fe.checkReportMissingProp=void 0;var be=ee(),Hl=de(),Qt=Nt(),M_=de();function B_(t,e){let{gen:n,data:r,it:s}=t;n.if(Vl(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,be._)`${e}`},!0),t.error()})}fe.checkReportMissingProp=B_;function F_({gen:t,data:e,it:{opts:n}},r,s){return(0,be.or)(...r.map(o=>(0,be.and)(Vl(t,e,o,n.ownProperties),(0,be._)`${s} = ${o}`)))}fe.checkMissingProp=F_;function H_(t,e){t.setParams({missingProperty:e},!0),t.error()}fe.reportMissingProp=H_;function Pf(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,be._)`Object.prototype.hasOwnProperty`})}fe.hasPropFunc=Pf;function Kl(t,e,n){return(0,be._)`${Pf(t)}.call(${e}, ${n})`}fe.isOwnProperty=Kl;function K_(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} !== undefined`;return r?(0,be._)`${s} && ${Kl(t,e,n)}`:s}fe.propertyInData=K_;function Vl(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} === undefined`;return r?(0,be.or)(s,(0,be.not)(Kl(t,e,n))):s}fe.noPropertyInData=Vl;function Af(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}fe.allSchemaProperties=Af;function V_(t,e){return Af(e).filter(n=>!(0,Hl.alwaysValidSchema)(t,e[n]))}fe.schemaProperties=V_;function G_({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:s,errorPath:o},it:i},a,l,u){let p=u?(0,be._)`${t}, ${e}, ${r}${s}`:e,f=[[Qt.default.instancePath,(0,be.strConcat)(Qt.default.instancePath,o)],[Qt.default.parentData,i.parentData],[Qt.default.parentDataProperty,i.parentDataProperty],[Qt.default.rootData,Qt.default.rootData]];i.opts.dynamicRef&&f.push([Qt.default.dynamicAnchors,Qt.default.dynamicAnchors]);let _=(0,be._)`${p}, ${n.object(...f)}`;return l!==be.nil?(0,be._)`${a}.call(${l}, ${_})`:(0,be._)`${a}(${_})`}fe.callValidateCode=G_;var W_=(0,be._)`new RegExp`;function J_({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,be._)`${s.code==="new RegExp"?W_:(0,M_.useFunc)(t,s)}(${n}, ${r})`})}fe.usePattern=J_;function Y_(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,be._)`${n}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Hl.Type.Num},o),e.if((0,be.not)(o),a)})}}fe.validateArray=Y_;function Z_(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,Hl.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,be._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,be.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}fe.validateUnion=Z_});var Of=U(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateKeywordUsage=St.validSchemaType=St.funcKeywordCode=St.macroKeywordCode=void 0;var Be=ee(),wn=Nt(),Q_=at(),X_=Jr();function e$(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=Cf(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:Be.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}St.macroKeywordCode=e$;function t$(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;r$(l,e);let u=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=Cf(r,s,u),f=r.let("valid");t.block$data(f,_),t.ok((n=e.valid)!==null&&n!==void 0?n:f);function _(){if(e.errors===!1)T(),e.modifying&&If(t),E(()=>t.error());else{let P=e.async?v():k();e.modifying&&If(t),E(()=>n$(t,P))}}function v(){let P=r.let("ruleErrs",null);return r.try(()=>T((0,Be._)`await `),C=>r.assign(f,!1).if((0,Be._)`${C} instanceof ${l.ValidationError}`,()=>r.assign(P,(0,Be._)`${C}.errors`),()=>r.throw(C))),P}function k(){let P=(0,Be._)`${p}.errors`;return r.assign(P,null),T(Be.nil),P}function T(P=e.async?(0,Be._)`await `:Be.nil){let C=l.opts.passContext?wn.default.this:wn.default.self,D=!("compile"in e&&!a||e.schema===!1);r.assign(f,(0,Be._)`${P}${(0,Q_.callValidateCode)(t,p,C,D)}`,e.modifying)}function E(P){var C;r.if((0,Be.not)((C=e.valid)!==null&&C!==void 0?C:f),P)}}St.funcKeywordCode=t$;function If(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Be._)`${r.parentData}[${r.parentDataProperty}]`))}function n$(t,e){let{gen:n}=t;n.if((0,Be._)`Array.isArray(${e})`,()=>{n.assign(wn.default.vErrors,(0,Be._)`${wn.default.vErrors} === null ? ${e} : ${wn.default.vErrors}.concat(${e})`).assign(wn.default.errors,(0,Be._)`${wn.default.vErrors}.length`),(0,X_.extendErrors)(t)},()=>t.error())}function r$({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Cf(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,Be.stringify)(n)})}function s$(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")}St.validSchemaType=s$;function o$({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)}}St.validateKeywordUsage=o$});var Lf=U(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.extendSubschemaMode=Xt.extendSubschemaData=Xt.getSubschema=void 0;var _t=ee(),Nf=de();function i$(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,_t._)`${t.schemaPath}${(0,_t.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,_t._)`${t.schemaPath}${(0,_t.getProperty)(e)}${(0,_t.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Nf.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')}Xt.getSubschema=i$;function a$(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:f}=e,_=a.let("data",(0,_t._)`${e.data}${(0,_t.getProperty)(n)}`,!0);l(_),t.errorPath=(0,_t.str)`${u}${(0,Nf.getErrorPath)(n,r,f.jsPropertySyntax)}`,t.parentDataProperty=(0,_t._)`${n}`,t.dataPathArr=[...p,t.parentDataProperty]}if(s!==void 0){let u=s instanceof _t.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]}}Xt.extendSubschemaData=a$;function l$(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}Xt.extendSubschemaMode=l$});var Gl=U((zN,jf)=>{"use strict";jf.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 Df=U((MN,Uf)=>{"use strict";var en=Uf.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(){};Do(e,r,s,t,"",t)};en.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};en.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};en.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};en.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 Do(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 f=r[p];if(Array.isArray(f)){if(p in en.arrayKeywords)for(var _=0;_<f.length;_++)Do(t,e,n,f[_],s+"/"+p+"/"+_,o,s,p,r,_)}else if(p in en.propsKeywords){if(f&&typeof f=="object")for(var v in f)Do(t,e,n,f[v],s+"/"+p+"/"+c$(v),o,s,p,r,v)}else(p in en.keywords||t.allKeys&&!(p in en.skipKeywords))&&Do(t,e,n,f,s+"/"+p,o,s,p,r)}n(r,s,o,i,a,l,u)}}function c$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Zr=U(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.getSchemaRefs=We.resolveUrl=We.normalizeId=We._getFullPath=We.getFullPath=We.inlineRef=void 0;var d$=de(),u$=Gl(),p$=Df(),h$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function f$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Wl(t):e?qf(t)<=e:!1}We.inlineRef=f$;var m$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Wl(t){for(let e in t){if(m$.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Wl)||typeof n=="object"&&Wl(n))return!0}return!1}function qf(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,d$.eachItem)(t[n],r=>e+=qf(r)),e===1/0))return 1/0}return e}function zf(t,e="",n){n!==!1&&(e=Qn(e));let r=t.parse(e);return Mf(t,r)}We.getFullPath=zf;function Mf(t,e){return t.serialize(e).split("#")[0]+"#"}We._getFullPath=Mf;var g$=/#\/?$/;function Qn(t){return t?t.replace(g$,""):""}We.normalizeId=Qn;function b$(t,e,n){return n=Qn(n),t.resolve(e,n)}We.resolveUrl=b$;var y$=/^[a-z_][-a-z0-9._]*$/i;function w$(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=Qn(t[n]||e),o={"":s},i=zf(r,s,!1),a={},l=new Set;return p$(t,{allKeys:!0},(f,_,v,k)=>{if(k===void 0)return;let T=i+_,E=o[k];typeof f[n]=="string"&&(E=P.call(this,f[n])),C.call(this,f.$anchor),C.call(this,f.$dynamicAnchor),o[_]=E;function P(D){let re=this.opts.uriResolver.resolve;if(D=Qn(E?re(E,D):D),l.has(D))throw p(D);l.add(D);let Y=this.refs[D];return typeof Y=="string"&&(Y=this.refs[Y]),typeof Y=="object"?u(f,Y.schema,D):D!==Qn(T)&&(D[0]==="#"?(u(f,a[D],D),a[D]=f):this.refs[D]=T),D}function C(D){if(typeof D=="string"){if(!y$.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(f,_,v){if(_!==void 0&&!u$(f,_))throw p(v)}function p(f){return new Error(`reference "${f}" resolves to more than one schema`)}}We.getSchemaRefs=w$});var es=U(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.getData=tn.KeywordCxt=tn.validateFunctionCode=void 0;var Vf=kf(),Bf=Yr(),Yl=zl(),qo=Yr(),v$=Ef(),Xr=Of(),Jl=Lf(),z=ee(),Z=Nt(),k$=Zr(),Lt=de(),Qr=Jr();function S$(t){if(Jf(t)&&(Yf(t),Wf(t))){x$(t);return}Gf(t,()=>(0,Vf.topBoolOrEmptySchema)(t))}tn.validateFunctionCode=S$;function Gf({gen:t,validateName:e,schema:n,schemaEnv:r,opts:s},o){s.code.es5?t.func(e,(0,z._)`${Z.default.data}, ${Z.default.valCxt}`,r.$async,()=>{t.code((0,z._)`"use strict"; ${Ff(n,s)}`),$$(t,s),t.code(o)}):t.func(e,(0,z._)`${Z.default.data}, ${_$(s)}`,r.$async,()=>t.code(Ff(n,s)).code(o))}function _$(t){return(0,z._)`{${Z.default.instancePath}="", ${Z.default.parentData}, ${Z.default.parentDataProperty}, ${Z.default.rootData}=${Z.default.data}${t.dynamicRef?(0,z._)`, ${Z.default.dynamicAnchors}={}`:z.nil}}={}`}function $$(t,e){t.if(Z.default.valCxt,()=>{t.var(Z.default.instancePath,(0,z._)`${Z.default.valCxt}.${Z.default.instancePath}`),t.var(Z.default.parentData,(0,z._)`${Z.default.valCxt}.${Z.default.parentData}`),t.var(Z.default.parentDataProperty,(0,z._)`${Z.default.valCxt}.${Z.default.parentDataProperty}`),t.var(Z.default.rootData,(0,z._)`${Z.default.valCxt}.${Z.default.rootData}`),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,z._)`${Z.default.valCxt}.${Z.default.dynamicAnchors}`)},()=>{t.var(Z.default.instancePath,(0,z._)`""`),t.var(Z.default.parentData,(0,z._)`undefined`),t.var(Z.default.parentDataProperty,(0,z._)`undefined`),t.var(Z.default.rootData,Z.default.data),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,z._)`{}`)})}function x$(t){let{schema:e,opts:n,gen:r}=t;Gf(t,()=>{n.$comment&&e.$comment&&Qf(t),A$(t),r.let(Z.default.vErrors,null),r.let(Z.default.errors,0),n.unevaluated&&T$(t),Zf(t),O$(t)})}function T$(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,z._)`${n}.evaluated`),e.if((0,z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,z._)`${t.evaluated}.props`,(0,z._)`undefined`)),e.if((0,z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,z._)`${t.evaluated}.items`,(0,z._)`undefined`))}function Ff(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,z._)`/*# sourceURL=${n} */`:z.nil}function R$(t,e){if(Jf(t)&&(Yf(t),Wf(t))){E$(t,e);return}(0,Vf.boolOrEmptySchema)(t,e)}function Wf({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 Jf(t){return typeof t.schema!="boolean"}function E$(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&Qf(t),I$(t),C$(t);let o=r.const("_errs",Z.default.errors);Zf(t,o),r.var(e,(0,z._)`${o} === ${Z.default.errors}`)}function Yf(t){(0,Lt.checkUnknownRules)(t),P$(t)}function Zf(t,e){if(t.opts.jtd)return Hf(t,[],!1,e);let n=(0,Bf.getSchemaTypes)(t.schema),r=(0,Bf.coerceAndCheckDataType)(t,n);Hf(t,n,!r,e)}function P$(t){let{schema:e,errSchemaPath:n,opts:r,self:s}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Lt.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function A$(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Lt.checkStrictMode)(t,"default is ignored in the schema root")}function I$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,k$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function C$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Qf({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:s}){let o=n.$comment;if(s.$comment===!0)t.code((0,z._)`${Z.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,z.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${Z.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function O$(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=t;n.$async?e.if((0,z._)`${Z.default.errors} === 0`,()=>e.return(Z.default.data),()=>e.throw((0,z._)`new ${s}(${Z.default.vErrors})`)):(e.assign((0,z._)`${r}.errors`,Z.default.vErrors),o.unevaluated&&N$(t),e.return((0,z._)`${Z.default.errors} === 0`))}function N$({gen:t,evaluated:e,props:n,items:r}){n instanceof z.Name&&t.assign((0,z._)`${e}.props`,n),r instanceof z.Name&&t.assign((0,z._)`${e}.items`,r)}function Hf(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,Lt.schemaHasRulesButRef)(o,p))){s.block(()=>em(t,"$ref",p.all.$ref.definition));return}l.jtd||L$(t,e),s.block(()=>{for(let _ of p.rules)f(_);f(p.post)});function f(_){(0,Yl.shouldUseGroup)(o,_)&&(_.type?(s.if((0,qo.checkDataType)(_.type,i,l.strictNumbers)),Kf(t,_),e.length===1&&e[0]===_.type&&n&&(s.else(),(0,qo.reportTypeError)(t)),s.endIf()):Kf(t,_),a||s.if((0,z._)`${Z.default.errors} === ${r||0}`))}}function Kf(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,v$.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,Yl.shouldUseRule)(r,o)&&em(t,o.keyword,o.definition,e.type)})}function L$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(j$(t,e),t.opts.allowUnionTypes||U$(t,e),D$(t,t.dataTypes))}function j$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Xf(t.dataTypes,n)||Zl(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),z$(t,e)}}function U$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Zl(t,"use allowUnionTypes to allow union type keyword")}function D$(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,Yl.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>q$(e,i))&&Zl(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function q$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Xf(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function z$(t,e){let n=[];for(let r of t.dataTypes)Xf(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Zl(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Lt.checkStrictMode)(t,e,t.opts.strictTypes)}var zo=class{constructor(e,n,r){if((0,Xr.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,Lt.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",tm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Xr.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",Z.default.errors))}result(e,n,r){this.failResult((0,z.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,z.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,z._)`${n} !== undefined && (${(0,z.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?Qr.reportExtraError:Qr.reportError)(this,this.def.error,n)}$dataError(){(0,Qr.reportError)(this,this.def.$dataError||Qr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Qr.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=z.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=z.nil,n=z.nil){if(!this.$data)return;let{gen:r,schemaCode:s,schemaType:o,def:i}=this;r.if((0,z.or)((0,z._)`${s} === undefined`,n)),e!==z.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==z.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:s,it:o}=this;return(0,z.or)(i(),a());function i(){if(r.length){if(!(n instanceof z.Name))throw new Error("ajv implementation error");let l=Array.isArray(r)?r:[r];return(0,z._)`${(0,qo.checkDataTypes)(l,n,o.opts.strictNumbers,qo.DataType.Wrong)}`}return z.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,z._)`!${l}(${n})`}return z.nil}}subschema(e,n){let r=(0,Jl.getSubschema)(this.it,e);(0,Jl.extendSubschemaData)(r,this.it,e),(0,Jl.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return R$(s,n),s}mergeEvaluated(e,n){let{it:r,gen:s}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Lt.mergeEvaluated.props(s,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Lt.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,z.Name)),!0}};tn.KeywordCxt=zo;function em(t,e,n,r){let s=new zo(t,n,e);"code"in n?n.code(s,r):s.$data&&n.validate?(0,Xr.funcKeywordCode)(s,n):"macro"in n?(0,Xr.macroKeywordCode)(s,n):(n.compile||n.validate)&&(0,Xr.funcKeywordCode)(s,n)}var M$=/^\/(?:[^~]|~0|~1)*$/,B$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function tm(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return Z.default.rootData;if(t[0]==="/"){if(!M$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Z.default.rootData}else{let u=B$.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,z._)`${o}${(0,z.getProperty)((0,Lt.unescapeJsonPointer)(u))}`,i=(0,z._)`${i} && ${o}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}tn.getData=tm});var Mo=U(Xl=>{"use strict";Object.defineProperty(Xl,"__esModule",{value:!0});var Ql=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Xl.default=Ql});var ts=U(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var ec=Zr(),tc=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,ec.resolveUrl)(e,n,r),this.missingSchema=(0,ec.normalizeId)((0,ec.getFullPath)(e,this.missingRef))}};nc.default=tc});var Fo=U(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.resolveSchema=lt.getCompilingSchema=lt.resolveRef=lt.compileSchema=lt.SchemaEnv=void 0;var gt=ee(),F$=Mo(),vn=Nt(),bt=Zr(),nm=de(),H$=es(),Xn=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,bt.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};lt.SchemaEnv=Xn;function sc(t){let e=rm.call(this,t);if(e)return e;let n=(0,bt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new gt.CodeGen(this.scope,{es5:r,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:F$.default,code:(0,gt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:vn.default.data,parentData:vn.default.parentData,parentDataProperty:vn.default.parentDataProperty,dataNames:[vn.default.data],dataPathArr:[gt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,gt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:gt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,gt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,H$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let f=i.toString();p=`${i.scopeRefs(vn.default.scope)}return ${f}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let v=new Function(`${vn.default.self}`,`${vn.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:v}),v.errors=null,v.schema=t.schema,v.schemaEnv=t,t.$async&&(v.$async=!0),this.opts.code.source===!0&&(v.source={validateName:l,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:T}=u;v.evaluated={props:k instanceof gt.Name?void 0:k,items:T instanceof gt.Name?void 0:T,dynamicProps:k instanceof gt.Name,dynamicItems:T instanceof gt.Name},v.source&&(v.source.evaluated=(0,gt.stringify)(v.evaluated))}return t.validate=v,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)}}lt.compileSchema=sc;function K$(t,e,n){var r;n=(0,bt.resolveUrl)(this.opts.uriResolver,e,n);let s=t.refs[n];if(s)return s;let o=W$.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 Xn({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=V$.call(this,o)}lt.resolveRef=K$;function V$(t){return(0,bt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:sc.call(this,t)}function rm(t){for(let e of this._compilations)if(G$(e,t))return e}lt.getCompilingSchema=rm;function G$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function W$(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Bo.call(this,t,e)}function Bo(t,e){let n=this.opts.uriResolver.parse(e),r=(0,bt._getFullPath)(this.opts.uriResolver,n),s=(0,bt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===s)return rc.call(this,n,t);let o=(0,bt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Bo.call(this,t,i);return typeof a?.schema!="object"?void 0:rc.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||sc.call(this,i),o===(0,bt.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(s=(0,bt.resolveUrl)(this.opts.uriResolver,s,u)),new Xn({schema:a,schemaId:l,root:t,baseId:s})}return rc.call(this,n,i)}}lt.resolveSchema=Bo;var J$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function rc(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,nm.unescapeFragment)(a)];if(l===void 0)return;n=l;let u=typeof n=="object"&&n[this.opts.schemaId];!J$.has(a)&&u&&(e=(0,bt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,nm.schemaHasRulesButRef)(n,this.RULES)){let a=(0,bt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=Bo.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new Xn({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var sm=U((GN,Y$)=>{Y$.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 ac=U((WN,dm)=>{"use strict";var Z$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),im=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),oc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),am=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Q$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function ic(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 X$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function om(t){return t.length=0,!0}function ex(t,e,n){if(t.length){let r=ic(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function tx(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=ex;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=om}else{s.push(u);continue}}return s.length&&(a===om?n.zone=s.join(""):i?r.push(s.join("")):r.push(ic(s))),n.address=r.join(""),n}function lm(t){if(nx(t,":")<2)return{host:t,isIPV6:!1};let e=tx(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 nx(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function rx(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 sx={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ox=/[@/?#:]/g,ix=/[@/?#]/g;function cm(t,e){let n=e?ix:ox;return n.lastIndex=0,t.replace(n,r=>sx[r])}function ax(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(oc(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&am(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function lx(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(oc(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&am(o)?e+=o:e+="%"+s,n+=2;continue}}Q$(t[n])?e+=t[n]:e+=escape(t[n])}return e}function cx(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(oc(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function dx(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!im(n)){let r=lm(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=cm(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}dm.exports={nonSimpleDomain:X$,recomposeAuthority:dx,reescapeHostDelimiters:cm,normalizePercentEncoding:ax,normalizePathEncoding:lx,escapePreservingEscapes:cx,removeDotSegments:rx,isIPv4:im,isUUID:Z$,normalizeIPv6:lm,stringArrayToHexStripped:ic}});var mm=U((JN,fm)=>{"use strict";var{isUUID:ux}=ac(),px=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,hx=["http","https","ws","wss","urn","urn:uuid"];function fx(t){return hx.indexOf(t)!==-1}function lc(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 um(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function pm(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 mx(t){return t.secure=lc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function gx(t){if((t.port===(lc(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 bx(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(px);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=cc(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function yx(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=cc(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 wx(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!ux(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function vx(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var hm={scheme:"http",domainHost:!0,parse:um,serialize:pm},kx={scheme:"https",domainHost:hm.domainHost,parse:um,serialize:pm},Ho={scheme:"ws",domainHost:!0,parse:mx,serialize:gx},Sx={scheme:"wss",domainHost:Ho.domainHost,parse:Ho.parse,serialize:Ho.serialize},_x={scheme:"urn",parse:bx,serialize:yx,skipNormalize:!0},$x={scheme:"urn:uuid",parse:wx,serialize:vx,skipNormalize:!0},Ko={http:hm,https:kx,ws:Ho,wss:Sx,urn:_x,"urn:uuid":$x};Object.setPrototypeOf(Ko,null);function cc(t){return t&&(Ko[t]||Ko[t.toLowerCase()])||void 0}fm.exports={wsIsSecure:lc,SCHEMES:Ko,isValidSchemeName:fx,getSchemeHandler:cc}});var vm=U((YN,Wo)=>{"use strict";var{normalizeIPv6:xx,removeDotSegments:ns,recomposeAuthority:Tx,normalizePercentEncoding:Rx,normalizePathEncoding:Ex,escapePreservingEscapes:Px,reescapeHostDelimiters:Ax,isIPv4:Ix,nonSimpleDomain:Cx}=ac(),{SCHEMES:Ox,getSchemeHandler:bm}=mm();function Nx(t,e){return typeof t=="string"?t=Mx(t,e):typeof t=="object"&&(t=Go(kn(t,e),e)),t}function Lx(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=Vo(t,r),{parsed:i,malformedAuthorityOrPort:a}=Vo(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=ym(s,i,r,!0);return r.skipEscape=!0,kn(l,r)}function ym(t,e,n,r){let s={};return r||(t=Go(kn(t,n),n),e=Go(kn(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=ns(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=ns(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=ns(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=ns(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 jx(t,e,n){let r=gm(t,n),s=gm(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function kn(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=bm(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=Rx(n.path):(n.path=Px(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=Tx(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=ns(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 Ux=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Dx=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,qx=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function zx(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 Vo(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(Dx);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(qx);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(Ux);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=zx(r,l);if(u!==void 0&&(r.error=r.error||u,s=!0),r.host)if(Ix(r.host)===!1){let _=xx(r.host);r.host=_.host.toLowerCase(),o=_.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=bm(n.scheme||r.scheme);if(!n.unicodeSupport&&(!p||!p.unicodeSupport)&&r.host&&(n.domainHost||p&&p.domainHost)&&o===!1&&Cx(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(f){r.error=r.error||"Host's domain name can not be converted to ASCII: "+f}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Ax(unescape(r.host),o))),r.path&&(r.path=Ex(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 Go(t,e){return Vo(t,e).parsed}function Mx(t,e){return wm(t,e).normalized}function wm(t,e){let{parsed:n,malformedAuthorityOrPort:r}=Vo(t,e);return{normalized:r?t:kn(n,e),malformedAuthorityOrPort:r}}function gm(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=wm(t,e);return r?void 0:n}if(typeof t=="object")return kn(t,e)}var dc={SCHEMES:Ox,normalize:Nx,resolve:Lx,resolveComponent:ym,equal:jx,serialize:kn,parse:Go};Wo.exports=dc;Wo.exports.default=dc;Wo.exports.fastUri=dc});var Sm=U(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});var km=vm();km.code='require("ajv/dist/runtime/uri").default';uc.default=km});var Am=U(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.CodeGen=Ie.Name=Ie.nil=Ie.stringify=Ie.str=Ie._=Ie.KeywordCxt=void 0;var Bx=es();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return Bx.KeywordCxt}});var er=ee();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return er._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return er.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return er.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return er.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return er.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return er.CodeGen}});var Fx=Mo(),Rm=ts(),Hx=ql(),rs=Fo(),Kx=ee(),ss=Zr(),Jo=Yr(),hc=de(),_m=sm(),Vx=Sm(),Em=(t,e)=>new RegExp(t,e);Em.code="new RegExp";var Gx=["removeAdditional","useDefaults","coerceTypes"],Wx=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Jx={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."},Yx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},$m=200;function Zx(t){var e,n,r,s,o,i,a,l,u,p,f,_,v,k,T,E,P,C,D,re,Y,je,Fe,jt,dt;let on=t.strict,ur=(e=t.code)===null||e===void 0?void 0:e.optimize,Ut=ur===!0||ur===void 0?1:ur||0,an=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Em,xn=(s=t.uriResolver)!==null&&s!==void 0?s:Vx.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:on)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:on)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:on)!==null&&p!==void 0?p:"log",strictTuples:(_=(f=t.strictTuples)!==null&&f!==void 0?f:on)!==null&&_!==void 0?_:"log",strictRequired:(k=(v=t.strictRequired)!==null&&v!==void 0?v:on)!==null&&k!==void 0?k:!1,code:t.code?{...t.code,optimize:Ut,regExp:an}:{optimize:Ut,regExp:an},loopRequired:(T=t.loopRequired)!==null&&T!==void 0?T:$m,loopEnum:(E=t.loopEnum)!==null&&E!==void 0?E:$m,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(C=t.messages)!==null&&C!==void 0?C:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(re=t.schemaId)!==null&&re!==void 0?re:"$id",addUsedSchema:(Y=t.addUsedSchema)!==null&&Y!==void 0?Y:!0,validateSchema:(je=t.validateSchema)!==null&&je!==void 0?je:!0,validateFormats:(Fe=t.validateFormats)!==null&&Fe!==void 0?Fe:!0,unicodeRegExp:(jt=t.unicodeRegExp)!==null&&jt!==void 0?jt:!0,int32range:(dt=t.int32range)!==null&&dt!==void 0?dt:!0,uriResolver:xn}}var os=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,...Zx(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Kx.ValueScope({scope:{},prefixes:Wx,es5:n,lines:r}),this.logger=rT(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Hx.getRules)(),xm.call(this,Jx,e,"NOT SUPPORTED"),xm.call(this,Yx,e,"DEPRECATED","warn"),this._metaOpts=tT.call(this),e.formats&&Xx.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&eT.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Qx.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=_m;r==="id"&&(s={..._m},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,f){await o.call(this,p.$schema);let _=this._addSchema(p,f);return _.validate||i.call(this,_)}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(f){if(!(f instanceof Rm.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 o.call(this,f.$schema),this.refs[p]||this.addSchema(f,p,n)}async function u(p){let f=this._loading[p];if(f)return f;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,ss.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=Tm.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new rs.SchemaEnv({schema:{},schemaId:r});if(n=rs.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=Tm.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,ss.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(oT.call(this,r,n),!n)return(0,hc.eachItem)(r,o=>pc.call(this,o)),this;aT.call(this,n);let s={...n,type:(0,Jo.getJSONTypes)(n.type),schemaType:(0,Jo.getJSONTypes)(n.schemaType)};return(0,hc.eachItem)(r,s.type.length===0?o=>pc.call(this,o,s):o=>s.type.forEach(i=>pc.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]=Pm(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,ss.normalizeId)(i||r);let u=ss.getSchemaRefs.call(this,e,r);return l=new rs.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):rs.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{rs.compileSchema.call(this,e)}finally{this.opts=n}}};os.ValidationError=Fx.default;os.MissingRefError=Rm.default;Ie.default=os;function xm(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 Tm(t){return t=(0,ss.normalizeId)(t),this.schemas[t]||this.refs[t]}function Qx(){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 Xx(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function eT(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 tT(){let t={...this.opts};for(let e of Gx)delete t[e];return t}var nT={log(){},warn(){},error(){}};function rT(t){if(t===!1)return nT;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 sT=/^[a-z_$][a-z0-9_$:-]*$/i;function oT(t,e){let{RULES:n}=this;if((0,hc.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!sT.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 pc(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,Jo.getJSONTypes)(e.type),schemaType:(0,Jo.getJSONTypes)(e.schemaType)}};e.before?iT.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 iT(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 aT(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Pm(e)),t.validateSchema=this.compile(e,!0))}var lT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Pm(t){return{anyOf:[t,lT]}}});var Im=U(fc=>{"use strict";Object.defineProperty(fc,"__esModule",{value:!0});var cT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};fc.default=cT});var Lm=U(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.callRef=Sn.getValidate=void 0;var dT=ts(),Cm=at(),Je=ee(),tr=Nt(),Om=Fo(),Yo=de(),uT={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 f();let p=Om.resolveRef.call(l,u,s,n);if(p===void 0)throw new dT.default(r.opts.uriResolver,s,n);if(p instanceof Om.SchemaEnv)return _(p);return v(p);function f(){if(o===u)return Zo(t,i,o,o.$async);let k=e.scopeValue("root",{ref:u});return Zo(t,(0,Je._)`${k}.validate`,u,u.$async)}function _(k){let T=Nm(t,k);Zo(t,T,k,k.$async)}function v(k){let T=e.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,Je.stringify)(k)}:{ref:k}),E=e.name("valid"),P=t.subschema({schema:k,dataTypes:[],schemaPath:Je.nil,topSchemaRef:T,errSchemaPath:n},E);t.mergeEvaluated(P),t.ok(E)}}};function Nm(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Je._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Sn.getValidate=Nm;function Zo(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,u=l.passContext?tr.default.this:Je.nil;r?p():f();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=s.let("valid");s.try(()=>{s.code((0,Je._)`await ${(0,Cm.callValidateCode)(t,e,u)}`),v(e),i||s.assign(k,!0)},T=>{s.if((0,Je._)`!(${T} instanceof ${o.ValidationError})`,()=>s.throw(T)),_(T),i||s.assign(k,!1)}),t.ok(k)}function f(){t.result((0,Cm.callValidateCode)(t,e,u),()=>v(e),()=>_(e))}function _(k){let T=(0,Je._)`${k}.errors`;s.assign(tr.default.vErrors,(0,Je._)`${tr.default.vErrors} === null ? ${T} : ${tr.default.vErrors}.concat(${T})`),s.assign(tr.default.errors,(0,Je._)`${tr.default.vErrors}.length`)}function v(k){var T;if(!o.opts.unevaluated)return;let E=(T=n?.validate)===null||T===void 0?void 0:T.evaluated;if(o.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(o.props=Yo.mergeEvaluated.props(s,E.props,o.props));else{let P=s.var("props",(0,Je._)`${k}.evaluated.props`);o.props=Yo.mergeEvaluated.props(s,P,o.props,Je.Name)}if(o.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(o.items=Yo.mergeEvaluated.items(s,E.items,o.items));else{let P=s.var("items",(0,Je._)`${k}.evaluated.items`);o.items=Yo.mergeEvaluated.items(s,P,o.items,Je.Name)}}}Sn.callRef=Zo;Sn.default=uT});var jm=U(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var pT=Im(),hT=Lm(),fT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",pT.default,hT.default];mc.default=fT});var Um=U(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var Qo=ee(),nn=Qo.operators,Xo={maximum:{okStr:"<=",ok:nn.LTE,fail:nn.GT},minimum:{okStr:">=",ok:nn.GTE,fail:nn.LT},exclusiveMaximum:{okStr:"<",ok:nn.LT,fail:nn.GTE},exclusiveMinimum:{okStr:">",ok:nn.GT,fail:nn.LTE}},mT={message:({keyword:t,schemaCode:e})=>(0,Qo.str)`must be ${Xo[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Qo._)`{comparison: ${Xo[t].okStr}, limit: ${e}}`},gT={keyword:Object.keys(Xo),type:"number",schemaType:"number",$data:!0,error:mT,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Qo._)`${n} ${Xo[e].fail} ${r} || isNaN(${n})`)}};gc.default=gT});var Dm=U(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var is=ee(),bT={message:({schemaCode:t})=>(0,is.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,is._)`{multipleOf: ${t}}`},yT={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:bT,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,is._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,is._)`${i} !== parseInt(${i})`;t.fail$data((0,is._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};bc.default=yT});var zm=U(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});function qm(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}yc.default=qm;qm.code='require("ajv/dist/runtime/ucs2length").default'});var Mm=U(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var _n=ee(),wT=de(),vT=zm(),kT={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,_n.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,_n._)`{limit: ${t}}`},ST={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:kT,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?_n.operators.GT:_n.operators.LT,i=s.opts.unicode===!1?(0,_n._)`${n}.length`:(0,_n._)`${(0,wT.useFunc)(t.gen,vT.default)}(${n})`;t.fail$data((0,_n._)`${i} ${o} ${r}`)}};wc.default=ST});var Bm=U(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var _T=at(),$T=de(),nr=ee(),xT={message:({schemaCode:t})=>(0,nr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,nr._)`{pattern: ${t}}`},TT={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:xT,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,nr._)`new RegExp`:(0,$T.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,nr._)`${u}(${o}, ${a}).test(${n})`),()=>e.assign(p,!1)),t.fail$data((0,nr._)`!${p}`)}else{let l=(0,_T.usePattern)(t,s);t.fail$data((0,nr._)`!${l}.test(${n})`)}}};vc.default=TT});var Fm=U(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var as=ee(),RT={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,as.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,as._)`{limit: ${t}}`},ET={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:RT,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?as.operators.GT:as.operators.LT;t.fail$data((0,as._)`Object.keys(${n}).length ${s} ${r}`)}};kc.default=ET});var Hm=U(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var ls=at(),cs=ee(),PT=de(),AT={message:({params:{missingProperty:t}})=>(0,cs.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,cs._)`{missingProperty: ${t}}`},IT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:AT,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 v=t.parentSchema.properties,{definedProperties:k}=t.it;for(let T of n)if(v?.[T]===void 0&&!k.has(T)){let E=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${T}" is not defined at "${E}" (strictRequired)`;(0,PT.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(cs.nil,f);else for(let v of n)(0,ls.checkReportMissingProp)(t,v)}function p(){let v=e.let("missing");if(l||o){let k=e.let("valid",!0);t.block$data(k,()=>_(v,k)),t.ok(k)}else e.if((0,ls.checkMissingProp)(t,n,v)),(0,ls.reportMissingProp)(t,v),e.else()}function f(){e.forOf("prop",r,v=>{t.setParams({missingProperty:v}),e.if((0,ls.noPropertyInData)(e,s,v,a.ownProperties),()=>t.error())})}function _(v,k){t.setParams({missingProperty:v}),e.forOf(v,r,()=>{e.assign(k,(0,ls.propertyInData)(e,s,v,a.ownProperties)),e.if((0,cs.not)(k),()=>{t.error(),e.break()})},cs.nil)}}};Sc.default=IT});var Km=U(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var ds=ee(),CT={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,ds.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,ds._)`{limit: ${t}}`},OT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:CT,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?ds.operators.GT:ds.operators.LT;t.fail$data((0,ds._)`${n}.length ${s} ${r}`)}};_c.default=OT});var ei=U($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var Vm=Gl();Vm.code='require("ajv/dist/runtime/equal").default';$c.default=Vm});var Gm=U(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var xc=Yr(),Ce=ee(),NT=de(),LT=ei(),jT={message:({params:{i:t,j:e}})=>(0,Ce.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ce._)`{i: ${t}, j: ${e}}`},UT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:jT,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,xc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,Ce._)`${i} === false`),t.ok(l);function p(){let k=e.let("i",(0,Ce._)`${n}.length`),T=e.let("j");t.setParams({i:k,j:T}),e.assign(l,!0),e.if((0,Ce._)`${k} > 1`,()=>(f()?_:v)(k,T))}function f(){return u.length>0&&!u.some(k=>k==="object"||k==="array")}function _(k,T){let E=e.name("item"),P=(0,xc.checkDataTypes)(u,E,a.opts.strictNumbers,xc.DataType.Wrong),C=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${k}--;`,()=>{e.let(E,(0,Ce._)`${n}[${k}]`),e.if(P,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${E} == "string"`,(0,Ce._)`${E} += "_"`),e.if((0,Ce._)`typeof ${C}[${E}] == "number"`,()=>{e.assign(T,(0,Ce._)`${C}[${E}]`),t.error(),e.assign(l,!1).break()}).code((0,Ce._)`${C}[${E}] = ${k}`)})}function v(k,T){let E=(0,NT.useFunc)(e,LT.default),P=e.name("outer");e.label(P).for((0,Ce._)`;${k}--;`,()=>e.for((0,Ce._)`${T} = ${k}; ${T}--;`,()=>e.if((0,Ce._)`${E}(${n}[${k}], ${n}[${T}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Tc.default=UT});var Wm=U(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Rc=ee(),DT=de(),qT=ei(),zT={message:"must be equal to constant",params:({schemaCode:t})=>(0,Rc._)`{allowedValue: ${t}}`},MT={keyword:"const",$data:!0,error:zT,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,Rc._)`!${(0,DT.useFunc)(e,qT.default)}(${n}, ${s})`):t.fail((0,Rc._)`${o} !== ${n}`)}};Ec.default=MT});var Jm=U(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var us=ee(),BT=de(),FT=ei(),HT={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,us._)`{allowedValues: ${t}}`},KT={keyword:"enum",schemaType:"array",$data:!0,error:HT,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,BT.useFunc)(e,FT.default)),p;if(a||r)p=e.let("valid"),t.block$data(p,f);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let v=e.const("vSchema",o);p=(0,us.or)(...s.map((k,T)=>_(v,T)))}t.pass(p);function f(){e.assign(p,!1),e.forOf("v",o,v=>e.if((0,us._)`${u()}(${n}, ${v})`,()=>e.assign(p,!0).break()))}function _(v,k){let T=s[k];return typeof T=="object"&&T!==null?(0,us._)`${u()}(${n}, ${v}[${k}])`:(0,us._)`${n} === ${T}`}}};Pc.default=KT});var Ym=U(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var VT=Um(),GT=Dm(),WT=Mm(),JT=Bm(),YT=Fm(),ZT=Hm(),QT=Km(),XT=Gm(),eR=Wm(),tR=Jm(),nR=[VT.default,GT.default,WT.default,JT.default,YT.default,ZT.default,QT.default,XT.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},eR.default,tR.default];Ac.default=nR});var Cc=U(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.validateAdditionalItems=void 0;var $n=ee(),Ic=de(),rR={message:({params:{len:t}})=>(0,$n.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,$n._)`{limit: ${t}}`},sR={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:rR,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Ic.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Zm(t,r)}};function Zm(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,$n._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,$n._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Ic.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,$n._)`${a} <= ${e.length}`);n.if((0,$n.not)(u),()=>l(u)),t.ok(u)}function l(u){n.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Ic.Type.Num},u),i.allErrors||n.if((0,$n.not)(u),()=>n.break())})}}ps.validateAdditionalItems=Zm;ps.default=sR});var Oc=U(hs=>{"use strict";Object.defineProperty(hs,"__esModule",{value:!0});hs.validateTuple=void 0;var Qm=ee(),ti=de(),oR=at(),iR={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Xm(t,"additionalItems",e);n.items=!0,!(0,ti.alwaysValidSchema)(n,e)&&t.ok((0,oR.validateArray)(t))}};function Xm(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=ti.mergeEvaluated.items(r,n.length,a.items));let l=r.name("valid"),u=r.const("len",(0,Qm._)`${o}.length`);n.forEach((f,_)=>{(0,ti.alwaysValidSchema)(a,f)||(r.if((0,Qm._)`${u} > ${_}`,()=>t.subschema({keyword:i,schemaProp:_,dataProp:_},l)),t.ok(l))});function p(f){let{opts:_,errSchemaPath:v}=a,k=n.length,T=k===f.minItems&&(k===f.maxItems||f[e]===!1);if(_.strictTuples&&!T){let E=`"${i}" is ${k}-tuple, but minItems or maxItems/${e} are not specified or different at path "${v}"`;(0,ti.checkStrictMode)(a,E,_.strictTuples)}}}hs.validateTuple=Xm;hs.default=iR});var eg=U(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var aR=Oc(),lR={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,aR.validateTuple)(t,"items")};Nc.default=lR});var ng=U(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var tg=ee(),cR=de(),dR=at(),uR=Cc(),pR={message:({params:{len:t}})=>(0,tg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,tg._)`{limit: ${t}}`},hR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:pR,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,cR.alwaysValidSchema)(r,e)&&(s?(0,uR.validateAdditionalItems)(t,s):t.ok((0,dR.validateArray)(t)))}};Lc.default=hR});var rg=U(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var ct=ee(),ni=de(),fR={message:({params:{min:t,max:e}})=>e===void 0?(0,ct.str)`must contain at least ${t} valid item(s)`:(0,ct.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ct._)`{minContains: ${t}}`:(0,ct._)`{minContains: ${t}, maxContains: ${e}}`},mR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:fR,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,ct._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ni.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ni.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ni.alwaysValidSchema)(o,n)){let T=(0,ct._)`${p} >= ${i}`;a!==void 0&&(T=(0,ct._)`${T} && ${p} <= ${a}`),t.pass(T);return}o.items=!0;let f=e.name("valid");a===void 0&&i===1?v(f,()=>e.if(f,()=>e.break())):i===0?(e.let(f,!0),a!==void 0&&e.if((0,ct._)`${s}.length > 0`,_)):(e.let(f,!1),_()),t.result(f,()=>t.reset());function _(){let T=e.name("_valid"),E=e.let("count",0);v(T,()=>e.if(T,()=>k(E)))}function v(T,E){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:ni.Type.Num,compositeRule:!0},T),E()})}function k(T){e.code((0,ct._)`${T}++`),a===void 0?e.if((0,ct._)`${T} >= ${i}`,()=>e.assign(f,!0).break()):(e.if((0,ct._)`${T} > ${a}`,()=>e.assign(f,!1).break()),i===1?e.assign(f,!0):e.if((0,ct._)`${T} >= ${i}`,()=>e.assign(f,!0)))}}};jc.default=mR});var ig=U($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.validateSchemaDeps=$t.validatePropertyDeps=$t.error=void 0;var Uc=ee(),gR=de(),fs=at();$t.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,Uc.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,Uc._)`{property: ${t},
1775
1775
  missingProperty: ${r},
1776
1776
  depsCount: ${e},
1777
- deps: ${n}}`};var bR={keyword:"dependencies",type:"object",schemaType:"object",error:$t.error,code(t){let[e,n]=yR(t);sg(t,e),og(t,n)}};function yR({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 sg(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,fs.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,fs.checkReportMissingProp)(t,u)}):(n.if((0,Uc._)`${l} && (${(0,fs.checkMissingProp)(t,a,o)})`),(0,fs.reportMissingProp)(t,o),n.else())}}$t.validatePropertyDeps=sg;function og(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,gR.alwaysValidSchema)(o,e[a])||(n.if((0,fs.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))}$t.validateSchemaDeps=og;$t.default=bR});var lg=U(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var ag=ee(),wR=de(),vR={message:"property name must be valid",params:({params:t})=>(0,ag._)`{propertyName: ${t.propertyName}}`},kR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:vR,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,wR.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,ag.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Dc.default=kR});var zc=U(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var ri=at(),yt=ee(),SR=Nt(),si=de(),_R={message:"must NOT have additional properties",params:({params:t})=>(0,yt._)`{additionalProperty: ${t.additionalProperty}}`},$R={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:_R,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,si.alwaysValidSchema)(i,n))return;let u=(0,ri.allSchemaProperties)(r.properties),p=(0,ri.allSchemaProperties)(r.patternProperties);f(),t.ok((0,yt._)`${o} === ${SR.default.errors}`);function f(){e.forIn("key",s,E=>{!u.length&&!p.length?k(E):e.if(_(E),()=>k(E))})}function _(E){let P;if(u.length>8){let C=(0,si.schemaRefOrVal)(i,r.properties,"properties");P=(0,ri.isOwnProperty)(e,C,E)}else u.length?P=(0,yt.or)(...u.map(C=>(0,yt._)`${E} === ${C}`)):P=yt.nil;return p.length&&(P=(0,yt.or)(P,...p.map(C=>(0,yt._)`${(0,ri.usePattern)(t,C)}.test(${E})`))),(0,yt.not)(P)}function v(E){e.code((0,yt._)`delete ${s}[${E}]`)}function k(E){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){v(E);return}if(n===!1){t.setParams({additionalProperty:E}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,si.alwaysValidSchema)(i,n)){let P=e.name("valid");l.removeAdditional==="failing"?(T(E,P,!1),e.if((0,yt.not)(P),()=>{t.reset(),v(E)})):(T(E,P),a||e.if((0,yt.not)(P),()=>e.break()))}}function T(E,P,C){let D={keyword:"additionalProperties",dataProp:E,dataPropType:si.Type.Str};C===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};qc.default=$R});var ug=U(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var xR=es(),cg=at(),Mc=de(),dg=zc(),TR={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&&dg.default.code(new xR.KeywordCxt(o,dg.default,"additionalProperties"));let i=(0,cg.allSchemaProperties)(n);for(let f of i)o.definedProperties.add(f);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Mc.mergeEvaluated.props(e,(0,Mc.toHash)(i),o.props));let a=i.filter(f=>!(0,Mc.alwaysValidSchema)(o,n[f]));if(a.length===0)return;let l=e.name("valid");for(let f of a)u(f)?p(f):(e.if((0,cg.propertyInData)(e,s,f,o.opts.ownProperties)),p(f),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function u(f){return o.opts.useDefaults&&!o.compositeRule&&n[f].default!==void 0}function p(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};Bc.default=TR});var mg=U(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var pg=at(),oi=ee(),hg=de(),fg=de(),RR={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,pg.allSchemaProperties)(n),l=a.filter(T=>(0,hg.alwaysValidSchema)(o,n[T]));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 oi.Name)&&(o.props=(0,fg.evaluatedPropsToName)(e,o.props));let{props:f}=o;_();function _(){for(let T of a)u&&v(T),o.allErrors?k(T):(e.var(p,!0),k(T),e.if(p))}function v(T){for(let E in u)new RegExp(T).test(E)&&(0,hg.checkStrictMode)(o,`property ${E} matches pattern ${T} (use allowMatchingProperties)`)}function k(T){e.forIn("key",r,E=>{e.if((0,oi._)`${(0,pg.usePattern)(t,T)}.test(${E})`,()=>{let P=l.includes(T);P||t.subschema({keyword:"patternProperties",schemaProp:T,dataProp:E,dataPropType:fg.Type.Str},p),o.opts.unevaluated&&f!==!0?e.assign((0,oi._)`${f}[${E}]`,!0):!P&&!o.allErrors&&e.if((0,oi.not)(p),()=>e.break())})})}}};Fc.default=RR});var gg=U(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var ER=de(),PR={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,ER.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"}};Hc.default=PR});var bg=U(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var AR=at(),IR={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:AR.validateUnion,error:{message:"must match a schema in anyOf"}};Kc.default=IR});var yg=U(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var ii=ee(),CR=de(),OR={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ii._)`{passingSchemas: ${t.passing}}`},NR={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:OR,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,f)=>{let _;(0,CR.alwaysValidSchema)(s,p)?e.var(l,!0):_=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,ii._)`${l} && ${i}`).assign(i,!1).assign(a,(0,ii._)`[${a}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,f),_&&t.mergeEvaluated(_,ii.Name)})})}}};Vc.default=NR});var wg=U(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var LR=de(),jR={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,LR.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Gc.default=jR});var Sg=U(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var ai=ee(),kg=de(),UR={message:({params:t})=>(0,ai.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ai._)`{failingKeyword: ${t.ifClause}}`},DR={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:UR,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,kg.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=vg(r,"then"),o=vg(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,ai.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 _=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(_,i),f?e.assign(f,(0,ai._)`${p}`):t.setParams({ifClause:p})}}}};function vg(t,e){let n=t.schema[e];return n!==void 0&&!(0,kg.alwaysValidSchema)(t,n)}Wc.default=DR});var _g=U(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var qR=de(),zR={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,qR.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Jc.default=zR});var $g=U(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var MR=Cc(),BR=eg(),FR=Oc(),HR=ng(),KR=rg(),VR=ig(),GR=lg(),WR=zc(),JR=ug(),YR=mg(),ZR=gg(),QR=bg(),XR=yg(),eE=wg(),tE=Sg(),nE=_g();function rE(t=!1){let e=[ZR.default,QR.default,XR.default,eE.default,tE.default,nE.default,GR.default,WR.default,VR.default,JR.default,YR.default];return t?e.push(BR.default,HR.default):e.push(MR.default,FR.default),e.push(KR.default),e}Yc.default=rE});var xg=U(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var ke=ee(),sE={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},oE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:sE,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:f}=a;if(!l.validateFormats)return;s?_():v();function _(){let k=n.scopeValue("formats",{ref:f.formats,code:l.code.formats}),T=n.const("fDef",(0,ke._)`${k}[${i}]`),E=n.let("fType"),P=n.let("format");n.if((0,ke._)`typeof ${T} == "object" && !(${T} instanceof RegExp)`,()=>n.assign(E,(0,ke._)`${T}.type || "string"`).assign(P,(0,ke._)`${T}.validate`),()=>n.assign(E,(0,ke._)`"string"`).assign(P,T)),t.fail$data((0,ke.or)(C(),D()));function C(){return l.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${P}`}function D(){let se=p.$async?(0,ke._)`(${T}.async ? await ${P}(${r}) : ${P}(${r}))`:(0,ke._)`${P}(${r})`,Y=(0,ke._)`(typeof ${P} == "function" ? ${se} : ${P}.test(${r}))`;return(0,ke._)`${P} && ${P} !== true && ${E} === ${e} && !${Y}`}}function v(){let k=f.formats[o];if(!k){C();return}if(k===!0)return;let[T,E,P]=D(k);T===e&&t.pass(se());function C(){if(l.strictSchema===!1){f.logger.warn(Y());return}throw new Error(Y());function Y(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function D(Y){let je=Y instanceof RegExp?(0,ke.regexpCode)(Y):l.code.formats?(0,ke._)`${l.code.formats}${(0,ke.getProperty)(o)}`:void 0,Fe=n.scopeValue("formats",{key:o,ref:Y,code:je});return typeof Y=="object"&&!(Y instanceof RegExp)?[Y.type||"string",Y.validate,(0,ke._)`${Fe}.validate`]:["string",Y,Fe]}function se(){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}(${r})`}return typeof E=="function"?(0,ke._)`${P}(${r})`:(0,ke._)`${P}.test(${r})`}}}};Zc.default=oE});var Tg=U(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var iE=xg(),aE=[iE.default];Qc.default=aE});var Rg=U(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.contentVocabulary=rr.metadataVocabulary=void 0;rr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];rr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Pg=U(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var lE=jm(),cE=Ym(),dE=$g(),uE=Tg(),Eg=Rg(),pE=[lE.default,cE.default,(0,dE.default)(),uE.default,Eg.metadataVocabulary,Eg.contentVocabulary];Xc.default=pE});var Ig=U(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.DiscrError=void 0;var Ag;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ag||(li.DiscrError=Ag={}))});var Og=U(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var sr=ee(),ed=Ig(),Cg=Fo(),hE=ts(),fE=de(),mE={message:({params:{discrError:t,tagName:e}})=>t===ed.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,sr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},gE={keyword:"discriminator",type:"object",schemaType:"object",error:mE,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,sr._)`${n}${(0,sr.getProperty)(a)}`);e.if((0,sr._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:ed.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let v=_();e.if(!1);for(let k in v)e.elseIf((0,sr._)`${u} === ${k}`),e.assign(l,f(v[k]));e.else(),t.error(!1,{discrError:ed.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function f(v){let k=e.name("valid"),T=t.subschema({keyword:"oneOf",schemaProp:v},k);return t.mergeEvaluated(T,sr.Name),k}function _(){var v;let k={},T=P(s),E=!0;for(let se=0;se<i.length;se++){let Y=i[se];if(Y?.$ref&&!(0,fE.schemaHasRulesButRef)(Y,o.self.RULES)){let Fe=Y.$ref;if(Y=Cg.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Fe),Y instanceof Cg.SchemaEnv&&(Y=Y.schema),Y===void 0)throw new hE.default(o.opts.uriResolver,o.baseId,Fe)}let je=(v=Y?.properties)===null||v===void 0?void 0:v[a];if(typeof je!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);E=E&&(T||P(Y)),C(je,se)}if(!E)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:se}){return Array.isArray(se)&&se.includes(a)}function C(se,Y){if(se.const)D(se.const,Y);else if(se.enum)for(let je of se.enum)D(je,Y);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(se,Y){if(typeof se!="string"||se in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[se]=Y}}}};td.default=gE});var Ng=U((qL,bE)=>{bE.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 rd=U((ye,nd)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var yE=Am(),wE=Pg(),vE=Og(),Lg=Ng(),kE=["/properties"],ci="http://json-schema.org/draft-07/schema",or=class extends yE.default{_addVocabularies(){super._addVocabularies(),wE.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(vE.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Lg,kE):Lg;this.addMetaSchema(e,ci,!1),this.refs["http://json-schema.org/schema"]=ci}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ci)?ci:void 0)}};ye.Ajv=or;nd.exports=ye=or;nd.exports.Ajv=or;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=or;var SE=es();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return SE.KeywordCxt}});var ir=ee();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return ir._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return ir.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return ir.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return ir.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return ir.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return ir.CodeGen}});var _E=Mo();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return _E.default}});var $E=ts();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return $E.default}})});var Fg=U(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.formatNames=Tt.fastFormats=Tt.fullFormats=void 0;function xt(t,e){return{validate:t,compare:e}}Tt.fullFormats={date:xt(qg,ad),time:xt(od(!0),ld),"date-time":xt(jg(!0),Mg),"iso-time":xt(od(),zg),"iso-date-time":xt(jg(),Bg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:AE,"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:UE,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:IE,int32:{type:"number",validate:NE},int64:{type:"number",validate:LE},float:{type:"number",validate:Dg},double:{type:"number",validate:Dg},password:!0,binary:!0};Tt.fastFormats={...Tt.fullFormats,date:xt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ad),time:xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ld),"date-time":xt(/^\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,Mg),"iso-time":xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,zg),"iso-date-time":xt(/^\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,Bg),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};Tt.formatNames=Object.keys(Tt.fullFormats);function xE(t){return t%4===0&&(t%100!==0||t%400===0)}var TE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,RE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function qg(t){let e=TE.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&&xE(n)?29:RE[r])}function ad(t,e){if(t&&e)return t>e?1:t<e?-1:0}var sd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function od(t){return function(n){let r=sd.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 f=o-p*l,_=s-u*l-(f<0?1:0);return(_===23||_===-1)&&(f===59||f===-1)&&i<61}}function ld(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 zg(t,e){if(!(t&&e))return;let n=sd.exec(t),r=sd.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 id=/t|\s/i;function jg(t){let e=od(t);return function(r){let s=r.split(id);return s.length===2&&qg(s[0])&&e(s[1])}}function Mg(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function Bg(t,e){if(!(t&&e))return;let[n,r]=t.split(id),[s,o]=e.split(id),i=ad(n,s);if(i!==void 0)return i||ld(r,o)}var EE=/\/|:/,PE=/^(?:[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 AE(t){return EE.test(t)&&PE.test(t)}var Ug=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function IE(t){return Ug.lastIndex=0,Ug.test(t)}var CE=-(2**31),OE=2**31-1;function NE(t){return Number.isInteger(t)&&t<=OE&&t>=CE}function LE(t){return Number.isInteger(t)}function Dg(){return!0}var jE=/[^\\]\\Z/;function UE(t){if(jE.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Hg=U(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.formatLimitDefinition=void 0;var DE=rd(),wt=ee(),sn=wt.operators,di={formatMaximum:{okStr:"<=",ok:sn.LTE,fail:sn.GT},formatMinimum:{okStr:">=",ok:sn.GTE,fail:sn.LT},formatExclusiveMaximum:{okStr:"<",ok:sn.LT,fail:sn.GTE},formatExclusiveMinimum:{okStr:">",ok:sn.GT,fail:sn.LTE}},qE={message:({keyword:t,schemaCode:e})=>(0,wt.str)`should be ${di[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wt._)`{comparison: ${di[t].okStr}, limit: ${e}}`};ar.formatLimitDefinition={keyword:Object.keys(di),type:"string",schemaType:"string",$data:!0,error:qE,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 DE.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let _=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),v=e.const("fmt",(0,wt._)`${_}[${l.schemaCode}]`);t.fail$data((0,wt.or)((0,wt._)`typeof ${v} != "object"`,(0,wt._)`${v} instanceof RegExp`,(0,wt._)`typeof ${v}.compare != "function"`,f(v)))}function p(){let _=l.schema,v=a.formats[_];if(!v||v===!0)return;if(typeof v!="object"||v instanceof RegExp||typeof v.compare!="function")throw new Error(`"${s}": format "${_}" does not define "compare" function`);let k=e.scopeValue("formats",{key:_,ref:v,code:i.code.formats?(0,wt._)`${i.code.formats}${(0,wt.getProperty)(_)}`:void 0});t.fail$data(f(k))}function f(_){return(0,wt._)`${_}.compare(${n}, ${r}) ${di[s].fail} 0`}},dependencies:["format"]};var zE=t=>(t.addKeyword(ar.formatLimitDefinition),t);ar.default=zE});var Wg=U((ms,Gg)=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var lr=Fg(),ME=Hg(),cd=ee(),Kg=new cd.Name("fullFormats"),BE=new cd.Name("fastFormats"),dd=(t,e={keywords:!0})=>{if(Array.isArray(e))return Vg(t,e,lr.fullFormats,Kg),t;let[n,r]=e.mode==="fast"?[lr.fastFormats,BE]:[lr.fullFormats,Kg],s=e.formats||lr.formatNames;return Vg(t,s,n,r),e.keywords&&(0,ME.default)(t),t};dd.get=(t,e="full")=>{let r=(e==="fast"?lr.fastFormats:lr.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Vg(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,cd._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}Gg.exports=ms=dd;Object.defineProperty(ms,"__esModule",{value:!0});ms.default=dd});function FE(){let t=new Jg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Yg.default)(t),t}var Jg,Yg,ui,Zg=j(()=>{Jg=xd(rd(),1),Yg=xd(Wg(),1);ui=class{constructor(e){this._ajv=e??FE()}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 pi,Qg=j(()=>{Kn();pi=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(_=>_.type==="tool_use").map(_=>_.id)),f=new Set(o.filter(_=>_.type==="tool_result").map(_=>_.toolUseId));if(p.size!==f.size||![...p].every(_=>f.has(_)))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},Dr,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},Hn,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 Xg(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 eb(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 tb=j(()=>{});var hi,nb=j(()=>{sf();Kn();Zg();Er();Qg();tb();hi=class extends Eo{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ur.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 ui,this.setRequestHandler($a,r=>this._oninitialize(r)),this.setNotificationHandler(xa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ca,async(r,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Ur.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new pi(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rf(this._capabilities,e)}setRequestHandler(e,n){let s=Gt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=qn(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=Vt(Fn,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new q(F.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:f}=p.data,_=await Promise.resolve(n(l,u));if(f.task){let k=Vt(Mn,_);if(!k.success){let T=k.error instanceof Error?k.error.message:String(k.error);throw new q(F.InvalidParams,`Invalid task creation result: ${T}`)}return k.data}let v=Vt(go,_);if(!v.success){let k=v.error instanceof Error?v.error.message:String(v.error);throw new q(F.InvalidParams,`Invalid tools/call result: ${k}`)}return v.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){eb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Xg(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:nh.includes(n)?n:wa,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"},Xs)}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(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(s.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},Oa,n):this.request({method:"sampling/createMessage",params:e},Dr,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},Hn,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},Hn,n);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new q(F.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof q?i:new q(F.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},Na,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 ud(t){return!!t&&typeof t=="object"&&sb in t}function ob(t){return t[sb]?.complete}var sb,rb,ib=j(()=>{sb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(rb||(rb={}))});var ab=j(()=>{});function KE(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"),!HE.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 VE(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 pd(t){let e=KE(t);return VE(t,e.warnings),e.isValid}var HE,lb=j(()=>{HE=/^[A-Za-z0-9._-]{1,128}$/});var fi,cb=j(()=>{fi=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 GE}from"zod";function pb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function hb(t){return"_def"in t||"_zod"in t||pb(t)}function hd(t){return typeof t!="object"||t===null||hb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(pb)}function db(t){if(t){if(hd(t))return hn(t);if(!hb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function JE(t){let e=Gt(t);return e?Object.entries(e).map(([n,r])=>{let s=eh(r),o=th(r);return{name:n,description:s,required:!o}}):[]}function on(t){let n=Gt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=qn(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function ub(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var mi,WE,gs,fb=j(()=>{nb();Er();bl();Kn();ib();ab();lb();cb();mi=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 hi(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new fi(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(on(mo)),this.server.assertCanSetRequestHandler(on(Fn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(mo,()=>({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=Dn(n.inputSchema);return s?fl(s,{strictUnions:!0,pipeStrategy:"input"}):WE})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=Dn(n.outputSchema);s&&(r.outputSchema=fl(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Fn,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new q(F.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new q(F.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 q(F.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new q(F.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 q&&r.code===F.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=Dn(e.inputSchema)??e.inputSchema,i=await Ws(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",l=Js(a);throw new q(F.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 q(F.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=Dn(e.outputSchema),o=await Ws(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Js(i);throw new q(F.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(_=>setTimeout(_,p));let f=await r.taskStore.getTask(l);if(!f)throw new q(F.InternalError,`Task ${l} not found during polling`);u=f}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(on(bo)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(bo,async e=>{switch(e.params.ref.type){case"ref/prompt":return yh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return wh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(F.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new q(F.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new q(F.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return gs;let o=Gt(r.argsSchema)?.[e.params.argument.name];if(!ud(o))return gs;let i=ob(o);if(!i)return gs;let a=await i(e.params.argument.value,e.params.context);return ub(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 gs;throw new q(F.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return gs;let o=await s(e.params.argument.value,e.params.context);return ub(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(on(co)),this.server.assertCanSetRequestHandler(on(uo)),this.server.assertCanSetRequestHandler(on(po)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(co,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(uo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(po,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new q(F.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 q(F.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(on(ho)),this.server.assertCanSetRequestHandler(on(fo)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ho,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?JE(n.argsSchema):void 0}))})),this.server.setRequestHandler(fo,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new q(F.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new q(F.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=Dn(r.argsSchema),o=await Ws(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",u=Js(l);throw new q(F.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:hn(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=hn(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 GE?l._def?.innerType:l;return ud(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,l,u){pd(e);let p={title:n,description:r,inputSchema:db(s),outputSchema:db(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:f=>{typeof f.name<"u"&&f.name!==e&&(typeof f.name=="string"&&pd(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=hn(f.paramsSchema)),typeof f.outputSchema<"u"&&(p.outputSchema=hn(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,...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(hd(l))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!hd(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()}},WE={type:"object",properties:{}};gs={completion:{values:[],hasMore:!1}}});function ZE(t){return dh.parse(JSON.parse(t))}function mb(t){return JSON.stringify(t)+`
1777
+ deps: ${n}}`};var bR={keyword:"dependencies",type:"object",schemaType:"object",error:$t.error,code(t){let[e,n]=yR(t);sg(t,e),og(t,n)}};function yR({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 sg(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,fs.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,fs.checkReportMissingProp)(t,u)}):(n.if((0,Uc._)`${l} && (${(0,fs.checkMissingProp)(t,a,o)})`),(0,fs.reportMissingProp)(t,o),n.else())}}$t.validatePropertyDeps=sg;function og(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,gR.alwaysValidSchema)(o,e[a])||(n.if((0,fs.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))}$t.validateSchemaDeps=og;$t.default=bR});var lg=U(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});var ag=ee(),wR=de(),vR={message:"property name must be valid",params:({params:t})=>(0,ag._)`{propertyName: ${t.propertyName}}`},kR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:vR,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,wR.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,ag.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Dc.default=kR});var zc=U(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var ri=at(),yt=ee(),SR=Nt(),si=de(),_R={message:"must NOT have additional properties",params:({params:t})=>(0,yt._)`{additionalProperty: ${t.additionalProperty}}`},$R={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:_R,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,si.alwaysValidSchema)(i,n))return;let u=(0,ri.allSchemaProperties)(r.properties),p=(0,ri.allSchemaProperties)(r.patternProperties);f(),t.ok((0,yt._)`${o} === ${SR.default.errors}`);function f(){e.forIn("key",s,E=>{!u.length&&!p.length?k(E):e.if(_(E),()=>k(E))})}function _(E){let P;if(u.length>8){let C=(0,si.schemaRefOrVal)(i,r.properties,"properties");P=(0,ri.isOwnProperty)(e,C,E)}else u.length?P=(0,yt.or)(...u.map(C=>(0,yt._)`${E} === ${C}`)):P=yt.nil;return p.length&&(P=(0,yt.or)(P,...p.map(C=>(0,yt._)`${(0,ri.usePattern)(t,C)}.test(${E})`))),(0,yt.not)(P)}function v(E){e.code((0,yt._)`delete ${s}[${E}]`)}function k(E){if(l.removeAdditional==="all"||l.removeAdditional&&n===!1){v(E);return}if(n===!1){t.setParams({additionalProperty:E}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,si.alwaysValidSchema)(i,n)){let P=e.name("valid");l.removeAdditional==="failing"?(T(E,P,!1),e.if((0,yt.not)(P),()=>{t.reset(),v(E)})):(T(E,P),a||e.if((0,yt.not)(P),()=>e.break()))}}function T(E,P,C){let D={keyword:"additionalProperties",dataProp:E,dataPropType:si.Type.Str};C===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};qc.default=$R});var ug=U(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var xR=es(),cg=at(),Mc=de(),dg=zc(),TR={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&&dg.default.code(new xR.KeywordCxt(o,dg.default,"additionalProperties"));let i=(0,cg.allSchemaProperties)(n);for(let f of i)o.definedProperties.add(f);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Mc.mergeEvaluated.props(e,(0,Mc.toHash)(i),o.props));let a=i.filter(f=>!(0,Mc.alwaysValidSchema)(o,n[f]));if(a.length===0)return;let l=e.name("valid");for(let f of a)u(f)?p(f):(e.if((0,cg.propertyInData)(e,s,f,o.opts.ownProperties)),p(f),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(f),t.ok(l);function u(f){return o.opts.useDefaults&&!o.compositeRule&&n[f].default!==void 0}function p(f){t.subschema({keyword:"properties",schemaProp:f,dataProp:f},l)}}};Bc.default=TR});var mg=U(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var pg=at(),oi=ee(),hg=de(),fg=de(),RR={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,pg.allSchemaProperties)(n),l=a.filter(T=>(0,hg.alwaysValidSchema)(o,n[T]));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 oi.Name)&&(o.props=(0,fg.evaluatedPropsToName)(e,o.props));let{props:f}=o;_();function _(){for(let T of a)u&&v(T),o.allErrors?k(T):(e.var(p,!0),k(T),e.if(p))}function v(T){for(let E in u)new RegExp(T).test(E)&&(0,hg.checkStrictMode)(o,`property ${E} matches pattern ${T} (use allowMatchingProperties)`)}function k(T){e.forIn("key",r,E=>{e.if((0,oi._)`${(0,pg.usePattern)(t,T)}.test(${E})`,()=>{let P=l.includes(T);P||t.subschema({keyword:"patternProperties",schemaProp:T,dataProp:E,dataPropType:fg.Type.Str},p),o.opts.unevaluated&&f!==!0?e.assign((0,oi._)`${f}[${E}]`,!0):!P&&!o.allErrors&&e.if((0,oi.not)(p),()=>e.break())})})}}};Fc.default=RR});var gg=U(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var ER=de(),PR={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,ER.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"}};Hc.default=PR});var bg=U(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var AR=at(),IR={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:AR.validateUnion,error:{message:"must match a schema in anyOf"}};Kc.default=IR});var yg=U(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var ii=ee(),CR=de(),OR={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ii._)`{passingSchemas: ${t.passing}}`},NR={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:OR,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,f)=>{let _;(0,CR.alwaysValidSchema)(s,p)?e.var(l,!0):_=t.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},l),f>0&&e.if((0,ii._)`${l} && ${i}`).assign(i,!1).assign(a,(0,ii._)`[${a}, ${f}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,f),_&&t.mergeEvaluated(_,ii.Name)})})}}};Vc.default=NR});var wg=U(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var LR=de(),jR={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,LR.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Gc.default=jR});var Sg=U(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var ai=ee(),kg=de(),UR={message:({params:t})=>(0,ai.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ai._)`{failingKeyword: ${t.ifClause}}`},DR={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:UR,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,kg.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=vg(r,"then"),o=vg(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,ai.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 _=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(_,i),f?e.assign(f,(0,ai._)`${p}`):t.setParams({ifClause:p})}}}};function vg(t,e){let n=t.schema[e];return n!==void 0&&!(0,kg.alwaysValidSchema)(t,n)}Wc.default=DR});var _g=U(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var qR=de(),zR={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,qR.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Jc.default=zR});var $g=U(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var MR=Cc(),BR=eg(),FR=Oc(),HR=ng(),KR=rg(),VR=ig(),GR=lg(),WR=zc(),JR=ug(),YR=mg(),ZR=gg(),QR=bg(),XR=yg(),eE=wg(),tE=Sg(),nE=_g();function rE(t=!1){let e=[ZR.default,QR.default,XR.default,eE.default,tE.default,nE.default,GR.default,WR.default,VR.default,JR.default,YR.default];return t?e.push(BR.default,HR.default):e.push(MR.default,FR.default),e.push(KR.default),e}Yc.default=rE});var xg=U(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var ke=ee(),sE={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},oE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:sE,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:f}=a;if(!l.validateFormats)return;s?_():v();function _(){let k=n.scopeValue("formats",{ref:f.formats,code:l.code.formats}),T=n.const("fDef",(0,ke._)`${k}[${i}]`),E=n.let("fType"),P=n.let("format");n.if((0,ke._)`typeof ${T} == "object" && !(${T} instanceof RegExp)`,()=>n.assign(E,(0,ke._)`${T}.type || "string"`).assign(P,(0,ke._)`${T}.validate`),()=>n.assign(E,(0,ke._)`"string"`).assign(P,T)),t.fail$data((0,ke.or)(C(),D()));function C(){return l.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${P}`}function D(){let re=p.$async?(0,ke._)`(${T}.async ? await ${P}(${r}) : ${P}(${r}))`:(0,ke._)`${P}(${r})`,Y=(0,ke._)`(typeof ${P} == "function" ? ${re} : ${P}.test(${r}))`;return(0,ke._)`${P} && ${P} !== true && ${E} === ${e} && !${Y}`}}function v(){let k=f.formats[o];if(!k){C();return}if(k===!0)return;let[T,E,P]=D(k);T===e&&t.pass(re());function C(){if(l.strictSchema===!1){f.logger.warn(Y());return}throw new Error(Y());function Y(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function D(Y){let je=Y instanceof RegExp?(0,ke.regexpCode)(Y):l.code.formats?(0,ke._)`${l.code.formats}${(0,ke.getProperty)(o)}`:void 0,Fe=n.scopeValue("formats",{key:o,ref:Y,code:je});return typeof Y=="object"&&!(Y instanceof RegExp)?[Y.type||"string",Y.validate,(0,ke._)`${Fe}.validate`]:["string",Y,Fe]}function re(){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}(${r})`}return typeof E=="function"?(0,ke._)`${P}(${r})`:(0,ke._)`${P}.test(${r})`}}}};Zc.default=oE});var Tg=U(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var iE=xg(),aE=[iE.default];Qc.default=aE});var Rg=U(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.contentVocabulary=rr.metadataVocabulary=void 0;rr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];rr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Pg=U(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var lE=jm(),cE=Ym(),dE=$g(),uE=Tg(),Eg=Rg(),pE=[lE.default,cE.default,(0,dE.default)(),uE.default,Eg.metadataVocabulary,Eg.contentVocabulary];Xc.default=pE});var Ig=U(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.DiscrError=void 0;var Ag;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ag||(li.DiscrError=Ag={}))});var Og=U(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var sr=ee(),ed=Ig(),Cg=Fo(),hE=ts(),fE=de(),mE={message:({params:{discrError:t,tagName:e}})=>t===ed.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,sr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},gE={keyword:"discriminator",type:"object",schemaType:"object",error:mE,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,sr._)`${n}${(0,sr.getProperty)(a)}`);e.if((0,sr._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:ed.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let v=_();e.if(!1);for(let k in v)e.elseIf((0,sr._)`${u} === ${k}`),e.assign(l,f(v[k]));e.else(),t.error(!1,{discrError:ed.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function f(v){let k=e.name("valid"),T=t.subschema({keyword:"oneOf",schemaProp:v},k);return t.mergeEvaluated(T,sr.Name),k}function _(){var v;let k={},T=P(s),E=!0;for(let re=0;re<i.length;re++){let Y=i[re];if(Y?.$ref&&!(0,fE.schemaHasRulesButRef)(Y,o.self.RULES)){let Fe=Y.$ref;if(Y=Cg.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,Fe),Y instanceof Cg.SchemaEnv&&(Y=Y.schema),Y===void 0)throw new hE.default(o.opts.uriResolver,o.baseId,Fe)}let je=(v=Y?.properties)===null||v===void 0?void 0:v[a];if(typeof je!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);E=E&&(T||P(Y)),C(je,re)}if(!E)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:re}){return Array.isArray(re)&&re.includes(a)}function C(re,Y){if(re.const)D(re.const,Y);else if(re.enum)for(let je of re.enum)D(je,Y);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(re,Y){if(typeof re!="string"||re in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[re]=Y}}}};td.default=gE});var Ng=U((DL,bE)=>{bE.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 rd=U((ye,nd)=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.MissingRefError=ye.ValidationError=ye.CodeGen=ye.Name=ye.nil=ye.stringify=ye.str=ye._=ye.KeywordCxt=ye.Ajv=void 0;var yE=Am(),wE=Pg(),vE=Og(),Lg=Ng(),kE=["/properties"],ci="http://json-schema.org/draft-07/schema",or=class extends yE.default{_addVocabularies(){super._addVocabularies(),wE.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(vE.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Lg,kE):Lg;this.addMetaSchema(e,ci,!1),this.refs["http://json-schema.org/schema"]=ci}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ci)?ci:void 0)}};ye.Ajv=or;nd.exports=ye=or;nd.exports.Ajv=or;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=or;var SE=es();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return SE.KeywordCxt}});var ir=ee();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return ir._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return ir.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return ir.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return ir.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return ir.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return ir.CodeGen}});var _E=Mo();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return _E.default}});var $E=ts();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return $E.default}})});var Fg=U(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.formatNames=Tt.fastFormats=Tt.fullFormats=void 0;function xt(t,e){return{validate:t,compare:e}}Tt.fullFormats={date:xt(qg,ad),time:xt(od(!0),ld),"date-time":xt(jg(!0),Mg),"iso-time":xt(od(),zg),"iso-date-time":xt(jg(),Bg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:AE,"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:UE,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:IE,int32:{type:"number",validate:NE},int64:{type:"number",validate:LE},float:{type:"number",validate:Dg},double:{type:"number",validate:Dg},password:!0,binary:!0};Tt.fastFormats={...Tt.fullFormats,date:xt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ad),time:xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ld),"date-time":xt(/^\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,Mg),"iso-time":xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,zg),"iso-date-time":xt(/^\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,Bg),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};Tt.formatNames=Object.keys(Tt.fullFormats);function xE(t){return t%4===0&&(t%100!==0||t%400===0)}var TE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,RE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function qg(t){let e=TE.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&&xE(n)?29:RE[r])}function ad(t,e){if(t&&e)return t>e?1:t<e?-1:0}var sd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function od(t){return function(n){let r=sd.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 f=o-p*l,_=s-u*l-(f<0?1:0);return(_===23||_===-1)&&(f===59||f===-1)&&i<61}}function ld(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 zg(t,e){if(!(t&&e))return;let n=sd.exec(t),r=sd.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 id=/t|\s/i;function jg(t){let e=od(t);return function(r){let s=r.split(id);return s.length===2&&qg(s[0])&&e(s[1])}}function Mg(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function Bg(t,e){if(!(t&&e))return;let[n,r]=t.split(id),[s,o]=e.split(id),i=ad(n,s);if(i!==void 0)return i||ld(r,o)}var EE=/\/|:/,PE=/^(?:[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 AE(t){return EE.test(t)&&PE.test(t)}var Ug=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function IE(t){return Ug.lastIndex=0,Ug.test(t)}var CE=-(2**31),OE=2**31-1;function NE(t){return Number.isInteger(t)&&t<=OE&&t>=CE}function LE(t){return Number.isInteger(t)}function Dg(){return!0}var jE=/[^\\]\\Z/;function UE(t){if(jE.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Hg=U(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.formatLimitDefinition=void 0;var DE=rd(),wt=ee(),rn=wt.operators,di={formatMaximum:{okStr:"<=",ok:rn.LTE,fail:rn.GT},formatMinimum:{okStr:">=",ok:rn.GTE,fail:rn.LT},formatExclusiveMaximum:{okStr:"<",ok:rn.LT,fail:rn.GTE},formatExclusiveMinimum:{okStr:">",ok:rn.GT,fail:rn.LTE}},qE={message:({keyword:t,schemaCode:e})=>(0,wt.str)`should be ${di[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wt._)`{comparison: ${di[t].okStr}, limit: ${e}}`};ar.formatLimitDefinition={keyword:Object.keys(di),type:"string",schemaType:"string",$data:!0,error:qE,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 DE.KeywordCxt(o,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let _=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),v=e.const("fmt",(0,wt._)`${_}[${l.schemaCode}]`);t.fail$data((0,wt.or)((0,wt._)`typeof ${v} != "object"`,(0,wt._)`${v} instanceof RegExp`,(0,wt._)`typeof ${v}.compare != "function"`,f(v)))}function p(){let _=l.schema,v=a.formats[_];if(!v||v===!0)return;if(typeof v!="object"||v instanceof RegExp||typeof v.compare!="function")throw new Error(`"${s}": format "${_}" does not define "compare" function`);let k=e.scopeValue("formats",{key:_,ref:v,code:i.code.formats?(0,wt._)`${i.code.formats}${(0,wt.getProperty)(_)}`:void 0});t.fail$data(f(k))}function f(_){return(0,wt._)`${_}.compare(${n}, ${r}) ${di[s].fail} 0`}},dependencies:["format"]};var zE=t=>(t.addKeyword(ar.formatLimitDefinition),t);ar.default=zE});var Wg=U((ms,Gg)=>{"use strict";Object.defineProperty(ms,"__esModule",{value:!0});var lr=Fg(),ME=Hg(),cd=ee(),Kg=new cd.Name("fullFormats"),BE=new cd.Name("fastFormats"),dd=(t,e={keywords:!0})=>{if(Array.isArray(e))return Vg(t,e,lr.fullFormats,Kg),t;let[n,r]=e.mode==="fast"?[lr.fastFormats,BE]:[lr.fullFormats,Kg],s=e.formats||lr.formatNames;return Vg(t,s,n,r),e.keywords&&(0,ME.default)(t),t};dd.get=(t,e="full")=>{let r=(e==="fast"?lr.fastFormats:lr.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Vg(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,cd._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}Gg.exports=ms=dd;Object.defineProperty(ms,"__esModule",{value:!0});ms.default=dd});function FE(){let t=new Jg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Yg.default)(t),t}var Jg,Yg,ui,Zg=j(()=>{Jg=xd(rd(),1),Yg=xd(Wg(),1);ui=class{constructor(e){this._ajv=e??FE()}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 pi,Qg=j(()=>{Kn();pi=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(_=>_.type==="tool_use").map(_=>_.id)),f=new Set(o.filter(_=>_.type==="tool_result").map(_=>_.toolUseId));if(p.size!==f.size||![...p].every(_=>f.has(_)))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},Dr,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},Hn,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 Xg(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 eb(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 tb=j(()=>{});var hi,nb=j(()=>{sf();Kn();Zg();Er();Qg();tb();hi=class extends Eo{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ur.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 ui,this.setRequestHandler($a,r=>this._oninitialize(r)),this.setNotificationHandler(xa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ca,async(r,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Ur.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new pi(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rf(this._capabilities,e)}setRequestHandler(e,n){let s=Vt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=qn(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=Kt(Fn,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new q(F.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:f}=p.data,_=await Promise.resolve(n(l,u));if(f.task){let k=Kt(Mn,_);if(!k.success){let T=k.error instanceof Error?k.error.message:String(k.error);throw new q(F.InvalidParams,`Invalid task creation result: ${T}`)}return k.data}let v=Kt(go,_);if(!v.success){let k=v.error instanceof Error?v.error.message:String(v.error);throw new q(F.InvalidParams,`Invalid tools/call result: ${k}`)}return v.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){eb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&Xg(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:nh.includes(n)?n:wa,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"},Xs)}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(f=>f.type==="tool_use").map(f=>f.id)),p=new Set(s.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},Oa,n):this.request({method:"sampling/createMessage",params:e},Dr,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},Hn,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},Hn,n);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new q(F.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof q?i:new q(F.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},Na,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 ud(t){return!!t&&typeof t=="object"&&sb in t}function ob(t){return t[sb]?.complete}var sb,rb,ib=j(()=>{sb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(rb||(rb={}))});var ab=j(()=>{});function KE(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"),!HE.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 VE(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 pd(t){let e=KE(t);return VE(t,e.warnings),e.isValid}var HE,lb=j(()=>{HE=/^[A-Za-z0-9._-]{1,128}$/});var fi,cb=j(()=>{fi=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 GE}from"zod";function pb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function hb(t){return"_def"in t||"_zod"in t||pb(t)}function hd(t){return typeof t!="object"||t===null||hb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(pb)}function db(t){if(t){if(hd(t))return hn(t);if(!hb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function JE(t){let e=Vt(t);return e?Object.entries(e).map(([n,r])=>{let s=eh(r),o=th(r);return{name:n,description:s,required:!o}}):[]}function sn(t){let n=Vt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=qn(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function ub(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var mi,WE,gs,fb=j(()=>{nb();Er();bl();Kn();ib();ab();lb();cb();mi=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 hi(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new fi(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(mo)),this.server.assertCanSetRequestHandler(sn(Fn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(mo,()=>({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=Dn(n.inputSchema);return s?fl(s,{strictUnions:!0,pipeStrategy:"input"}):WE})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=Dn(n.outputSchema);s&&(r.outputSchema=fl(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Fn,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new q(F.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new q(F.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 q(F.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new q(F.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 q&&r.code===F.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=Dn(e.inputSchema)??e.inputSchema,i=await Ws(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",l=Js(a);throw new q(F.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 q(F.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=Dn(e.outputSchema),o=await Ws(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Js(i);throw new q(F.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(_=>setTimeout(_,p));let f=await r.taskStore.getTask(l);if(!f)throw new q(F.InternalError,`Task ${l} not found during polling`);u=f}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(sn(bo)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(bo,async e=>{switch(e.params.ref.type){case"ref/prompt":return yh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return wh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(F.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new q(F.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new q(F.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return gs;let o=Vt(r.argsSchema)?.[e.params.argument.name];if(!ud(o))return gs;let i=ob(o);if(!i)return gs;let a=await i(e.params.argument.value,e.params.context);return ub(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 gs;throw new q(F.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return gs;let o=await s(e.params.argument.value,e.params.context);return ub(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(co)),this.server.assertCanSetRequestHandler(sn(uo)),this.server.assertCanSetRequestHandler(sn(po)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(co,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(uo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(po,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new q(F.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 q(F.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(ho)),this.server.assertCanSetRequestHandler(sn(fo)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ho,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?JE(n.argsSchema):void 0}))})),this.server.setRequestHandler(fo,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new q(F.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new q(F.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=Dn(r.argsSchema),o=await Ws(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",u=Js(l);throw new q(F.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:hn(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=hn(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 GE?l._def?.innerType:l;return ud(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,l,u){pd(e);let p={title:n,description:r,inputSchema:db(s),outputSchema:db(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:f=>{typeof f.name<"u"&&f.name!==e&&(typeof f.name=="string"&&pd(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=hn(f.paramsSchema)),typeof f.outputSchema<"u"&&(p.outputSchema=hn(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,...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(hd(l))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!hd(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()}},WE={type:"object",properties:{}};gs={completion:{values:[],hasMore:!1}}});function ZE(t){return dh.parse(JSON.parse(t))}function mb(t){return JSON.stringify(t)+`
1778
1778
  `}var YE,gi,gb=j(()=>{Kn();YE=10*1024*1024,gi=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??YE}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(`
1779
1779
  `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),ZE(n)}clear(){this._buffer=void 0}}});import bb from"node:process";var bi,yb=j(()=>{gb();bi=class{constructor(e=bb.stdin,n=bb.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 gi({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=mb(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var wb,vb=j(()=>{wb=[]});var Pb={};$d(Pb,{AUTHORING_MCP_SERVER_NAME:()=>xb,AUTHORING_MCP_SERVER_VERSION:()=>Tb,AUTHORING_RESOURCES:()=>t0,AUTHORING_TOOLS:()=>e0,AUTHORING_TOOLS_PUBLIC:()=>Eb,buildAuthoringMcpServer:()=>Rb,runAuthoringMcpServer:()=>n0});import{promises as QE}from"node:fs";import{resolve as kb}from"node:path";import{z as M}from"zod";function $b(){return _b??=import("../mcp/grounding.js").then(e=>e,()=>null),_b}function Se(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function XE(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 Rb(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let v=await ut(t.baseUrl);if(!v)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:v.baseUrl,token:v.token}}let n=t.grounding??{},r=await $b(),s=null;if(r)try{let v=await e();s={surface:"mcp-authoring",baseUrl:v.baseUrl,token:v.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(v=>({id:v.id,record_type:v.record_type,intent:v.intent}))}catch{l=[]}}let u=s?await XE(s,n):null,p=new mi({name:xb,version:Tb},r?{instructions:r.renderAuthoringInstructions({baseUrl:s?.baseUrl??t.baseUrl??"this instance",sources:o,recipeIntents:l,promptNames:a.map(v=>v.id),deployedExtensions:u,docsToken:n.docsToken??r.docsPublicToken()})}:void 0);if(r&&s){let v=s;for(let k of a)p.registerPrompt(k.id,{title:k.name,description:k.description},async()=>{let T=await r.getMcpPromptSkill(v,k.id,n);if(!T)throw new Error(`unknown prompt: ${k.id}`);return{description:T.description,messages:[{role:"user",content:{type:"text",text:(T.prompts??[]).join(`
1780
1780
 
1781
- `)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:v,token:k}=await e(),T=await fetch(`${v}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog fetch failed: ${T.status}`);return Se(await T.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:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.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:v,source:k})=>{let{baseUrl:T,token:E}=await e(),P=k?`?source=${encodeURIComponent(k)}`:"",C=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(v)}${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(C.status===404)throw new Error(`unknown record type "${v}" \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`record anatomy fetch failed: ${C.status}`);return Se(await C.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:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.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:v,source:k})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({types:v.join(",")});k&&P.set("source",k);let C=await fetch(`${T}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(C.status===404)throw new Error(`none of those record types resolved: ${v.join(", ")} \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`common columns fetch failed: ${C.status}`);return Se(await C.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:v,token:k}=await e(),T=await fetch(`${v}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog census failed: ${T.status}`);return Se(await T.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:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(Sb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:v,kind:k,limit:T})=>{let{baseUrl:E,token:P}=await e(),C=new URLSearchParams({q:v});k&&C.set("kind",k),T!==void 0&&C.set("limit",String(T));let D=await fetch(`${E}/v1/catalog/objects?${C}`,{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:M.enum(Sb),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:v,externalId:k})=>{let{baseUrl:T,token:E}=await e(),P=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(v)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${v}:${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:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:v,limit:k})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({q:v});k!==void 0&&P.set("limit",String(k));let C=await fetch(`${T}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!C.ok)throw new Error(`kb search failed: ${C.status}`);return Se(await C.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:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:v})=>{let{baseUrl:k,token:T}=await e(),E=await fetch(`${k}/v1/kb/document/${encodeURIComponent(v)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!E.ok&&E.status!==404)throw new Error(`kb document fetch failed: ${E.status}`);return Se(await E.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:M.boolean().optional()}},async({recordsOnly:v})=>{let{baseUrl:k,token:T}=await e();return{content:[{type:"text",text:await qt({baseUrl:k,token:T,recordsOnly:v})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async v=>{let k=Ft("hook",{recordType:v.recordType,event:v.event,template:v.template,field:v.field,regex:v.regex,source:v.source,id:v.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:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async v=>{let k=Ft("conduit",{recordType:v.recordType,source:v.source,to:v.to,toRecordType:v.toRecordType,event:v.event,id:v.id});return Se({path:k.relativePath,content:k.content})}),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:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:v,samplesDir:k})=>{let T=kb(process.cwd(),k??"samples"),E=await br(T),P=await Ps(v,E.map(D=>D.fixture)),C=P.filter(D=>!D.pass).length;return Se({total:P.length,passed:P.length-C,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async v=>{let{baseUrl:k,token:T}=await e(),P=await new B({baseUrl:k,token:T}).deploy({id:v.id,recordType:v.recordType,event:v.event,source:v.source,sourceCode:v.sourceCode,extensionKind:v.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:M.string(),limit:M.number().int().positive().optional()}},async({id:v,limit:k})=>{let{baseUrl:T,token:E}=await e(),P=new B({baseUrl:T,token:E});return Se({id:v,logs:await P.logs(v,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:v,token:k}=await e(),T=new B({baseUrl:v,token:k});return Se(await T.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:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:v,name:k,description:T})=>{let{baseUrl:E,token:P}=await e(),C=new B({baseUrl:E,token:P});return Se(await C.appsCreate({slug:v,name:k,description:T}))}),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:M.string().describe("App slug or id.")}},async({app:v})=>{let{baseUrl:k,token:T}=await e(),E=new B({baseUrl:k,token:T});return Se(await E.appsPull(v))}),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:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:v,files:k,note:T})=>{let{baseUrl:E,token:P}=await e(),C=new B({baseUrl:E,token:P});return Se(await C.appsPush(v,k,{note:T}))});let f=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),_=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(f).describe("At least one field."),rowLevelOwner:M.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:v,token:k}=await e(),T=new B({baseUrl:v,token:k});return Se(await T.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:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:k})=>{let{baseUrl:T,token:E}=await e(),P=new B({baseUrl:T,token:E});return Se(await P.tablesPlan({tables:v,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:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:k})=>{let{baseUrl:T,token:E}=await e(),P=new B({baseUrl:T,token:E});return Se(await P.tablesApply({tables:v,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async v=>{let{baseUrl:k,token:T}=await e(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}})).text();return{contents:[{uri:v.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async v=>{let{baseUrl:k,token:T}=await e(),E=await qt({baseUrl:k,token:T});return{contents:[{uri:v.href,mimeType:"text/plain",text:E}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async v=>{let k=kb(process.cwd(),"samples"),T=[];try{T=(await QE.readdir(k)).filter(P=>P.endsWith(".json"))}catch{T=[]}let E=await br(k);return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({files:T,samples:E.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 v=>{let k=await $b(),T=[];if(k){let{baseUrl:E,token:P}=await e();T=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:E,token:P},n)}return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({recipes:T})}]}}),p}async function n0(t={}){let e=await Rb(t),n=new bi;await e.connect(n)}var Sb,_b,xb,Tb,Eb,e0,t0,Ab=j(()=>{fb();yb();Li();fr();Et();Hi();Ns();vb();Sb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];xb="turbobase-authoring",Tb="0.1.0";Eb=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],e0=[...Eb,...wb],t0=["catalog:///","types://all","samples:///","recipes:///"]});Li();fr();Et();Hi();import{spawn as wd}from"node:child_process";import{promises as re}from"node:fs";import{homedir as r0}from"node:os";import{basename as Cb,dirname as cr,join as Ye,relative as wi,resolve as ie,sep as yd}from"node:path";import{Command as s0}from"commander";Bi();import{promises as Wd}from"node:fs";function Vd(t,e){return e===t?"same-type-merge":"different-type-mint"}var Jd=4;function Ki(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Pn(t,"id"),n=Pn(t,"on"),r=Pn(t,"source"),s=Pn(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Pn(o,"source"),a=Pn(o,"recordType"),l=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!s||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:n,fromSource:r,fromRecordType:s,toSource:i,toRecordType:a,cycleBudget:l?Number(l[1]):Jd}}function Pn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function py(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 Yd(t,e,n="fixture"){let r=e.name??n,s=[],o;try{o=Ki(t)}catch(l){return{fixtureName:r,conduit:fy(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=py(e),a=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Es(t),p=!!(await gr(l,i,{member:"when",timeoutMs:200})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let f=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${f} vs cycleBudget=${o.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!p)return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let _=await gr(l,i,{member:"transform",timeoutMs:200}),v=_.effects.logs,k=_.effects.result;if(!k||typeof k!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let T=k,E=Vd(o.fromRecordType,o.toRecordType),{wouldWriteBindings:P,masterAction:C}=hy(o,E,e);return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,transformResult:T,applyBranch:E,wouldWriteBindings:P,masterAction:C,logs:v}}catch(l){return{fixtureName:r,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function hy(t,e,n){return e==="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:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:n.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function fy(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Jd}}async function Zd(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 Qd(t){let e=await Wd.readFile(t,"utf8");return JSON.parse(e)}function Xd(t){return Wd.readFile(t,"utf8")}function eu(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;let r=[];r.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),r.push(`conduit: ${n.id}`),r.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${n.toSource}.${n.toRecordType}${n.on?` on=${n.on}`:""}`),r.push(""),r.push("guards (dispatch order):");for(let s of t.guards){let o=s.status==="passed"?"\u2713":s.status==="failed"?"\u2717":"\u2298";r.push(` ${o} ${s.name} [${s.status}] \u2014 ${s.detail}`)}if(r.push(""),r.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)r.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let s of t.atlasResolutions)r.push(` ${s.key} \u2192 ${s.resolved===null?"null (no Atlas link \u2014 noted)":s.resolved}`);if(!t.whenPassed)return r.push(""),r.push("transform: SKIPPED (from.when gate did not fire)."),r.join(`
1781
+ `)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:v,token:k}=await e(),T=await fetch(`${v}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog fetch failed: ${T.status}`);return Se(await T.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:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.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:v,source:k})=>{let{baseUrl:T,token:E}=await e(),P=k?`?source=${encodeURIComponent(k)}`:"",C=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(v)}${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(C.status===404)throw new Error(`unknown record type "${v}" \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`record anatomy fetch failed: ${C.status}`);return Se(await C.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:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.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:v,source:k})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({types:v.join(",")});k&&P.set("source",k);let C=await fetch(`${T}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(C.status===404)throw new Error(`none of those record types resolved: ${v.join(", ")} \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`common columns fetch failed: ${C.status}`);return Se(await C.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:v,token:k}=await e(),T=await fetch(`${v}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog census failed: ${T.status}`);return Se(await T.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:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(Sb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:v,kind:k,limit:T})=>{let{baseUrl:E,token:P}=await e(),C=new URLSearchParams({q:v});k&&C.set("kind",k),T!==void 0&&C.set("limit",String(T));let D=await fetch(`${E}/v1/catalog/objects?${C}`,{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:M.enum(Sb),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:v,externalId:k})=>{let{baseUrl:T,token:E}=await e(),P=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(v)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${v}:${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:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:v,limit:k})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({q:v});k!==void 0&&P.set("limit",String(k));let C=await fetch(`${T}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!C.ok)throw new Error(`kb search failed: ${C.status}`);return Se(await C.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:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:v})=>{let{baseUrl:k,token:T}=await e(),E=await fetch(`${k}/v1/kb/document/${encodeURIComponent(v)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!E.ok&&E.status!==404)throw new Error(`kb document fetch failed: ${E.status}`);return Se(await E.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:M.boolean().optional()}},async({recordsOnly:v})=>{let{baseUrl:k,token:T}=await e();return{content:[{type:"text",text:await cn({baseUrl:k,token:T,recordsOnly:v})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async v=>{let k=Bt("hook",{recordType:v.recordType,event:v.event,template:v.template,field:v.field,regex:v.regex,source:v.source,id:v.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:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async v=>{let k=Bt("conduit",{recordType:v.recordType,source:v.source,to:v.to,toRecordType:v.toRecordType,event:v.event,id:v.id});return Se({path:k.relativePath,content:k.content})}),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:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:v,samplesDir:k})=>{let T=kb(process.cwd(),k??"samples"),E=await br(T),P=await Ps(v,E.map(D=>D.fixture)),C=P.filter(D=>!D.pass).length;return Se({total:P.length,passed:P.length-C,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async v=>{let{baseUrl:k,token:T}=await e(),P=await new B({baseUrl:k,token:T}).deploy({id:v.id,recordType:v.recordType,event:v.event,source:v.source,sourceCode:v.sourceCode,extensionKind:v.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:M.string(),limit:M.number().int().positive().optional()}},async({id:v,limit:k})=>{let{baseUrl:T,token:E}=await e(),P=new B({baseUrl:T,token:E});return Se({id:v,logs:await P.logs(v,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:v,token:k}=await e(),T=new B({baseUrl:v,token:k});return Se(await T.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:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:v,name:k,description:T})=>{let{baseUrl:E,token:P}=await e(),C=new B({baseUrl:E,token:P});return Se(await C.appsCreate({slug:v,name:k,description:T}))}),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:M.string().describe("App slug or id.")}},async({app:v})=>{let{baseUrl:k,token:T}=await e(),E=new B({baseUrl:k,token:T});return Se(await E.appsPull(v))}),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:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:v,files:k,note:T})=>{let{baseUrl:E,token:P}=await e(),C=new B({baseUrl:E,token:P});return Se(await C.appsPush(v,k,{note:T}))});let f=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),_=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(f).describe("At least one field."),rowLevelOwner:M.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:v,token:k}=await e(),T=new B({baseUrl:v,token:k});return Se(await T.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:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:k})=>{let{baseUrl:T,token:E}=await e(),P=new B({baseUrl:T,token:E});return Se(await P.tablesPlan({tables:v,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:M.array(_),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:k})=>{let{baseUrl:T,token:E}=await e(),P=new B({baseUrl:T,token:E});return Se(await P.tablesApply({tables:v,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async v=>{let{baseUrl:k,token:T}=await e(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}})).text();return{contents:[{uri:v.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async v=>{let{baseUrl:k,token:T}=await e(),E=await cn({baseUrl:k,token:T});return{contents:[{uri:v.href,mimeType:"text/plain",text:E}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async v=>{let k=kb(process.cwd(),"samples"),T=[];try{T=(await QE.readdir(k)).filter(P=>P.endsWith(".json"))}catch{T=[]}let E=await br(k);return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({files:T,samples:E.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 v=>{let k=await $b(),T=[];if(k){let{baseUrl:E,token:P}=await e();T=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:E,token:P},n)}return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({recipes:T})}]}}),p}async function n0(t={}){let e=await Rb(t),n=new bi;await e.connect(n)}var Sb,_b,xb,Tb,Eb,e0,t0,Ab=j(()=>{fb();yb();Li();fr();Et();Hi();Ns();vb();Sb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];xb="turbobase-authoring",Tb="0.1.0";Eb=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],e0=[...Eb,...wb],t0=["catalog:///","types://all","samples:///","recipes:///"]});Li();fr();Et();Hi();import{spawn as wd}from"node:child_process";import{promises as se}from"node:fs";import{homedir as r0}from"node:os";import{basename as Cb,dirname as cr,join as Ye,relative as wi,resolve as le,sep as yd}from"node:path";import{Command as s0}from"commander";Bi();import{promises as Wd}from"node:fs";function Vd(t,e){return e===t?"same-type-merge":"different-type-mint"}var Jd=4;function Ki(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Pn(t,"id"),n=Pn(t,"on"),r=Pn(t,"source"),s=Pn(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Pn(o,"source"),a=Pn(o,"recordType"),l=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!r||!s||!i||!a)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:n,fromSource:r,fromRecordType:s,toSource:i,toRecordType:a,cycleBudget:l?Number(l[1]):Jd}}function Pn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function py(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 Yd(t,e,n="fixture"){let r=e.name??n,s=[],o;try{o=Ki(t)}catch(l){return{fixtureName:r,conduit:fy(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=py(e),a=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Es(t),p=!!(await gr(l,i,{member:"when",timeoutMs:200})).whenResult;s.push({name:"from.when",status:p?"passed":"failed",detail:p?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let f=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${f} vs cycleBudget=${o.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!p)return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let _=await gr(l,i,{member:"transform",timeoutMs:200}),v=_.effects.logs,k=_.effects.result;if(!k||typeof k!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let T=k,E=Vd(o.fromRecordType,o.toRecordType),{wouldWriteBindings:P,masterAction:C}=hy(o,E,e);return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,transformResult:T,applyBranch:E,wouldWriteBindings:P,masterAction:C,logs:v}}catch(l){return{fixtureName:r,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function hy(t,e,n){return e==="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:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:n.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function fy(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Jd}}async function Zd(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 Qd(t){let e=await Wd.readFile(t,"utf8");return JSON.parse(e)}function Xd(t){return Wd.readFile(t,"utf8")}function eu(t,e){let n=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${n.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${n.id}]: WHEN-FAILED (conduit short-circuited)`;let r=[];r.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),r.push(`conduit: ${n.id}`),r.push(`route: ${n.fromSource}.${n.fromRecordType} \u2192 ${n.toSource}.${n.toRecordType}${n.on?` on=${n.on}`:""}`),r.push(""),r.push("guards (dispatch order):");for(let s of t.guards){let o=s.status==="passed"?"\u2713":s.status==="failed"?"\u2717":"\u2298";r.push(` ${o} ${s.name} [${s.status}] \u2014 ${s.detail}`)}if(r.push(""),r.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)r.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let s of t.atlasResolutions)r.push(` ${s.key} \u2192 ${s.resolved===null?"null (no Atlas link \u2014 noted)":s.resolved}`);if(!t.whenPassed)return r.push(""),r.push("transform: SKIPPED (from.when gate did not fire)."),r.join(`
1782
1782
  `);if(r.push(""),r.push("transform \u2192 patch:"),r.push(my(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&r.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){r.push(""),r.push("conduit logs:");for(let s of t.logs)r.push(` [${s.level}] ${s.message}${s.meta?` ${JSON.stringify(s.meta)}`:""}`)}r.push(""),r.push(`apply-branch: ${t.applyBranch}`),r.push(` ${t.masterAction}`),r.push(""),r.push("bindings that WOULD be written (txn_source_link):");for(let s of t.wouldWriteBindings)r.push(` ${s.source} role=${s.role} external_id=${s.externalId??"null"} \u2014 ${s.why}`);return r.join(`
1783
1783
  `)}function my(t,e){return t.split(`
1784
1784
  `).map(n=>e+n).join(`
@@ -1788,7 +1788,7 @@ lint: ${r(`${e.warnings.length} warning(s).`)}`),i.join(`
1788
1788
  `)}function cu(t){return t.cases.filter(e=>e.status==="failed").length}function wr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Oy(t){let e=cu(t),n=[];n.push('<?xml version="1.0" encoding="UTF-8"?>'),n.push(`<testsuite name="${wr(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let r of t.cases){let s=` <testcase name="${wr(r.name)}"`;if(r.status==="passed"){n.push(`${s} />`);continue}n.push(`${s}>`);let o=r.detail??"failed",i=r.type?` type="${wr(r.type)}"`:"";n.push(` <failure${i} message="${wr(o)}">${wr(o)}</failure>`),n.push(" </testcase>")}return n.push("</testsuite>"),`${n.join(`
1789
1789
  `)}
1790
1790
  `}function Ny(t){let e={suite:t.name,tests:t.cases.length,failures:cu(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
1791
- `}function Is(t,e){return e==="junit"?Oy(t):Ny(t)}var Ke={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`},An=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Xe={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},du=/\x1b\[[0-9;]*m/g;function Pt(t){return t.replace(du,"").length}function Vi(t,e){return e<=0?1:Math.max(1,Math.ceil(Pt(t)/e))}function Ly(){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 Gi=Ly();function Ee(){return Gi}function Wi(t){Gi=t}function De(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function et(t,e){return Gi?`${t}${e}${Ke.reset}`:e}var m={bold:t=>et(Ke.bold,t),dim:t=>et(Ke.dim,t),red:t=>et(Ke.red,t),green:t=>et(Ke.green,t),yellow:t=>et(Ke.yellow,t),blue:t=>et(Ke.blue,t),magenta:t=>et(Ke.magenta,t),cyan:t=>et(Ke.cyan,t),grey:t=>et(Ke.grey,t)};var ve={success:t=>`${m.green("\u2713")} ${t}`,error:t=>`${m.red("\u2716")} ${t}`,warn:t=>`${m.yellow("\u26A0")} ${t}`,info:t=>`${m.dim("\xB7")} ${t}`,step:t=>`${m.cyan("\u25B8")} ${t}`},zt={add:t=>m.green(`+ ${t}`),change:t=>m.yellow(`~ ${t}`),destroy:t=>m.red(`- ${t}`)},jy=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Uy=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),Dy=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function In(t){let e=t.toLowerCase();return jy.has(e)?m.green(t):Uy.has(e)?m.red(t):Dy.has(e)?m.yellow(t):t}function Mt(t,e=[]){let n=Math.max(Pt(t),...e.map(Pt),0),r=n+2,s=m.cyan(Xe.v),o=a=>` ${a}${" ".repeat(n-Pt(a))} `,i=[m.cyan(`${Xe.tl}${Xe.h.repeat(r)}${Xe.tr}`),`${s}${m.bold(o(t))}${s}`];if(e.length){i.push(`${m.cyan(Xe.ml)}${m.dim(Xe.h.repeat(r))}${m.cyan(Xe.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(m.cyan(`${Xe.bl}${Xe.h.repeat(r)}${Xe.br}`)),i.join(`
1791
+ `}function Is(t,e){return e==="junit"?Oy(t):Ny(t)}var Ke={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`},An=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],Xe={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},du=/\x1b\[[0-9;]*m/g;function Pt(t){return t.replace(du,"").length}function Vi(t,e){return e<=0?1:Math.max(1,Math.ceil(Pt(t)/e))}function Ly(){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 Gi=Ly();function Ee(){return Gi}function Wi(t){Gi=t}function De(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function et(t,e){return Gi?`${t}${e}${Ke.reset}`:e}var m={bold:t=>et(Ke.bold,t),dim:t=>et(Ke.dim,t),red:t=>et(Ke.red,t),green:t=>et(Ke.green,t),yellow:t=>et(Ke.yellow,t),blue:t=>et(Ke.blue,t),magenta:t=>et(Ke.magenta,t),cyan:t=>et(Ke.cyan,t),grey:t=>et(Ke.grey,t)};var ve={success:t=>`${m.green("\u2713")} ${t}`,error:t=>`${m.red("\u2716")} ${t}`,warn:t=>`${m.yellow("\u26A0")} ${t}`,info:t=>`${m.dim("\xB7")} ${t}`,step:t=>`${m.cyan("\u25B8")} ${t}`},qt={add:t=>m.green(`+ ${t}`),change:t=>m.yellow(`~ ${t}`),destroy:t=>m.red(`- ${t}`)},jy=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Uy=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),Dy=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function In(t){let e=t.toLowerCase();return jy.has(e)?m.green(t):Uy.has(e)?m.red(t):Dy.has(e)?m.yellow(t):t}function zt(t,e=[]){let n=Math.max(Pt(t),...e.map(Pt),0),r=n+2,s=m.cyan(Xe.v),o=a=>` ${a}${" ".repeat(n-Pt(a))} `,i=[m.cyan(`${Xe.tl}${Xe.h.repeat(r)}${Xe.tr}`),`${s}${m.bold(o(t))}${s}`];if(e.length){i.push(`${m.cyan(Xe.ml)}${m.dim(Xe.h.repeat(r))}${m.cyan(Xe.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(m.cyan(`${Xe.bl}${Xe.h.repeat(r)}${Xe.br}`)),i.join(`
1792
1792
  `)}function pt(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=>Pt(p[u]??"")));let a=u=>{let p=u.map((f,_)=>{let v=f??"";return _===u.length-1?v:v+" ".repeat(Math.max(0,i[_]-Pt(v)))});return n+p.join(r)},l=[];e.head&&(l.push(a(e.head.map(u=>m.bold(u)))),l.push(a(e.head.map((u,p)=>m.dim("\u2500".repeat(i[p]??Pt(u)))))));for(let u of t)l.push(a(u));return l.join(`
1793
1793
  `)}function Ji(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`${Ee()?e.map(r=>et(Ke.cyan,r)).join(`
1794
1794
  `):e.join(`
@@ -1799,7 +1799,7 @@ ${m.dim(` ${t}`)}`}var tt=t=>{process.stderr.write(t)};
1799
1799
  `),o()},status(l){n=l,o()},done(l){clearInterval(a),i(),tt(_e.showCursor);let u=l.stage!=="failed",p=`${t} ${m.dim("\u25B8")} ${qy(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;tt(`${u?ve.success(p):ve.error(p)}
1800
1800
  `)},stop(){clearInterval(a),i(),tt(_e.showCursor)}}}function qy(t){return t==="completed"?m.green(t):t==="failed"?m.red(t):m.cyan(t)}function qe(t,e,n={}){return new Promise((r,s)=>{let o=e.findIndex(T=>!T.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=T=>{process.stderr.write(T)},l=process.stdin,u=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${m.bold(m.cyan("?"))} ${m.bold(t)}
1801
1801
  `),a(`${m.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
1802
- `),a(_e.hideCursor);let p=0,f=()=>{let T=process.stderr.columns??process.stdout.columns??80;p>0&&(a(_e.cursorUp(p)),a(_e.clearToEnd));let E=0;for(let P=0;P<e.length;P+=1){let C=e[P],D=P===i,se=D?m.cyan("\u25B6"):" ",Y=C.disabled?m.grey(C.label):D?m.bold(m.cyan(C.label)):C.label,je=C.description?` ${m.dim(C.description)}`:"",Fe=` ${se} ${Y}${je}`;a(`\r${Fe}
1802
+ `),a(_e.hideCursor);let p=0,f=()=>{let T=process.stderr.columns??process.stdout.columns??80;p>0&&(a(_e.cursorUp(p)),a(_e.clearToEnd));let E=0;for(let P=0;P<e.length;P+=1){let C=e[P],D=P===i,re=D?m.cyan("\u25B6"):" ",Y=C.disabled?m.grey(C.label):D?m.bold(m.cyan(C.label)):C.label,je=C.description?` ${m.dim(C.description)}`:"",Fe=` ${re} ${Y}${je}`;a(`\r${Fe}
1803
1803
  `),E+=Vi(Fe,T)}p=E},_=()=>{l.removeListener("data",k),l.setRawMode?.(u??!1),l.pause(),a(_e.showCursor)},v=T=>{let E=i;for(let P=0;P<e.length;P+=1)if(E=(E+T+e.length)%e.length,!e[E].disabled){i=E;return}},k=T=>{let E=T.toString("utf8");if(E===""||E==="q"){_(),a(`
1804
1804
  `),s(new Error("aborted"));return}if(E==="\r"||E===`
1805
1805
  `){let C=e[i];if(C.disabled)return;_(),r(C.value);return}if(E==="\x1B[A"||E==="k"){v(-1),f();return}if(E==="\x1B[B"||E==="j"){v(1),f();return}let P=Number(E);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,f())};l.on("data",k),f()})}function Os(t,e){return`${In(t)}${" ".repeat(Math.max(0,e-t.length))}`}var hu=t=>new Promise(e=>setTimeout(e,t));function pu(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}] ${Os(t.state,9)} ${t.conduitId} \u2192 ${e}${r} hop=${t.hop}${s}${n}`}async function fu(t,e,n={}){let r=n.sink??(p=>{process.stdout.write(`${p}
@@ -2418,21 +2418,20 @@ turbobase ext deploy hooks/<file>.ts # lands ACTIVE \u2014 it gates writes imme
2418
2418
  A hook is pure and credentials-free: no secrets, no network, no Node builtins,
2419
2419
  and nothing factored into a shared module.
2420
2420
 
2421
- **Reading data yourself, without a browser.** The PAT in \`.mcp.json\` authenticates
2422
- the authoring MCP, but PostgREST rejects it outright (\`PGRST301 \u2026 Expected 3
2423
- parts; got 1\`) \u2014 it is an opaque bearer, not a JWT. To read rows from a script or
2424
- a terminal, trade it for a short-lived session first:
2421
+ **Reading data yourself.** A PAT reads SCHEMA, never rows. The one in
2422
+ \`.mcp.json\` authenticates the authoring MCP, and PostgREST rejects it outright
2423
+ (\`PGRST301 \u2026 Expected 3 parts; got 1\`) \u2014 it is an opaque bearer, not a JWT.
2424
+ There is no token you can mint that reads data: reading rows is a per-user act,
2425
+ so it carries a real person's identity and their row-level permissions rather
2426
+ than a token owner's.
2425
2427
 
2426
- \`\`\`sh
2427
- curl -sX POST "$INSTANCE/auth/pat-exchange" -H "Authorization: Bearer $PAT"
2428
- # \u2192 { "token": "<15-min session JWT>", ... }
2429
- curl -s "$INSTANCE/rest/v1/<table>?select=..." \\
2430
- -H "Authorization: Bearer $SESSION" -H "apikey: $SESSION"
2431
- \`\`\`
2428
+ Two ways to actually read rows:
2432
2429
 
2433
- The PAT must carry the \`data:read\` scope (Settings \u203A Tokens) \u2014 it is opt-in, so
2434
- a token minted without it gets \`403 insufficient_scope\`. PostgREST wants the JWT
2435
- in BOTH the \`Authorization\` and \`apikey\` positions.
2430
+ - **In the app** \u2014 the browser session does it. \`src/lib/turbobase.ts\` is already
2431
+ wired for this; \`select()\` through it and RLS applies to the signed-in user.
2432
+ - **From your editor or an agent** \u2014 connect the **data MCP**, which signs you in
2433
+ once over OAuth and then exposes \`list_records\` / \`get_record\` / \`search_fields\`
2434
+ as tools. The connect URL is on your instance under Settings \u203A Integrations.
2436
2435
 
2437
2436
  **\`permission denied for table <x>\` usually means NOT SIGNED IN.** With no
2438
2437
  session, PostgREST answers as the anonymous role and every table denies \u2014 it
@@ -2557,7 +2556,7 @@ they are \u2014 the ingest finds entries by heading, not by filename.
2557
2556
  // Pure and credentials-free: no secrets, no network, no Node builtins, one
2558
2557
  // concern per file, nothing factored into a shared module (the sandbox fences
2559
2558
  // every import except the SDK).
2560
- `;function rw(){let t=Ft("hook",{recordType:Cn,event:"before_save",template:"enforce-format",field:dn,regex:tw,id:`app:${Cn}:${dn}-format`,description:`Reject a ${Cn} write whose ${dn} is not an address.`}),e=(n,r,s)=>JSON.stringify({name:s,context:{recordType:Cn,event:"before_save",payload:n},expect:r},null,2)+`
2559
+ `;function rw(){let t=Bt("hook",{recordType:Cn,event:"before_save",template:"enforce-format",field:dn,regex:tw,id:`app:${Cn}:${dn}-format`,description:`Reject a ${Cn} write whose ${dn} is not an address.`}),e=(n,r,s)=>JSON.stringify({name:s,context:{recordType:Cn,event:"before_save",payload:n},expect:r},null,2)+`
2561
2560
  `;return[{path:t.relativePath,content:`${nw}${t.content}`},{path:`samples/${Cn}.${dn}-ok.json`,content:e({company_name:"Acme Supply",[dn]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${Cn}.${dn}-malformed.json`,content:e({company_name:"Acme Supply",[dn]:"ada-at-example"},"reject","a malformed address is rejected")}]}var sw="---\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",ow=`---
2562
2561
  name: ship-app
2563
2562
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
@@ -3213,7 +3212,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3213
3212
  .mcp.json
3214
3213
 
3215
3214
  .DS_Store
3216
- `;function Qi(t={}){let e=Yy.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:bw(n)},{path:"INSTANCE-LEARNINGS.md",content:lw(s)},{path:"TURBOBASE-FEEDBACK.md",content:cw(s)},{path:".claude/settings.json",content:hw},{path:`.claude/output-styles/${uw}.md`,content:pw},{path:".claude/skills/generate-types/SKILL.md",content:Zy(r)},{path:".claude/skills/record-learning/SKILL.md",content:aw(s)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:iw},{path:".claude/hooks/session-start-refresh-types.sh",content:dw(r,s),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:fw,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:mw}];return n?[{path:"CLAUDE.md",content:ew(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:sw},{path:".claude/skills/ship-app/SKILL.md",content:ow},{path:".claude/skills/app-design/SKILL.md",content:gw},...rw(),{path:"conduits/.gitkeep",content:Ls},{path:"turbobase/sync.json",content:ku},{path:"turbobase/schedules.json",content:Su},...vu()]:[{path:"CLAUDE.md",content:Jy},...o,{path:".claude/skills/mock-test/SKILL.md",content:Qy},{path:".claude/skills/deploy/SKILL.md",content:Xy},{path:"hooks/.gitkeep",content:Ls},{path:"conduits/.gitkeep",content:Ls},{path:"samples/.gitkeep",content:Ls},{path:"turbobase/sync.json",content:ku},{path:"turbobase/schedules.json",content:Su}]}import{promises as ea}from"node:fs";import{join as At,resolve as Pu}from"node:path";function Tu(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var vr="bundle.json",js="turbobase";function Ru(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 Xi(a)}function Xi(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(xu)),tables:[...t.sync.tables].sort(e(n=>n.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(xu)),conduits:[...t.guardrails.conduits].sort(e(n=>n.conduitId))},schedules:[...t.schedules].sort(e(n=>n.name))}}function xu(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Eu(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 qs="hooks",zs="conduits",Ht="turbobase/sync.json",Kt="turbobase/schedules.json";function ta(t){let e=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return u?u[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(t),r=/\bdefineHook\s*[<(]/.test(t);if(!n&&!r)return null;let s=e("id"),o=e("recordType");if(n){let l=e("on"),u=e("source");return!s||!o||!l||!u?null:{id:s,recordType:o,event:l,source:u,extensionKind:"conduit"}}let i=e("event"),a=e("source")??"standalone";return!s||!o||!i?null:{id:s,recordType:o,event:i,source:a,extensionKind:"hook"}}async function Us(t){let e;try{e=await ea.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 Us(At(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 Ds(t,e){let n;try{n=await ea.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 yw(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function ww(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function vw(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 Au(t=process.cwd()){let e=Pu(t),[n,r]=await Promise.all([Us(At(e,qs)),Us(At(e,zs))]);if(n.length>0||r.length>0)return!0;let[s,o]=await Promise.all([Ds(At(e,Ht),Ht).catch(()=>{}),Ds(At(e,Kt),Kt).catch(()=>{})]);return s!==void 0||o!==void 0}async function Iu(t=process.cwd(),e={}){let n=Pu(t),r=Tu(e.tenant),s=[],o=[];for(let l of[qs,zs])for(let u of await Us(At(n,l))){let p=`${l}/${u}`,f=await ea.readFile(At(n,l,u),"utf8"),_=ta(f);if(!_){/\bdefine(Hook|Conduit)\s*[<(]/.test(f)&&o.push({file:p,reason:"could not read id / recordType / event"});continue}let v={id:_.id,kind:_.extensionKind,recordType:_.recordType,event:_.event,source:_.source,sourceCode:f};_.extensionKind==="conduit"?r.conduits.push(v):r.hooks.push(v),s.push(p)}let i=await Ds(At(n,Ht),Ht);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Ht} 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(yw(u));for(let u of Array.isArray(l.tables)?l.tables:[])r.sync.tables.push(ww(u));s.push(Ht)}let a=await Ds(At(n,Kt),Kt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Kt} must be a JSON array, or an object with a "schedules" array.`);for(let u of l)r.schedules.push(vw(u));s.push(Kt)}return r.guardrails.fieldRules=[...r.sync.fields],r.guardrails.validationHooks=r.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:Xi(r),contributed:s,unparsed:o}}import{promises as sa}from"node:fs";import{resolve as Tw}from"node:path";var kw="For app developers \u2014 adopt these";function Cu(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 Ou(t,e){let n=Cu(t),r=Cu(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 Sw(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var sA=Sw(kw);fr();Et();var _w=t=>new Promise(e=>setTimeout(e,t));function Nu(t){return t.stage==="completed"||t.stage==="failed"}function $w(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function xw(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(`
3215
+ `;function Qi(t={}){let e=Yy.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:bw(n)},{path:"INSTANCE-LEARNINGS.md",content:lw(s)},{path:"TURBOBASE-FEEDBACK.md",content:cw(s)},{path:".claude/settings.json",content:hw},{path:`.claude/output-styles/${uw}.md`,content:pw},{path:".claude/skills/generate-types/SKILL.md",content:Zy(r)},{path:".claude/skills/record-learning/SKILL.md",content:aw(s)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:iw},{path:".claude/hooks/session-start-refresh-types.sh",content:dw(r,s),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:fw,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:mw}];return n?[{path:"CLAUDE.md",content:ew(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:sw},{path:".claude/skills/ship-app/SKILL.md",content:ow},{path:".claude/skills/app-design/SKILL.md",content:gw},...rw(),{path:"conduits/.gitkeep",content:Ls},{path:"turbobase/sync.json",content:ku},{path:"turbobase/schedules.json",content:Su},...vu()]:[{path:"CLAUDE.md",content:Jy},...o,{path:".claude/skills/mock-test/SKILL.md",content:Qy},{path:".claude/skills/deploy/SKILL.md",content:Xy},{path:"hooks/.gitkeep",content:Ls},{path:"conduits/.gitkeep",content:Ls},{path:"samples/.gitkeep",content:Ls},{path:"turbobase/sync.json",content:ku},{path:"turbobase/schedules.json",content:Su}]}import{promises as ea}from"node:fs";import{join as At,resolve as Pu}from"node:path";function Tu(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var vr="bundle.json",js="turbobase";function Ru(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 Xi(a)}function Xi(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(xu)),tables:[...t.sync.tables].sort(e(n=>n.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(xu)),conduits:[...t.guardrails.conduits].sort(e(n=>n.conduitId))},schedules:[...t.schedules].sort(e(n=>n.name))}}function xu(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Eu(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 qs="hooks",zs="conduits",Ft="turbobase/sync.json",Ht="turbobase/schedules.json";function ta(t){let e=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return u?u[2]:void 0},n=/\bdefineConduit\s*[<(]/.test(t),r=/\bdefineHook\s*[<(]/.test(t);if(!n&&!r)return null;let s=e("id"),o=e("recordType");if(n){let l=e("on"),u=e("source");return!s||!o||!l||!u?null:{id:s,recordType:o,event:l,source:u,extensionKind:"conduit"}}let i=e("event"),a=e("source")??"standalone";return!s||!o||!i?null:{id:s,recordType:o,event:i,source:a,extensionKind:"hook"}}async function Us(t){let e;try{e=await ea.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 Us(At(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 Ds(t,e){let n;try{n=await ea.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 yw(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function ww(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function vw(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 Au(t=process.cwd()){let e=Pu(t),[n,r]=await Promise.all([Us(At(e,qs)),Us(At(e,zs))]);if(n.length>0||r.length>0)return!0;let[s,o]=await Promise.all([Ds(At(e,Ft),Ft).catch(()=>{}),Ds(At(e,Ht),Ht).catch(()=>{})]);return s!==void 0||o!==void 0}async function Iu(t=process.cwd(),e={}){let n=Pu(t),r=Tu(e.tenant),s=[],o=[];for(let l of[qs,zs])for(let u of await Us(At(n,l))){let p=`${l}/${u}`,f=await ea.readFile(At(n,l,u),"utf8"),_=ta(f);if(!_){/\bdefine(Hook|Conduit)\s*[<(]/.test(f)&&o.push({file:p,reason:"could not read id / recordType / event"});continue}let v={id:_.id,kind:_.extensionKind,recordType:_.recordType,event:_.event,source:_.source,sourceCode:f};_.extensionKind==="conduit"?r.conduits.push(v):r.hooks.push(v),s.push(p)}let i=await Ds(At(n,Ft),Ft);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Ft} 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(yw(u));for(let u of Array.isArray(l.tables)?l.tables:[])r.sync.tables.push(ww(u));s.push(Ft)}let a=await Ds(At(n,Ht),Ht);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Ht} must be a JSON array, or an object with a "schedules" array.`);for(let u of l)r.schedules.push(vw(u));s.push(Ht)}return r.guardrails.fieldRules=[...r.sync.fields],r.guardrails.validationHooks=r.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:Xi(r),contributed:s,unparsed:o}}import{promises as sa}from"node:fs";import{resolve as Tw}from"node:path";var kw="For app developers \u2014 adopt these";function Cu(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 Ou(t,e){let n=Cu(t),r=Cu(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 Sw(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var rA=Sw(kw);fr();Et();var _w=t=>new Promise(e=>setTimeout(e,t));function Nu(t){return t.stage==="completed"||t.stage==="failed"}function $w(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function xw(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(`
3217
3216
  `))n(i)}return r}async function na(t,e={}){let n=e.sink??(_=>{process.stdout.write(`${_}
3218
3217
  `)}),r=e.sleep??_w,s=e.intervalMs??2e3,o=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(_=>n($w(_))),a=e.onPoll,l="",u="",p=_=>{a?.(_),_.stage!==u&&i(_),l=xw(_,l,n),u=_.stage},f=await t();if(p(f),Nu(f))return f;for(let _=0;_<o;_+=1)if(await r(s),f=await t(),p(f),Nu(f))return f;return f}var y=t=>{process.stdout.write(`${t}
3219
3218
  `)},L=t=>{process.stderr.write(`${t}
@@ -3232,7 +3231,7 @@ ${s.map(Iw).join(`
3232
3231
  `)}
3233
3232
  `,carried:o}}function Du(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 H(e.baseUrl),s=Tw(process.cwd(),e.out),o=e.since?.trim()||await Ew(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||w(`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((E,P)=>E+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 f=u.currentVersion??u.releases[0]?.version??"",_=`<!-- GENERATED by \`turbobase project adopt\` against ${n} \u2014 adopted-through=${f}. Re-run to refresh; delete this file once every line is done. -->
3234
3233
 
3235
- `,v=await sa.readFile(s,"utf8").catch(()=>null),k=u.markdown,T=0;if(v!==null&&v.trim()!==""){let E=Cw(v,u.markdown);E||w(`${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>\`.`),k=E.markdown,T=E.carried}await sa.writeFile(s,_+k,"utf8"),y(`wrote ${s} \u2014 ${p} item(s) across ${u.releases.length} release(s)${o?` since v${o.replace(/^v/,"")}`:""}${T>0?`, keeping ${T} unticked item(s) already in the file`:""}.`)})}Et();var Sr=["suggested_kb_edit","kb_correction"];var Ow=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function Nw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var bA=new Map(Ow.map(t=>[Nw(t.heading),t]));var yA=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 Lw(t){return t.diff??!!t.dryRun}var jw={update_page:"append to the existing page",new_page:"create a NEW page"},It=(t,e)=>` ${m.dim(t.padEnd(11))}${e}`,zu=t=>t.ownerEmail??t.ownerId;function On(t){return!t.needsPageRef&&!t.blockedBy}var Ms=t=>m.green(t?` + ${t}`:" +"),Uw=t=>m.red(t?` - ${t}`:" -"),un=t=>m.dim(` ${t}`),Dw=` ${m.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,oa=80;function qw(t){let e=[Dw];t.target?(e.push(un(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(Uw(`visibility: ${t.target.visibility}`)),e.push(Ms("visibility: admin"))):e.push(un(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(un("title, slug, evidence: untouched")),e.push(un("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(un("turbobase.document \xB7 new")),e.push(Ms(`title: ${t.pageTitle}`)),e.push(Ms("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(un('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(un('appended under "## From app developers":'));let n=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3234
+ `,v=await sa.readFile(s,"utf8").catch(()=>null),k=u.markdown,T=0;if(v!==null&&v.trim()!==""){let E=Cw(v,u.markdown);E||w(`${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>\`.`),k=E.markdown,T=E.carried}await sa.writeFile(s,_+k,"utf8"),y(`wrote ${s} \u2014 ${p} item(s) across ${u.releases.length} release(s)${o?` since v${o.replace(/^v/,"")}`:""}${T>0?`, keeping ${T} unticked item(s) already in the file`:""}.`)})}Et();var Sr=["suggested_kb_edit","kb_correction"];var Ow=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function Nw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var gA=new Map(Ow.map(t=>[Nw(t.heading),t]));var bA=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 Lw(t){return t.diff??!!t.dryRun}var jw={update_page:"append to the existing page",new_page:"create a NEW page"},It=(t,e)=>` ${m.dim(t.padEnd(11))}${e}`,zu=t=>t.ownerEmail??t.ownerId;function On(t){return!t.needsPageRef&&!t.blockedBy}var Ms=t=>m.green(t?` + ${t}`:" +"),Uw=t=>m.red(t?` - ${t}`:" -"),un=t=>m.dim(` ${t}`),Dw=` ${m.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,oa=80;function qw(t){let e=[Dw];t.target?(e.push(un(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(Uw(`visibility: ${t.target.visibility}`)),e.push(Ms("visibility: admin"))):e.push(un(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(un("title, slug, evidence: untouched")),e.push(un("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(un("turbobase.document \xB7 new")),e.push(Ms(`title: ${t.pageTitle}`)),e.push(Ms("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(un('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(un('appended under "## From app developers":'));let n=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3236
3235
  `);for(let r of n.slice(0,oa))e.push(Ms(r?` ${r}`:""));return n.length>oa&&e.push(m.yellow(` \u2026 ${n.length-oa} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function zw(t,e={}){let n=[];return t.forEach((r,s)=>{let{target:o,entries:i}=r;if(n.push(`${String(s+1).padStart(2)}. ${m.bold(r.pageTitle)}`),n.push(It("page",o?`${o.title} (${o.slug}) [${o.visibility}]`:m.dim("new \u2014 no existing page matches"))),n.push(It("action",On(r)?jw[r.action]:m.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(It("unresolved",m.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(It("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?` ${m.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${m.dim(`(${a.kb_page_ref})`)}`:"";n.push(` ${m.dim("\xB7")} ${a.title.trim()}${u}${l}`)}),n.push(It("confidence",r.withdraws?m.red("WITHDRAWN from readers (text untouched)"):m.dim("untouched"))),r.supersedes&&n.push(It("supersedes",m.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(It("blocked",m.red(`unpublished work on this page belongs to ${zu(r.blockedBy)} \u2014 this page will be SKIPPED`))),r.alsoMatched.length>0&&n.push(It("ambiguous",m.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(f=>f.key===l),p=u>=0?t[u]:void 0;return p?`#${u+1} "${p.pageTitle}"`:l});n.push(It("similar",m.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&&On(r)&&n.push(...qw(r)),n.push("")}),n}function Mw(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(On)} page(s)`,`${e(u=>u.action==="update_page"&&On(u))} appended`,`${e(u=>u.action==="new_page"&&On(u))} created (unpublished)`,...o>0?[m.red(`${o} SKIPPED \u2014 correction with no page to correct`)]:[]],a=r>0?m.red(`${r} page(s) WITHDRAWN from readers`):m.dim("no page withdrawn"),l=s>0?` \xB7 ${m.red(`${s} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function Bw(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(`${m.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${s.blockedBy?zu(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(`${m.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(`${m.yellow("skipped")} ${i} \u2014 ${s.skipped.replace(/_/g," ")}`);continue}let a=s.created?m.green("created "):m.green("appended");r.push(`${a} ${i} \u2014 ${s.appliedEntryIds.length} finding(s) \u2192 page ${m.bold(s.documentId??"?")}`+(s.created?m.dim(" (unpublished)"):"")),s.confidence==="downgraded"?r.push(` ${m.red("withdrawn from readers:")} ${i}`):s.confidence==="already_withdrawn"?r.push(` ${m.dim("page was already unpublished \u2014 left as is")}`):s.confidence==="missing"&&r.push(` ${m.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return r}function qu(t){if(t instanceof X){let e=t.body;t.status===403&&e?.reason==="admin_required"&&w("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&&w("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}V(t,"extensions:deploy","learnings push-kb")}async function _r(t,e){let n;try{n=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(s){return s instanceof X&&s.status===404?L(m.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`.")):L(m.yellow(`could not re-read the pushed markdown: ${Fw(s)} \u2014 planning anyway.`)),null}if(n.filesScanned===0)return L(m.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(m.yellow(`${n.parseSkipped} unparseable`)),L(m.dim(r.join(" \xB7 "))),n}function Fw(t){return t instanceof Error?t.message:String(t)}async function Mu(t,e=n=>new B(n)){t.section&&!Sr.includes(t.section.trim())&&w(`unknown --section "${t.section}" \u2014 expected one of ${Sr.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let n=await H(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 _r(r,t.app),i;try{i=await J("reading the pending queue",()=>r.learningsPending(s))}catch(u){qu(u),w(`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(zw(i.items,{diff:Lw(t)}).join(`
3237
3236
  `)),y(Mw(i.items)),t.dryRun){L(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(On);if(a.length===0){L(m.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(!De()){L(m.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 qe(`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(Bw(u.applied,i.items).join(`
3238
3237
  `))}catch(u){if(u instanceof X&&u.status===409){L(m.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${kr} kb push\` to review the current plan.`),process.exitCode=2;return}qu(u),L(m.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}Et();var Nn=t=>new B(t);async function Ln(t,e){let n=await H(t.baseUrl);return e(n)}async function Bs(t,e,n,r){return r.yes?!0:De()?await qe(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(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function Hw(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function Bu(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function Kw(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(`${Bu(m.bold(o.slug),e)} ${Bu(Hw(o),10)} ${m.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 Fu(t,e=Nn){let n={};t.status&&(t.status!=="draft"&&t.status!=="published"&&w(`--status must be 'draft' or 'published' (got '${t.status}').`),n.status=t.status);let r=await Ln(t,e),s;try{s=await J("reading the knowledge base",()=>r.docsList(n))}catch(o){V(o,"docs:publish","read the knowledge base"),w(`could not read the knowledge base: ${o instanceof Error?o.message:String(o)}`)}y(Kw(s).join(`
@@ -3243,16 +3242,15 @@ ${s.map(Iw).join(`
3243
3242
  `))}async function lp(t,e,n=jn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let s=await Un(e,n);if(!await Ks(`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){V(a,"skills:publish","publish a skill"),w(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(m.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function cp(t,e,n=jn){let r=[...new Set(t.map(a=>a.trim()).filter(Boolean))];r.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let s=await Un(e,n);if(!await Ks(`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){V(a,"skills:publish","unpublish a skill"),w(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(m.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function dp(t,e,n=jn){let r=Number(t);(!Number.isInteger(r)||r<1)&&w(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await Un(e,n);if(await Ks(`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(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function up(t,e=jn){let n=await Un(t,e),r;try{r=await J("reading the releases",()=>n.skillsReleases())}catch(s){V(s,"skills:publish","read the skills releases"),w(`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?m.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";y(`${o} v${s.version_no} ${s.skill_count} skill(s) ${m.dim(s.published_at)}${s.published_by?m.dim(` by ${s.published_by}`):""}${m.dim(i)}`)}}async function pp(t,e,n=jn){let r=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];r.length===0&&w("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await Un(e,n);if(!await Ks(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
3244
3243
  ${r.join(`
3245
3244
  `)}`,"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 X&&p.status===404){a.push(u);continue}i.length>0&&L(m.dim(`deleted before the error: ${i.map(f=>f.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),w(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as hp}from"node:fs";import{join as sv,relative as ov,resolve as iv,sep as av}from"node:path";var lv=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),cv=new Set([".mcp.json",".env"]);function dv(t){return cv.has(t)||t.startsWith(".env.")&&t!==".env.example"}function uv(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function pv(t){return t.includes(0)}async function fp(t){let e=iv(t),n={},r=[],s=[],o=[];async function i(a){let l=await hp.readdir(a,{withFileTypes:!0});for(let u of l){let p=sv(a,u.name);if(u.isDirectory()){if(lv.has(u.name))continue;await i(p);continue}if(!u.isFile())continue;let f=ov(e,p).split(av).join("/");if(dv(u.name)){s.push(f);continue}let _=await hp.readFile(p);if(!uv(_)){r.push(f);continue}pv(_)&&o.push(f),n[f]=_.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as hv}from"node:crypto";var fv="/_tb/app-assets",mv=16,gv=/^[0-9a-f]{32}$/;function mp(){return hv(mv).toString("hex")}function bv(t){return gv.test(t)}function gp(t){if(!bv(t))throw new Error(`not a build id: ${t}`);return`${fv}/${t}/`}var bp=7;import Vs from"node:fs/promises";import $r from"node:path";var la={esbuild:"0.28.1","isolated-vm":"6.1.2"},ca="@turbobase/isolated-vm-prebuilds";function da(t,e){return`${t}-${e}`}function ua(t=process.versions){return`abi${t.modules}`}var yp=["darwin-x64","win32-arm64"];async function wp(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=da(e,n),s=$r.join(t.home,"node_modules"),o=$r.join(s,...ca.split("/"),"prebuilds",r),i=$r.join(s,"isolated-vm","prebuilds",r),a;try{a=await Vs.readdir(o)}catch{return[]}let l=[];await Vs.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=$r.join(i,u);try{await Vs.copyFile($r.join(o,u),p,Vs.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as yv}from"node:os";import{join as vp}from"node:path";import{promises as pa}from"node:fs";function Sp(){let t=process.env.TURBOBASE_HOME??vp(yv(),".turbobase");return{dir:t,file:vp(t,"sandboxes.json")}}var wv={s:1e3,m:6e4,h:36e5,d:864e5};function vv(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*wv[e[2]]}function kv(t,e=Date.now()){return new Date(e+vv(t)).toISOString()}function Sv(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function _v(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 $v(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 xv="[REDACTED]",xr=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},ha=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 Tv(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new ha(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:xv:r[s]=o}return r}function Rv(t,e,n){return e.map(r=>Tv(t,r,n))}var kp=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Ev=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function Pv(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 fa(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 Ev)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=Pv(t);if(!kp.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...kp].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function Av(t,e=Iv){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Iv(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Cv(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Ov(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function ma(){let{file:t}=Sp();try{let e=await pa.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function _p(t){let{dir:e,file:n}=Sp();await pa.mkdir(e,{recursive:!0}),await pa.writeFile(n,`${JSON.stringify(t,null,2)}
3246
- `,{mode:384})}async function Nv(t){let e=await ma();e.push(t),await _p(e)}async function $p(t){let e=await ma(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await _p(e),r??null}async function Gs(){return ma()}function ga(t,e=Date.now()){let n=[],r=[];for(let s of t)Sv(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function xp(t,e){fa(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new xr(n);let r=_v(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Av(u)))(e.fromTenant),i=Cv(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=$v(u.rows,r),f=Rv(u.table,p,u.classification);f.length>0&&await t.copyRows(i,u.table,f)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:kv(e.ttl,s),sampleFraction:r,url:Ov(o,e.baseUrl)};return await Nv(l),l}async function Tp(t,e){fa(t.target());let r=(await Gs()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await $p(e),r):null}async function ba(t,e=Date.now()){fa(t.target());let n=await Gs(),{expired:r}=ga(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await $p(o.name),s.push(o)}return s}var Tr={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","data:read"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},eI=Object.keys(Tr).filter(t=>Tr[t].mintable);var rI=Tr.pat.prefix,Lv=Object.entries(Tr).map(([t,e])=>[e.prefix,t]),jv=/^[A-Za-z0-9_-]{20,}$/;function Uv(t){if(typeof t!="string")return null;for(let[e,n]of Lv)if(t.startsWith(e)&&jv.test(t.slice(e.length)))return n;return null}function Rp(t){return Uv(t)==="pat"}fr();var Dv=8e3,qv={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 zv(t){return qv[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Mv(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(Dv)})}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 Ep(t){return t.state==="accepted"?Ee()?m.green("accepted"):"accepted":t.state==="rejected"?Ee()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ee()?m.yellow("unreachable"):"unreachable"}async function Pp(t={},e=fetch){let n=await Rt(),{file:r}=xs();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${r}.`));return}let s=await ut(),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 Mv(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ee())y(pt(o.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Ep(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${Ep(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${zv(i.check.reason)}.`)),L(m.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(m.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 o0(t,e){try{let n=await fetch(`${t.replace(/\/+$/,"")}/auth/pat-exchange`,{method:"POST",headers:{Authorization:`Bearer ${e}`}});if(!n.ok)return null;let r=await n.json();return typeof r.token=="string"&&r.token.length>0?r.token:null}catch{return null}}async function i0(t){let e=await Rt();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),De()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await qe(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{w("cancelled.")}}async function a0(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 l0(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 c0(t,e,n){let r=await Bd({baseUrl:t,token:e}),s=(await Rt()).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).`:".")),l0(r.baseUrl),!n)return;let o=await a0(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 d0(t){let e=await yr(t),n=ta(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);w(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 dr(t,e,n,r){try{return await re.access(t),"skipped"}catch{}return await re.mkdir(cr(t),{recursive:!0}),await re.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await re.chmod(t,r),"wrote"}async function Ib(t,e){if(Cb(t)!==".gitignore")return dr(t,e.content,e.executable,e.mode);let n=await re.readFile(t,"utf8").catch(()=>null);if(n===null)return dr(t,e.content,e.executable,e.mode);let r=_u(n);return r===null?"skipped":(await re.writeFile(t,r,"utf8"),"merged")}function fd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function yi(t){process.exit(t)}function u0(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 p0(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 h0(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 vd({includeInternal:t=!0}={}){let e=new s0;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.4.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Ji()}
3245
+ `,{mode:384})}async function Nv(t){let e=await ma();e.push(t),await _p(e)}async function $p(t){let e=await ma(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await _p(e),r??null}async function Gs(){return ma()}function ga(t,e=Date.now()){let n=[],r=[];for(let s of t)Sv(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function xp(t,e){fa(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new xr(n);let r=_v(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Av(u)))(e.fromTenant),i=Cv(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=$v(u.rows,r),f=Rv(u.table,p,u.classification);f.length>0&&await t.copyRows(i,u.table,f)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:kv(e.ttl,s),sampleFraction:r,url:Ov(o,e.baseUrl)};return await Nv(l),l}async function Tp(t,e){fa(t.target());let r=(await Gs()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await $p(e),r):null}async function ba(t,e=Date.now()){fa(t.target());let n=await Gs(),{expired:r}=ga(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await $p(o.name),s.push(o)}return s}var Tr={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},XA=Object.keys(Tr).filter(t=>Tr[t].mintable);var nI=Tr.pat.prefix,Lv=Object.entries(Tr).map(([t,e])=>[e.prefix,t]),jv=/^[A-Za-z0-9_-]{20,}$/;function Uv(t){if(typeof t!="string")return null;for(let[e,n]of Lv)if(t.startsWith(e)&&jv.test(t.slice(e.length)))return n;return null}function Rp(t){return Uv(t)==="pat"}fr();var Dv=8e3,qv={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 zv(t){return qv[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Mv(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(Dv)})}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 Ep(t){return t.state==="accepted"?Ee()?m.green("accepted"):"accepted":t.state==="rejected"?Ee()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ee()?m.yellow("unreachable"):"unreachable"}async function Pp(t={},e=fetch){let n=await Rt(),{file:r}=xs();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${r}.`));return}let s=await ut(),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 Mv(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Ee())y(pt(o.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Ep(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${Ep(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${zv(i.check.reason)}.`)),L(m.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(m.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 o0(t){let e=await Rt();e.length===0&&w("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),De()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await qe(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{w("cancelled.")}}async function i0(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 a0(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 l0(t,e,n){let r=await Bd({baseUrl:t,token:e}),s=(await Rt()).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).`:".")),a0(r.baseUrl),!n)return;let o=await i0(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 c0(t){let e=await yr(t),n=ta(e);if(!n){let r=/\bdefineConduit\s*[<(]/.test(e);w(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 dr(t,e,n,r){try{return await se.access(t),"skipped"}catch{}return await se.mkdir(cr(t),{recursive:!0}),await se.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await se.chmod(t,r),"wrote"}async function Ib(t,e){if(Cb(t)!==".gitignore")return dr(t,e.content,e.executable,e.mode);let n=await se.readFile(t,"utf8").catch(()=>null);if(n===null)return dr(t,e.content,e.executable,e.mode);let r=_u(n);return r===null?"skipped":(await se.writeFile(t,r,"utf8"),"merged")}function fd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function yi(t){process.exit(t)}function d0(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 u0(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 p0(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 vd({includeInternal:t=!0}={}){let e=new s0;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.4.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Ji()}
3247
3246
  `),e.hook("preAction",(d,h)=>{Lu(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=Qe(d.baseUrl);d.token||w(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3248
- ${kr} auth login --base-url ${h} --token tb_pat_\u2026`),Rp(d.token)||w("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await c0(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=>Pp({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 i0("Pick the active instance:"),b=await Ts(h);if(!b){let $=await Rt();w(`no stored sign-in for ${Qe(h)}.`+($.length?` Stored: ${$.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Qe(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${b.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 Rt();for(let S of $)await Di(S.baseUrl);y(`removed ${$.length} stored sign-in${$.length===1?"":"s"}.`);return}let h=await Di(d.baseUrl);h||w(d.baseUrl?`no stored sign-in for ${Qe(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let b=await ut();y(`signed out of ${h}.`+(b?` Active instance \u2192 ${b.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:b}=await H(d.baseUrl),$;try{$=await qt({baseUrl:h,token:b,recordsOnly:d.recordsOnly})}catch(g){let x=g instanceof Error?g.message:String(g);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(x)){let R=await o0(h,b);if(R)try{$=await qt({baseUrl:h,token:R,recordsOnly:!1});let A=ie(process.cwd(),d.out);await re.writeFile(A,$,"utf8"),y(`wrote ${A} (${$.split(`
3249
- `).length} lines).`);return}catch{}L("types-gen: /v1/catalog/openapi.json needs a session \u2014 emitting record shapes only. To get the OpenAPI half headlessly, mint a PAT with the `data:read` scope (Settings \u203A Tokens); the CLI then exchanges it for a short-lived session automatically.");try{$=await qt({baseUrl:h,token:b,recordsOnly:!0})}catch(A){w(`types generation failed: ${A instanceof Error?A.message:String(A)}`)}}else w(`types generation failed: ${x}`)}let S=ie(process.cwd(),d.out);await re.writeFile(S,$,"utf8"),y(`wrote ${S} (${$.split(`
3250
- `).length} lines).`)}),Du(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:b}=await H(d.baseUrl),$=new URLSearchParams;d.records&&$.set("records",d.records),d.query&&$.set("query",d.query);let S=$.toString(),g=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});g.ok||w(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let R=((await g.json()).markdown??"").trim(),A=ie(process.cwd(),d.out),I=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${I} \u2014 do not edit; re-run to refresh. -->
3247
+ ${kr} auth login --base-url ${h} --token tb_pat_\u2026`),Rp(d.token)||w("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await l0(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=>Pp({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 o0("Pick the active instance:"),b=await Ts(h);if(!b){let x=await Rt();w(`no stored sign-in for ${Qe(h)}.`+(x.length?` Stored: ${x.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Qe(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${b.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 x=await Rt();for(let S of x)await Di(S.baseUrl);y(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let h=await Di(d.baseUrl);h||w(d.baseUrl?`no stored sign-in for ${Qe(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let b=await ut();y(`signed out of ${h}.`+(b?` Active instance \u2192 ${b.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:b}=await H(d.baseUrl),x;try{x=await cn({baseUrl:h,token:b,recordsOnly:d.recordsOnly})}catch(g){let $=g instanceof Error?g.message:String(g);if(!d.recordsOnly&&/openapi\.json failed \(401/.test($)){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 cn({baseUrl:h,token:b,recordsOnly:!0})}catch(R){w(`types generation failed: ${R instanceof Error?R.message:String(R)}`)}}else w(`types generation failed: ${$}`)}let S=le(process.cwd(),d.out);await se.writeFile(S,x,"utf8"),y(`wrote ${S} (${x.split(`
3248
+ `).length} lines).`)}),Du(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:b}=await H(d.baseUrl),x=new URLSearchParams;d.records&&x.set("records",d.records),d.query&&x.set("query",d.query);let S=x.toString(),g=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});g.ok||w(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${g.status}`);let R=((await g.json()).markdown??"").trim(),A=le(process.cwd(),d.out),I=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${I} \u2014 do not edit; re-run to refresh. -->
3251
3249
 
3252
- `;await re.writeFile(A,O+(R?`${R}
3250
+ `;await se.writeFile(A,O+(R?`${R}
3253
3251
  `:`(no grounding available yet)
3254
- `),"utf8"),y(`wrote ${A}${R?"":" (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 (${Sr.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=>Mu(d)),o.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>Fu(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)=>Hu(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)=>Ku(d,h)),o.command("versions").description("List knowledge-base releases, newest first, marking the current one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Vu(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)=>Gu(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)=>Wu(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("--yes","Skip the confirmation (for scripted runs).").action(d=>Ju(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>ap(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)=>lp(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)=>cp(d,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>up(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)=>dp(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)=>pp(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=Ft("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(S){w(S instanceof Error?S.message:String(S))}let b=ie(process.cwd(),h.relativePath);await dr(b,h.content)==="skipped"&&w(`refusing to overwrite existing file: ${b}`),y(`wrote ${b}`)}),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=Ft("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(S){w(S instanceof Error?S.message:String(S))}let b=ie(process.cwd(),h.relativePath);await dr(b,h.content)==="skipped"&&w(`refusing to overwrite existing file: ${b}`),y(`wrote ${b}`)}),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 b=fd(h.reporter),$=await yr(ie(process.cwd(),d)),S=ie(process.cwd(),h.samples),g=await br(S);g.length===0&&!b&&y(`no samples found under ${S} \u2014 add JSON fixtures to dry-run against.`);let x;try{x=await Ps($,g.map(I=>I.fixture))}catch(I){w(`bundle failed: ${I instanceof Error?I.message:String(I)}`)}if(b){let I=u0(x);y(Is(I,b)),yi(I.cases.some(O=>O.status==="failed")?1:0)}let R=0;for(let I of x){let O=I.pass?m.green("PASS"):m.red("FAIL");I.pass||(R+=1);let W=I.error?` (error: ${I.error})`:I.observed!==I.expected?` (expected ${I.expected}, observed ${I.observed})`:I.rejection?` (rejected: ${I.rejection.code??"rejected"})`:"";y(` ${O} ${I.name}${W}`)}let A=`${x.length-R}/${x.length} sample(s) passed.`;y(`
3255
- ${R===0?m.green(A):m.yellow(A)}`),yi(R>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 md(),{baseUrl:R,token:A}=await H(h.baseUrl),I=new B({baseUrl:R,token:A});try{let O=await J(`applying bundle to ${h.to}`,()=>I.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 W=O.skippedDestroys??[];if(W.length>0){L(`${W.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let N of W)L(` ${N.kind} ${N.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 X&&O.status===403&&w("apply forbidden (403) \u2014 the stored PAT is not for an admin."),w(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}d||w("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:b,token:$}=await H(h.baseUrl),S=await d0(ie(process.cwd(),d)),g=new B({baseUrl:b,token:$});try{let x=await J(`deploying ${Cb(d)}`,()=>g.deploy(S));Ee()?y(Mt("Deployed",[`${m.bold(x.id)} ${In(x.status)} ${m.dim(x.outcome)}`])):y(`deployed ${x.id} \u2192 status=${x.status} (${x.outcome}).`)}catch(x){x instanceof X&&x.status===403&&w("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),w(`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,b)=>{let $=!!(b.preview||b.replace||b.replaceLabel);b.replace&&b.replaceLabel&&w("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let S=ie(process.cwd(),h??".");await re.mkdir(S,{recursive:!0});let g=b.proposal??await T(S),{baseUrl:x,token:R}=await H(b.baseUrl),A=new B({baseUrl:x,token:R}),I=!1;try{I=(await A.appsList()).some(ce=>ce.slug===d||ce.id===d)}catch(ce){V(ce,"extensions:deploy","deploy"),w(`could not reach ${x}: ${ce instanceof Error?ce.message:String(ce)}`)}if(!I){b.create||w(`no app "${d}" on ${x} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let ce=await J(`creating app ${d}`,()=>p(x,R,{slug:d},{tolerateExisting:!0}));ce.existed||y(`created ${ce.slug??d}.`)}let O;if(b.replace)if(typeof b.replace=="string")O=b.replace;else{let{previews:ce}=await se(x,R,d);if(ce.length===0&&w(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ce.length>1){for(let Te of ce)y(` ${Te.previewId} v${Te.version}${Te.label?` ${Te.label}`:""} ${Te.url}`);w(`${d} has ${ce.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ce[0].previewId}\`.`)}O=ce[0].previewId}let W;if(b.replaceLabel){let ce=b.replaceLabel,{previews:Te}=await se(x,R,d),vt=Te.filter(ki=>ki.label===ce);vt.length>0?(O=vt[0].previewId,vt.length>1&&L(`${vt.length} open previews carry the label "${ce}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):y(`no open preview labelled "${ce}" \u2014 opening one.`),W=ce}let N=ce=>re.stat(Ye(S,ce)).then(()=>!0).catch(()=>!1),K=d,he=S,me=b.build!==!1;if(me&&!await N("package.json"))if(await N("index.html"))y("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),me=!1;else if(b.pull===!1)w(`${S} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ce=await J(`pulling ${d}`,()=>f(x,R,d));K=ce.slug??d,await _(S,ce.files,!0),y(`pulled generated source (rev ${ce.rev}).`)}let Rn;if(me){let ce=mp();if(Rn={buildId:ce,assetBase:gp(ce)},b.install!==!1&&!await N("node_modules")){y("installing dependencies\u2026");try{await P(["install"],S)}catch(Te){w(`npm install failed: ${Te instanceof Error?Te.message:String(Te)}`)}}y("building\u2026");try{await P(["run","build"],S,{TURBOBASE_ASSET_BASE:Rn.assetBase})}catch(Te){w(`build failed: ${Te instanceof Error?Te.message:String(Te)}`)}await N("dist")||w(`no dist/ after build in ${S} \u2014 check the app's build script.`),he=Ye(S,"dist")}$&&!Rn&&w(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${K}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let He=await Y(x,R,K,he,b.entry,g,Rn,$?{label:b.label??W,replacePreviewId:O}:void 0);if($){let ce=He.previewUrl??"(no url returned)",Te=He.expiresAt?new Date(He.expiresAt).toLocaleDateString():`${bp} days`,vt=He.replacedVersion==null?null:`replaced v${He.replacedVersion} \u2014 same URL`;if(Ee())y(Mt(vt?"Preview replaced":"Preview deployed",[`${m.bold(K)} ${m.green(`v${He.version??"?"}`)} ${m.dim("not live")}`,`${m.bold(ce)}`,...vt?[m.dim(vt)]:[],m.dim(`expires ${Te}`)]));else{let ki=vt?`; ${vt}`:"";y(`preview ${K} v${He.version??"?"} \u2192 ${ce} (expires ${Te}; /a/${K} unchanged${ki}).`)}y(`next: turbobase apps promote ${K} ${He.previewId??"<preview-id>"} # make it live`),y(` turbobase apps preview discard ${He.previewId??"<preview-id>"}`);return}Ee()?y(Mt("Deployed",[`${m.bold(K)} ${m.green(`v${He.version??"?"}`)} ${m.dim(He.url??`/a/${K}`)}`])):y(`deployed ${K} \u2192 v${He.version??"?"} (${He.url??`/a/${K}`}).`),await je(He,S)}),l.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts + guardrail-blocked writes. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").action(async(d,h)=>{let b=await m0(d??".");b||w(`no public/turbobase.json under ${ie(process.cwd(),d??".")}.`);let $=Array.isArray(b.manifest.tables)?b.manifest.tables:[],S=Array.isArray(b.manifest.writes)?b.manifest.writes:[];if($.length===0&&S.length===0)return y(`${b.manifestPath} declares no tables and no writes \u2014 nothing to plan.`);let{baseUrl:g,token:x}=await H(h.baseUrl),R=new B({baseUrl:g,token:x});if($.length>0){let A;try{A=await J("planning tables",()=>R.tablesPlan({claimedBy:h.as,tables:$}))}catch(I){V(I,"extensions:deploy","plan tables"),xn(I)}y(`claiming as ${m.bold(A.claimedBy)}`);for(let I of A.tables)ln(I,{showClaimants:!0})}if(S.length>0){let A;try{A=await J("checking declared writes",()=>R.appsPlan(S))}catch(I){V(I,"extensions:deploy","plan writes"),w(`plan writes failed: ${I instanceof Error?I.message:String(I)}`)}y("");for(let I of A.verdicts){let O=`${I.source} ${I.recordType}.${I.op}`;I.allowed?I.heldForApproval?y(`${m.dim("HELD")} ${O} \u2014 allowed, but each write waits for operator approval.`):y(`${m.dim("ok")} ${O}`):L(`${m.bold("DENIED")} ${O}${I.rule?` \u2014 guardrail "${I.rule}"`:""} (${I.reason})`)}A.ok||(y(""),w(A.message??"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them."))}y(""),y(m.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,b)=>{let{baseUrl:$,token:S}=await H(b.baseUrl),g=await J(`promoting ${h}`,()=>D($,S,d,"promote",{previewId:h}));Ee()?y(Mt("Promoted",[`${m.bold(d)} ${m.green(`v${g.version??"?"}`)} ${m.dim(g.url??`/a/${d}`)}`])):y(`promoted ${d} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${d}`}.`),await je(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:b,token:$}=await H(h.baseUrl),S=await se(b,$,d);if(h.json)return y(JSON.stringify(S.previews,null,2));if(S.previews.length===0){y(`no open previews for ${d}.`);return}for(let g of S.previews){let x=g.label?` ${g.label}`:"",R=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";y(`v${g.version} ${g.previewId}${x} ${g.url} (expires ${R})`)}}),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,b)=>{let{baseUrl:$,token:S}=await H(b.baseUrl);await J(`discarding ${h}`,()=>D($,S,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:b,token:$}=await H(h.baseUrl),S=await J(`creating ${d}`,()=>p(b,$,{slug:d,name:h.name,description:h.description})),g=S.slug??d;Ee()?y(Mt("Created",[`${m.bold(g)} ${m.dim(S.url??`/a/${g}`)}`])):y(`created ${g} (${S.url??`/a/${g}`}).`),y(`next: turbobase apps push ${g} . # store the source`),y(` turbobase apps deploy ${g} # build + go live`)});async function p(d,h,b,$={}){let S=`${d.replace(/\/+$/,"")}/v1/apps`,g;try{g=await fetch(S,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:b.slug,name:b.name??b.slug,description:b.description})})}catch(x){w(`create request failed: ${x instanceof Error?x.message:String(x)}`)}if(g.status===401&&w("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if($.tolerateExisting)return{slug:b.slug,existed:!0};w(`an app with slug "${b.slug}" already exists.`)}return g.ok||w(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function f(d,h,b){let $=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/pull`,S;try{S=await fetch($,{headers:{Authorization:`Bearer ${h}`}})}catch(g){w(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return S.status===401&&w("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&w("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&w(`no generated source for "${b}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||w(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function _(d,h,b){let $=ie(d),S=0;for(let[g,x]of Object.entries(h)){let R=ie($,g);R!==$&&!R.startsWith($+yd)&&w(`refusing to write outside ${$}: ${g}`),b||await re.stat(R).then(()=>!0).catch(()=>!1)&&w(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(cr(R),{recursive:!0}),await re.writeFile(R,x,"utf8"),S+=1}return S}function v(d){let h=d.indexOf(","),b=d.startsWith("data:")?h>=0?d.slice(h+1):"":d;if(!b)return null;try{let $=Buffer.from(b,"base64");return $.length>0?new Uint8Array($):null}catch{return null}}async function k(d,h,b){let $=ie(d),S=async(x,R)=>{let A=ie($,x);A!==$&&!A.startsWith($+yd)&&w(`refusing to write outside ${$}: ${x}`),b||await re.stat(A).then(()=>!0).catch(()=>!1)&&w(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await re.mkdir(cr(A),{recursive:!0}),await re.writeFile(A,R)},g=`# ${h.title||"App change request"}
3252
+ `),"utf8"),y(`wrote ${A}${R?"":" (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 (${Sr.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=>Mu(d)),o.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>Fu(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)=>Hu(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)=>Ku(d,h)),o.command("versions").description("List knowledge-base releases, newest first, marking the current one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Vu(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)=>Gu(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)=>Wu(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("--yes","Skip the confirmation (for scripted runs).").action(d=>Ju(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>ap(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)=>lp(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)=>cp(d,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>up(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)=>dp(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)=>pp(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=Bt("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(S){w(S instanceof Error?S.message:String(S))}let b=le(process.cwd(),h.relativePath);await dr(b,h.content)==="skipped"&&w(`refusing to overwrite existing file: ${b}`),y(`wrote ${b}`)}),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=Bt("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(S){w(S instanceof Error?S.message:String(S))}let b=le(process.cwd(),h.relativePath);await dr(b,h.content)==="skipped"&&w(`refusing to overwrite existing file: ${b}`),y(`wrote ${b}`)}),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 b=fd(h.reporter),x=await yr(le(process.cwd(),d)),S=le(process.cwd(),h.samples),g=await br(S);g.length===0&&!b&&y(`no samples found under ${S} \u2014 add JSON fixtures to dry-run against.`);let $;try{$=await Ps(x,g.map(I=>I.fixture))}catch(I){w(`bundle failed: ${I instanceof Error?I.message:String(I)}`)}if(b){let I=d0($);y(Is(I,b)),yi(I.cases.some(O=>O.status==="failed")?1:0)}let R=0;for(let I of $){let O=I.pass?m.green("PASS"):m.red("FAIL");I.pass||(R+=1);let W=I.error?` (error: ${I.error})`:I.observed!==I.expected?` (expected ${I.expected}, observed ${I.observed})`:I.rejection?` (rejected: ${I.rejection.code??"rejected"})`:"";y(` ${O} ${I.name}${W}`)}let A=`${$.length-R}/${$.length} sample(s) passed.`;y(`
3253
+ ${R===0?m.green(A):m.yellow(A)}`),yi(R>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 $=await md(),{baseUrl:R,token:A}=await H(h.baseUrl),I=new B({baseUrl:R,token:A});try{let O=await J(`applying bundle to ${h.to}`,()=>I.configApply($,{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 W=O.skippedDestroys??[];if(W.length>0){L(`${W.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let N of W)L(` ${N.kind} ${N.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 X&&O.status===403&&w("apply forbidden (403) \u2014 the stored PAT is not for an admin."),w(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}d||w("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:b,token:x}=await H(h.baseUrl),S=await c0(le(process.cwd(),d)),g=new B({baseUrl:b,token:x});try{let $=await J(`deploying ${Cb(d)}`,()=>g.deploy(S));Ee()?y(zt("Deployed",[`${m.bold($.id)} ${In($.status)} ${m.dim($.outcome)}`])):y(`deployed ${$.id} \u2192 status=${$.status} (${$.outcome}).`)}catch($){$ instanceof X&&$.status===403&&w("deploy forbidden (403) \u2014 the stored PAT is not for an admin."),w(`deploy failed: ${$ instanceof Error?$.message:String($)}`)}});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,b)=>{let x=!!(b.preview||b.replace||b.replaceLabel);b.replace&&b.replaceLabel&&w("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let S=le(process.cwd(),h??".");await se.mkdir(S,{recursive:!0});let g=b.proposal??await T(S),{baseUrl:$,token:R}=await H(b.baseUrl),A=new B({baseUrl:$,token:R}),I=!1;try{I=(await A.appsList()).some(ce=>ce.slug===d||ce.id===d)}catch(ce){V(ce,"extensions:deploy","deploy"),w(`could not reach ${$}: ${ce instanceof Error?ce.message:String(ce)}`)}if(!I){b.create||w(`no app "${d}" on ${$} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let ce=await J(`creating app ${d}`,()=>p($,R,{slug:d},{tolerateExisting:!0}));ce.existed||y(`created ${ce.slug??d}.`)}let O;if(b.replace)if(typeof b.replace=="string")O=b.replace;else{let{previews:ce}=await re($,R,d);if(ce.length===0&&w(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ce.length>1){for(let Te of ce)y(` ${Te.previewId} v${Te.version}${Te.label?` ${Te.label}`:""} ${Te.url}`);w(`${d} has ${ce.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ce[0].previewId}\`.`)}O=ce[0].previewId}let W;if(b.replaceLabel){let ce=b.replaceLabel,{previews:Te}=await re($,R,d),vt=Te.filter(ki=>ki.label===ce);vt.length>0?(O=vt[0].previewId,vt.length>1&&L(`${vt.length} open previews carry the label "${ce}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):y(`no open preview labelled "${ce}" \u2014 opening one.`),W=ce}let N=ce=>se.stat(Ye(S,ce)).then(()=>!0).catch(()=>!1),K=d,he=S,me=b.build!==!1;if(me&&!await N("package.json"))if(await N("index.html"))y("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),me=!1;else if(b.pull===!1)w(`${S} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ce=await J(`pulling ${d}`,()=>f($,R,d));K=ce.slug??d,await _(S,ce.files,!0),y(`pulled generated source (rev ${ce.rev}).`)}let Rn;if(me){let ce=mp();if(Rn={buildId:ce,assetBase:gp(ce)},b.install!==!1&&!await N("node_modules")){y("installing dependencies\u2026");try{await P(["install"],S)}catch(Te){w(`npm install failed: ${Te instanceof Error?Te.message:String(Te)}`)}}y("building\u2026");try{await P(["run","build"],S,{TURBOBASE_ASSET_BASE:Rn.assetBase})}catch(Te){w(`build failed: ${Te instanceof Error?Te.message:String(Te)}`)}await N("dist")||w(`no dist/ after build in ${S} \u2014 check the app's build script.`),he=Ye(S,"dist")}x&&!Rn&&w(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${K}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let He=await Y($,R,K,he,b.entry,g,Rn,x?{label:b.label??W,replacePreviewId:O}:void 0);if(x){let ce=He.previewUrl??"(no url returned)",Te=He.expiresAt?new Date(He.expiresAt).toLocaleDateString():`${bp} days`,vt=He.replacedVersion==null?null:`replaced v${He.replacedVersion} \u2014 same URL`;if(Ee())y(zt(vt?"Preview replaced":"Preview deployed",[`${m.bold(K)} ${m.green(`v${He.version??"?"}`)} ${m.dim("not live")}`,`${m.bold(ce)}`,...vt?[m.dim(vt)]:[],m.dim(`expires ${Te}`)]));else{let ki=vt?`; ${vt}`:"";y(`preview ${K} v${He.version??"?"} \u2192 ${ce} (expires ${Te}; /a/${K} unchanged${ki}).`)}y(`next: turbobase apps promote ${K} ${He.previewId??"<preview-id>"} # make it live`),y(` turbobase apps preview discard ${He.previewId??"<preview-id>"}`);return}Ee()?y(zt("Deployed",[`${m.bold(K)} ${m.green(`v${He.version??"?"}`)} ${m.dim(He.url??`/a/${K}`)}`])):y(`deployed ${K} \u2192 v${He.version??"?"} (${He.url??`/a/${K}`}).`),await je(He,S)}),l.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts + guardrail-blocked writes. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").action(async(d,h)=>{let b=await f0(d??".");b||w(`no public/turbobase.json under ${le(process.cwd(),d??".")}.`);let x=Array.isArray(b.manifest.tables)?b.manifest.tables:[],S=Array.isArray(b.manifest.writes)?b.manifest.writes:[];if(x.length===0&&S.length===0)return y(`${b.manifestPath} declares no tables and no writes \u2014 nothing to plan.`);let{baseUrl:g,token:$}=await H(h.baseUrl),R=new B({baseUrl:g,token:$});if(x.length>0){let A;try{A=await J("planning tables",()=>R.tablesPlan({claimedBy:h.as,tables:x}))}catch(I){V(I,"extensions:deploy","plan tables"),xn(I)}y(`claiming as ${m.bold(A.claimedBy)}`);for(let I of A.tables)an(I,{showClaimants:!0})}if(S.length>0){let A;try{A=await J("checking declared writes",()=>R.appsPlan(S))}catch(I){V(I,"extensions:deploy","plan writes"),w(`plan writes failed: ${I instanceof Error?I.message:String(I)}`)}y("");for(let I of A.verdicts){let O=`${I.source} ${I.recordType}.${I.op}`;I.allowed?I.heldForApproval?y(`${m.dim("HELD")} ${O} \u2014 allowed, but each write waits for operator approval.`):y(`${m.dim("ok")} ${O}`):L(`${m.bold("DENIED")} ${O}${I.rule?` \u2014 guardrail "${I.rule}"`:""} (${I.reason})`)}A.ok||(y(""),w(A.message??"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them."))}y(""),y(m.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,b)=>{let{baseUrl:x,token:S}=await H(b.baseUrl),g=await J(`promoting ${h}`,()=>D(x,S,d,"promote",{previewId:h}));Ee()?y(zt("Promoted",[`${m.bold(d)} ${m.green(`v${g.version??"?"}`)} ${m.dim(g.url??`/a/${d}`)}`])):y(`promoted ${d} \u2192 v${g.version??"?"} is now live at ${g.url??`/a/${d}`}.`),await je(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:b,token:x}=await H(h.baseUrl),S=await re(b,x,d);if(h.json)return y(JSON.stringify(S.previews,null,2));if(S.previews.length===0){y(`no open previews for ${d}.`);return}for(let g of S.previews){let $=g.label?` ${g.label}`:"",R=g.expiresAt?new Date(g.expiresAt).toLocaleDateString():"?";y(`v${g.version} ${g.previewId}${$} ${g.url} (expires ${R})`)}}),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,b)=>{let{baseUrl:x,token:S}=await H(b.baseUrl);await J(`discarding ${h}`,()=>D(x,S,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:b,token:x}=await H(h.baseUrl),S=await J(`creating ${d}`,()=>p(b,x,{slug:d,name:h.name,description:h.description})),g=S.slug??d;Ee()?y(zt("Created",[`${m.bold(g)} ${m.dim(S.url??`/a/${g}`)}`])):y(`created ${g} (${S.url??`/a/${g}`}).`),y(`next: turbobase apps push ${g} . # store the source`),y(` turbobase apps deploy ${g} # build + go live`)});async function p(d,h,b,x={}){let S=`${d.replace(/\/+$/,"")}/v1/apps`,g;try{g=await fetch(S,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:b.slug,name:b.name??b.slug,description:b.description})})}catch($){w(`create request failed: ${$ instanceof Error?$.message:String($)}`)}if(g.status===401&&w("create unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("create forbidden (403) \u2014 the PAT is not for an admin."),g.status===409){if(x.tolerateExisting)return{slug:b.slug,existed:!0};w(`an app with slug "${b.slug}" already exists.`)}return g.ok||w(`create failed: HTTP ${g.status} ${(await g.text().catch(()=>"")).slice(0,200)}`),await g.json().catch(()=>({}))}async function f(d,h,b){let x=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/pull`,S;try{S=await fetch(x,{headers:{Authorization:`Bearer ${h}`}})}catch(g){w(`pull request failed: ${g instanceof Error?g.message:String(g)}`)}return S.status===401&&w("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&w("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&w(`no generated source for "${b}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||w(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function _(d,h,b){let x=le(d),S=0;for(let[g,$]of Object.entries(h)){let R=le(x,g);R!==x&&!R.startsWith(x+yd)&&w(`refusing to write outside ${x}: ${g}`),b||await se.stat(R).then(()=>!0).catch(()=>!1)&&w(`${R} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await se.mkdir(cr(R),{recursive:!0}),await se.writeFile(R,$,"utf8"),S+=1}return S}function v(d){let h=d.indexOf(","),b=d.startsWith("data:")?h>=0?d.slice(h+1):"":d;if(!b)return null;try{let x=Buffer.from(b,"base64");return x.length>0?new Uint8Array(x):null}catch{return null}}async function k(d,h,b){let x=le(d),S=async($,R)=>{let A=le(x,$);A!==x&&!A.startsWith(x+yd)&&w(`refusing to write outside ${x}: ${$}`),b||await se.stat(A).then(()=>!0).catch(()=>!1)&&w(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await se.mkdir(cr(A),{recursive:!0}),await se.writeFile(A,R)},g=`# ${h.title||"App change request"}
3256
3254
 
3257
3255
  > Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
3258
3256
  > \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
@@ -3262,35 +3260,35 @@ ${h.bodyMarkdown||"_No description provided._"}
3262
3260
  ## Screen context
3263
3261
 
3264
3262
  `+(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.
3265
- `);if(await S("PROPOSAL.md",g),h.screenshot){let x=v(h.screenshot);x&&await S("proposal-screenshot.png",x)}await S(Ye(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
3266
- `)}async function T(d){try{let h=await re.readFile(Ye(d,".turbobase","proposal.json"),"utf8"),b=JSON.parse(h);return typeof b.proposalId=="string"&&b.proposalId?b.proposalId:void 0}catch{return}}async function E(d,h,b,$,S,g){let x=new B({baseUrl:d,token:h});try{return await x.appsPush(b,$,{note:S,proposalId:g})}catch(R){if(R instanceof X){let A=R.body;if(R.status===401&&w("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&A?.error==="admin_required"&&w("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&V(R,"extensions:deploy","push app source"),R.status===404&&w(`no app "${b}" on this instance \u2014 create it with \`turbobase apps create ${b}\`.`),R.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&w("push rejected: the request body exceeded the instance limit."),w(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),R.status===400){let I=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";w(`push rejected: ${A?.error??"bad request"}${O}${I}.`)}}w(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function P(d,h,b){return new Promise(($,S)=>{let g=wd("npm",d,{cwd:h,stdio:"inherit",...b?{env:{...process.env,...b}}:{}});g.on("error",S),g.on("exit",x=>x===0?$():S(new Error(`npm ${d.join(" ")} exited ${x??"?"}`)))})}async function C(d,h,b,$){let S=`${d.replace(/\/+$/,"")}${b}`,g;try{g=await fetch(S,{method:$.method,headers:{Authorization:`Bearer ${h}`,...$.body?{"content-type":"application/json"}:{}},...$.body?{body:JSON.stringify($.body)}:{}})}catch(x){w(`request failed: ${x instanceof Error?x.message:String(x)}`)}if(g.status===401&&w("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let x=await g.text().catch(()=>""),R=x.slice(0,300);try{let A=JSON.parse(x);R=A.message??A.error??R}catch{}w(`failed: HTTP ${g.status} ${R}`)}return await g.json().catch(()=>({}))}async function D(d,h,b,$,S){return await C(d,h,`/v1/apps/${encodeURIComponent(b)}/preview/${$}`,{method:"POST",body:S})}async function se(d,h,b){return{previews:(await C(d,h,`/v1/apps/${encodeURIComponent(b)}/previews`,{method:"GET"})).previews??[]}}async function Y(d,h,b,$,S,g,x,R){let A;try{A=await J(`zipping ${$}`,()=>ou($))}catch(N){w(`could not zip ${$}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&w(`${$} is empty \u2014 the build produced nothing.`);let I={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};S&&(I["x-app-entry"]=S),g&&(I["x-proposal-id"]=g),x&&(I["x-app-build-id"]=x.buildId,I["x-app-asset-base"]=x.assetBase),R&&(I["x-app-channel"]="preview",R.label&&(I["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(I["x-app-preview-replace"]=R.replacePreviewId));let O=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/deploy`,W;try{W=await J(`deploying ${b} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(O,{method:"POST",headers:I,body:new Uint8Array(A.buffer)}))}catch(N){w(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(W.status===401&&w("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),W.status===403&&w("deploy forbidden (403) \u2014 the PAT is not for an admin."),W.status===404){let N=await W.text().catch(()=>""),K={};try{K=JSON.parse(N)}catch{}K.error==="no_preview"&&w(`${K.message??`no open preview to replace on ${b}`} \u2014 list them with \`turbobase apps preview list ${b}\`.`),w(`no app "${b}" on ${d} \u2014 create it with \`turbobase apps create ${b}\`.`)}if(!W.ok){let N=await W.text().catch(()=>""),K=N.slice(0,300);try{let he=JSON.parse(N);K=he.message??he.error??K}catch{}w(`deploy failed: HTTP ${W.status} ${K}`)}return await W.json().catch(()=>({}))}async function je(d,h){let b=yu(d,{localDocsModifiedAt:await Fe(h)});b&&y(b.level==="warn"?m.yellow(b.message):m.dim(b.message))}async function Fe(d){if(!d)return null;let h=null;for(let b of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let $=await re.stat(Ye(d,b));(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,b)=>{let{baseUrl:$,token:S}=await H(b.baseUrl);if(b.proposal){let A=new B({baseUrl:$,token:S}),I;try{I=await J(`fetching proposal ${b.proposal}`,()=>A.appPullContext(b.proposal))}catch(he){V(he,"extensions:deploy","pull proposal"),he instanceof X&&he.status===404&&w(`no widget proposal "${b.proposal}" on ${$}.`),w(`could not fetch proposal ${b.proposal}: ${he instanceof Error?he.message:String(he)}`)}let O=await J(`pulling ${I.appSlug}`,()=>f($,S,I.appSlug)),W=h??d,N=ie(process.cwd(),W??I.appSlug);await re.mkdir(N,{recursive:!0});let K=await _(N,O.files,!!b.force);await k(N,I,!!b.force),y(`pulled ${K} file${K===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${I.proposalId}.`),y(`next: cd ${wi(process.cwd(),N)||"."} && turbobase apps deploy ${I.appSlug}`);return}d||w("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await J(`pulling ${d}`,()=>f($,S,d)),x=ie(process.cwd(),h??g.slug??d);await re.mkdir(x,{recursive:!0});let R=await _(x,g.files,!!b.force);y(`pulled ${R} file${R===1?"":"s"} \u2192 ${x} (rev ${g.rev}).`),y(`next: cd ${wi(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,b)=>{let $=ie(process.cwd(),h??d),S=await ut(b.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:x}=await Promise.resolve().then(()=>(Qp(),Zp)),R=b.title??d,A=g({slug:d,title:R,appTsx:x(R),instanceOrigin:S?.baseUrl});await re.mkdir($,{recursive:!0});let I=await _($,A,!!b.force);if(y(`scaffolded ${I} file${I===1?"":"s"} \u2192 ${$}`),b.claude!==!1){let W=Qi({baseUrl:S?.baseUrl,token:S?.token,appSlug:d}),N=0;for(let K of W){let he=await Ib(Ye($,K.path),K);(he==="wrote"||he==="merged")&&(N+=1)}y(`wired Claude Code: ${N} file${N===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||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=wi(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:b}=await H(d.baseUrl),$=new B({baseUrl:h,token:b}),S;try{S=await $.appsList()}catch(g){V(g,"extensions:deploy","list apps"),w(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(S,null,2));if(S.length===0)return y("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");y(pt(S.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,b)=>{let $=ie(process.cwd(),h??".");await re.stat($).then(me=>me.isDirectory()).catch(()=>!1)||w(`${$} is not a directory.`);let{baseUrl:g,token:x}=await H(b.baseUrl),R=b.proposal??await T($),{files:A,skipped:I,secrets:O,unstorable:W}=await fp($),N=Object.keys(A).length;if(N===0&&w(`no source files found under ${$} (build output and node_modules are skipped).`),W.length>0){for(let me of W)L(`${me} contains a NUL byte (U+0000), which cannot be stored.`);w(`push aborted: ${W.length} ${W.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let me of I)L(m.dim(`skipped binary file ${me}`));for(let me of O)L(m.dim(`skipped ${me} (holds credentials \u2014 never pushed)`));let K=await J(`pushing ${N} file${N===1?"":"s"}`,()=>E(g,x,d,A,b.note,R));y(`pushed ${K.files} file${K.files===1?"":"s"} \u2192 ${K.slug} rev ${K.rev} (source only, nothing deployed).`);let he=await _r(new B({baseUrl:g,token:x}),K.slug);he&&he.entriesAdded>0&&y(`${he.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),y(`next: turbobase apps deploy ${K.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 md(),{baseUrl:b,token:$}=await H(d.baseUrl),S=new B({baseUrl:b,token:$}),g;try{g=await J(`planning against ${d.to??b}`,()=>S.configPlan(h))}catch(x){w(`plan failed: ${x instanceof Error?x.message:String(x)}`)}b0(g,d.to??b)}),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 md(),{baseUrl:b,token:$}=await H(d.baseUrl),S=h.tenant??y0(b),g=Eu(d.confirm,S);g.ok||w(`promote refused (fail-closed): ${g.reason}`);let x=new B({baseUrl:b,token:$});try{let R=await J(`promoting ${d.from} \u2192 ${d.to} (${S})`,()=>x.configApply(h,{prune:d.prune}));if(Ee()){let I=[`${m.bold(`${d.from} \u2192 ${d.to}`)} ${m.dim(S??"")}`,`${zt.add(String(R.applied.add))} ${zt.change(String(R.applied.change))} ${zt.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&I.push(m.dim(`${R.backfillsQueued.length} backfill(s) queued`)),y(Mt("Promoted",I))}else y(`promoted ${d.from} \u2192 ${d.to} (${S}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let A=R.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(R){R instanceof X&&R.status===403&&w("promote forbidden (403) \u2014 the stored PAT is not for an admin."),w(`promote failed: ${R instanceof Error?R.message:String(R)}`)}}),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 b=fd(h.reporter),$=ie(process.cwd(),d),S=await yr($),g=au(S);b?y(Is(p0(d,g),b)):y(lu(d,g,{warn:m.yellow,ok:m.green,dim:m.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 b=fd(h.reporter),$=await Xd(ie(process.cwd(),d));if(h.against){h.against!=="sandbox"&&w(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Zd(Ki($))}catch(x){w(x instanceof Error?x.message:String(x))}return}h.fixture||w("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await Qd(ie(process.cwd(),h.fixture))}catch(x){w(`could not read fixture ${h.fixture}: ${x instanceof Error?x.message:String(x)}`)}let g=await Yd($,S,h.fixture);if(b){let x=h0(g);y(Is(x,b)),yi(x.cases.some(R=>R.status==="failed")?1:0)}y(eu(g,!!h.trace)),yi(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:b}=await H(d.baseUrl),$=new B({baseUrl:h,token:b});try{await mu($,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:y})}catch(S){S instanceof X&&S.status===403&&w("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof X&&S.status===409&&w("binding is not retryable (only divergent/blocked bindings can be retried)."),w(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}});let jt=s.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");jt.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 np(d)}),jt.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 rp(d??[],h)}),jt.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 sp(d,h)}),jt.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 op(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 b=d.lastIndexOf("@"),$=b>0?d.slice(0,b):d,S=b>0?d.slice(b+1):void 0,g=qi();g||w(`marketplace not configured \u2014 set ${En} and ${Rs}.
3267
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=zi(g.registryUrl);x&&w(x);let{baseUrl:R,token:A}=await H(h.baseUrl),I=new mr(g),O;try{O=await J(`fetching ${d}`,()=>I.fetchBundle($,S))}catch(me){w(`marketplace fetch failed for ${d}: ${me instanceof Error?me.message:String(me)}`)}let W=vs(O.manifest),N=null;if(W.length>0){if(!h.connection){let me=W.map(Rn=>Rn.source_system).join(", ");w(`${O.name}@${O.version} declares a connection input (source: ${me}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=h.connection}let K=f0(O.bundle,O.name,O.kind),he=new B({baseUrl:R,token:A});try{let me=await J(`installing ${O.name}@${O.version}`,()=>he.deploy({...K,provenance:"marketplace",...N?{connectionId:N}:{}}));y(`installed ${O.name}@${O.version} \u2192 ${me.id} (status=${me.status}, ${me.outcome})`+(N?` bound to connection ${N}.`:"."))}catch(me){me instanceof X&&me.status===403&&w("install forbidden (403) \u2014 the stored PAT is not for an admin."),w(`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 b=qi();b||w(`marketplace not configured \u2014 set ${En} and ${Rs}.
3268
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let $=zi(b.registryUrl);$&&w($);let S=ie(process.cwd(),d),g=await yr(S),x=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",R={};if(h.manifest){let O=ie(process.cwd(),h.manifest),W;try{W=await re.readFile(O,"utf8")}catch{w(`manifest not found at ${h.manifest}.`)}let N;try{N=JSON.parse(W)}catch{w(`manifest is not valid JSON: ${h.manifest}.`)}(typeof N!="object"||N===null||Array.isArray(N))&&w("manifest must be a JSON object."),R=N}try{$i(R,g)}catch(O){O instanceof Dt&&w(O.message),w(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new mr(b);try{await J(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:x,bundle:g,manifest:R}))}catch(O){O instanceof X&&O.status===403&&w("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof X&&O.status===409&&w(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),w(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let I=vs(R);y(`published ${h.name}@${h.pkgVersion} (kind=${x}) to the marketplace.`),I.length>0&&y(` declares ${I.length} connection input(s): ${I.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 ut(d.baseUrl).catch(()=>null),b=Qi({baseUrl:h?.baseUrl,token:h?.token}),$=0,S=0,g=0;for(let x of b){let R=ie(process.cwd(),x.path),A=await Ib(R,x);A==="wrote"?($+=1,y(` wrote ${x.path}`)):A==="merged"?(g+=1,y(` merged ${x.path} (added the .mcp.json rule)`)):(S+=1,y(` skipped ${x.path} (exists)`))}y(`
3269
- project init: ${$} written, ${g} merged, ${S} skipped.`)}),r.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Zi} (non-destructive).`).action(async()=>{let d=wu(),h=0,b=0;for(let $ of d){let S=ie(process.cwd(),$.path);await dr(S,$.content,$.executable)==="wrote"?(h+=1,y(` wrote ${$.path}`)):(b+=1,y(` skipped ${$.path} (exists)`))}y(`
3263
+ `);if(await S("PROPOSAL.md",g),h.screenshot){let $=v(h.screenshot);$&&await S("proposal-screenshot.png",$)}await S(Ye(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
3264
+ `)}async function T(d){try{let h=await se.readFile(Ye(d,".turbobase","proposal.json"),"utf8"),b=JSON.parse(h);return typeof b.proposalId=="string"&&b.proposalId?b.proposalId:void 0}catch{return}}async function E(d,h,b,x,S,g){let $=new B({baseUrl:d,token:h});try{return await $.appsPush(b,x,{note:S,proposalId:g})}catch(R){if(R instanceof X){let A=R.body;if(R.status===401&&w("push unauthorized (401) \u2014 re-run `turbobase auth login`."),R.status===403&&A?.error==="admin_required"&&w("push forbidden (403) \u2014 the PAT is not for an admin."),R.status===403&&V(R,"extensions:deploy","push app source"),R.status===404&&w(`no app "${b}" on this instance \u2014 create it with \`turbobase apps create ${b}\`.`),R.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&w("push rejected: the request body exceeded the instance limit."),w(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),R.status===400){let I=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";w(`push rejected: ${A?.error??"bad request"}${O}${I}.`)}}w(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function P(d,h,b){return new Promise((x,S)=>{let g=wd("npm",d,{cwd:h,stdio:"inherit",...b?{env:{...process.env,...b}}:{}});g.on("error",S),g.on("exit",$=>$===0?x():S(new Error(`npm ${d.join(" ")} exited ${$??"?"}`)))})}async function C(d,h,b,x){let S=`${d.replace(/\/+$/,"")}${b}`,g;try{g=await fetch(S,{method:x.method,headers:{Authorization:`Bearer ${h}`,...x.body?{"content-type":"application/json"}:{}},...x.body?{body:JSON.stringify(x.body)}:{}})}catch($){w(`request failed: ${$ instanceof Error?$.message:String($)}`)}if(g.status===401&&w("unauthorized (401) \u2014 re-run `turbobase auth login`."),g.status===403&&w("forbidden (403) \u2014 the PAT is not for an admin."),!g.ok){let $=await g.text().catch(()=>""),R=$.slice(0,300);try{let A=JSON.parse($);R=A.message??A.error??R}catch{}w(`failed: HTTP ${g.status} ${R}`)}return await g.json().catch(()=>({}))}async function D(d,h,b,x,S){return await C(d,h,`/v1/apps/${encodeURIComponent(b)}/preview/${x}`,{method:"POST",body:S})}async function re(d,h,b){return{previews:(await C(d,h,`/v1/apps/${encodeURIComponent(b)}/previews`,{method:"GET"})).previews??[]}}async function Y(d,h,b,x,S,g,$,R){let A;try{A=await J(`zipping ${x}`,()=>ou(x))}catch(N){w(`could not zip ${x}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&w(`${x} is empty \u2014 the build produced nothing.`);let I={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};S&&(I["x-app-entry"]=S),g&&(I["x-proposal-id"]=g),$&&(I["x-app-build-id"]=$.buildId,I["x-app-asset-base"]=$.assetBase),R&&(I["x-app-channel"]="preview",R.label&&(I["x-app-preview-label"]=encodeURIComponent(R.label)),R.replacePreviewId&&(I["x-app-preview-replace"]=R.replacePreviewId));let O=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/deploy`,W;try{W=await J(`deploying ${b} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(O,{method:"POST",headers:I,body:new Uint8Array(A.buffer)}))}catch(N){w(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(W.status===401&&w("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),W.status===403&&w("deploy forbidden (403) \u2014 the PAT is not for an admin."),W.status===404){let N=await W.text().catch(()=>""),K={};try{K=JSON.parse(N)}catch{}K.error==="no_preview"&&w(`${K.message??`no open preview to replace on ${b}`} \u2014 list them with \`turbobase apps preview list ${b}\`.`),w(`no app "${b}" on ${d} \u2014 create it with \`turbobase apps create ${b}\`.`)}if(!W.ok){let N=await W.text().catch(()=>""),K=N.slice(0,300);try{let he=JSON.parse(N);K=he.message??he.error??K}catch{}w(`deploy failed: HTTP ${W.status} ${K}`)}return await W.json().catch(()=>({}))}async function je(d,h){let b=yu(d,{localDocsModifiedAt:await Fe(h)});b&&y(b.level==="warn"?m.yellow(b.message):m.dim(b.message))}async function Fe(d){if(!d)return null;let h=null;for(let b of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let x=await se.stat(Ye(d,b));(h===null||x.mtimeMs>h)&&(h=x.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,b)=>{let{baseUrl:x,token:S}=await H(b.baseUrl);if(b.proposal){let A=new B({baseUrl:x,token:S}),I;try{I=await J(`fetching proposal ${b.proposal}`,()=>A.appPullContext(b.proposal))}catch(he){V(he,"extensions:deploy","pull proposal"),he instanceof X&&he.status===404&&w(`no widget proposal "${b.proposal}" on ${x}.`),w(`could not fetch proposal ${b.proposal}: ${he instanceof Error?he.message:String(he)}`)}let O=await J(`pulling ${I.appSlug}`,()=>f(x,S,I.appSlug)),W=h??d,N=le(process.cwd(),W??I.appSlug);await se.mkdir(N,{recursive:!0});let K=await _(N,O.files,!!b.force);await k(N,I,!!b.force),y(`pulled ${K} file${K===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${I.proposalId}.`),y(`next: cd ${wi(process.cwd(),N)||"."} && turbobase apps deploy ${I.appSlug}`);return}d||w("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let g=await J(`pulling ${d}`,()=>f(x,S,d)),$=le(process.cwd(),h??g.slug??d);await se.mkdir($,{recursive:!0});let R=await _($,g.files,!!b.force);y(`pulled ${R} file${R===1?"":"s"} \u2192 ${$} (rev ${g.rev}).`),y(`next: cd ${wi(process.cwd(),$)||"."} && 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,b)=>{let x=le(process.cwd(),h??d),S=await ut(b.baseUrl).catch(()=>null),{scaffoldAppFiles:g,starterApp:$}=await Promise.resolve().then(()=>(Qp(),Zp)),R=b.title??d,A=g({slug:d,title:R,appTsx:$(R),instanceOrigin:S?.baseUrl});await se.mkdir(x,{recursive:!0});let I=await _(x,A,!!b.force);if(y(`scaffolded ${I} file${I===1?"":"s"} \u2192 ${x}`),b.claude!==!1){let W=Qi({baseUrl:S?.baseUrl,token:S?.token,appSlug:d}),N=0;for(let K of W){let he=await Ib(Ye(x,K.path),K);(he==="wrote"||he==="merged")&&(N+=1)}y(`wired Claude Code: ${N} file${N===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||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=wi(process.cwd(),x)||".";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:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),S;try{S=await x.appsList()}catch(g){V(g,"extensions:deploy","list apps"),w(`list apps failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(S,null,2));if(S.length===0)return y("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");y(pt(S.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,b)=>{let x=le(process.cwd(),h??".");await se.stat(x).then(me=>me.isDirectory()).catch(()=>!1)||w(`${x} is not a directory.`);let{baseUrl:g,token:$}=await H(b.baseUrl),R=b.proposal??await T(x),{files:A,skipped:I,secrets:O,unstorable:W}=await fp(x),N=Object.keys(A).length;if(N===0&&w(`no source files found under ${x} (build output and node_modules are skipped).`),W.length>0){for(let me of W)L(`${me} contains a NUL byte (U+0000), which cannot be stored.`);w(`push aborted: ${W.length} ${W.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let me of I)L(m.dim(`skipped binary file ${me}`));for(let me of O)L(m.dim(`skipped ${me} (holds credentials \u2014 never pushed)`));let K=await J(`pushing ${N} file${N===1?"":"s"}`,()=>E(g,$,d,A,b.note,R));y(`pushed ${K.files} file${K.files===1?"":"s"} \u2192 ${K.slug} rev ${K.rev} (source only, nothing deployed).`);let he=await _r(new B({baseUrl:g,token:$}),K.slug);he&&he.entriesAdded>0&&y(`${he.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),y(`next: turbobase apps deploy ${K.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 md(),{baseUrl:b,token:x}=await H(d.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await J(`planning against ${d.to??b}`,()=>S.configPlan(h))}catch($){w(`plan failed: ${$ instanceof Error?$.message:String($)}`)}g0(g,d.to??b)}),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 md(),{baseUrl:b,token:x}=await H(d.baseUrl),S=h.tenant??b0(b),g=Eu(d.confirm,S);g.ok||w(`promote refused (fail-closed): ${g.reason}`);let $=new B({baseUrl:b,token:x});try{let R=await J(`promoting ${d.from} \u2192 ${d.to} (${S})`,()=>$.configApply(h,{prune:d.prune}));if(Ee()){let I=[`${m.bold(`${d.from} \u2192 ${d.to}`)} ${m.dim(S??"")}`,`${qt.add(String(R.applied.add))} ${qt.change(String(R.applied.change))} ${qt.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&I.push(m.dim(`${R.backfillsQueued.length} backfill(s) queued`)),y(zt("Promoted",I))}else y(`promoted ${d.from} \u2192 ${d.to} (${S}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let A=R.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(R){R instanceof X&&R.status===403&&w("promote forbidden (403) \u2014 the stored PAT is not for an admin."),w(`promote failed: ${R instanceof Error?R.message:String(R)}`)}}),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 b=fd(h.reporter),x=le(process.cwd(),d),S=await yr(x),g=au(S);b?y(Is(u0(d,g),b)):y(lu(d,g,{warn:m.yellow,ok:m.green,dim:m.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 b=fd(h.reporter),x=await Xd(le(process.cwd(),d));if(h.against){h.against!=="sandbox"&&w(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Zd(Ki(x))}catch($){w($ instanceof Error?$.message:String($))}return}h.fixture||w("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await Qd(le(process.cwd(),h.fixture))}catch($){w(`could not read fixture ${h.fixture}: ${$ instanceof Error?$.message:String($)}`)}let g=await Yd(x,S,h.fixture);if(b){let $=p0(g);y(Is($,b)),yi($.cases.some(R=>R.status==="failed")?1:0)}y(eu(g,!!h.trace)),yi(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:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b});try{await mu(x,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:y})}catch(S){S instanceof X&&S.status===403&&w("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof X&&S.status===409&&w("binding is not retryable (only divergent/blocked bindings can be retried)."),w(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}});let jt=s.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");jt.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 np(d)}),jt.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 rp(d??[],h)}),jt.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 sp(d,h)}),jt.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 op(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 b=d.lastIndexOf("@"),x=b>0?d.slice(0,b):d,S=b>0?d.slice(b+1):void 0,g=qi();g||w(`marketplace not configured \u2014 set ${En} and ${Rs}.
3265
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let $=zi(g.registryUrl);$&&w($);let{baseUrl:R,token:A}=await H(h.baseUrl),I=new mr(g),O;try{O=await J(`fetching ${d}`,()=>I.fetchBundle(x,S))}catch(me){w(`marketplace fetch failed for ${d}: ${me instanceof Error?me.message:String(me)}`)}let W=vs(O.manifest),N=null;if(W.length>0){if(!h.connection){let me=W.map(Rn=>Rn.source_system).join(", ");w(`${O.name}@${O.version} declares a connection input (source: ${me}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=h.connection}let K=h0(O.bundle,O.name,O.kind),he=new B({baseUrl:R,token:A});try{let me=await J(`installing ${O.name}@${O.version}`,()=>he.deploy({...K,provenance:"marketplace",...N?{connectionId:N}:{}}));y(`installed ${O.name}@${O.version} \u2192 ${me.id} (status=${me.status}, ${me.outcome})`+(N?` bound to connection ${N}.`:"."))}catch(me){me instanceof X&&me.status===403&&w("install forbidden (403) \u2014 the stored PAT is not for an admin."),w(`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 b=qi();b||w(`marketplace not configured \u2014 set ${En} and ${Rs}.
3266
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=zi(b.registryUrl);x&&w(x);let S=le(process.cwd(),d),g=await yr(S),$=/\bdefineConduit\s*[<(]/.test(g)?"conduit":"hook",R={};if(h.manifest){let O=le(process.cwd(),h.manifest),W;try{W=await se.readFile(O,"utf8")}catch{w(`manifest not found at ${h.manifest}.`)}let N;try{N=JSON.parse(W)}catch{w(`manifest is not valid JSON: ${h.manifest}.`)}(typeof N!="object"||N===null||Array.isArray(N))&&w("manifest must be a JSON object."),R=N}try{$i(R,g)}catch(O){O instanceof Dt&&w(O.message),w(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new mr(b);try{await J(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:$,bundle:g,manifest:R}))}catch(O){O instanceof X&&O.status===403&&w("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof X&&O.status===409&&w(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),w(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let I=vs(R);y(`published ${h.name}@${h.pkgVersion} (kind=${$}) to the marketplace.`),I.length>0&&y(` declares ${I.length} connection input(s): ${I.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 ut(d.baseUrl).catch(()=>null),b=Qi({baseUrl:h?.baseUrl,token:h?.token}),x=0,S=0,g=0;for(let $ of b){let R=le(process.cwd(),$.path),A=await Ib(R,$);A==="wrote"?(x+=1,y(` wrote ${$.path}`)):A==="merged"?(g+=1,y(` merged ${$.path} (added the .mcp.json rule)`)):(S+=1,y(` skipped ${$.path} (exists)`))}y(`
3267
+ project init: ${x} written, ${g} merged, ${S} skipped.`)}),r.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Zi} (non-destructive).`).action(async()=>{let d=wu(),h=0,b=0;for(let x of d){let S=le(process.cwd(),x.path);await dr(S,x.content,x.executable)==="wrote"?(h+=1,y(` wrote ${x.path}`)):(b+=1,y(` skipped ${x.path} (exists)`))}y(`
3270
3268
  project ci: ${h} written, ${b} skipped.`),h>0&&(y(`
3271
- 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:b}=await H(d.baseUrl),$=new B({baseUrl:h,token:b}),S;try{S=await $.catalogRecords()}catch(I){I instanceof X&&(I.status===401||I.status===403)&&w("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),w(`catalog fetch failed: ${I instanceof Error?I.message:String(I)}`)}if(S.length===0){y("no records in the instance catalog \u2014 nothing to generate.");return}let g=ie(process.cwd(),d.out),x=nu(S,{event:d.event}),R=0,A=0;for(let{recordType:I,fixture:O}of x){let W=Ye(g,`${I}.json`),N=`${JSON.stringify(O,null,2)}
3272
- `;d.force?(await re.mkdir(cr(W),{recursive:!0}),await re.writeFile(W,N,{mode:420}),R+=1,y(` wrote ${d.out}/${I}.json`)):await dr(W,N)==="wrote"?(R+=1,y(` wrote ${d.out}/${I}.json`)):(A+=1,y(` skipped ${d.out}/${I}.json (exists \u2014 use --force to overwrite)`))}y(`
3273
- samples init: ${R} written, ${A} skipped.`)});let dt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),an=d=>[d.name??m.dim(d.id.slice(0,8)),d.status==="active"?m.green("active"):d.status==="proposed"?m.yellow("proposed"):m.dim("inactive"),d.decision==="deny"?m.red(d.decision):d.decision==="require_confirm"?m.yellow(d.decision):m.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??m.dim("any"),d.when||m.dim("(always)"),d.reason??""],ur=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];dt.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:b}=await H(d.baseUrl),$=new B({baseUrl:h,token:b}),S;try{S=await $.guardrailsList()}catch(g){V(g,"extensions:deploy","list guardrails"),w(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(S,null,2));if(S.length===0)return y(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3274
- `+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(pt(S.map(an),{head:ur})),y(m.dim(" first match wins; lower PRIO is evaluated first."))}),dt.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:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$}),g;try{g=await S.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(x){V(x,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${x instanceof Error?x.message:String(x)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} created${g.status==="active"?"":m.dim(` (${g.status} \u2014 activate it to take effect)`)}`),y(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),y(m.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),dt.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&&w("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$}),g;try{g=await S.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(x){V(x,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${x instanceof Error?x.message:String(x)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} updated`),y(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[d,h,b]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])dt.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($,S)=>{let{baseUrl:g,token:x}=await H(S.baseUrl),R=new B({baseUrl:g,token:x});try{await R.guardrailUpdate($,{status:h})}catch(A){V(A,"extensions:deploy",`${d} a guardrail`),w(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${m.green("\u2713")} guardrail ${m.bold($)} ${b}`),h==="inactive"&&y(m.dim(" writes it was gating now fall through to the other rules."))});dt.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:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$});try{await S.guardrailDelete(d)}catch(g){V(g,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(d)} deleted`)}),dt.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:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$}),g=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await S.guardrailPostureGet()}catch(I){V(I,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}y(`guardrail posture: ${m.bold(g(A.mode))}`),y(m.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"&&w("posture must be 'allow' or 'deny'.");let R;try{R=await S.guardrailPostureSet(x)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${m.green("\u2713")} guardrail posture set to ${m.bold(g(R.mode))}`),R.mode==="deny"&&y(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),dt.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(R){w(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:b,token:$}=await H(d.baseUrl),S=new B({baseUrl:b,token:$}),g;try{g=await S.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){V(R,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return y(JSON.stringify(g,null,2));let x=`${d.source}/${g.op??d.record}`;g.degraded?(y(`${m.red("\u2717")} ${x} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(m.dim(` ${g.reason}`))):g.allowed?y(`${m.green("\u2713")} ${x} \u2014 ${g.decision}`+(g.blockedBy?m.dim(` (rule ${g.blockedBy})`):m.dim(" (no rule matched)"))):(y(`${m.red("\u2717")} ${x} \u2014 ${g.decision} by ${m.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&y(m.dim(` ${g.message}`))),g.decision==="require_confirm"&&y(m.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let Ut=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),ln=(d,h={})=>{let b=`${m.bold(d.table)} ${m.dim(d.displayName)}`;y(d.exists===!1?`${b} ${m.dim("(new)")}`:b);for(let $ of d.fields){let S=[$.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&$.claimedBy?.length?` ${m.dim(`\u2190 ${$.claimedBy.join(", ")}`)}`:"";y(` ${$.column.padEnd(28)} ${$.type}${S?` (${S})`:""}${g}`)}h.showClaimants&&d.claimants.length>1&&y(m.dim(` claimed by ${d.claimants.join(", ")}`))};function xn(d){if(d instanceof X&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}w(`tables: ${d instanceof Error?d.message:String(d)}`)}let kd=async d=>{let h=Ye(ie(process.cwd(),d),"public","turbobase.json"),b=await re.readFile(h,"utf8").catch(()=>null);if(b===null)return null;let $;try{$=JSON.parse(b)}catch(g){w(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=$.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||w(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};Ut.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:b}=await H(d.baseUrl),$=new B({baseUrl:h,token:b}),S;try{S=await $.tablesList()}catch(g){V(g,"extensions:deploy","list tables"),w(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(S,null,2));if(S.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(pt(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Ut.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 b=await kd(d??".");if(b||w(`no public/turbobase.json under ${ie(process.cwd(),d??".")}.`),b.tables.length===0)return y(`${b.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:$,token:S}=await H(h.baseUrl),g=new B({baseUrl:$,token:S}),x;try{x=await J("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:b.tables}))}catch(R){V(R,"extensions:deploy","plan tables"),xn(R)}y(`claiming as ${m.bold(x.claimedBy)}`);for(let R of x.tables)ln(R,{showClaimants:!0});y(""),y(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Ut.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 b=await kd(d??".");if(b||w(`no public/turbobase.json under ${ie(process.cwd(),d??".")}.`),b.tables.length===0)return y(`${b.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:$,token:S}=await H(h.baseUrl),g=new B({baseUrl:$,token:S}),x;try{x=await J("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:b.tables}))}catch(R){V(R,"extensions:deploy","apply tables"),xn(R)}for(let R of x.tables)ln(R,{showClaimants:!0});y(`applied ${x.tables.length} table${x.tables.length===1?"":"s"} as ${x.claimedBy}.`)}),Ut.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 b=h.field.map(R=>{let[A,I,O]=R.split(":");return(!A||!I)&&w(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&w(`--field "${R}": the third part may only be "required".`),{name:A,type:I,...O==="required"?{required:!0}:{}}}),{baseUrl:$,token:S}=await H(h.baseUrl),g=new B({baseUrl:$,token:S}),x;try{x=await J(`creating cr_${d}`,()=>g.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:b,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){V(R,"extensions:deploy","create a table"),xn(R)}for(let R of x.tables)ln(R);y(""),y(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Ut.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&&w(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$}),g;try{g=await J(`dropping cr_${d}`,()=>S.tablesDrop(d,h.confirm))}catch(x){V(x,"extensions:deploy","drop a table"),w(`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 vi=e.command("sandbox").description("Ephemeral local authoring sandboxes.");vi.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=gd(),b;try{b=await xp(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch($){$ instanceof xr&&w($.message),w(`sandbox create failed: ${$ instanceof Error?$.message:String($)}`)}y(`sandbox ${b.name} ready.`),y(` source: ${b.fromTenant} (sampled ${Math.round(b.sampleFraction*100)}%, redacted)`),y(` url: ${b.url}`),y(` expires: ${b.expiresAt}`)}),vi.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=gd();await ba(h).catch(()=>[]);let b;try{b=await Tp(h,d)}catch($){w(`sandbox destroy failed: ${$ instanceof Error?$.message:String($)}`)}b||w(`no sandbox named '${d}'.`),y(`destroyed sandbox ${b.name} (dropped ${b.database}).`)}),vi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=gd(),h=await ba(d).catch(()=>[]),b=await Gs(),{active:$}=ga(b);if($.length===0)y("no active sandboxes.");else{for(let S of $)y(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);y(`
3275
- ${$.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.",js).action(async d=>{let{baseUrl:h,token:b}=await H(d.baseUrl),$=new B({baseUrl:h,token:b}),S;try{S=await J("exporting instance config",()=>$.configExport())}catch(R){R instanceof X&&(R.status===401||R.status===403)&&w("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),w(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let g=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
3276
- `,x=ie(process.cwd(),d.out,vr);await re.mkdir(cr(x),{recursive:!0}),await re.writeFile(x,g,"utf8"),y(`wrote ${d.out}/${vr} (${g.split(`
3277
- `).length} lines).`)});let Sd=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Ob=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],_d=()=>process.env.TURBOBASE_HOME?.trim()||Ye(r0(),".turbobase"),Nb=()=>"1.4.0",ys=async()=>Promise.all(Ob.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Sd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await ys();for(let h of d)y(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3278
- run \`${kr} ext extras install\` to fetch them into ${_d()}.`)}),Sd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await ys();if(d.every(A=>A.present)){y(ve.success("extras already installed \u2014 nothing to do."));return}let h=_d();await re.mkdir(h,{recursive:!0});let b=d.filter(A=>!A.present).map(A=>A.name),$=da(process.platform,process.arch),S=async(A,I)=>{let{code:O,stderr:W}=await bs("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&w(`extras install failed while installing ${I} (npm exited ${O}).
3269
+ 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:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),S;try{S=await x.catalogRecords()}catch(I){I instanceof X&&(I.status===401||I.status===403)&&w("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),w(`catalog fetch failed: ${I instanceof Error?I.message:String(I)}`)}if(S.length===0){y("no records in the instance catalog \u2014 nothing to generate.");return}let g=le(process.cwd(),d.out),$=nu(S,{event:d.event}),R=0,A=0;for(let{recordType:I,fixture:O}of $){let W=Ye(g,`${I}.json`),N=`${JSON.stringify(O,null,2)}
3270
+ `;d.force?(await se.mkdir(cr(W),{recursive:!0}),await se.writeFile(W,N,{mode:420}),R+=1,y(` wrote ${d.out}/${I}.json`)):await dr(W,N)==="wrote"?(R+=1,y(` wrote ${d.out}/${I}.json`)):(A+=1,y(` skipped ${d.out}/${I}.json (exists \u2014 use --force to overwrite)`))}y(`
3271
+ samples init: ${R} written, ${A} skipped.`)});let dt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),on=d=>[d.name??m.dim(d.id.slice(0,8)),d.status==="active"?m.green("active"):d.status==="proposed"?m.yellow("proposed"):m.dim("inactive"),d.decision==="deny"?m.red(d.decision):d.decision==="require_confirm"?m.yellow(d.decision):m.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??m.dim("any"),d.when||m.dim("(always)"),d.reason??""],ur=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];dt.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:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),S;try{S=await x.guardrailsList()}catch(g){V(g,"extensions:deploy","list guardrails"),w(`list guardrails failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(S,null,2));if(S.length===0)return y(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3272
+ `+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(pt(S.map(on),{head:ur})),y(m.dim(" first match wins; lower PRIO is evaluated first."))}),dt.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:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch($){V($,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${$ instanceof Error?$.message:String($)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} created${g.status==="active"?"":m.dim(` (${g.status} \u2014 activate it to take effect)`)}`),y(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.actor?` actor=${g.actor}`:""}${g.when?` where ${g.when}`:""} @prio ${g.priority}`)),y(m.dim(` verify with: turbobase guardrails test --source ${g.source==="*"?"<source>":g.source} --record <record>`))}),dt.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&&w("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch($){V($,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${$ instanceof Error?$.message:String($)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(g.name??g.id)} updated`),y(m.dim(` ${g.decision} ${g.source}/${g.record??g.op}${g.when?` where ${g.when}`:""} @prio ${g.priority}`))});for(let[d,h,b]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])dt.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(x,S)=>{let{baseUrl:g,token:$}=await H(S.baseUrl),R=new B({baseUrl:g,token:$});try{await R.guardrailUpdate(x,{status:h})}catch(A){V(A,"extensions:deploy",`${d} a guardrail`),w(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(x)} ${b}`),h==="inactive"&&y(m.dim(" writes it was gating now fall through to the other rules."))});dt.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:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x});try{await S.guardrailDelete(d)}catch(g){V(g,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${g instanceof Error?g.message:String(g)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(d)} deleted`)}),dt.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:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,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 S.guardrailPostureGet()}catch(I){V(I,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}y(`guardrail posture: ${m.bold(g(A.mode))}`),y(m.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 $=d.trim().toLowerCase();$!=="allow"&&$!=="deny"&&w("posture must be 'allow' or 'deny'.");let R;try{R=await S.guardrailPostureSet($)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${m.green("\u2713")} guardrail posture set to ${m.bold(g(R.mode))}`),R.mode==="deny"&&y(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),dt.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(R){w(`--fields must be valid JSON: ${R instanceof Error?R.message:String(R)}`)}let{baseUrl:b,token:x}=await H(d.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){V(R,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return y(JSON.stringify(g,null,2));let $=`${d.source}/${g.op??d.record}`;g.degraded?(y(`${m.red("\u2717")} ${$} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(m.dim(` ${g.reason}`))):g.allowed?y(`${m.green("\u2713")} ${$} \u2014 ${g.decision}`+(g.blockedBy?m.dim(` (rule ${g.blockedBy})`):m.dim(" (no rule matched)"))):(y(`${m.red("\u2717")} ${$} \u2014 ${g.decision} by ${m.bold(g.blockedBy??"?")} at the ${g.phase} gate`),g.message&&y(m.dim(` ${g.message}`))),g.decision==="require_confirm"&&y(m.yellow(" this write is HELD for operator approval, not refused.")),g.allowed||(process.exitCode=1)});let Ut=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),an=(d,h={})=>{let b=`${m.bold(d.table)} ${m.dim(d.displayName)}`;y(d.exists===!1?`${b} ${m.dim("(new)")}`:b);for(let x of d.fields){let S=[x.required?"required":null].filter(Boolean).join(", "),g=h.showClaimants&&x.claimedBy?.length?` ${m.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";y(` ${x.column.padEnd(28)} ${x.type}${S?` (${S})`:""}${g}`)}h.showClaimants&&d.claimants.length>1&&y(m.dim(` claimed by ${d.claimants.join(", ")}`))};function xn(d){if(d instanceof X&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}w(`tables: ${d instanceof Error?d.message:String(d)}`)}let kd=async d=>{let h=Ye(le(process.cwd(),d),"public","turbobase.json"),b=await se.readFile(h,"utf8").catch(()=>null);if(b===null)return null;let x;try{x=JSON.parse(b)}catch(g){w(`${h} is not valid JSON: ${g instanceof Error?g.message:String(g)}`)}let S=x.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||w(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};Ut.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:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),S;try{S=await x.tablesList()}catch(g){V(g,"extensions:deploy","list tables"),w(`list tables failed: ${g instanceof Error?g.message:String(g)}`)}if(d.json)return y(JSON.stringify(S,null,2));if(S.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(pt(S.map(g=>[g.table,g.displayName,String(g.fields.length),g.status,g.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Ut.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 b=await kd(d??".");if(b||w(`no public/turbobase.json under ${le(process.cwd(),d??".")}.`),b.tables.length===0)return y(`${b.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:x,token:S}=await H(h.baseUrl),g=new B({baseUrl:x,token:S}),$;try{$=await J("planning tables",()=>g.tablesPlan({claimedBy:h.as,tables:b.tables}))}catch(R){V(R,"extensions:deploy","plan tables"),xn(R)}y(`claiming as ${m.bold($.claimedBy)}`);for(let R of $.tables)an(R,{showClaimants:!0});y(""),y(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Ut.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 b=await kd(d??".");if(b||w(`no public/turbobase.json under ${le(process.cwd(),d??".")}.`),b.tables.length===0)return y(`${b.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:x,token:S}=await H(h.baseUrl),g=new B({baseUrl:x,token:S}),$;try{$=await J("applying tables",()=>g.tablesApply({claimedBy:h.as,tables:b.tables}))}catch(R){V(R,"extensions:deploy","apply tables"),xn(R)}for(let R of $.tables)an(R,{showClaimants:!0});y(`applied ${$.tables.length} table${$.tables.length===1?"":"s"} as ${$.claimedBy}.`)}),Ut.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 b=h.field.map(R=>{let[A,I,O]=R.split(":");return(!A||!I)&&w(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&w(`--field "${R}": the third part may only be "required".`),{name:A,type:I,...O==="required"?{required:!0}:{}}}),{baseUrl:x,token:S}=await H(h.baseUrl),g=new B({baseUrl:x,token:S}),$;try{$=await J(`creating cr_${d}`,()=>g.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:b,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){V(R,"extensions:deploy","create a table"),xn(R)}for(let R of $.tables)an(R);y(""),y(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Ut.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&&w(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await J(`dropping cr_${d}`,()=>S.tablesDrop(d,h.confirm))}catch($){V($,"extensions:deploy","drop a table"),w(`drop failed: ${$ instanceof Error?$.message:String($)}`)}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 vi=e.command("sandbox").description("Ephemeral local authoring sandboxes.");vi.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=gd(),b;try{b=await xp(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(x){x instanceof xr&&w(x.message),w(`sandbox create failed: ${x instanceof Error?x.message:String(x)}`)}y(`sandbox ${b.name} ready.`),y(` source: ${b.fromTenant} (sampled ${Math.round(b.sampleFraction*100)}%, redacted)`),y(` url: ${b.url}`),y(` expires: ${b.expiresAt}`)}),vi.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=gd();await ba(h).catch(()=>[]);let b;try{b=await Tp(h,d)}catch(x){w(`sandbox destroy failed: ${x instanceof Error?x.message:String(x)}`)}b||w(`no sandbox named '${d}'.`),y(`destroyed sandbox ${b.name} (dropped ${b.database}).`)}),vi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=gd(),h=await ba(d).catch(()=>[]),b=await Gs(),{active:x}=ga(b);if(x.length===0)y("no active sandboxes.");else{for(let S of x)y(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);y(`
3273
+ ${x.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.",js).action(async d=>{let{baseUrl:h,token:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),S;try{S=await J("exporting instance config",()=>x.configExport())}catch(R){R instanceof X&&(R.status===401||R.status===403)&&w("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),w(`ext export failed: ${R instanceof Error?R.message:String(R)}`)}let g=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
3274
+ `,$=le(process.cwd(),d.out,vr);await se.mkdir(cr($),{recursive:!0}),await se.writeFile($,g,"utf8"),y(`wrote ${d.out}/${vr} (${g.split(`
3275
+ `).length} lines).`)});let Sd=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Ob=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],_d=()=>process.env.TURBOBASE_HOME?.trim()||Ye(r0(),".turbobase"),Nb=()=>"1.4.1",ys=async()=>Promise.all(Ob.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Sd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await ys();for(let h of d)y(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3276
+ run \`${kr} ext extras install\` to fetch them into ${_d()}.`)}),Sd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await ys();if(d.every(A=>A.present)){y(ve.success("extras already installed \u2014 nothing to do."));return}let h=_d();await se.mkdir(h,{recursive:!0});let b=d.filter(A=>!A.present).map(A=>A.name),x=da(process.platform,process.arch),S=async(A,I)=>{let{code:O,stderr:W}=await bs("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&w(`extras install failed while installing ${I} (npm exited ${O}).
3279
3277
  ${W.trim()}
3280
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=b.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(I=>`${I}@${la[I]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(A,g.join(", "))}if(b.includes("isolated-vm")){let A=`isolated-vm@${la["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),yp.includes($)){let O=`${ca}@${Nb()}`;y(`fetching ${O} (no upstream binary for ${$}) \u2026`);let{code:W}=await bs("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);W!==0&&y(ve.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let I=await wp({home:h});I.length>0&&y(` ${ve.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${$}`)}let x=await ys(),R=x.filter(A=>!A.present).map(A=>A.name);if(R.includes("isolated-vm")){y(ve.warn(`no prebuilt isolated-vm for ${$} / Node ${process.versions.node} (${ua()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await bs("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(x=await ys(),R=x.filter(I=>!I.present).map(I=>I.name))}R.length>0&&w(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${$} / Node ${process.versions.node} (${ua()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),y(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Tn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Tn.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||w(`--target must be 'auto' or 'approved' (got '${d.target}').`);let b=await w0(ie(process.cwd(),d.project??".")),$=Object.keys(b).length;!d.solution&&$===0&&w("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 bd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await bd(["rev-parse","HEAD"]),x=d.gitRepo??process.env.GITHUB_REPOSITORY??await bd(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:I,token:O}=await H(d.baseUrl),W=new B({baseUrl:I,token:O}),N;try{N=await W.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:$>0?b:null,gitRepo:x,gitRef:R,gitSha:g,prUrl:A})}catch(K){V(K,"releases:write","release deploy"),K instanceof X&&K.status===404&&w("solution_not_found \u2014 no solution with that id."),w(`release deploy failed: ${K instanceof Error?K.message:String(K)}`)}y(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+($>0?`, uploaded ${$} bundle file(s)`:", live-fetch")+")."),d.follow&&await ra(()=>W.releaseStatus(N.releaseId),`release ${N.releaseId}`,d.intervalMs)}),Tn.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:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$}),g;try{g=await S.releaseFiles(d)}catch(A){A instanceof X&&A.status===404&&w(`release ${d} not found.`),A instanceof X&&A.status===409&&w(`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.`),V(A,"releases:write","pull a release"),w(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let x=ie(process.cwd(),h.dir),R=0;for(let[A,I]of[["owned",g.owned],["context",g.context]])for(let[O,W]of Object.entries(I)){let N=Ye(x,A,O);await re.mkdir(cr(N),{recursive:!0}),await re.writeFile(N,W,"utf8"),R++}await re.writeFile(Ye(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}
3278
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},g=b.filter(A=>A!=="isolated-vm");if(g.length>0){let A=g.map(I=>`${I}@${la[I]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(A,g.join(", "))}if(b.includes("isolated-vm")){let A=`isolated-vm@${la["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),yp.includes(x)){let O=`${ca}@${Nb()}`;y(`fetching ${O} (no upstream binary for ${x}) \u2026`);let{code:W}=await bs("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);W!==0&&y(ve.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let I=await wp({home:h});I.length>0&&y(` ${ve.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let $=await ys(),R=$.filter(A=>!A.present).map(A=>A.name);if(R.includes("isolated-vm")){y(ve.warn(`no prebuilt isolated-vm for ${x} / Node ${process.versions.node} (${ua()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await bs("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&($=await ys(),R=$.filter(I=>!I.present).map(I=>I.name))}R.length>0&&w(`npm succeeded but ${R.join(", ")} still will not load \u2014 no prebuilt binary for ${x} / Node ${process.versions.node} (${ua()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),y(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Tn=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return Tn.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||w(`--target must be 'auto' or 'approved' (got '${d.target}').`);let b=await y0(le(process.cwd(),d.project??".")),x=Object.keys(b).length;!d.solution&&x===0&&w("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 bd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await bd(["rev-parse","HEAD"]),$=d.gitRepo??process.env.GITHUB_REPOSITORY??await bd(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:I,token:O}=await H(d.baseUrl),W=new B({baseUrl:I,token:O}),N;try{N=await W.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:x>0?b:null,gitRepo:$,gitRef:R,gitSha:g,prUrl:A})}catch(K){V(K,"releases:write","release deploy"),K instanceof X&&K.status===404&&w("solution_not_found \u2014 no solution with that id."),w(`release deploy failed: ${K instanceof Error?K.message:String(K)}`)}y(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+(x>0?`, uploaded ${x} bundle file(s)`:", live-fetch")+")."),d.follow&&await ra(()=>W.releaseStatus(N.releaseId),`release ${N.releaseId}`,d.intervalMs)}),Tn.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:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.releaseFiles(d)}catch(A){A instanceof X&&A.status===404&&w(`release ${d} not found.`),A instanceof X&&A.status===409&&w(`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.`),V(A,"releases:write","pull a release"),w(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let $=le(process.cwd(),h.dir),R=0;for(let[A,I]of[["owned",g.owned],["context",g.context]])for(let[O,W]of Object.entries(I)){let N=Ye($,A,O);await se.mkdir(cr(N),{recursive:!0}),await se.writeFile(N,W,"utf8"),R++}await se.writeFile(Ye($,".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 ${$}
3281
3279
  ${Object.keys(g.owned).length} owned file(s), ${Object.keys(g.context).length} context file(s), ${R} total
3282
3280
  `+(g.logTail?`
3283
3281
  the failure these bytes produced:
3284
3282
  ${g.logTail.trim()}
3285
3283
  `:"")+`
3286
3284
  edit the files under owned/, then:
3287
- turbobase release push ${g.releaseId} --dir ${h.dir}`)}),Tn.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:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$}),g=ie(process.cwd(),h.dir),x;try{x=await S.releaseFiles(d)}catch(N){N instanceof X&&N.status===404&&w(`release ${d} not found.`),V(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}let R=async(N,K)=>{try{return await re.readFile(Ye(g,N,K),"utf8")}catch{return null}},A=[];for(let[N,K]of Object.entries(x.context)){let he=await R("context",N);he!==null&&he!==K&&A.push(N)}A.length>0&&w(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
3285
+ turbobase release push ${g.releaseId} --dir ${h.dir}`)}),Tn.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:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g=le(process.cwd(),h.dir),$;try{$=await S.releaseFiles(d)}catch(N){N instanceof X&&N.status===404&&w(`release ${d} not found.`),V(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}let R=async(N,K)=>{try{return await se.readFile(Ye(g,N,K),"utf8")}catch{return null}},A=[];for(let[N,K]of Object.entries($.context)){let he=await R("context",N);he!==null&&he!==K&&A.push(N)}A.length>0&&w(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
3288
3286
  `+A.map(N=>` context/${N}`).join(`
3289
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let I={...x.context},O=0;for(let[N,K]of Object.entries(x.owned)){let he=await R("owned",N);I[N]=he??K,he!==null&&he!==K&&O++}O===0&&y("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let W=h.target==="approved"?"approved":"auto";try{let N=await S.releasePush(d,{files:I,target:W,...h.approvedBy?{approvedBy:h.approvedBy}:{}});y(`pushed ${Object.keys(I).length} file(s) (${O} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
3287
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let I={...$.context},O=0;for(let[N,K]of Object.entries($.owned)){let he=await R("owned",N);I[N]=he??K,he!==null&&he!==K&&O++}O===0&&y("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let W=h.target==="approved"?"approved":"auto";try{let N=await S.releasePush(d,{files:I,target:W,...h.approvedBy?{approvedBy:h.approvedBy}:{}});y(`pushed ${Object.keys(I).length} file(s) (${O} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
3290
3288
  follow it with:
3291
- turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof X&&N.status===403&&w("an approved target needs --approved-by (the deploy gate fails closed)."),N instanceof X&&N.status===409&&w("that solution already has an active release \u2014 roll it back or wait for it."),V(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),Tn.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:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$});if(h.follow){await ra(()=>S.releaseStatus(d),`release ${d}`,h.intervalMs);return}let g;try{g=await S.releaseStatus(d)}catch(x){V(x,"releases:write","release status"),x instanceof X&&x.status===404&&w(`release ${d} not found.`),w(`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+$/,""))}),Tn.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:b,token:$}=await H(h.baseUrl),S=new B({baseUrl:b,token:$}),g;try{g=await S.releaseRollback(d)}catch(x){V(x,"releases:write","release rollback"),x instanceof X&&x.status===404&&w(`release ${d} not found.`),x instanceof X&&x.status===409&&w(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),w(`release rollback failed: ${x instanceof Error?x.message:String(x)}`)}y(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),Tn.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:b}=await H(d.baseUrl),$=new B({baseUrl:h,token:b}),S;try{S=await $.releaseList()}catch(g){V(g,"releases:write","release list"),w(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(S.length===0){y("no releases.");return}if(Ee())y(pt(S.map(g=>[g.id,In(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map(x=>`"${x}"`).join(", "):m.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of S){let x=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";y(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${x}`)}y(`
3292
- ${S.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:b}=await H(d.baseUrl),$=new B({baseUrl:h,token:b}),S=d.limit?Number(d.limit):void 0,g=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await fu($,d.conduit,{...d.follow?{follow:!0}:{},...S!==void 0?{limit:S}:{},...g!==void 0?{intervalMs:g}:{},sink:y})}catch(x){w(`logs --conduit failed: ${x instanceof Error?x.message:String(x)}`)}return}if(d.extension){try{let x=await $.logs(d.extension,S);x.length===0&&y(`no logs for ${d.extension}.`);for(let R of x)y(` [${R.level}] ${R.ts??""} ${R.message}`)}catch(x){w(`logs --extension failed: ${x instanceof Error?x.message:String(x)}`)}return}try{await gu($,{...d.subsystem?{subsystem:d.subsystem}:{},...d.severity?{severity:d.severity}:{},...d.code?{code:d.code}:{},...d.since?{since:d.since}:{},...d.correlationId?{correlationId:d.correlationId}:{},...d.follow?{follow:!0}:{},...d.json?{json:!0}:{},...S!==void 0?{limit:S}:{},...g!==void 0?{intervalMs:g}:{},sink:y})}catch(x){w(`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(()=>(Ab(),Pb));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(`
3293
- `)),t&&void 0,e}function f0(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 m0(t){let e=Ye(ie(process.cwd(),t),"public","turbobase.json"),n=await re.readFile(e,"utf8").catch(()=>null);if(n===null)return null;let r;try{r=JSON.parse(n)}catch(s){w(`${e} is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}return(typeof r!="object"||r===null||Array.isArray(r))&&w(`${e} must be a JSON object.`),{manifest:r,manifestPath:e}}async function g0(){let t=ie(process.cwd(),js,vr),e;try{e=await re.readFile(t,"utf8")}catch{w(`no config found \u2014 this project authors none (no ${qs}/, ${zs}/, ${Ht} or ${Kt}) and there is no ${js}/${vr}.
3294
- Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Ru(e)}catch(n){w(`bundle is invalid: ${n instanceof Error?n.message:String(n)}`)}}async function md(){let t=process.cwd();if(!await Au(t))return g0();let e;try{e=await Iu(t)}catch(n){w(`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&&w(`${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 b0(t,e){y(`plan against ${e}:`);for(let n of t.add)y(` ${zt.add(`${n.kind} ${n.id}`)}`);for(let n of t.change)y(` ${zt.change(`${n.kind} ${n.id}`)}`);for(let n of t.destroy)y(` ${zt.destroy(`${n.kind} ${n.id}`)}`);y(`
3295
- ${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 y0(t){try{let n=new URL(t).hostname.split(".")[0];return n&&n!=="localhost"?n:void 0}catch{return}}function bs(t,e,n){return new Promise(r=>{let s=wd(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 gd(){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 bs("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 bs("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 w0(t){let e=ie(t,"src"),n={},r=async s=>{let o;try{o=await re.readdir(s,{withFileTypes:!0})}catch{return}for(let i of o){let a=Ye(s,i.name);if(i.isDirectory())await r(a);else if(i.isFile()){let l=wi(e,a).split(yd).join("/");n[l]=await re.readFile(a,"utf8")}}};return await r(e),n}function bd(t){return new Promise(e=>{let n=wd("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 v0=!1;v0&&vd().parseAsync(process.argv).catch(t=>w(t instanceof Error?t.message:String(t)));vd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3289
+ turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof X&&N.status===403&&w("an approved target needs --approved-by (the deploy gate fails closed)."),N instanceof X&&N.status===409&&w("that solution already has an active release \u2014 roll it back or wait for it."),V(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),Tn.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:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x});if(h.follow){await ra(()=>S.releaseStatus(d),`release ${d}`,h.intervalMs);return}let g;try{g=await S.releaseStatus(d)}catch($){V($,"releases:write","release status"),$ instanceof X&&$.status===404&&w(`release ${d} not found.`),w(`release status failed: ${$ instanceof Error?$.message:String($)}`)}y(`release ${d}: status=${g.releaseStatus??"?"} stage=${g.stage} ${g.percent}%`+(g.runStatus?` (${g.runStatus})`:"")),g.outputTail&&y(g.outputTail.replace(/\n+$/,""))}),Tn.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:b,token:x}=await H(h.baseUrl),S=new B({baseUrl:b,token:x}),g;try{g=await S.releaseRollback(d)}catch($){V($,"releases:write","release rollback"),$ instanceof X&&$.status===404&&w(`release ${d} not found.`),$ instanceof X&&$.status===409&&w(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),w(`release rollback failed: ${$ instanceof Error?$.message:String($)}`)}y(`release ${g.releaseId} rolled back \u2192 status=${g.release?.status??"rolled_back"}.`)}),Tn.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:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),S;try{S=await x.releaseList()}catch(g){V(g,"releases:write","release list"),w(`release list failed: ${g instanceof Error?g.message:String(g)}`)}if(S.length===0){y("no releases.");return}if(Ee())y(pt(S.map(g=>[g.id,In(g.status),g.target,g.backend,g.solutionTitles?.length?g.solutionTitles.map($=>`"${$}"`).join(", "):m.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let g of S){let $=g.solutionTitles?.length?` "${g.solutionTitles.join('", "')}"`:"";y(` ${g.id} ${g.status.padEnd(11)} target=${g.target} backend=${g.backend}${$}`)}y(`
3290
+ ${S.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:b}=await H(d.baseUrl),x=new B({baseUrl:h,token:b}),S=d.limit?Number(d.limit):void 0,g=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await fu(x,d.conduit,{...d.follow?{follow:!0}:{},...S!==void 0?{limit:S}:{},...g!==void 0?{intervalMs:g}:{},sink:y})}catch($){w(`logs --conduit failed: ${$ instanceof Error?$.message:String($)}`)}return}if(d.extension){try{let $=await x.logs(d.extension,S);$.length===0&&y(`no logs for ${d.extension}.`);for(let R of $)y(` [${R.level}] ${R.ts??""} ${R.message}`)}catch($){w(`logs --extension failed: ${$ instanceof Error?$.message:String($)}`)}return}try{await gu(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}:{},...S!==void 0?{limit:S}:{},...g!==void 0?{intervalMs:g}:{},sink:y})}catch($){w(`logs failed: ${$ instanceof Error?$.message:String($)}`)}}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(Ab(),Pb));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(`
3291
+ `)),t&&void 0,e}function h0(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 f0(t){let e=Ye(le(process.cwd(),t),"public","turbobase.json"),n=await se.readFile(e,"utf8").catch(()=>null);if(n===null)return null;let r;try{r=JSON.parse(n)}catch(s){w(`${e} is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}return(typeof r!="object"||r===null||Array.isArray(r))&&w(`${e} must be a JSON object.`),{manifest:r,manifestPath:e}}async function m0(){let t=le(process.cwd(),js,vr),e;try{e=await se.readFile(t,"utf8")}catch{w(`no config found \u2014 this project authors none (no ${qs}/, ${zs}/, ${Ft} or ${Ht}) and there is no ${js}/${vr}.
3292
+ Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Ru(e)}catch(n){w(`bundle is invalid: ${n instanceof Error?n.message:String(n)}`)}}async function md(){let t=process.cwd();if(!await Au(t))return m0();let e;try{e=await Iu(t)}catch(n){w(`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&&w(`${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 g0(t,e){y(`plan against ${e}:`);for(let n of t.add)y(` ${qt.add(`${n.kind} ${n.id}`)}`);for(let n of t.change)y(` ${qt.change(`${n.kind} ${n.id}`)}`);for(let n of t.destroy)y(` ${qt.destroy(`${n.kind} ${n.id}`)}`);y(`
3293
+ ${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 b0(t){try{let n=new URL(t).hostname.split(".")[0];return n&&n!=="localhost"?n:void 0}catch{return}}function bs(t,e,n){return new Promise(r=>{let s=wd(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 gd(){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 bs("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 bs("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 y0(t){let e=le(t,"src"),n={},r=async s=>{let o;try{o=await se.readdir(s,{withFileTypes:!0})}catch{return}for(let i of o){let a=Ye(s,i.name);if(i.isDirectory())await r(a);else if(i.isFile()){let l=wi(e,a).split(yd).join("/");n[l]=await se.readFile(a,"utf8")}}};return await r(e),n}function bd(t){return new Promise(e=>{let n=wd("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 w0=!1;w0&&vd().parseAsync(process.argv).catch(t=>w(t instanceof Error?t.message:String(t)));vd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3296
3294
  `),process.exit(1)});