@turbobase/cli 1.6.5 → 1.6.6

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,27 +1,27 @@
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 jb=Object.create;var _i=Object.defineProperty;var Ub=Object.getOwnPropertyDescriptor;var Db=Object.getOwnPropertyNames;var qb=Object.getPrototypeOf,Mb=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),xd=(t,e)=>{for(var r in e)_i(t,r,{get:e[r],enumerable:!0})},zb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Db(e))!Mb.call(t,s)&&s!==r&&_i(t,s,{get:()=>e[s],enumerable:!(n=Ub(e,s))||n.enumerable});return t};var Td=(t,e,r)=>(r=t!=null?jb(qb(t)):{},zb(e||!t||!t.__esModule?_i(r,"default",{value:t,enumerable:!0}):r,t));function un(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var vs=j(()=>{});import{z as or}from"zod";function ks(t){let e=$i.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function xi(t,e){let r=$i.safeParse(t);if(!r.success)throw new Dt(`invalid manifest: ${r.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(Rd.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 n=JSON.stringify(r.data);if(Rd.test(n))throw new Dt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Ed,Pd,$i,Dt,Rd,Ad=j(()=>{Ed=or.object({type:or.literal("connection"),source_system:or.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:or.string().min(1).max(200).optional()}),Pd=or.discriminatedUnion("type",[Ed]),$i=or.object({inputs:or.array(Pd).optional()}).passthrough(),Dt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Rd=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ss,Ti=j(()=>{Ss=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as De}from"zod";var Ri,Id,Cd=j(()=>{vs();Ti();Ri=De.object({id:De.string().min(1,"hook id must be non-empty"),recordType:De.union([De.string().min(1),De.array(De.string().min(1)).min(1),De.literal("*")]),event:De.enum(Ss),source:De.string().min(1).optional(),when:De.unknown().optional(),run:De.unknown(),failClosed:De.boolean().optional(),timeoutMs:De.number().int().positive().optional(),description:De.string().optional(),systemReserved:De.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"})}),Id=un({kind:"hook",schema:Ri,factoryName:"defineHook"})});var Od=j(()=>{Cd();Ti()});var _s,Ei=j(()=>{_s=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as Re}from"zod";var Pi,Nd,Ld=j(()=>{vs();Ei();Pi=Re.object({id:Re.string().min(1,"conduit id must be non-empty"),on:Re.enum(_s),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 r=t.from?.when;r!==void 0&&typeof r!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let n=t.idempotencyKey;n!==void 0&&typeof n!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let 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"})}),Nd=un({kind:"conduit",schema:Pi,factoryName:"defineConduit"})});var jd=j(()=>{Ld();Ei()});async function Vb(t){let e;try{e=await import("openapi-typescript")}catch{throw new Error("types-gen: 'openapi-typescript' is not installed. Add it to the environment running `turbobase project types`, or pass a `transform` override to generateTypes().")}let r=await e.default(t,{defaultNonNullable:!1});return e.astToString(r)}async function $s(t,e={}){return(e.transform??Vb)(t)}var Ai=j(()=>{});function Ii(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 Ud(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Ci(t){return`${Ud(t.source)}${Ud(t.recordType)}`}function Gb(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Wb(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 Oi(t){let e=Ci(t),r=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&r.push(t.description);let n=r.length===1?`/** ${r[0]} */`:`/**
5
- * ${r.join(`
4
+ var Ub=Object.create;var _i=Object.defineProperty;var Mb=Object.getOwnPropertyDescriptor;var zb=Object.getOwnPropertyNames;var qb=Object.getPrototypeOf,Bb=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ed=(t,e)=>{for(var n in e)_i(t,n,{get:e[n],enumerable:!0})},Fb=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of zb(e))!Bb.call(t,s)&&s!==n&&_i(t,s,{get:()=>e[s],enumerable:!(r=Mb(e,s))||r.enumerable});return t};var Pd=(t,e,n)=>(n=t!=null?Ub(qb(t)):{},Fb(e||!t||!t.__esModule?_i(n,"default",{value:t,enumerable:!0}):n,t));function ur(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var vs=j(()=>{});import{z as on}from"zod";function ks(t){let e=$i.safeParse(t);return e.success?(e.data.inputs??[]).filter(n=>n.type==="connection"):[]}function xi(t,e){let n=$i.safeParse(t);if(!n.success)throw new Ut(`invalid manifest: ${n.error.issues.map(s=>`${s.path.join(".")||"(root)"}: ${s.message}`).join("; ")}`);if(Ad.test(e))throw new Ut('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(Ad.test(r))throw new Ut("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Id,Cd,$i,Ut,Ad,Od=j(()=>{Id=on.object({type:on.literal("connection"),source_system:on.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:on.string().min(1).max(200).optional()}),Cd=on.discriminatedUnion("type",[Id]),$i=on.object({inputs:on.array(Cd).optional()}).passthrough(),Ut=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};Ad=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Ss,Ti=j(()=>{Ss=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Ue}from"zod";var Ri,Nd,Ld=j(()=>{vs();Ti();Ri=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(Ss),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"})}),Nd=ur({kind:"hook",schema:Ri,factoryName:"defineHook"})});var jd=j(()=>{Ld();Ti()});var _s,Ei=j(()=>{_s=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as Re}from"zod";var Pi,Dd,Ud=j(()=>{vs();Ei();Pi=Re.object({id:Re.string().min(1,"conduit id must be non-empty"),on:Re.enum(_s),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"})}),Dd=ur({kind:"conduit",schema:Pi,factoryName:"defineConduit"})});var Md=j(()=>{Ud();Ei()});async function Wb(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??Wb)(t)}var Ai=j(()=>{});function Ii(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 zd(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Ci(t){return`${zd(t.source)}${zd(t.recordType)}`}function Jb(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Yb(t){let e=[t.pgType];return t.label&&e.push(`"${t.label}"`),t.role==="display"&&t.displayFor?e.push(`display column for ${t.displayFor} \u2014 render this, filter/join on ${t.displayFor}`):t.role==="identifier"&&t.idFor?e.push(`identifier \u2014 render ${t.idFor} instead`):t.role&&e.push(t.role),t.format&&e.push(`format: ${t.format}`),t.currencyKey&&e.push(`currency from ${t.currencyKey}`),t.description&&e.push(t.description),e.join(" \xB7 ")}function Oi(t){let e=Ci(t),n=[`${t.source}:${t.recordType}`+(t.table?` \u2192 turbobase.${t.table}`:" (no backing table)")+`${t.listOnly?" (list-only)":""} \u2014 origin: ${t.origin}.`];t.description&&n.push(t.description);let r=n.length===1?`/** ${n[0]} */`:`/**
5
+ * ${n.join(`
6
6
  * `)}
7
- */`;if(t.columns.length===0)return`${n}
7
+ */`;if(t.columns.length===0)return`${r}
8
8
  export interface ${e} {
9
9
  // no columns introspected
10
10
  [key: string]: unknown;
11
- }`;let s=t.columns.map(o=>{let i=Ii(o.pgType),a=o.nullable?"?":"",l=o.nullable?" | null":"";return` /** ${Wb(o)} */
12
- ${Gb(o.name)}${a}: ${i}${l};`});return`${n}
11
+ }`;let s=t.columns.map(o=>{let i=Ii(o.pgType),a=o.nullable?"?":"",l=o.nullable?" | null":"";return` /** ${Yb(o)} */
12
+ ${Jb(o.name)}${a}: ${i}${l};`});return`${r}
13
13
  export interface ${e} {
14
14
  ${s.join(`
15
15
  `)}
16
- }`}function xs(t){return[...t.records].sort((n,s)=>`${n.source}:${n.recordType}`.localeCompare(`${s.source}:${s.recordType}`)).map(Oi).join(`
16
+ }`}function xs(t){return[...t.records].sort((r,s)=>`${r.source}:${r.recordType}`.localeCompare(`${s.source}:${s.recordType}`)).map(Oi).join(`
17
17
 
18
- `)}function Dd(t){let e=new Map,r=(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&&r(s.table,s.columns);for(let o of s.lines??[])r(o.table,o.columns)}let n={};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){n[s]=["parent_pg_row_id",i];continue}if(o.get("pg_row_id")===!1){n[s]="pg_row_id";continue}if(o.get("external_id")===!1){n[s]="external_id";continue}}return n}function Jb(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Ni(t){let e=Dd(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,s])=>{let o=Array.isArray(s)?`[${s.map(i=>`'${i}'`).join(", ")}]`:`'${s}'`;return` ${Jb(n)}: ${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 Li=j(()=>{});function Yb(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function qd(t,e,r){let n=await r(t,{headers:{Accept:"application/json",Authorization:`Bearer ${e}`}});if(!n.ok)throw new Error(`types-gen: GET ${t} failed (${n.status} ${n.statusText})`);return n.json()}async function ir(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=Yb(t.baseUrl),n=await qd(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let s=xs(n),o=[Zb,"// ----- Record shapes (from /v1/catalog/records) -----",s,"// ----- Keyset seek keys (derived from column nullability) -----",Ni(n)];if(!t.recordsOnly){let i=await qd(r.openapi,t.token,e),a=await $s(i,t.openApi);o.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return o.join(`
18
+ `)}function qd(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 Zb(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Ni(t){let e=qd(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` ${Zb(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 Li=j(()=>{});function Xb(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Bd(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 an(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let n=Xb(t.baseUrl),r=await Bd(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=xs(r),o=[Qb,"// ----- Record shapes (from /v1/catalog/records) -----",s,"// ----- Keyset seek keys (derived from column nullability) -----",Ni(r)];if(!t.recordsOnly){let i=await Bd(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
- `}var Zb,Md=j(()=>{Ai();Li();Li();Ai();Zb=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
23
- `)});var ji=j(()=>{vs();Ad();Od();jd();Md()});import{homedir as Qb}from"node:os";import{join as zd}from"node:path";import{promises as Ui}from"node:fs";function Xe(t){return t.trim().replace(/\/+$/,"")}function Ts(){let t=process.env.TURBOBASE_HOME??zd(Qb(),".turbobase");return{dir:t,file:zd(t,"credentials")}}function Bd(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function pn(){let{file:t}=Ts(),e;try{let o=await Ui.readFile(t,"utf8");e=JSON.parse(o)}catch(o){if(o.code==="ENOENT")return{tenants:{}};throw o}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let o={};for(let[a,l]of Object.entries(r.tenants))Bd(l)&&(o[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof r.active=="string"&&o[r.active]?r.active:void 0,tenants:o}}let n={};for(let[o,i]of Object.entries(r))Bd(i)&&(n[o]={token:i.token,updatedAt:i.updatedAt});return{active:Xb(n),tenants:n}}function Xb(t){let e,r="";for(let[n,s]of Object.entries(t))(!e||String(s.updatedAt)>r)&&(e=n,r=String(s.updatedAt));return e}async function Di(t){let{dir:e,file:r}=Ts();await Ui.mkdir(e,{recursive:!0,mode:448}),await Ui.writeFile(r,JSON.stringify(t,null,2)+`
24
- `,{mode:384})}async function Fd(t){let e=Xe(t.baseUrl),r=await pn(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await Di(r),{baseUrl:e,token:t.token,updatedAt:n}}async function ut(t){let e=await pn();if(t){let o=Xe(t),i=e.tenants[o];return i?{baseUrl:o,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let s=e.tenants[n];return{baseUrl:n,token:s.token,updatedAt:s.updatedAt}}async function Rs(t){let e=Xe(t),r=await pn(),n=r.tenants[e];return n?(r.active=e,await Di(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function qi(t){let e=await pn(),r=t?Xe(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!r||!e.tenants[r])return null;if(delete e.tenants[r],e.active===r){let n=Object.keys(e.tenants);e.active=n.length===1?n[0]:void 0}return await Di(e),r}async function Rt(){let t=await pn();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var hn=j(()=>{});function Hd(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,r=typeof e.message=="string"&&e.message?e.message:e.error;return typeof r=="string"?r.trim().slice(0,200):""}function Kd(t){return t.replace(/\/+$/,"")}function Mi(t=process.env){let e=(t[xr]??"").trim(),r=(t[Es]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function zi(t){let e;try{e=new URL(t)}catch{return`${xr} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let r=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&r?null:`${xr} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var X,F,xr,Es,fn,Et=j(()=>{X=class extends Error{constructor(r,n,s){super(r);this.status=n;this.body=s;this.name="ApiError"}status;body};F=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Kd(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n,s){let o=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...s??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Hd(a);throw new X(`${e} ${r} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let s=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${s}`)).events??[]}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],roles:e.roles??[]})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},xr="TURBOBASE_REGISTRY_URL",Es="TURBOBASE_REGISTRY_TOKEN";fn=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Kd(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let s={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(s["Content-Type"]="application/json");let o=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:s,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Hd(a);throw new X(`${e} ${r} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function ty(t){if(ey.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function ny(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:ty(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||oy(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:ry,loader:"js"}))}}}function oy(t){let e=t.startsWith("node:")?t.slice(5):t;return sy.has(e.split("/")[0])}function Vd(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function iy(){try{return(await import("esbuild")).build}catch(t){throw Vd("esbuild",t)}}async function ay(){try{return(await import("isolated-vm")).default}catch(t){throw Vd("isolated-vm",t)}}async function Ps(t){let e=await iy(),r;try{r=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[ny()]})}catch(n){let o=n.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Bi(o||`extension bundle failed: ${String(n)}`)}return r.outputFiles?.[0]?.text??""}async function mn(t,e,r={}){let n=r.timeoutMs??200,s=r.memoryLimitMb??16,o=r.member??"run",i={patches:[],logs:[]},a=await ay(),l=new a.Isolate({memoryLimit:s});try{let u=await l.createContext(),p=u.global,g=new a.Callback(O=>{let D=JSON.parse(String(O));i.rejection||(i.rejection=D)}),$=new a.Callback(O=>{i.patches.push(JSON.parse(String(O)))}),v=new a.Callback(O=>{let D=JSON.parse(String(O));i.logs.push(D)}),S=new a.Callback(O=>{i.result=JSON.parse(String(O))});await p.set("__tb_reject",g),await p.set("__tb_patch",$),await p.set("__tb_log",v),await p.set("__tb_result",S),await p.set("__tb_ctx_json",JSON.stringify(ly(e)));let T=cy(t,o),P=await(await l.compileScript(T)).run(u,{timeout:n,promise:!0});return o==="when"?{effects:i,whenResult:!!P}:{effects:i}}finally{l.isDisposed||l.dispose()}}function ly(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function cy(t,e){return`
22
+ `}var Qb,Fd=j(()=>{Ai();Li();Li();Ai();Qb=["/**"," * GENERATED by `turbobase project types` (@turbobase/extensions). DO NOT EDIT."," *"," * Record shapes from /v1/catalog/records + PostgREST operations from"," * /v1/catalog/openapi.json, RLS-scoped to the token used to generate this."," */","","/* eslint-disable */"].join(`
23
+ `)});var ji=j(()=>{vs();Od();jd();Md();Fd()});import{homedir as ey}from"node:os";import{join as Hd}from"node:path";import{promises as Di}from"node:fs";function Qe(t){return t.trim().replace(/\/+$/,"")}function Ts(){let t=process.env.TURBOBASE_HOME??Hd(ey(),".turbobase");return{dir:t,file:Hd(t,"credentials")}}function Kd(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function pr(){let{file:t}=Ts(),e;try{let o=await Di.readFile(t,"utf8");e=JSON.parse(o)}catch(o){if(o.code==="ENOENT")return{tenants:{}};throw o}if(!e||typeof e!="object")return{tenants:{}};let n=e;if(n.tenants&&typeof n.tenants=="object"){let o={};for(let[a,l]of Object.entries(n.tenants))Kd(l)&&(o[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof n.active=="string"&&o[n.active]?n.active:void 0,tenants:o}}let r={};for(let[o,i]of Object.entries(n))Kd(i)&&(r[o]={token:i.token,updatedAt:i.updatedAt});return{active:ty(r),tenants:r}}function ty(t){let e,n="";for(let[r,s]of Object.entries(t))(!e||String(s.updatedAt)>n)&&(e=r,n=String(s.updatedAt));return e}async function Ui(t){let{dir:e,file:n}=Ts();await Di.mkdir(e,{recursive:!0,mode:448}),await Di.writeFile(n,JSON.stringify(t,null,2)+`
24
+ `,{mode:384})}async function Vd(t){let e=Qe(t.baseUrl),n=await pr(),r=new Date().toISOString();return n.tenants[e]={token:t.token,updatedAt:r},n.active=e,await Ui(n),{baseUrl:e,token:t.token,updatedAt:r}}async function ut(t){let e=await pr();if(t){let o=Qe(t),i=e.tenants[o];return i?{baseUrl:o,token:i.token,updatedAt:i.updatedAt}:null}let n=Object.keys(e.tenants),r=e.active&&e.tenants[e.active]?e.active:n.length===1?n[0]:void 0;if(!r)return null;let s=e.tenants[r];return{baseUrl:r,token:s.token,updatedAt:s.updatedAt}}async function Rs(t){let e=Qe(t),n=await pr(),r=n.tenants[e];return r?(n.active=e,await Ui(n),{baseUrl:e,token:r.token,updatedAt:r.updatedAt}):null}async function Mi(t){let e=await pr(),n=t?Qe(t):e.active&&e.tenants[e.active]?e.active:Object.keys(e.tenants).length===1?Object.keys(e.tenants)[0]:void 0;if(!n||!e.tenants[n])return null;if(delete e.tenants[n],e.active===n){let r=Object.keys(e.tenants);e.active=r.length===1?r[0]:void 0}return await Ui(e),n}async function Rt(){let t=await pr();return Object.entries(t.tenants).map(([e,n])=>({baseUrl:e,token:n.token,updatedAt:n.updatedAt}))}var hr=j(()=>{});function Gd(t){if(typeof t=="string")return t.trim().slice(0,200);if(!t||typeof t!="object")return"";let e=t,n=typeof e.message=="string"&&e.message?e.message:e.error;return typeof n=="string"?n.trim().slice(0,200):""}function Wd(t){return t.replace(/\/+$/,"")}function zi(t=process.env){let e=(t[Tn]??"").trim(),n=(t[Es]??"").trim();return!e||!n?null:{registryUrl:e,token:n}}function qi(t){let e;try{e=new URL(t)}catch{return`${Tn} is not a valid URL: ${t}`}if(e.protocol==="https:")return null;let n=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname==="[::1]";return e.protocol==="http:"&&n?null:`${Tn} must be https:// (got ${e.protocol}//${e.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var Q,F,Tn,Es,fr,Et=j(()=>{Q=class extends Error{constructor(n,r,s){super(n);this.status=r;this.body=s;this.name="ApiError"}status;body};F=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Wd(e.baseUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r,s){let o=await this.fetchImpl(`${this.baseUrl}${n}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...r!==void 0?{"Content-Type":"application/json"}:{},...s??{}},...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Gd(a);throw new Q(`${e} ${n} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let n=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${n}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}async proposals(e={}){let n=new URLSearchParams;e.status?.length&&n.set("status",e.status.join(",")),e.provenance?.length&&n.set("provenance",e.provenance.join(",")),e.recordType&&n.set("recordType",e.recordType),e.source&&n.set("source",e.source),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString();return(await this.request("GET",`/v1/extensions/proposals${r?`?${r}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,n){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,n?{reason:n}:{})}async logs(e,n){let r=n&&n>0?`?limit=${Math.floor(n)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${r}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,n={}){let r=new URLSearchParams;n.since&&r.set("since",n.since),n.limit&&n.limit>0&&r.set("limit",String(Math.floor(n.limit)));let s=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${s}`)).events??[]}async platformEvents(e={}){let n=new URLSearchParams;e.subsystem&&n.set("subsystem",e.subsystem),e.severity&&n.set("severity",e.severity),e.code&&n.set("code",e.code),e.since&&n.set("since",e.since),e.after&&n.set("after",e.after),e.correlationId&&n.set("correlationId",e.correlationId),e.extension&&n.set("extension",e.extension),e.conduit&&n.set("conduit",e.conduit),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/events${r}`)).events??[]}async bindings(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status),e.limit&&e.limit>0&&n.set("limit",String(Math.floor(e.limit)));let r=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/bindings${r}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,n,r={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:n,...r.note?{note:r.note}:{},...r.meta?{meta:r.meta}:{}},r.proposalId?{"x-proposal-id":r.proposalId}:void 0)}learningsPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.section&&n.set("section",e.section),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false");let r=n.toString();return this.request("GET",`/v1/learnings/pending${r?`?${r}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let n=new URLSearchParams;e.app&&n.set("app",e.app),e.limit!==void 0&&n.set("limit",String(e.limit)),e.group===!1&&n.set("group","false"),e.reapply&&n.set("reapply","true");let r=n.toString();return this.request("GET",`/v1/learnings/rules-pending${r?`?${r}`:""}`)}rulesPush(e,n={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...n.app?{app:n.app}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.group===!1?{group:!1}:{},...n.reapply?{reapply:!0}:{}})}skillsList(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/skills${r?`?${r}`:""}`)}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let n=new URLSearchParams;e.status&&n.set("status",e.status);let r=n.toString();return this.request("GET",`/v1/docs${r?`?${r}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,n={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...n.app?{app:n.app}:{},...n.section?{section:n.section}:{},...n.limit!==void 0?{limit:n.limit}:{},...n.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,n={}){return this.request("POST","/v1/config/apply",{bundle:e,...n.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],roles:e.roles??[]})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,n){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(n)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,n){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,n)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,n){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:n.files,target:n.target,...n.approvedBy?{approvedBy:n.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Tn="TURBOBASE_REGISTRY_URL",Es="TURBOBASE_REGISTRY_TOKEN";fr=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Wd(e.registryUrl),this.token=e.token;let n=e.fetchImpl??fetch;if(typeof n!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=n}async request(e,n,r){let s={Authorization:`Bearer ${this.token}`,Accept:"application/json"};r!==void 0&&(s["Content-Type"]="application/json");let o=await this.fetchImpl(`${this.registryUrl}${n}`,{method:e,headers:s,...r!==void 0?{body:JSON.stringify(r)}:{}}),i=await o.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!o.ok){let l=Gd(a);throw new Q(`${e} ${n} \u2192 ${o.status}${l?`: ${l}`:""}`,o.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,n){let r=n?`?version=${encodeURIComponent(n)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${r}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});function ry(t){if(ny.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function oy(){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},e=>e.kind==="entry-point"?null:ry(e.path)?{path:e.path,namespace:"extension-sdk"}:{errors:[{text:`extension ${e.path.startsWith(".")||e.path.startsWith("/")?`imports a sibling/local file ('${e.path}')`:e.path.startsWith("node:")||ay(e.path)?`imports a Node builtin ('${e.path}')`:`imports an external module ('${e.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed import is the SDK factory ('@/sync/hooks' or '@turbobase/extensions'); inline everything else into the extension file.`}]}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:sy,loader:"js"}))}}}function ay(t){let e=t.startsWith("node:")?t.slice(5):t;return iy.has(e.split("/")[0])}function Jd(t,e){return new Error(`'${t}' is not installed \u2014 \`turbobase ext test\` and \`turbobase ext replay\` compile and execute extensions locally, which needs the native sandbox extras. Run \`turbobase ext extras install\` once, then re-run this command. (cause: ${e instanceof Error?e.message:String(e)})`)}async function ly(){try{return(await import("esbuild")).build}catch(t){throw Jd("esbuild",t)}}async function cy(){try{return(await import("isolated-vm")).default}catch(t){throw Jd("isolated-vm",t)}}async function Ps(t){let e=await ly(),n;try{n=await e({stdin:{contents:t,loader:"ts",resolveDir:process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[oy()]})}catch(r){let o=r.errors?.map(i=>i.text).filter(Boolean).join("; ");throw new Bi(o||`extension bundle failed: ${String(r)}`)}return n.outputFiles?.[0]?.text??""}async function mr(t,e,n={}){let r=n.timeoutMs??200,s=n.memoryLimitMb??16,o=n.member??"run",i={patches:[],logs:[]},a=await cy(),l=new a.Isolate({memoryLimit:s});try{let u=await l.createContext(),p=u.global,g=new a.Callback(O=>{let U=JSON.parse(String(O));i.rejection||(i.rejection=U)}),$=new a.Callback(O=>{i.patches.push(JSON.parse(String(O)))}),v=new a.Callback(O=>{let U=JSON.parse(String(O));i.logs.push(U)}),S=new a.Callback(O=>{i.result=JSON.parse(String(O))});await p.set("__tb_reject",g),await p.set("__tb_patch",$),await p.set("__tb_log",v),await p.set("__tb_result",S),await p.set("__tb_ctx_json",JSON.stringify(dy(e)));let T=uy(t,o),P=await(await l.compileScript(T)).run(u,{timeout:r,promise:!0});return o==="when"?{effects:i,whenResult:!!P}:{effects:i}}finally{l.isDisposed||l.dispose()}}function dy(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null}}function uy(t,e){return`
25
25
  "use strict";
26
26
  (async () => {
27
27
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -90,16 +90,16 @@ ${s.join(`
90
90
  ${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":""}
91
91
  return ${e==="when"?"out":"undefined"};
92
92
  })()
93
- `}var ey,ry,Bi,sy,Fi=j(()=>{ey=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);ry=`
93
+ `}var ny,sy,Bi,iy,Fi=j(()=>{ny=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit"]);sy=`
94
94
  export const defineHook = (def) => def;
95
95
  export const defineConduit = (def) => def;
96
96
  export default defineHook;
97
- `,Bi=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};sy=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 Hi}from"node:fs";import{join as dy}from"node:path";function uy(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 py(t,e,r){let n=e.name??r,s=e.expect??"pass";try{let{effects:o}=await mn(t,uy(e.context)),i=o.rejection?"reject":"pass";return{name:n,expected:s,observed:i,pass:i===s,rejection:o.rejection,patchCount:o.patches.length}}catch(o){return{name:n,expected:s,observed:"pass",pass:!1,patchCount:0,error:o instanceof Error?o.message:String(o)}}}async function As(t,e){let r=await Ps(t),n=[];for(let s=0;s<e.length;s+=1)n.push(await py(r,e[s],`sample[${s}]`));return n}async function gn(t){let e;try{e=await Hi.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let s=await Hi.readFile(dy(t,n),"utf8"),o=JSON.parse(s),i=Array.isArray(o)?o:[o];for(let a=0;a<i.length;a+=1){let l=i[a];r.push({file:n,fixture:{...l,name:l.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function bn(t){return Hi.readFile(t,"utf8")}var Ki=j(()=>{Fi()});function zt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function Fy(t){let e=t.recordType;if(!e)throw new nt("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",s=t.source,o=s?`
98
- source: ${JSON.stringify(s)},`:"",i,a;if(n==="blank")i=`
97
+ `,Bi=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};iy=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 Hi}from"node:fs";import{join as py}from"node:path";function hy(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 fy(t,e,n){let r=e.name??n,s=e.expect??"pass";try{let{effects:o}=await mr(t,hy(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 As(t,e){let n=await Ps(t),r=[];for(let s=0;s<e.length;s+=1)r.push(await fy(n,e[s],`sample[${s}]`));return r}async function gr(t){let e;try{e=await Hi.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 Hi.readFile(py(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 br(t){return Hi.readFile(t,"utf8")}var Ki=j(()=>{Fi()});function qt(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function Ky(t){let e=t.recordType;if(!e)throw new rt("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
+ 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
101
101
  // with ctx.patch({...}); observe with ctx.log('info', '...').
102
- },`,a="custom";else if(n==="require-field"){let $=t.field;if(!$)throw new nt("require-field template needs --field=<name>");i=`
102
+ },`,a="custom";else if(r==="require-field"){let $=t.field;if(!$)throw new rt("require-field template needs --field=<name>");i=`
103
103
  run: (ctx) => {
104
104
  const v = ctx.payload[${JSON.stringify($)}];
105
105
  if (v === undefined || v === null || v === '') {
@@ -109,7 +109,7 @@ export default defineHook;
109
109
  message: ${JSON.stringify(`${$} is required`)},
110
110
  });
111
111
  }
112
- },`,a=`require-field-${$}`}else if(n==="enforce-format"){let $=t.field;if(!$)throw new nt("enforce-format template needs --field=<name>");if(!t.regex)throw new nt("enforce-format template needs --regex=<pattern>");i=`
112
+ },`,a=`require-field-${$}`}else if(r==="enforce-format"){let $=t.field;if(!$)throw new rt("enforce-format template needs --field=<name>");if(!t.regex)throw new rt("enforce-format template needs --regex=<pattern>");i=`
113
113
  run: (ctx) => {
114
114
  const v = ctx.payload[${JSON.stringify($)}];
115
115
  if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
@@ -119,8 +119,8 @@ 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: ${n}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${zt(t.regex).slice(0,24)}`:""}`,p=`/**
123
- * ${t.description??`${a} on ${e}.${r}`}
122
+ },`,a=`enforce-format-${$}`}else throw new rt(`unsupported template: ${r}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${qt(t.regex).slice(0,24)}`:""}`,p=`/**
123
+ * ${t.description??`${a} on ${e}.${n}`}
124
124
  *
125
125
  * Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
126
126
  * \`turbobase ext deploy\`.
@@ -130,10 +130,10 @@ import { defineHook } from '@turbobase/extensions';
130
130
  export default defineHook<Record<string, unknown>>({
131
131
  id: ${JSON.stringify(l)},
132
132
  recordType: ${JSON.stringify(e)},
133
- event: ${JSON.stringify(r)},${o}${i}
133
+ event: ${JSON.stringify(n)},${o}${i}
134
134
  });
135
- `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:p}}function Hy(t){let e=t.recordType;if(!e)throw new nt("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new nt("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new nt("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new nt(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let s=t.toRecordType??e,o=t.event??"after_canonicalize_inbound",i=t.id??`${zt(r)}2${zt(n)}:${zt(e)}`,l=`/**
136
- * ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${s} (${o}).`}
135
+ `;return{relativePath:`hooks/${e}/${n}.${a}.ts`,content:p}}function Vy(t){let e=t.recordType;if(!e)throw new rt("record type is required (e.g. --record=order)");let n=t.source;if(!n)throw new rt("--source is required (the origin source, e.g. --source=shopify)");let r=t.to;if(!r)throw new rt("--to is required (the target source, e.g. --to=netsuite)");if(n===r)throw new rt(`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??`${qt(n)}2${qt(r)}:${qt(e)}`,l=`/**
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
139
139
  * transform: read ctx, RETURN a { patch, createdFrom } \u2014 never call a source API
@@ -149,12 +149,12 @@ export default defineConduit<Record<string, unknown>>({
149
149
  id: ${JSON.stringify(i)},
150
150
  on: ${JSON.stringify(o)},
151
151
  from: {
152
- source: ${JSON.stringify(r)},
152
+ source: ${JSON.stringify(n)},
153
153
  recordType: ${JSON.stringify(e)},
154
154
  // when: (ctx) => true, // optional gate on the inbound payload
155
155
  },
156
156
  to: {
157
- source: ${JSON.stringify(n)},
157
+ source: ${JSON.stringify(r)},
158
158
  recordType: ${JSON.stringify(s)},
159
159
  },
160
160
  mode: 'dual-bind',
@@ -167,7 +167,7 @@ export default defineConduit<Record<string, unknown>>({
167
167
  // ...mapped canonical fields...
168
168
  },
169
169
  createdFrom: {
170
- source: ${JSON.stringify(r)},
170
+ source: ${JSON.stringify(n)},
171
171
  recordType: ${JSON.stringify(e)},
172
172
  externalId: ctx.externalId,
173
173
  },
@@ -175,19 +175,19 @@ export default defineConduit<Record<string, unknown>>({
175
175
  },
176
176
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
177
177
  });
178
- `;return{relativePath:`conduits/${zt(r)}-${zt(e)}-to-${zt(n)}-${zt(s)}.ts`,content:l}}function Bt(t,e){let r=Ky[t];if(!r)throw new nt(`unknown extension kind '${t}'. Scaffoldable kinds: ${yu.join(", ")}.`);return r(e)}var yu,nt,Ky,Ls=j(()=>{yu=["hook","conduit"];nt=class extends Error{};Ky={hook:Fy,conduit:Hy}});function Hv(t){let e=2166136261;for(let r=0;r<t.length;r+=1)e^=t.charCodeAt(r),e=Math.imul(e,16777619)>>>0;return e>>>0}function Kv(t){return Ip[Hv(t)%Ip.length]}function Vv(t){let e=t.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return e.length===0?t.trim().slice(0,1).toUpperCase()||"\u2022":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[1][0]).toUpperCase()}function Cp(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Op(t,e){let[r,n]=Kv(t),s=Cp(Vv(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Cp(e)}">
178
+ `;return{relativePath:`conduits/${qt(n)}-${qt(e)}-to-${qt(r)}-${qt(s)}.ts`,content:l}}function Bt(t,e){let n=Gy[t];if(!n)throw new rt(`unknown extension kind '${t}'. Scaffoldable kinds: ${ku.join(", ")}.`);return n(e)}var ku,rt,Gy,Ls=j(()=>{ku=["hook","conduit"];rt=class extends Error{};Gy={hook:Ky,conduit:Vy}});var ca,da=j(()=>{ca=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function Vv(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 Gv(t){return Np[Vv(t)%Np.length]}function Wv(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 Lp(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function jp(t,e){let[n,r]=Gv(t),s=Lp(Wv(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Lp(e)}">
179
179
  <defs>
180
180
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
181
- <stop offset="0" stop-color="${r}"/>
182
- <stop offset="1" stop-color="${n}"/>
181
+ <stop offset="0" stop-color="${n}"/>
182
+ <stop offset="1" stop-color="${r}"/>
183
183
  </linearGradient>
184
184
  </defs>
185
185
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
186
186
  <text x="32" y="34" text-anchor="middle" dominant-baseline="central" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="26" font-weight="600" fill="#ffffff">${s}</text>
187
187
  </svg>
188
- `}var Ip,Np=j(()=>{Ip=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Lp,jp=j(()=>{Lp=Object.freeze({instance:!0,platform:!0,share:"inherit"})});var Qp={};xd(Qp,{CN_UTIL:()=>Bp,COMPONENTS_JSON:()=>zp,MAIN_TSX:()=>Hp,STYLES_CSS:()=>Kp,TSCONFIG:()=>Mp,TURBOBASE_CLIENT:()=>Up,UI_BADGE:()=>Wp,UI_BUTTON:()=>Vp,UI_CARD:()=>Gp,UI_INPUT:()=>Yp,UI_LABEL:()=>Zp,UI_TABLE:()=>Jp,indexHtml:()=>Fp,instanceOriginFromEnv:()=>Xv,packageJson:()=>Dp,scaffoldAppFiles:()=>tk,starterApp:()=>rk,viteConfig:()=>qp});function Wv(t){let e={name:t.title},r=(t.description??"").trim().slice(0,Gv);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Lp},JSON.stringify(e,null,2)+`
189
- `}function Dp(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:Jv},dependencies:{react:"^18.3.1","react-dom":"^18.3.1","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
190
- `}function Qv(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}function Xv(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function qp(t,e={}){let r=Qv(e.instanceOrigin);return`import { defineConfig } from 'vite';
188
+ `}var Np,Dp=j(()=>{Np=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Qp={};Ed(Qp,{CN_UTIL:()=>Fp,COMPONENTS_JSON:()=>Bp,MAIN_TSX:()=>Kp,STYLES_CSS:()=>Vp,TSCONFIG:()=>qp,TURBOBASE_CLIENT:()=>Up,UI_BADGE:()=>Jp,UI_BUTTON:()=>Gp,UI_CARD:()=>Wp,UI_INPUT:()=>Zp,UI_LABEL:()=>Xp,UI_TABLE:()=>Yp,indexHtml:()=>Hp,instanceOriginFromEnv:()=>tk,packageJson:()=>Mp,scaffoldAppFiles:()=>rk,starterApp:()=>sk,viteConfig:()=>zp});function Yv(t){let e={name:t.title},n=(t.description??"").trim().slice(0,Jv);return n&&(e.description=n),e.icon="favicon.svg",e.learnings={...ca},JSON.stringify(e,null,2)+`
189
+ `}function Mp(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:Zv},dependencies:{react:"^18.3.1","react-dom":"^18.3.1","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^18.3.3","@types/react-dom":"^18.3.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
190
+ `}function ek(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="http:"&&e.protocol!=="https:"?null:e.origin}catch{return null}}function tk(t=process.env){let e=(t.TENANT_SLUG??"").trim(),n=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!n))return`https://${e}.${n}`}function zp(t,e={}){let n=ek(e.instanceOrigin);return`import { defineConfig } from 'vite';
191
191
  import { fileURLToPath, URL } from 'node:url';
192
192
  import react from '@vitejs/plugin-react';
193
193
  // Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
@@ -206,8 +206,8 @@ import tailwindcss from '@tailwindcss/vite';
206
206
  // you sign in, and the cookies land on localhost:3000. Override the targets
207
207
  // with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
208
208
  // them at boot; restart the dev server after changing one).
209
- const TENANT = process.env.SUPABASE_URL || '${r??Yv}'; // /rest + the Realtime WS
210
- const API = process.env.TURBOBASE_API_URL || '${r??Zv}'; // /v1, /auth, /login, /_app
209
+ const TENANT = process.env.SUPABASE_URL || '${n??Xv}'; // /rest + the Realtime WS
210
+ const API = process.env.TURBOBASE_API_URL || '${n??Qv}'; // /v1, /auth, /login, /_app
211
211
 
212
212
  // Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
213
213
  // this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
@@ -245,7 +245,7 @@ export default defineConfig({
245
245
  },
246
246
  build: { outDir: 'dist' },
247
247
  });
248
- `}function Fp(t){return`<!doctype html>
248
+ `}function Hp(t){return`<!doctype html>
249
249
  <html lang="en">
250
250
  <head>
251
251
  <meta charset="UTF-8" />
@@ -258,7 +258,7 @@ export default defineConfig({
258
258
  <script type="module" src="/src/main.tsx"></script>
259
259
  </body>
260
260
  </html>
261
- `}function tk(t){return{"package.json":Dp(t.slug),"vite.config.ts":qp(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":ek,"tsconfig.json":Mp,"index.html":Fp(t.title),"public/turbobase.json":Wv(t),"public/favicon.svg":Op(t.slug,t.title),"src/main.tsx":Hp,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Up,"src/styles.css":Kp,"components.json":zp,"src/lib/utils.ts":Bp,"src/components/ui/button.tsx":Vp,"src/components/ui/card.tsx":Gp,"src/components/ui/badge.tsx":Wp,"src/components/ui/table.tsx":Jp,"src/components/ui/input.tsx":Yp,"src/components/ui/label.tsx":Zp,"README.md":`# ${t.title}
261
+ `}function rk(t){return{"package.json":Mp(t.slug),"vite.config.ts":zp(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":nk,"tsconfig.json":qp,"index.html":Hp(t.title),"public/turbobase.json":Yv(t),"public/favicon.svg":jp(t.slug,t.title),"src/main.tsx":Kp,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":Up,"src/styles.css":Vp,"components.json":Bp,"src/lib/utils.ts":Fp,"src/components/ui/button.tsx":Gp,"src/components/ui/card.tsx":Wp,"src/components/ui/badge.tsx":Jp,"src/components/ui/table.tsx":Yp,"src/components/ui/input.tsx":Zp,"src/components/ui/label.tsx":Xp,"README.md":`# ${t.title}
262
262
 
263
263
  \`\`\`sh
264
264
  npm install
@@ -279,7 +279,7 @@ every read comes back "permission denied", which looks like an RLS problem.
279
279
 
280
280
  \`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
281
281
  live access token and is gitignored \u2014 keep it that way.
282
- `}}function rk(t){return`import React from 'react';
282
+ `}}function sk(t){return`import React from 'react';
283
283
  import { Loader2, Trash2 } from 'lucide-react';
284
284
 
285
285
  import { select, write, del } from '@/lib/turbobase';
@@ -504,7 +504,7 @@ export default function App() {
504
504
  </main>
505
505
  );
506
506
  }
507
- `}var Gv,Up,Tn,Jv,Yv,Zv,ek,Mp,zp,Bp,Hp,Kp,Vp,Gp,Wp,Jp,Yp,Zp,Xp=j(()=>{Np();jp();Gv=200;Up=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
507
+ `}var Jv,Up,Tr,Zv,Xv,Qv,nk,qp,Bp,Fp,Kp,Vp,Gp,Wp,Jp,Yp,Zp,Xp,eh=j(()=>{Dp();da();Jv=200;Up=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
508
508
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
509
509
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
510
510
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -1521,7 +1521,7 @@ export async function selectPage<T = unknown>(
1521
1521
  }
1522
1522
  return { rows, nextCursor };
1523
1523
  }
1524
- `,Tn="src/types.ts",Jv=`turbobase project types -o ${Tn} || node -e "if(require('node:fs').existsSync('${Tn}')){console.error('turbobase: could not refresh ${Tn} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Tn} is missing. It is generated from the instance catalog and gitignored, so a fresh checkout has no copy. Run: turbobase auth login --base-url <your-instance> --token tb_pat_... , then turbobase project types -o ${Tn}');process.exit(1)}"`;Yv="http://localhost:54331",Zv="http://localhost:4100";ek=`node_modules/
1524
+ `,Tr="src/types.ts",Zv=`turbobase project types -o ${Tr} || node -e "if(require('node:fs').existsSync('${Tr}')){console.error('turbobase: could not refresh ${Tr} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Tr} is missing. It is generated from the instance catalog and gitignored, so a fresh checkout has no copy. Run: turbobase auth login --base-url <your-instance> --token tb_pat_... , then turbobase project types -o ${Tr}');process.exit(1)}"`;Xv="http://localhost:54331",Qv="http://localhost:4100";nk=`node_modules/
1525
1525
  dist/
1526
1526
  build/
1527
1527
 
@@ -1533,9 +1533,9 @@ build/
1533
1533
  !.env.example
1534
1534
 
1535
1535
  .DS_Store
1536
- `,Mp=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
1537
- `,zp=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
1538
- `,Bp=`import { clsx, type ClassValue } from 'clsx';
1536
+ `,qp=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,baseUrl:".",paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
1537
+ `,Bp=`${JSON.stringify({$schema:"https://ui.shadcn.com/schema.json",style:"new-york",rsc:!1,tsx:!0,tailwind:{config:"",css:"src/styles.css",baseColor:"neutral",cssVariables:!0,prefix:""},aliases:{components:"@/components",utils:"@/lib/utils",ui:"@/components/ui",lib:"@/lib",hooks:"@/hooks"},iconLibrary:"lucide"},null,2)}
1538
+ `,Fp=`import { clsx, type ClassValue } from 'clsx';
1539
1539
  import { twMerge } from 'tailwind-merge';
1540
1540
 
1541
1541
  /**
@@ -1549,7 +1549,7 @@ import { twMerge } from 'tailwind-merge';
1549
1549
  export function cn(...inputs: ClassValue[]) {
1550
1550
  return twMerge(clsx(inputs));
1551
1551
  }
1552
- `;Hp=`import React from 'react';
1552
+ `;Kp=`import React from 'react';
1553
1553
  import { createRoot } from 'react-dom/client';
1554
1554
  import App from './App';
1555
1555
  import './styles.css';
@@ -1559,7 +1559,7 @@ createRoot(document.getElementById('root')!).render(
1559
1559
  <App />
1560
1560
  </React.StrictMode>,
1561
1561
  );
1562
- `,Kp=`@import 'tailwindcss';
1562
+ `,Vp=`@import 'tailwindcss';
1563
1563
  @import 'tw-animate-css';
1564
1564
 
1565
1565
  /* Inter, self-hosted \u2014 the design system's font.
@@ -1647,7 +1647,7 @@ createRoot(document.getElementById('root')!).render(
1647
1647
  transition-duration: 0.01ms !important;
1648
1648
  }
1649
1649
  }
1650
- `,Vp=`import * as React from 'react';
1650
+ `,Gp=`import * as React from 'react';
1651
1651
  import { cva, type VariantProps } from 'class-variance-authority';
1652
1652
 
1653
1653
  import { cn } from '@/lib/utils';
@@ -1687,7 +1687,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
1687
1687
  Button.displayName = 'Button';
1688
1688
 
1689
1689
  export { Button, buttonVariants };
1690
- `,Gp=`import * as React from 'react';
1690
+ `,Wp=`import * as React from 'react';
1691
1691
 
1692
1692
  import { cn } from '@/lib/utils';
1693
1693
 
@@ -1725,7 +1725,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
1725
1725
  CardContent.displayName = 'CardContent';
1726
1726
 
1727
1727
  export { Card, CardHeader, CardTitle, CardDescription, CardContent };
1728
- `,Wp=`import * as React from 'react';
1728
+ `,Jp=`import * as React from 'react';
1729
1729
  import { cva, type VariantProps } from 'class-variance-authority';
1730
1730
 
1731
1731
  import { cn } from '@/lib/utils';
@@ -1760,7 +1760,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
1760
1760
  }
1761
1761
 
1762
1762
  export { Badge, badgeVariants };
1763
- `,Jp=`import * as React from 'react';
1763
+ `,Yp=`import * as React from 'react';
1764
1764
 
1765
1765
  import { cn } from '@/lib/utils';
1766
1766
 
@@ -1819,7 +1819,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
1819
1819
  TableCell.displayName = 'TableCell';
1820
1820
 
1821
1821
  export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
1822
- `,Yp=`import * as React from 'react';
1822
+ `,Zp=`import * as React from 'react';
1823
1823
 
1824
1824
  import { cn } from '@/lib/utils';
1825
1825
 
@@ -1839,7 +1839,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
1839
1839
  Input.displayName = 'Input';
1840
1840
 
1841
1841
  export { Input };
1842
- `,Zp=`import * as React from 'react';
1842
+ `,Xp=`import * as React from 'react';
1843
1843
 
1844
1844
  import { cn } from '@/lib/utils';
1845
1845
 
@@ -1856,51 +1856,51 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
1856
1856
  Label.displayName = 'Label';
1857
1857
 
1858
1858
  export { Label };
1859
- `});import*as eh from"zod/v3";import*as cr from"zod/v4-mini";function kt(t){return!!t._zod}function dr(t){let e=Object.values(t);if(e.length===0)return cr.object({});let r=e.every(kt),n=e.every(s=>!kt(s));if(r)return cr.object(t);if(n)return eh.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Kt(t,e){return kt(t)?cr.safeParse(t,e):t.safeParse(e)}async function Js(t,e){return kt(t)?await cr.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 Lr(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(s=>typeof s=="object"&&s!==null&&(s._def!==void 0||s._zod!==void 0||typeof s.parse=="function")))return dr(t)}}if(kt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function nk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function Ys(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 ${nk(e.path)}`:e.message).join(`
1860
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function th(t){return t.description}function rh(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 jr(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 r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Rn=j(()=>{});import*as c from"zod/v4";function wh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function vh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var va,nh,Gt,Qs,xe,sh,oh,gI,sk,ok,ka,Qe,En,ih,Pe,st,ot,Ae,Xs,ah,Sa,lh,ch,_a,Pn,H,$a,dh,uh,bI,eo,ik,to,ak,An,Ur,ph,lk,ck,dk,uk,pk,hk,xa,fk,mk,Ta,ro,gk,bk,no,yk,In,Cn,wk,On,Dr,vk,Nn,so,oo,io,yI,ao,lo,co,hh,fh,mh,Ra,gh,Ln,qr,bh,kk,uo,Sk,po,_k,Ea,$k,ho,xk,Tk,Rk,Ek,Pk,Ak,Ik,Ck,Ok,Nk,fo,Lk,jk,mo,Pa,Aa,Ia,Uk,Dk,qk,Ca,Mk,zk,Bk,Fk,Hk,yh,go,Kk,bo,wI,Vk,Mr,Gk,vI,jn,Wk,Oa,Jk,Yk,Zk,Qk,Xk,eS,tS,Zs,rS,nS,sS,Un,Na,oS,iS,aS,lS,cS,dS,uS,pS,hS,fS,mS,gS,bS,yS,wS,vS,kS,SS,zr,_S,$S,xS,yo,TS,RS,ES,La,PS,kI,SI,_I,$I,xI,TI,M,wa,Br=j(()=>{va="2025-11-25",nh=[va,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Gt="io.modelcontextprotocol/related-task",Qs="2.0",xe=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),sh=c.union([c.string(),c.number().int()]),oh=c.string(),gI=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),sk=c.object({ttl:c.number().optional()}),ok=c.object({taskId:c.string()}),ka=c.looseObject({progressToken:sh.optional(),[Gt]:ok.optional()}),Qe=c.object({_meta:ka.optional()}),En=Qe.extend({task:sk.optional()}),ih=t=>En.safeParse(t).success,Pe=c.object({method:c.string(),params:Qe.loose().optional()}),st=c.object({_meta:ka.optional()}),ot=c.object({method:c.string(),params:st.loose().optional()}),Ae=c.looseObject({_meta:ka.optional()}),Xs=c.union([c.string(),c.number().int()]),ah=c.object({jsonrpc:c.literal(Qs),id:Xs,...Pe.shape}).strict(),Sa=t=>ah.safeParse(t).success,lh=c.object({jsonrpc:c.literal(Qs),...ot.shape}).strict(),ch=t=>lh.safeParse(t).success,_a=c.object({jsonrpc:c.literal(Qs),id:Xs,result:Ae}).strict(),Pn=t=>_a.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"})(H||(H={}));$a=c.object({jsonrpc:c.literal(Qs),id:Xs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),dh=t=>$a.safeParse(t).success,uh=c.union([ah,lh,_a,$a]),bI=c.union([_a,$a]),eo=Ae.strict(),ik=st.extend({requestId:Xs.optional(),reason:c.string().optional()}),to=ot.extend({method:c.literal("notifications/cancelled"),params:ik}),ak=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),An=c.object({icons:c.array(ak).optional()}),Ur=c.object({name:c.string(),title:c.string().optional()}),ph=Ur.extend({...Ur.shape,...An.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),lk=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),ck=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:lk.optional(),url:xe.optional()}),c.record(c.string(),c.unknown()).optional())),dk=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()}),uk=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({tools:c.looseObject({call:xe.optional()}).optional()}).optional()}),pk=c.object({experimental:c.record(c.string(),xe).optional(),sampling:c.object({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:ck.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:dk.optional(),extensions:c.record(c.string(),xe).optional()}),hk=Qe.extend({protocolVersion:c.string(),capabilities:pk,clientInfo:ph}),xa=Pe.extend({method:c.literal("initialize"),params:hk}),fk=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:uk.optional(),extensions:c.record(c.string(),xe).optional()}),mk=Ae.extend({protocolVersion:c.string(),capabilities:fk,serverInfo:ph,instructions:c.string().optional()}),Ta=ot.extend({method:c.literal("notifications/initialized"),params:st.optional()}),ro=Pe.extend({method:c.literal("ping"),params:Qe.optional()}),gk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),bk=c.object({...st.shape,...gk.shape,progressToken:sh}),no=ot.extend({method:c.literal("notifications/progress"),params:bk}),yk=Qe.extend({cursor:oh.optional()}),In=Pe.extend({params:yk.optional()}),Cn=Ae.extend({nextCursor:oh.optional()}),wk=c.enum(["working","input_required","completed","failed","cancelled"]),On=c.object({taskId:c.string(),status:wk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Dr=Ae.extend({task:On}),vk=st.merge(On),Nn=ot.extend({method:c.literal("notifications/tasks/status"),params:vk}),so=Pe.extend({method:c.literal("tasks/get"),params:Qe.extend({taskId:c.string()})}),oo=Ae.merge(On),io=Pe.extend({method:c.literal("tasks/result"),params:Qe.extend({taskId:c.string()})}),yI=Ae.loose(),ao=In.extend({method:c.literal("tasks/list")}),lo=Cn.extend({tasks:c.array(On)}),co=Pe.extend({method:c.literal("tasks/cancel"),params:Qe.extend({taskId:c.string()})}),hh=Ae.merge(On),fh=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),mh=fh.extend({text:c.string()}),Ra=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),gh=fh.extend({blob:Ra}),Ln=c.enum(["user","assistant"]),qr=c.object({audience:c.array(Ln).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),bh=c.object({...Ur.shape,...An.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:qr.optional(),_meta:c.optional(c.looseObject({}))}),kk=c.object({...Ur.shape,...An.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:qr.optional(),_meta:c.optional(c.looseObject({}))}),uo=In.extend({method:c.literal("resources/list")}),Sk=Cn.extend({resources:c.array(bh)}),po=In.extend({method:c.literal("resources/templates/list")}),_k=Cn.extend({resourceTemplates:c.array(kk)}),Ea=Qe.extend({uri:c.string()}),$k=Ea,ho=Pe.extend({method:c.literal("resources/read"),params:$k}),xk=Ae.extend({contents:c.array(c.union([mh,gh]))}),Tk=ot.extend({method:c.literal("notifications/resources/list_changed"),params:st.optional()}),Rk=Ea,Ek=Pe.extend({method:c.literal("resources/subscribe"),params:Rk}),Pk=Ea,Ak=Pe.extend({method:c.literal("resources/unsubscribe"),params:Pk}),Ik=st.extend({uri:c.string()}),Ck=ot.extend({method:c.literal("notifications/resources/updated"),params:Ik}),Ok=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),Nk=c.object({...Ur.shape,...An.shape,description:c.optional(c.string()),arguments:c.optional(c.array(Ok)),_meta:c.optional(c.looseObject({}))}),fo=In.extend({method:c.literal("prompts/list")}),Lk=Cn.extend({prompts:c.array(Nk)}),jk=Qe.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),mo=Pe.extend({method:c.literal("prompts/get"),params:jk}),Pa=c.object({type:c.literal("text"),text:c.string(),annotations:qr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Aa=c.object({type:c.literal("image"),data:Ra,mimeType:c.string(),annotations:qr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ia=c.object({type:c.literal("audio"),data:Ra,mimeType:c.string(),annotations:qr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Uk=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()}),Dk=c.object({type:c.literal("resource"),resource:c.union([mh,gh]),annotations:qr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),qk=bh.extend({type:c.literal("resource_link")}),Ca=c.union([Pa,Aa,Ia,qk,Dk]),Mk=c.object({role:Ln,content:Ca}),zk=Ae.extend({description:c.string().optional(),messages:c.array(Mk)}),Bk=ot.extend({method:c.literal("notifications/prompts/list_changed"),params:st.optional()}),Fk=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Hk=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),yh=c.object({...Ur.shape,...An.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:Fk.optional(),execution:Hk.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),go=In.extend({method:c.literal("tools/list")}),Kk=Cn.extend({tools:c.array(yh)}),bo=Ae.extend({content:c.array(Ca).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),wI=bo.or(Ae.extend({toolResult:c.unknown()})),Vk=En.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Mr=Pe.extend({method:c.literal("tools/call"),params:Vk}),Gk=ot.extend({method:c.literal("notifications/tools/list_changed"),params:st.optional()}),vI=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),jn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Wk=Qe.extend({level:jn}),Oa=Pe.extend({method:c.literal("logging/setLevel"),params:Wk}),Jk=st.extend({level:jn,logger:c.string().optional(),data:c.unknown()}),Yk=ot.extend({method:c.literal("notifications/message"),params:Jk}),Zk=c.object({name:c.string().optional()}),Qk=c.object({hints:c.array(Zk).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()}),Xk=c.object({mode:c.enum(["auto","required","none"]).optional()}),eS=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(Ca).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),tS=c.discriminatedUnion("type",[Pa,Aa,Ia]),Zs=c.discriminatedUnion("type",[Pa,Aa,Ia,Uk,eS]),rS=c.object({role:Ln,content:c.union([Zs,c.array(Zs)]),_meta:c.record(c.string(),c.unknown()).optional()}),nS=En.extend({messages:c.array(rS),modelPreferences:Qk.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(yh).optional(),toolChoice:Xk.optional()}),sS=Pe.extend({method:c.literal("sampling/createMessage"),params:nS}),Un=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Ln,content:tS}),Na=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Ln,content:c.union([Zs,c.array(Zs)])}),oS=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),iS=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()}),aS=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()}),lS=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),cS=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()}),dS=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()}),uS=c.union([lS,cS]),pS=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()}),hS=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()}),fS=c.union([pS,hS]),mS=c.union([dS,uS,fS]),gS=c.union([mS,oS,iS,aS]),bS=En.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),gS),required:c.array(c.string()).optional()})}),yS=En.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),wS=c.union([bS,yS]),vS=Pe.extend({method:c.literal("elicitation/create"),params:wS}),kS=st.extend({elicitationId:c.string()}),SS=ot.extend({method:c.literal("notifications/elicitation/complete"),params:kS}),zr=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())}),_S=c.object({type:c.literal("ref/resource"),uri:c.string()}),$S=c.object({type:c.literal("ref/prompt"),name:c.string()}),xS=Qe.extend({ref:c.union([$S,_S]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),yo=Pe.extend({method:c.literal("completion/complete"),params:xS});TS=Ae.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),RS=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ES=Pe.extend({method:c.literal("roots/list"),params:Qe.optional()}),La=Ae.extend({roots:c.array(RS)}),PS=ot.extend({method:c.literal("notifications/roots/list_changed"),params:st.optional()}),kI=c.union([ro,xa,yo,Oa,mo,fo,uo,po,ho,Ek,Ak,Mr,go,so,io,ao,co]),SI=c.union([to,no,Ta,PS,Nn]),_I=c.union([eo,Un,Na,zr,La,oo,lo,Dr]),$I=c.union([ro,sS,vS,ES,so,io,ao,co]),xI=c.union([to,no,Yk,Ck,Tk,Gk,Bk,Nn,SS]),TI=c.union([eo,mk,TS,zk,Lk,Sk,_k,xk,bo,Kk,oo,lo,Dr]),M=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===H.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new wa(s.elicitations,r)}return new t(e,r,n)}},wa=class extends M{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(H.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Wt(t){return t==="completed"||t==="failed"||t==="cancelled"}var kh=j(()=>{});var _h,Sh,$h,wo=j(()=>{_h=Symbol("Let zodToJsonSchema decide on which parser to use"),Sh={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"?{...Sh,name:t}:{...Sh,...t}});var xh,ja=j(()=>{wo();xh=t=>{let e=$h(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Ua(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ie(t,e,r,n,s){t[e]=r,Ua(t,e,n,s)}var Jt=j(()=>{});var vo,ko=j(()=>{vo=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function we(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?vo(e,t.currentPath):e.join("/")}}var it=j(()=>{ko()});import{ZodFirstPartyTypeKind as AS}from"zod/v3";function Th(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==AS.ZodAny&&(r.items=W(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ie(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ie(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ie(r,"minItems",t.exactLength.value,t.exactLength.message,e),ie(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Da=j(()=>{Jt();$e()});function Rh(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}var qa=j(()=>{Jt()});function Eh(){return{type:"boolean"}}var Ma=j(()=>{});function So(t,e){return W(t.type._def,e)}var _o=j(()=>{$e()});var Ph,za=j(()=>{$e();Ph=(t,e)=>W(t.innerType._def,e)});function Ba(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Ba(t,e,s))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return IS(t,e)}}var IS,Fa=j(()=>{Jt();IS=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ie(r,"minimum",n.value,n.message,e);break;case"max":ie(r,"maximum",n.value,n.message,e);break}return r}});function Ah(t,e){return{...W(t.innerType._def,e),default:t.defaultValue()}}var Ha=j(()=>{$e()});function Ih(t,e){return e.effectStrategy==="input"?W(t.schema._def,e):we(e)}var Ka=j(()=>{$e();it()});function Ch(t){return{type:"string",enum:Array.from(t.values)}}var Va=j(()=>{});function Oh(t,e){let r=[W(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),W(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(o=>!!o),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,s=[];return r.forEach(o=>{if(CS(o))s.push(...o.allOf),o.unevaluatedProperties===void 0&&(n=void 0);else{let i=o;if("additionalProperties"in o&&o.additionalProperties===!1){let{additionalProperties:a,...l}=o;i=l}else n=void 0;s.push(i)}}),s.length?{allOf:s,...n}:void 0}var CS,Ga=j(()=>{$e();CS=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Nh(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Wa=j(()=>{});function $o(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":ft(r,"email",n.message,e);break;case"format:idn-email":ft(r,"idn-email",n.message,e);break;case"pattern:zod":ze(r,ht.email,n.message,e);break}break;case"url":ft(r,"uri",n.message,e);break;case"uuid":ft(r,"uuid",n.message,e);break;case"regex":ze(r,n.regex,n.message,e);break;case"cuid":ze(r,ht.cuid,n.message,e);break;case"cuid2":ze(r,ht.cuid2,n.message,e);break;case"startsWith":ze(r,RegExp(`^${Ya(n.value,e)}`),n.message,e);break;case"endsWith":ze(r,RegExp(`${Ya(n.value,e)}$`),n.message,e);break;case"datetime":ft(r,"date-time",n.message,e);break;case"date":ft(r,"date",n.message,e);break;case"time":ft(r,"time",n.message,e);break;case"duration":ft(r,"duration",n.message,e);break;case"length":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ze(r,RegExp(Ya(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&ft(r,"ipv4",n.message,e),n.version!=="v4"&&ft(r,"ipv6",n.message,e);break}case"base64url":ze(r,ht.base64url,n.message,e);break;case"jwt":ze(r,ht.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ze(r,ht.ipv4Cidr,n.message,e),n.version!=="v4"&&ze(r,ht.ipv6Cidr,n.message,e);break}case"emoji":ze(r,ht.emoji(),n.message,e);break;case"ulid":{ze(r,ht.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{ft(r,"binary",n.message,e);break}case"contentEncoding:base64":{ie(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ze(r,ht.base64,n.message,e);break}}break}case"nanoid":ze(r,ht.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Ya(t,e){return e.patternStrategy==="escape"?NS(t):t}function NS(t){let e="";for(let r=0;r<t.length;r++)OS.has(t[r])||(e+="\\"),e+=t[r];return e}function ft(t,e,r,n){t.format||t.anyOf?.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ie(t,"format",e,r,n)}function ze(t,e,r,n){t.pattern||t.allOf?.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Lh(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ie(t,"pattern",Lh(e,n),r,n)}function Lh(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,s="",o=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(o){s+=n[l],o=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(s+=n[l],s+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(s+=n[l],a=!0):s+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){s+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){s+=`(^|(?<=[\r
1861
- ]))`;continue}else if(n[l]==="$"){s+=`($|(?=[\r
1862
- ]))`;continue}}if(r.s&&n[l]==="."){s+=i?`${n[l]}\r
1863
- `:`[${n[l]}\r
1864
- ]`;continue}s+=n[l],n[l]==="\\"?o=!0:i&&n[l]==="]"?i=!1:!i&&n[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 Ja,ht,OS,xo=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:()=>(Ja===void 0&&(Ja=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ja),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-_]*$/};OS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Dn}from"zod/v3";function To(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===Dn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,s)=>({...n,[s]:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Dn.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=$o(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===Dn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Dn.ZodBranded&&t.keyType._def.type._def.typeName===Dn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=So(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var Ro=j(()=>{$e();xo();_o();it()});function jh(t,e){if(e.mapStrategy==="record")return To(t,e);let r=W(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),n=W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||we(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Za=j(()=>{$e();Ro();it()});function Uh(t){let e=t.values,n=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),s=Array.from(new Set(n.map(o=>typeof o)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:n}}var Qa=j(()=>{});function Dh(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}var Xa=j(()=>{it()});function qh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var el=j(()=>{});function zh(t,e){if(e.target==="openApi3")return Mh(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in qn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=qn[o._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.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(n.length===r.length){let s=n.filter((o,i,a)=>a.indexOf(o)===i);return{type:s.length>1?s:s[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,s)=>[...n,...s._def.values.filter(o=>!n.includes(o))],[])};return Mh(t,e)}var qn,Mh,Eo=j(()=>{$e();qn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Mh=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,s)=>W(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function Bh(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:qn[t.innerType._def.typeName],nullable:!0}:{type:[qn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=W(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var tl=j(()=>{$e();Eo()});function Fh(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Ua(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}var rl=j(()=>{Jt()});function Hh(t,e){let r=e.target==="openAi",n={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=jS(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=W(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,u||s.push(a))}s.length&&(n.required=s);let i=LS(t,e);return i!==void 0&&(n.additionalProperties=i),n}function LS(t,e){if(t.catchall._def.typeName!=="ZodNever")return W(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 jS(t){try{return t.isOptional()}catch{return!0}}var nl=j(()=>{$e()});var Kh,sl=j(()=>{$e();it();Kh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return W(t.innerType._def,e);let r=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:we(e)},r]}:we(e)}});var Vh,ol=j(()=>{$e();Vh=(t,e)=>{if(e.pipeStrategy==="input")return W(t.in._def,e);if(e.pipeStrategy==="output")return W(t.out._def,e);let r=W(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=W(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(s=>s!==void 0)}}});function Gh(t,e){return W(t.type._def,e)}var il=j(()=>{$e()});function Wh(t,e){let n={type:"array",uniqueItems:!0,items:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var al=j(()=>{Jt();$e()});function Jh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>W(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:W(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>W(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var ll=j(()=>{$e()});function Yh(t){return{not:we(t)}}var cl=j(()=>{it()});function Zh(t){return we(t)}var dl=j(()=>{it()});var Qh,ul=j(()=>{$e();Qh=(t,e)=>W(t.innerType._def,e)});import{ZodFirstPartyTypeKind as oe}from"zod/v3";var Xh,pl=j(()=>{it();Da();qa();Ma();_o();za();Fa();Ha();Ka();Va();Ga();Wa();Za();Qa();Xa();el();tl();rl();nl();sl();ol();il();Ro();al();xo();ll();cl();Eo();dl();ul();Xh=(t,e,r)=>{switch(e){case oe.ZodString:return $o(t,r);case oe.ZodNumber:return Fh(t,r);case oe.ZodObject:return Hh(t,r);case oe.ZodBigInt:return Rh(t,r);case oe.ZodBoolean:return Eh();case oe.ZodDate:return Ba(t,r);case oe.ZodUndefined:return Yh(r);case oe.ZodNull:return qh(r);case oe.ZodArray:return Th(t,r);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return zh(t,r);case oe.ZodIntersection:return Oh(t,r);case oe.ZodTuple:return Jh(t,r);case oe.ZodRecord:return To(t,r);case oe.ZodLiteral:return Nh(t,r);case oe.ZodEnum:return Ch(t);case oe.ZodNativeEnum:return Uh(t);case oe.ZodNullable:return Bh(t,r);case oe.ZodOptional:return Kh(t,r);case oe.ZodMap:return jh(t,r);case oe.ZodSet:return Wh(t,r);case oe.ZodLazy:return()=>t.getter()._def;case oe.ZodPromise:return Gh(t,r);case oe.ZodNaN:case oe.ZodNever:return Dh(r);case oe.ZodEffects:return Ih(t,r);case oe.ZodAny:return we(r);case oe.ZodUnknown:return Zh(r);case oe.ZodDefault:return Ah(t,r);case oe.ZodBranded:return So(t,r);case oe.ZodReadonly:return Qh(t,r);case oe.ZodCatch:return Ph(t,r);case oe.ZodPipeline:return Vh(t,r);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(n=>{})(e)}}});function W(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==_h)return a}if(n&&!r){let a=US(n,e);if(a!==void 0)return a}let s={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,s);let o=Xh(t,t.typeName,e),i=typeof o=="function"?W(o(),e):o;if(i&&DS(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var US,DS,$e=j(()=>{wo();pl();ko();it();US=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:vo(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),we(e)):e.$refStrategy==="seen"?we(e):void 0}},DS=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var ef=j(()=>{});var hl,fl=j(()=>{$e();ja();it();hl=(t,e)=>{let r=xh(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:W(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??we(r)}),{}):void 0,s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,o=W(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??we(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(o.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=s===void 0?n?{...o,[r.definitionPath]:n}:o:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...n,[s]:o}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var tf=j(()=>{wo();ja();Jt();ko();$e();ef();it();Da();qa();Ma();_o();za();Fa();Ha();Ka();Va();Ga();Wa();Za();Qa();Xa();el();tl();rl();nl();sl();ol();il();ul();Ro();al();xo();ll();cl();Eo();dl();pl();fl();fl()});import*as rf from"zod/v4-mini";function qS(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ml(t,e){return kt(t)?rf.toJSONSchema(t,{target:qS(e?.target),io:e?.pipeStrategy??"input"}):hl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function gl(t){let r=Vt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=jr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function bl(t,e){let r=Kt(t,e);if(!r.success)throw r.error;return r.data}var yl=j(()=>{Rn();tf()});function nf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function sf(t,e){let r={...t};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let i=r[s];nf(i)&&nf(o)?r[s]={...i,...o}:r[s]=o}return r}var MS,Po,of=j(()=>{Rn();Br();kh();yl();MS=6e4,Po=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(to,r=>{this._oncancel(r)}),this.setNotificationHandler(no,r=>{this._onprogress(r)}),this.setRequestHandler(ro,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(so,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new M(H.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(io,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(l);else{let g=l,$=new M(g.error.code,g.error.message,g.error.data);p($)}else{let g=a.type==="response"?"Response":"Error";this._onerror(new Error(`${g} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new M(H.InvalidParams,`Task not found: ${o}`);if(!Wt(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(Wt(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[Gt]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(ao,async(r,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new M(H.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(co,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new M(H.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wt(s.status))throw new M(H.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new M(H.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof M?s:new M(H.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,r,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),M.fromError(H.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,i)=>{s?.(o,i),Pn(o)||dh(o)?this._onresponse(o):Sa(o)?this._onrequest(o,i):ch(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 n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=M.fromError(H.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[Gt]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:H.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):s?.send(p).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=ih(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 g={relatedRequestId:e.id};o&&(g.relatedTask={taskId:o}),await this.notification(p,g)},sendRequest:async(p,g,$)=>{if(i.signal.aborted)throw new M(H.ConnectionClosed,"Request was cancelled");let v={...$,relatedRequestId:e.id};o&&!v.relatedTask&&(v.relatedTask={taskId:o});let S=v.relatedTask?.taskId??o;return S&&l&&await l.updateTaskStatus(S,"input_required"),await this.request(p,g,v)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:o,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async p=>{if(i.signal.aborted)return;let g={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:g,timestamp:Date.now()},s?.sessionId):await s?.send(g)},async p=>{if(i.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:H.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:g,timestamp:Date.now()},s?.sessionId):await s?.send(g)}).catch(p=>this._onerror(new Error(`Failed to send response: ${p}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,s=Number(r),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(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Pn(e))n(e);else{let i=new M(e.error.code,e.error.message,e.error.data);n(i)}return}let s=this._responseHandlers.get(r);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let o=!1;if(Pn(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,r))}}if(o||this._progressHandlers.delete(r),Pn(e))s(e);else{let i=M.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,r,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof M?i:new M(H.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Dr,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new M(H.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},Wt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new M(H.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new M(H.InternalError,`Task ${o} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof M?i:new M(H.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((u,p)=>{let g=O=>{p(O)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(O){g(O);return}n?.signal?.throwIfAborted();let $=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:$};n?.onprogress&&(this._progressHandlers.set($,n.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 S=O=>{this._responseHandlers.delete($),this._progressHandlers.delete($),this._cleanupTimeout($),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:$,reason:String(O)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(ne=>this._onerror(new Error(`Failed to send cancellation: ${ne}`)));let D=O instanceof M?O:new M(H.RequestTimeout,String(O));p(D)};this._responseHandlers.set($,O=>{if(!n?.signal?.aborted){if(O instanceof Error)return p(O);try{let D=Kt(r,O.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{S(n?.signal?.reason)});let T=n?.timeout??MS,E=()=>S(M.fromError(H.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout($,T,n?.maxTotalTimeout,E,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let O=D=>{let ne=this._responseHandlers.get($);ne?ne(D):this._onerror(new Error(`Response handler missing for side-channeled request ${$}`))};this._requestResolvers.set($,O),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(O=>{this._cleanupTimeout($),p(O)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},oo,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},lo,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},hh,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[Gt]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[Gt]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[Gt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=gl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=bl(e,s);return Promise.resolve(r(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,r){let n=gl(e);this._notificationHandlers.set(n,s=>{let o=bl(e,s);return Promise.resolve(r(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,s)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let s of n)if(s.type==="request"&&Sa(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new M(H.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,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(r.aborted){o(new M(H.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new M(H.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},r)},getTask:async s=>{let o=await n.getTask(s,r);if(!o)throw new M(H.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,i)=>{await n.storeTaskResult(s,o,i,r);let a=await n.getTask(s,r);if(a){let l=Nn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Wt(a.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,r),updateTaskStatus:async(s,o,i)=>{let a=await n.getTask(s,r);if(!a)throw new M(H.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Wt(a.status))throw new M(H.InvalidParams,`Cannot update task "${s}" from terminal status "${a.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,i,r);let l=await n.getTask(s,r);if(l){let u=Nn.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Wt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var Bn=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 Mn=class{};pe._CodeOrName=Mn;pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ur=class extends Mn{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=ur;var at=class extends Mn{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof ur&&(r[n.str]=(r[n.str]||0)+1),r),{})}};pe._Code=at;pe.nil=new at("");function af(t,...e){let r=[t[0]],n=0;for(;n<e.length;)vl(r,e[n]),r.push(t[++n]);return new at(r)}pe._=af;var wl=new at("+");function lf(t,...e){let r=[zn(t[0])],n=0;for(;n<e.length;)r.push(wl),vl(r,e[n]),r.push(wl,zn(t[++n]));return zS(r),new at(r)}pe.str=lf;function vl(t,e){e instanceof at?t.push(...e._items):e instanceof ur?t.push(e):t.push(HS(e))}pe.addCodeArg=vl;function zS(t){let e=1;for(;e<t.length-1;){if(t[e]===wl){let r=BS(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function BS(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ur||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 ur))return`"${t}${e.slice(1)}`}function FS(t,e){return e.emptyStr()?t:t.emptyStr()?e:lf`${t}${e}`}pe.strConcat=FS;function HS(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:zn(Array.isArray(t)?t.join(","):t)}function KS(t){return new at(zn(t))}pe.stringify=KS;function zn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}pe.safeStringify=zn;function VS(t){return typeof t=="string"&&pe.IDENTIFIER.test(t)?new at(`.${t}`):af`[${t}]`}pe.getProperty=VS;function GS(t){if(typeof t=="string"&&pe.IDENTIFIER.test(t))return new at(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}pe.getEsmExportName=GS;function WS(t){return new at(t.toString())}pe.regexpCode=WS});var _l=U(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var Ve=Bn(),kl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ao;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ao||(Ge.UsedValueState=Ao={}));Ge.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var Io=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ve.Name?e:this.name(e)}name(e){return new Ve.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Ge.Scope=Io;var Co=class extends Ve.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ve._)`.${new Ve.Name(r)}[${n}]`}};Ge.ValueScopeName=Co;var JS=(0,Ve._)`\n`,Sl=class extends Io{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?JS:Ve.nil}}get(){return this._scope}name(e){return new Co(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let s=this.toName(e),{prefix:o}=s,i=(n=r.key)!==null&&n!==void 0?n:r.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]=r.ref,s.setValue(r,{property:o,itemIndex:u}),s}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ve._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,s=>{if(s.value===void 0)throw new Error(`CodeGen: name "${s}" has no value`);return s.value.code},r,n)}_reduceValues(e,r,n={},s){let o=Ve.nil;for(let i in e){let a=e[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(u=>{if(l.has(u))return;l.set(u,Ao.Started);let p=r(u);if(p){let g=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;o=(0,Ve._)`${o}${g} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,Ve._)`${o}${p}${this.opts._n}`;else throw new kl(u);l.set(u,Ao.Completed)})}return o}};Ge.ValueScope=Sl});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=Bn(),mt=_l(),Yt=Bn();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 jo=_l();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return jo.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return jo.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return jo.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return jo.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,r){return this}},$l=class extends Ct{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?mt.varKinds.var:this.varKind,s=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${s};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Hr(this.rhs,e,r)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},Oo=class extends Ct{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof ae.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Hr(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return Lo(e,this.rhs)}},xl=class extends Oo{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Tl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Rl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},El=class extends Ct{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Pl=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,r){return this.code=Hr(this.code,e,r),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},Fn=class extends Ct{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,s=n.length;for(;s--;){let o=n[s];o.optimizeNames(e,r)||(YS(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>fr(e,r.names),{})}},Ot=class extends Fn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Al=class extends Fn{},Fr=class extends Ot{};Fr.kind="else";var pr=class t extends Ot{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Fr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(cf(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Hr(this.condition,e,r),this}get names(){let e=super.names;return Lo(e,this.condition),this.else&&fr(e,this.else.names),e}};pr.kind="if";var hr=class extends Ot{};hr.kind="for";var Il=class extends hr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Hr(this.iteration,e,r),this}get names(){return fr(super.names,this.iteration.names)}},Cl=class extends hr{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?mt.varKinds.var:this.varKind,{name:n,from:s,to:o}=this;return`for(${r} ${n}=${s}; ${n}<${o}; ${n}++)`+super.render(e)}get names(){let e=Lo(super.names,this.from);return Lo(e,this.to)}},No=class extends hr{constructor(e,r,n,s){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=s}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Hr(this.iterable,e,r),this}get names(){return fr(super.names,this.iterable.names)}},Hn=class extends Ot{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};Hn.kind="func";var Kn=class extends Fn{render(e){return"return "+super.render(e)}};Kn.kind="return";var Ol=class extends Ot{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,s;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(s=this.finally)===null||s===void 0||s.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&fr(e,this.catch.names),this.finally&&fr(e,this.finally.names),e}},Vn=class extends Ot{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Vn.kind="catch";var Gn=class extends Ot{render(e){return"finally"+super.render(e)}};Gn.kind="finally";var Nl=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
1865
- `:""},this._extScope=e,this._scope=new mt.Scope({parent:e}),this._nodes=[new Al]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,s){let o=this._scope.toName(r);return n!==void 0&&s&&(this._constants[o.str]=n),this._leafNode(new $l(e,o,n)),o}const(e,r,n){return this._def(mt.varKinds.const,e,r,n)}let(e,r,n){return this._def(mt.varKinds.let,e,r,n)}var(e,r,n){return this._def(mt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Oo(e,r,n))}add(e,r){return this._leafNode(new xl(e,te.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new Pl(e)),this}object(...e){let r=["{"];for(let[n,s]of e)r.length>1&&r.push(","),r.push(n),(n!==s||this.opts.es5)&&(r.push(":"),(0,ae.addCodeArg)(r,s));return r.push("}"),new ae._Code(r)}if(e,r,n){if(this._blockNode(new pr(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new pr(e))}else(){return this._elseNode(new Fr)}endIf(){return this._endBlockNode(pr,Fr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Il(e),r)}forRange(e,r,n,s,o=this.opts.es5?mt.varKinds.var:mt.varKinds.let){let i=this._scope.toName(e);return this._for(new Cl(o,i,r,n),()=>s(i))}forOf(e,r,n,s=mt.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ae.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ae._)`${i}.length`,a=>{this.var(o,(0,ae._)`${i}[${a}]`),n(o)})}return this._for(new No("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?mt.varKinds.var:mt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ae._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new No("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(hr)}label(e){return this._leafNode(new Tl(e))}break(e){return this._leafNode(new Rl(e))}return(e){let r=new Kn;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Kn)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Ol;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Vn(o),r(o)}return n&&(this._currNode=s.finally=new Gn,this.code(n)),this._endBlockNode(Vn,Gn)}throw(e){return this._leafNode(new El(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=ae.nil,n,s){return this._blockNode(new Hn(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Hn)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof pr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};te.CodeGen=Nl;function fr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Lo(t,e){return e instanceof ae._CodeOrName?fr(t,e.names):t}function Hr(t,e,r){if(t instanceof ae.Name)return n(t);if(!s(t))return t;return new ae._Code(t._items.reduce((o,i)=>(i instanceof ae.Name&&(i=n(i)),i instanceof ae._Code?o.push(...i._items):o.push(i),o),[]));function n(o){let i=r[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&&r[i.str]!==void 0)}}function YS(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function cf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${Ll(t)}`}te.not=cf;var ZS=df(te.operators.AND);function QS(...t){return t.reduce(ZS)}te.and=QS;var XS=df(te.operators.OR);function e_(...t){return t.reduce(XS)}te.or=e_;function df(t){return(e,r)=>e===ae.nil?r:r===ae.nil?e:(0,ae._)`${Ll(e)} ${t} ${Ll(r)}`}function Ll(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var de=U(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var ge=ee(),t_=Bn();function r_(t){let e={};for(let r of t)e[r]=!0;return e}re.toHash=r_;function n_(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(hf(t,e),!ff(e,t.self.RULES.all))}re.alwaysValidSchema=n_;function hf(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let s=n.RULES.keywords;for(let o in e)s[o]||bf(t,`unknown keyword: "${o}"`)}re.checkUnknownRules=hf;function ff(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}re.schemaHasRules=ff;function s_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}re.schemaHasRulesButRef=s_;function o_({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ge._)`${r}`}return(0,ge._)`${t}${e}${(0,ge.getProperty)(n)}`}re.schemaRefOrVal=o_;function i_(t){return mf(decodeURIComponent(t))}re.unescapeFragment=i_;function a_(t){return encodeURIComponent(Ul(t))}re.escapeFragment=a_;function Ul(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=Ul;function mf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=mf;function l_(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}re.eachItem=l_;function uf({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){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):r(o,i);return a===ge.Name&&!(l instanceof ge.Name)?n(s,l):l}}re.mergeEvaluated={props:uf({mergeNames:(t,e,r)=>t.if((0,ge._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ge._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ge._)`${r} || {}`).code((0,ge._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ge._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ge._)`${r} || {}`),Dl(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:gf}),items:uf({mergeNames:(t,e,r)=>t.if((0,ge._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ge._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ge._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ge._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function gf(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ge._)`{}`);return e!==void 0&&Dl(t,r,e),r}re.evaluatedPropsToName=gf;function Dl(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(n)}`,!0))}re.setEvaluated=Dl;var pf={};function c_(t,e){return t.scopeValue("func",{ref:e,code:pf[e.code]||(pf[e.code]=new t_._Code(e.code))})}re.useFunc=c_;var jl;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(jl||(re.Type=jl={}));function d_(t,e,r){if(t instanceof ge.Name){let n=e===jl.Num;return r?n?(0,ge._)`"[" + ${t} + "]"`:(0,ge._)`"['" + ${t} + "']"`:n?(0,ge._)`"/" + ${t}`:(0,ge._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ge.getProperty)(t).toString():"/"+Ul(t)}re.getErrorPath=d_;function bf(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=bf});var Nt=U(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var Oe=ee(),u_={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")};ql.default=u_});var Wn=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(),Uo=de(),Be=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 p_(t,e=Ne.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=vf(t,e,r);n??(i||a)?yf(o,l):wf(s,(0,ue._)`[${l}]`)}Ne.reportError=p_;function h_(t,e=Ne.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=vf(t,e,r);yf(s,a),o||i||wf(n,Be.default.vErrors)}Ne.reportExtraError=h_;function f_(t,e){t.assign(Be.default.errors,e),t.if((0,ue._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ue._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Ne.resetErrorsCount=f_;function m_({gen:t,keyword:e,schemaValue:r,data:n,errsCount:s,it:o}){if(s===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",s,Be.default.errors,a=>{t.const(i,(0,ue._)`${Be.default.vErrors}[${a}]`),t.if((0,ue._)`${i}.instancePath === undefined`,()=>t.assign((0,ue._)`${i}.instancePath`,(0,ue.strConcat)(Be.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`,r),t.assign((0,ue._)`${i}.data`,n))})}Ne.extendErrors=m_;function yf(t,e){let r=t.const("err",e);t.if((0,ue._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,ue._)`[${r}]`),(0,ue._)`${Be.default.vErrors}.push(${r})`),t.code((0,ue._)`${Be.default.errors}++`)}function wf(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,ue._)`new ${t.ValidationError}(${e})`):(r.assign((0,ue._)`${n}.errors`,e),r.return(!1))}var mr={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 vf(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ue._)`{}`:g_(t,e,r)}function g_(t,e,r={}){let{gen:n,it:s}=t,o=[b_(s,r),y_(t,r)];return w_(t,e,o),n.object(...o)}function b_({errorPath:t},{instancePath:e}){let r=e?(0,ue.str)`${t}${(0,Uo.getErrorPath)(e,Uo.Type.Str)}`:t;return[Be.default.instancePath,(0,ue.strConcat)(Be.default.instancePath,r)]}function y_({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,ue.str)`${e}/${t}`;return r&&(s=(0,ue.str)`${s}${(0,Uo.getErrorPath)(r,Uo.Type.Str)}`),[mr.schemaPath,s]}function w_(t,{params:e,message:r},n){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:g}=a;n.push([mr.keyword,s],[mr.params,typeof e=="function"?e(t):e||(0,ue._)`{}`]),l.messages&&n.push([mr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([mr.schema,i],[mr.parentSchema,(0,ue._)`${p}${g}`],[Be.default.data,o]),u&&n.push([mr.propertyName,u])}});var Sf=U(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.boolOrEmptySchema=Kr.topBoolOrEmptySchema=void 0;var v_=Wn(),k_=ee(),S_=Nt(),__={message:"boolean schema is false"};function $_(t){let{gen:e,schema:r,validateName:n}=t;r===!1?kf(t,!1):typeof r=="object"&&r.$async===!0?e.return(S_.default.data):(e.assign((0,k_._)`${n}.errors`,null),e.return(!0))}Kr.topBoolOrEmptySchema=$_;function x_(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),kf(t)):r.var(e,!0)}Kr.boolOrEmptySchema=x_;function kf(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,v_.reportError)(s,__,void 0,e)}});var Ml=U(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.getRules=Vr.isJSONType=void 0;var T_=["string","number","integer","boolean","null","object","array"],R_=new Set(T_);function E_(t){return typeof t=="string"&&R_.has(t)}Vr.isJSONType=E_;function P_(){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:{}}}Vr.getRules=P_});var zl=U(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.shouldUseRule=Zt.shouldUseGroup=Zt.schemaHasRulesForType=void 0;function A_({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&_f(t,n)}Zt.schemaHasRulesForType=A_;function _f(t,e){return e.rules.some(r=>$f(t,r))}Zt.shouldUseGroup=_f;function $f(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Zt.shouldUseRule=$f});var Jn=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 I_=Ml(),C_=zl(),O_=Wn(),Q=ee(),xf=de(),Gr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gr||(Le.DataType=Gr={}));function N_(t){let e=Tf(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=N_;function Tf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(I_.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=Tf;function L_(t,e){let{gen:r,data:n,opts:s}=t,o=j_(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,C_.schemaHasRulesForType)(t,e[0]));if(i){let a=Fl(e,n,s.strictNumbers,Gr.Wrong);r.if(a,()=>{o.length?U_(t,e,o):Hl(t)})}return i}Le.coerceAndCheckDataType=L_;var Rf=new Set(["string","number","integer","boolean","null"]);function j_(t,e){return e?t.filter(r=>Rf.has(r)||e==="array"&&r==="array"):[]}function U_(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,Q._)`typeof ${s}`),a=n.let("coerced",(0,Q._)`undefined`);o.coerceTypes==="array"&&n.if((0,Q._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,Q._)`${s}[0]`).assign(i,(0,Q._)`typeof ${s}`).if(Fl(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,Q._)`${a} !== undefined`);for(let u of r)(Rf.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);n.else(),Hl(t),n.endIf(),n.if((0,Q._)`${a} !== undefined`,()=>{n.assign(s,a),D_(t,a)});function l(u){switch(u){case"string":n.elseIf((0,Q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Q._)`"" + ${s}`).elseIf((0,Q._)`${s} === null`).assign(a,(0,Q._)`""`);return;case"number":n.elseIf((0,Q._)`${i} == "boolean" || ${s} === null
1866
- || (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,Q._)`+${s}`);return;case"integer":n.elseIf((0,Q._)`${i} === "boolean" || ${s} === null
1867
- || (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,Q._)`+${s}`);return;case"boolean":n.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":n.elseIf((0,Q._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Q._)`${i} === "string" || ${i} === "number"
1868
- || ${i} === "boolean" || ${s} === null`).assign(a,(0,Q._)`[${s}]`)}}}function D_({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Q._)`${e} !== undefined`,()=>t.assign((0,Q._)`${e}[${r}]`,n))}function Bl(t,e,r,n=Gr.Correct){let s=n===Gr.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 n===Gr.Correct?o:(0,Q.not)(o);function i(a=Q.nil){return(0,Q.and)((0,Q._)`typeof ${e} == "number"`,a,r?(0,Q._)`isFinite(${e})`:Q.nil)}}Le.checkDataType=Bl;function Fl(t,e,r,n){if(t.length===1)return Bl(t[0],e,r,n);let s,o=(0,xf.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,Bl(i,e,r,n));return s}Le.checkDataTypes=Fl;var q_={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Q._)`{type: ${t}}`:(0,Q._)`{type: ${e}}`};function Hl(t){let e=M_(t);(0,O_.reportError)(e,q_)}Le.reportTypeError=Hl;function M_(t){let{gen:e,data:r,schema:n}=t,s=(0,xf.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var Pf=U(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.assignDefaults=void 0;var Wr=ee(),z_=de();function B_(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)Ef(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>Ef(t,o,s.default))}Do.assignDefaults=B_;function Ef(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Wr._)`${o}${(0,Wr.getProperty)(e)}`;if(s){(0,z_.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Wr._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Wr._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,Wr._)`${a} = ${(0,Wr.stringify)(r)}`)}});var lt=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(),Kl=de(),Qt=Nt(),F_=de();function H_(t,e){let{gen:r,data:n,it:s}=t;r.if(Gl(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,be._)`${e}`},!0),t.error()})}fe.checkReportMissingProp=H_;function K_({gen:t,data:e,it:{opts:r}},n,s){return(0,be.or)(...n.map(o=>(0,be.and)(Gl(t,e,o,r.ownProperties),(0,be._)`${s} = ${o}`)))}fe.checkMissingProp=K_;function V_(t,e){t.setParams({missingProperty:e},!0),t.error()}fe.reportMissingProp=V_;function Af(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,be._)`Object.prototype.hasOwnProperty`})}fe.hasPropFunc=Af;function Vl(t,e,r){return(0,be._)`${Af(t)}.call(${e}, ${r})`}fe.isOwnProperty=Vl;function G_(t,e,r,n){let s=(0,be._)`${e}${(0,be.getProperty)(r)} !== undefined`;return n?(0,be._)`${s} && ${Vl(t,e,r)}`:s}fe.propertyInData=G_;function Gl(t,e,r,n){let s=(0,be._)`${e}${(0,be.getProperty)(r)} === undefined`;return n?(0,be.or)(s,(0,be.not)(Vl(t,e,r))):s}fe.noPropertyInData=Gl;function If(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}fe.allSchemaProperties=If;function W_(t,e){return If(e).filter(r=>!(0,Kl.alwaysValidSchema)(t,e[r]))}fe.schemaProperties=W_;function J_({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,l,u){let p=u?(0,be._)`${t}, ${e}, ${n}${s}`:e,g=[[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&&g.push([Qt.default.dynamicAnchors,Qt.default.dynamicAnchors]);let $=(0,be._)`${p}, ${r.object(...g)}`;return l!==be.nil?(0,be._)`${a}.call(${l}, ${$})`:(0,be._)`${a}(${$})`}fe.callValidateCode=J_;var Y_=(0,be._)`new RegExp`;function Z_({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,be._)`${s.code==="new RegExp"?Y_:(0,F_.useFunc)(t,s)}(${r}, ${n})`})}fe.usePattern=Z_;function Q_(t){let{gen:e,data:r,keyword:n,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._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Kl.Type.Num},o),e.if((0,be.not)(o),a)})}}fe.validateArray=Q_;function X_(t){let{gen:e,schema:r,keyword:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Kl.alwaysValidSchema)(s,l))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,u)=>{let p=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,be._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,be.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}fe.validateUnion=X_});var Nf=U(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateKeywordUsage=St.validSchemaType=St.funcKeywordCode=St.macroKeywordCode=void 0;var Fe=ee(),gr=Nt(),e$=lt(),t$=Wn();function r$(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=Of(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Fe.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}St.macroKeywordCode=r$;function n$(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;o$(l,e);let u=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=Of(n,s,u),g=n.let("valid");t.block$data(g,$),t.ok((r=e.valid)!==null&&r!==void 0?r:g);function $(){if(e.errors===!1)T(),e.modifying&&Cf(t),E(()=>t.error());else{let P=e.async?v():S();e.modifying&&Cf(t),E(()=>s$(t,P))}}function v(){let P=n.let("ruleErrs",null);return n.try(()=>T((0,Fe._)`await `),O=>n.assign(g,!1).if((0,Fe._)`${O} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Fe._)`${O}.errors`),()=>n.throw(O))),P}function S(){let P=(0,Fe._)`${p}.errors`;return n.assign(P,null),T(Fe.nil),P}function T(P=e.async?(0,Fe._)`await `:Fe.nil){let O=l.opts.passContext?gr.default.this:gr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(g,(0,Fe._)`${P}${(0,e$.callValidateCode)(t,p,O,D)}`,e.modifying)}function E(P){var O;n.if((0,Fe.not)((O=e.valid)!==null&&O!==void 0?O:g),P)}}St.funcKeywordCode=n$;function Cf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Fe._)`${n.parentData}[${n.parentDataProperty}]`))}function s$(t,e){let{gen:r}=t;r.if((0,Fe._)`Array.isArray(${e})`,()=>{r.assign(gr.default.vErrors,(0,Fe._)`${gr.default.vErrors} === null ? ${e} : ${gr.default.vErrors}.concat(${e})`).assign(gr.default.errors,(0,Fe._)`${gr.default.vErrors}.length`),(0,t$.extendErrors)(t)},()=>t.error())}function o$({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Of(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Fe.stringify)(r)})}function i$(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}St.validSchemaType=i$;function a$({schema:t,opts:e,self:r,errSchemaPath:n},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 "${n}": `+r.errorsText(s.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}St.validateKeywordUsage=a$});var jf=U(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.extendSubschemaMode=Xt.extendSubschemaData=Xt.getSubschema=void 0;var _t=ee(),Lf=de();function l$(t,{keyword:e,schemaProp:r,schema:n,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,_t._)`${t.schemaPath}${(0,_t.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,_t._)`${t.schemaPath}${(0,_t.getProperty)(e)}${(0,_t.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Lf.escapeFragment)(r)}`}}if(n!==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:n,schemaPath:s,topSchemaRef:i,errSchemaPath:o}}throw new Error('either "keyword" or "schema" must be passed')}Xt.getSubschema=l$;function c$(t,e,{dataProp:r,dataPropType:n,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:p,opts:g}=e,$=a.let("data",(0,_t._)`${e.data}${(0,_t.getProperty)(r)}`,!0);l($),t.errorPath=(0,_t.str)`${u}${(0,Lf.getErrorPath)(r,n,g.jsPropertySyntax)}`,t.parentDataProperty=(0,_t._)`${r}`,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=c$;function d$(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:s,allErrors:o}){n!==void 0&&(t.compositeRule=n),s!==void 0&&(t.createErrors=s),o!==void 0&&(t.allErrors=o),t.jtdDiscriminator=e,t.jtdMetadata=r}Xt.extendSubschemaMode=d$});var Wl=U((BN,Uf)=>{"use strict";Uf.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,s,o;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(s=n;s--!==0;)if(!t(e[s],r[s]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(o=Object.keys(e),n=o.length,n!==Object.keys(r).length)return!1;for(s=n;s--!==0;)if(!Object.prototype.hasOwnProperty.call(r,o[s]))return!1;for(s=n;s--!==0;){var i=o[s];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var qf=U((FN,Df)=>{"use strict";var er=Df.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};qo(e,n,s,t,"",t)};er.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};er.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};er.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};er.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 qo(t,e,r,n,s,o,i,a,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,s,o,i,a,l,u);for(var p in n){var g=n[p];if(Array.isArray(g)){if(p in er.arrayKeywords)for(var $=0;$<g.length;$++)qo(t,e,r,g[$],s+"/"+p+"/"+$,o,s,p,n,$)}else if(p in er.propsKeywords){if(g&&typeof g=="object")for(var v in g)qo(t,e,r,g[v],s+"/"+p+"/"+u$(v),o,s,p,n,v)}else(p in er.keywords||t.allKeys&&!(p in er.skipKeywords))&&qo(t,e,r,g,s+"/"+p,o,s,p,n)}r(n,s,o,i,a,l,u)}}function u$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Yn=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 p$=de(),h$=Wl(),f$=qf(),m$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function g$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Jl(t):e?Mf(t)<=e:!1}We.inlineRef=g$;var b$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Jl(t){for(let e in t){if(b$.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Jl)||typeof r=="object"&&Jl(r))return!0}return!1}function Mf(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!m$.has(r)&&(typeof t[r]=="object"&&(0,p$.eachItem)(t[r],n=>e+=Mf(n)),e===1/0))return 1/0}return e}function zf(t,e="",r){r!==!1&&(e=Jr(e));let n=t.parse(e);return Bf(t,n)}We.getFullPath=zf;function Bf(t,e){return t.serialize(e).split("#")[0]+"#"}We._getFullPath=Bf;var y$=/#\/?$/;function Jr(t){return t?t.replace(y$,""):""}We.normalizeId=Jr;function w$(t,e,r){return r=Jr(r),t.resolve(e,r)}We.resolveUrl=w$;var v$=/^[a-z_][-a-z0-9._]*$/i;function k$(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Jr(t[r]||e),o={"":s},i=zf(n,s,!1),a={},l=new Set;return f$(t,{allKeys:!0},(g,$,v,S)=>{if(S===void 0)return;let T=i+$,E=o[S];typeof g[r]=="string"&&(E=P.call(this,g[r])),O.call(this,g.$anchor),O.call(this,g.$dynamicAnchor),o[$]=E;function P(D){let ne=this.opts.uriResolver.resolve;if(D=Jr(E?ne(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(g,Y.schema,D):D!==Jr(T)&&(D[0]==="#"?(u(g,a[D],D),a[D]=g):this.refs[D]=T),D}function O(D){if(typeof D=="string"){if(!v$.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(g,$,v){if($!==void 0&&!h$(g,$))throw p(v)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}We.getSchemaRefs=k$});var Xn=U(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.getData=tr.KeywordCxt=tr.validateFunctionCode=void 0;var Gf=Sf(),Ff=Jn(),Zl=zl(),Mo=Jn(),S$=Pf(),Qn=Nf(),Yl=jf(),z=ee(),Z=Nt(),_$=Yn(),Lt=de(),Zn=Wn();function $$(t){if(Yf(t)&&(Zf(t),Jf(t))){R$(t);return}Wf(t,()=>(0,Gf.topBoolOrEmptySchema)(t))}tr.validateFunctionCode=$$;function Wf({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,z._)`${Z.default.data}, ${Z.default.valCxt}`,n.$async,()=>{t.code((0,z._)`"use strict"; ${Hf(r,s)}`),T$(t,s),t.code(o)}):t.func(e,(0,z._)`${Z.default.data}, ${x$(s)}`,n.$async,()=>t.code(Hf(r,s)).code(o))}function x$(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$(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 R$(t){let{schema:e,opts:r,gen:n}=t;Wf(t,()=>{r.$comment&&e.$comment&&Xf(t),C$(t),n.let(Z.default.vErrors,null),n.let(Z.default.errors,0),r.unevaluated&&E$(t),Qf(t),L$(t)})}function E$(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,z._)`${r}.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 Hf(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,z._)`/*# sourceURL=${r} */`:z.nil}function P$(t,e){if(Yf(t)&&(Zf(t),Jf(t))){A$(t,e);return}(0,Gf.boolOrEmptySchema)(t,e)}function Jf({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Yf(t){return typeof t.schema!="boolean"}function A$(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&Xf(t),O$(t),N$(t);let o=n.const("_errs",Z.default.errors);Qf(t,o),n.var(e,(0,z._)`${o} === ${Z.default.errors}`)}function Zf(t){(0,Lt.checkUnknownRules)(t),I$(t)}function Qf(t,e){if(t.opts.jtd)return Kf(t,[],!1,e);let r=(0,Ff.getSchemaTypes)(t.schema),n=(0,Ff.coerceAndCheckDataType)(t,r);Kf(t,r,!n,e)}function I$(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Lt.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function C$(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Lt.checkStrictMode)(t,"default is ignored in the schema root")}function O$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,_$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function N$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Xf({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$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)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${Z.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function L$(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$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._)`${n}.errors`,Z.default.vErrors),o.unevaluated&&j$(t),e.return((0,z._)`${Z.default.errors} === 0`))}function j$({gen:t,evaluated:e,props:r,items:n}){r instanceof z.Name&&t.assign((0,z._)`${e}.props`,r),n instanceof z.Name&&t.assign((0,z._)`${e}.items`,n)}function Kf(t,e,r,n){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(()=>tm(t,"$ref",p.all.$ref.definition));return}l.jtd||U$(t,e),s.block(()=>{for(let $ of p.rules)g($);g(p.post)});function g($){(0,Zl.shouldUseGroup)(o,$)&&($.type?(s.if((0,Mo.checkDataType)($.type,i,l.strictNumbers)),Vf(t,$),e.length===1&&e[0]===$.type&&r&&(s.else(),(0,Mo.reportTypeError)(t)),s.endIf()):Vf(t,$),a||s.if((0,z._)`${Z.default.errors} === ${n||0}`))}}function Vf(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,S$.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Zl.shouldUseRule)(n,o)&&tm(t,o.keyword,o.definition,e.type)})}function U$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(D$(t,e),t.opts.allowUnionTypes||q$(t,e),M$(t,t.dataTypes))}function D$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{em(t.dataTypes,r)||Ql(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),B$(t,e)}}function q$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ql(t,"use allowUnionTypes to allow union type keyword")}function M$(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Zl.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>z$(e,i))&&Ql(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function z$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function em(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function B$(t,e){let r=[];for(let n of t.dataTypes)em(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ql(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Lt.checkStrictMode)(t,e,t.opts.strictTypes)}var zo=class{constructor(e,r,n){if((0,Qn.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Lt.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",rm(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Qn.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Z.default.errors))}result(e,r,n){this.failResult((0,z.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,z.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,z._)`${r} !== undefined && (${(0,z.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Zn.reportExtraError:Zn.reportError)(this,this.def.error,r)}$dataError(){(0,Zn.reportError)(this,this.def.$dataError||Zn.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Zn.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=z.nil,r=z.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,z.or)((0,z._)`${s} === undefined`,r)),e!==z.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,z.or)(i(),a());function i(){if(n.length){if(!(r instanceof z.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,z._)`${(0,Mo.checkDataTypes)(l,r,o.opts.strictNumbers,Mo.DataType.Wrong)}`}return z.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,z._)`!${l}(${r})`}return z.nil}}subschema(e,r){let n=(0,Yl.getSubschema)(this.it,e);(0,Yl.extendSubschemaData)(n,this.it,e),(0,Yl.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return P$(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Lt.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Lt.mergeEvaluated.items(s,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:s}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return s.if(r,()=>this.mergeEvaluated(e,z.Name)),!0}};tr.KeywordCxt=zo;function tm(t,e,r,n){let s=new zo(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Qn.funcKeywordCode)(s,r):"macro"in r?(0,Qn.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Qn.funcKeywordCode)(s,r)}var F$=/^\/(?:[^~]|~0|~1)*$/,H$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function rm(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Z.default.rootData;if(t[0]==="/"){if(!F$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Z.default.rootData}else{let u=H$.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 n[e-p]}if(p>e)throw new Error(l("data",p));if(o=r[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}`}}tr.getData=rm});var Bo=U(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});var Xl=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};ec.default=Xl});var es=U(nc=>{"use strict";Object.defineProperty(nc,"__esModule",{value:!0});var tc=Yn(),rc=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,tc.resolveUrl)(e,r,n),this.missingSchema=(0,tc.normalizeId)((0,tc.getFullPath)(e,this.missingRef))}};nc.default=rc});var Ho=U(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.resolveSchema=ct.getCompilingSchema=ct.resolveRef=ct.compileSchema=ct.SchemaEnv=void 0;var gt=ee(),K$=Bo(),br=Nt(),bt=Yn(),nm=de(),V$=Xn(),Yr=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,bt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ct.SchemaEnv=Yr;function oc(t){let e=sm.call(this,t);if(e)return e;let r=(0,bt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new gt.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:K$.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:br.default.data,parentData:br.default.parentData,parentDataProperty:br.default.parentDataProperty,dataNames:[br.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:r,baseId:t.baseId||r,schemaPath:gt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,gt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,V$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(br.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let v=new Function(`${br.default.self}`,`${br.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:g,scopeValues:i._values}),this.opts.unevaluated){let{props:S,items:T}=u;v.evaluated={props:S instanceof gt.Name?void 0:S,items:T instanceof gt.Name?void 0:T,dynamicProps:S instanceof gt.Name,dynamicItems:T instanceof gt.Name},v.source&&(v.source.evaluated=(0,gt.stringify)(v.evaluated))}return t.validate=v,t}catch(g){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),g}finally{this._compilations.delete(t)}}ct.compileSchema=oc;function G$(t,e,r){var n;r=(0,bt.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=Y$.call(this,t,r);if(o===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(o=new Yr({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=W$.call(this,o)}ct.resolveRef=G$;function W$(t){return(0,bt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:oc.call(this,t)}function sm(t){for(let e of this._compilations)if(J$(e,t))return e}ct.getCompilingSchema=sm;function J$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function Y$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Fo.call(this,t,e)}function Fo(t,e){let r=this.opts.uriResolver.parse(e),n=(0,bt._getFullPath)(this.opts.uriResolver,r),s=(0,bt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return sc.call(this,r,t);let o=(0,bt.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Fo.call(this,t,i);return typeof a?.schema!="object"?void 0:sc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||oc.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 Yr({schema:a,schemaId:l,root:t,baseId:s})}return sc.call(this,r,i)}}ct.resolveSchema=Fo;var Z$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function sc(t,{baseId:e,schema:r,root:n}){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 r=="boolean")return;let l=r[(0,nm.unescapeFragment)(a)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!Z$.has(a)&&u&&(e=(0,bt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,nm.schemaHasRulesButRef)(r,this.RULES)){let a=(0,bt.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Fo.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new Yr({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var om=U((JN,Q$)=>{Q$.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 lc=U((YN,um)=>{"use strict";var X$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),am=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),ic=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),lm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ex=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function ac(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var tx=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function im(t){return t.length=0,!0}function rx(t,e,r){if(t.length){let n=ac(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function nx(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=rx;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(o===!0&&(i=!0),!a(s,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(o=!0),n.push(":");continue}else if(u==="%"){if(!a(s,n,r))break;a=im}else{s.push(u);continue}}return s.length&&(a===im?r.zone=s.join(""):i?n.push(s.join("")):n.push(ac(s))),r.address=n.join(""),r}function cm(t){if(sx(t,":")<2)return{host:t,isIPV6:!1};let e=nx(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function sx(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function ox(t){let e=t,r=[],n=-1,s=0;for(;s=e.length;){if(s===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.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]==="/")){r.push("/");break}}else if(s===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var ix={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ax=/[@/?#:]/g,lx=/[@/?#]/g;function dm(t,e){let r=e?lx:ax;return r.lastIndex=0,t.replace(r,n=>ix[n])}function cx(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let s=t.slice(n+1,n+3);if(ic(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&lm(i)?r+=i:r+="%"+o,n+=2;continue}}r+=t[n]}return r}function dx(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(ic(n)){let s=n.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&lm(o)?e+=o:e+="%"+s,r+=2;continue}}ex(t[r])?e+=t[r]:e+=escape(t[r])}return e}function ux(t){let e="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let n=t.slice(r+1,r+3);if(ic(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function px(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!am(r)){let n=cm(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=dm(r,!1)}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}um.exports={nonSimpleDomain:tx,recomposeAuthority:px,reescapeHostDelimiters:dm,normalizePercentEncoding:cx,normalizePathEncoding:dx,escapePreservingEscapes:ux,removeDotSegments:ox,isIPv4:am,isUUID:X$,normalizeIPv6:cm,stringArrayToHexStripped:ac}});var gm=U((ZN,mm)=>{"use strict";var{isUUID:hx}=lc(),fx=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,mx=["http","https","ws","wss","urn","urn:uuid"];function gx(t){return mx.indexOf(t)!==-1}function cc(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 pm(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function hm(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 bx(t){return t.secure=cc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function yx(t){if((t.port===(cc(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function wx(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(fx);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let s=`${n}:${e.nid||t.nid}`,o=dc(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function vx(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),s=`${r}:${e.nid||n}`,o=dc(s);o&&(t=o.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function kx(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!hx(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function Sx(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var fm={scheme:"http",domainHost:!0,parse:pm,serialize:hm},_x={scheme:"https",domainHost:fm.domainHost,parse:pm,serialize:hm},Ko={scheme:"ws",domainHost:!0,parse:bx,serialize:yx},$x={scheme:"wss",domainHost:Ko.domainHost,parse:Ko.parse,serialize:Ko.serialize},xx={scheme:"urn",parse:wx,serialize:vx,skipNormalize:!0},Tx={scheme:"urn:uuid",parse:kx,serialize:Sx,skipNormalize:!0},Vo={http:fm,https:_x,ws:Ko,wss:$x,urn:xx,"urn:uuid":Tx};Object.setPrototypeOf(Vo,null);function dc(t){return t&&(Vo[t]||Vo[t.toLowerCase()])||void 0}mm.exports={wsIsSecure:cc,SCHEMES:Vo,isValidSchemeName:gx,getSchemeHandler:dc}});var km=U((QN,Jo)=>{"use strict";var{normalizeIPv6:Rx,removeDotSegments:ts,recomposeAuthority:Ex,normalizePercentEncoding:Px,normalizePathEncoding:Ax,escapePreservingEscapes:Ix,reescapeHostDelimiters:Cx,isIPv4:Ox,nonSimpleDomain:Nx}=lc(),{SCHEMES:Lx,getSchemeHandler:ym}=gm();function jx(t,e){return typeof t=="string"?t=Fx(t,e):typeof t=="object"&&(t=Wo(yr(t,e),e)),t}function Ux(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=Go(t,n),{parsed:i,malformedAuthorityOrPort:a}=Go(e,n);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=wm(s,i,n,!0);return n.skipEscape=!0,yr(l,n)}function wm(t,e,r,n){let s={};return n||(t=Wo(yr(t,r),r),e=Wo(yr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(s.scheme=e.scheme,s.userinfo=e.userinfo,s.host=e.host,s.port=e.port,s.path=ts(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=ts(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=ts(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=ts(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 Dx(t,e,r){let n=bm(t,r),s=bm(e,r);return n!==void 0&&s!==void 0&&n.toLowerCase()===s.toLowerCase()}function yr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),s=[],o=ym(n.scheme||r.scheme);o&&o.serialize&&o.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=Px(r.path):(r.path=Ix(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&s.push(r.scheme,":");let i=Ex(r);if(i!==void 0&&(n.reference!=="suffix"&&s.push("//"),s.push(i),r.path&&r.path[0]!=="/"&&s.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!o||!o.absolutePath)&&(a=ts(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),s.push(a)}return r.query!==void 0&&s.push("?",r.query),r.fragment!==void 0&&s.push("#",r.fragment),s.join("")}var qx=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Mx=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,zx=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function Bx(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 Go(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},s=!1,o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(Mx);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(zx);if(a!==null){let u=a[1],p=u.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",s=!0):u.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",s=!0))}let l=t.match(qx);if(l){n.scheme=l[1],n.userinfo=l[3],n.host=l[4],n.port=parseInt(l[5],10),n.path=l[6]||"",n.query=l[7],n.fragment=l[8],isNaN(n.port)&&(n.port=l[5]);let u=Bx(n,l);if(u!==void 0&&(n.error=n.error||u,s=!0),n.host)if(Ox(n.host)===!1){let $=Rx(n.host);n.host=$.host.toLowerCase(),o=$.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let p=ym(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&o===!1&&Nx(n.host))try{n.host=new URL("http://"+n.host).hostname}catch(g){n.error=n.error||"Host's domain name can not be converted to ASCII: "+g}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=Cx(unescape(n.host),o))),n.path&&(n.path=Ax(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}p&&p.parse&&p.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:s}}function Wo(t,e){return Go(t,e).parsed}function Fx(t,e){return vm(t,e).normalized}function vm(t,e){let{parsed:r,malformedAuthorityOrPort:n}=Go(t,e);return{normalized:n?t:yr(r,e),malformedAuthorityOrPort:n}}function bm(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=vm(t,e);return n?void 0:r}if(typeof t=="object")return yr(t,e)}var uc={SCHEMES:Lx,normalize:jx,resolve:Ux,resolveComponent:wm,equal:Dx,serialize:yr,parse:Wo};Jo.exports=uc;Jo.exports.default=uc;Jo.exports.fastUri=uc});var _m=U(pc=>{"use strict";Object.defineProperty(pc,"__esModule",{value:!0});var Sm=km();Sm.code='require("ajv/dist/runtime/uri").default';pc.default=Sm});var Im=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 Hx=Xn();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return Hx.KeywordCxt}});var Zr=ee();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return Zr._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return Zr.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return Zr.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return Zr.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return Zr.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return Zr.CodeGen}});var Kx=Bo(),Em=es(),Vx=Ml(),rs=Ho(),Gx=ee(),ns=Yn(),Yo=Jn(),fc=de(),$m=om(),Wx=_m(),Pm=(t,e)=>new RegExp(t,e);Pm.code="new RegExp";var Jx=["removeAdditional","useDefaults","coerceTypes"],Yx=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Zx={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."},Qx={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},xm=200;function Xx(t){var e,r,n,s,o,i,a,l,u,p,g,$,v,S,T,E,P,O,D,ne,Y,He,je,cn,jt;let Ze=t.strict,dn=(e=t.code)===null||e===void 0?void 0:e.optimize,bs=dn===!0||dn===void 0?1:dn||0,Ut=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Pm,Sr=(s=t.uriResolver)!==null&&s!==void 0?s:Wx.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:Ze)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:Ze)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:Ze)!==null&&p!==void 0?p:"log",strictTuples:($=(g=t.strictTuples)!==null&&g!==void 0?g:Ze)!==null&&$!==void 0?$:"log",strictRequired:(S=(v=t.strictRequired)!==null&&v!==void 0?v:Ze)!==null&&S!==void 0?S:!1,code:t.code?{...t.code,optimize:bs,regExp:Ut}:{optimize:bs,regExp:Ut},loopRequired:(T=t.loopRequired)!==null&&T!==void 0?T:xm,loopEnum:(E=t.loopEnum)!==null&&E!==void 0?E:xm,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(O=t.messages)!==null&&O!==void 0?O:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(ne=t.schemaId)!==null&&ne!==void 0?ne:"$id",addUsedSchema:(Y=t.addUsedSchema)!==null&&Y!==void 0?Y:!0,validateSchema:(He=t.validateSchema)!==null&&He!==void 0?He:!0,validateFormats:(je=t.validateFormats)!==null&&je!==void 0?je:!0,unicodeRegExp:(cn=t.unicodeRegExp)!==null&&cn!==void 0?cn:!0,int32range:(jt=t.int32range)!==null&&jt!==void 0?jt:!0,uriResolver:Sr}}var ss=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,...Xx(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new Gx.ValueScope({scope:{},prefixes:Yx,es5:r,lines:n}),this.logger=oT(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Vx.getRules)(),Tm.call(this,Zx,e,"NOT SUPPORTED"),Tm.call(this,Qx,e,"DEPRECATED","warn"),this._metaOpts=nT.call(this),e.formats&&tT.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&rT.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),eT.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=$m;n==="id"&&(s={...$m},s.id=s.$id,delete s.$id),r&&e&&this.addMetaSchema(s,s[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let s=n(r);return"$async"in n||(this.errors=n.errors),s}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return s.call(this,e,r);async function s(p,g){await o.call(this,p.$schema);let $=this._addSchema(p,g);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(g){if(!(g instanceof Em.default))throw g;return a.call(this,g),await l.call(this,g.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:g}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${g} cannot be resolved`)}async function l(p){let g=await u.call(this,p);this.refs[p]||await o.call(this,g.$schema),this.refs[p]||this.addSchema(g,p,r)}async function u(p){let g=this._loading[p];if(g)return g;try{return await(this._loading[p]=n(p))}finally{delete this._loading[p]}}}addSchema(e,r,n,s=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,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 r=(0,ns.normalizeId)(r||o),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,s,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let s=this.validate(n,e);if(!s&&r){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 r;for(;typeof(r=Rm.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new rs.SchemaEnv({schema:{},schemaId:n});if(r=rs.resolveSchema.call(this,s,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Rm.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,ns.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(aT.call(this,n,r),!r)return(0,fc.eachItem)(n,o=>hc.call(this,o)),this;cT.call(this,r);let s={...r,type:(0,Yo.getJSONTypes)(r.type),schemaType:(0,Yo.getJSONTypes)(r.schemaType)};return(0,fc.eachItem)(n,s.type.length===0?o=>hc.call(this,o,s):o=>s.type.forEach(i=>hc.call(this,o,s,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let s=n.rules.findIndex(o=>o.keyword===e);s>=0&&n.rules.splice(s,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(s=>`${n}${s.instancePath} ${s.message}`).reduce((s,o)=>s+r+o)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let s of r){let o=s.split("/").slice(1),i=e;for(let a of o)i=i[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:u}=l.definition,p=i[a];u&&p&&(i[a]=Am(p))}}return e}_removeAllSchemas(e,r){for(let n in e){let s=e[n];(!r||r.test(n))&&(typeof s=="string"?delete e[n]:s&&!s.meta&&(this._cache.delete(s.schema),delete e[n]))}}_addSchema(e,r,n,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;n=(0,ns.normalizeId)(i||n);let u=ns.getSchemaRefs.call(this,e,n);return l=new rs.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(l.schema,l),o&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=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 r=this.opts;this.opts=this._metaOpts;try{rs.compileSchema.call(this,e)}finally{this.opts=r}}};ss.ValidationError=Kx.default;ss.MissingRefError=Em.default;Ie.default=ss;function Tm(t,e,r,n="error"){for(let s in t){let o=s;o in e&&this.logger[n](`${r}: option ${s}. ${t[o]}`)}}function Rm(t){return t=(0,ns.normalizeId)(t),this.schemas[t]||this.refs[t]}function eT(){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 tT(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function rT(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function nT(){let t={...this.opts};for(let e of Jx)delete t[e];return t}var sT={log(){},warn(){},error(){}};function oT(t){if(t===!1)return sT;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 iT=/^[a-z_$][a-z0-9_$:-]*$/i;function aT(t,e){let{RULES:r}=this;if((0,fc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!iT.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function hc(t,e,r){var n;let s=e?.post;if(r&&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===r);if(i||(i={type:r,rules:[]},o.rules.push(i)),o.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Yo.getJSONTypes)(e.type),schemaType:(0,Yo.getJSONTypes)(e.schemaType)}};e.before?lT.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function lT(t,e,r){let n=t.rules.findIndex(s=>s.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function cT(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Am(e)),t.validateSchema=this.compile(e,!0))}var dT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Am(t){return{anyOf:[t,dT]}}});var Cm=U(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var uT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};mc.default=uT});var jm=U(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.callRef=wr.getValidate=void 0;var pT=es(),Om=lt(),Je=ee(),Qr=Nt(),Nm=Ho(),Zo=de(),hT={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:s,schemaEnv:o,validateName:i,opts:a,self:l}=n,{root:u}=o;if((r==="#"||r==="#/")&&s===u.baseId)return g();let p=Nm.resolveRef.call(l,u,s,r);if(p===void 0)throw new pT.default(n.opts.uriResolver,s,r);if(p instanceof Nm.SchemaEnv)return $(p);return v(p);function g(){if(o===u)return Qo(t,i,o,o.$async);let S=e.scopeValue("root",{ref:u});return Qo(t,(0,Je._)`${S}.validate`,u,u.$async)}function $(S){let T=Lm(t,S);Qo(t,T,S,S.$async)}function v(S){let T=e.scopeValue("schema",a.code.source===!0?{ref:S,code:(0,Je.stringify)(S)}:{ref:S}),E=e.name("valid"),P=t.subschema({schema:S,dataTypes:[],schemaPath:Je.nil,topSchemaRef:T,errSchemaPath:r},E);t.mergeEvaluated(P),t.ok(E)}}};function Lm(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Je._)`${r.scopeValue("wrapper",{ref:e})}.validate`}wr.getValidate=Lm;function Qo(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,u=l.passContext?Qr.default.this:Je.nil;n?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let S=s.let("valid");s.try(()=>{s.code((0,Je._)`await ${(0,Om.callValidateCode)(t,e,u)}`),v(e),i||s.assign(S,!0)},T=>{s.if((0,Je._)`!(${T} instanceof ${o.ValidationError})`,()=>s.throw(T)),$(T),i||s.assign(S,!1)}),t.ok(S)}function g(){t.result((0,Om.callValidateCode)(t,e,u),()=>v(e),()=>$(e))}function $(S){let T=(0,Je._)`${S}.errors`;s.assign(Qr.default.vErrors,(0,Je._)`${Qr.default.vErrors} === null ? ${T} : ${Qr.default.vErrors}.concat(${T})`),s.assign(Qr.default.errors,(0,Je._)`${Qr.default.vErrors}.length`)}function v(S){var T;if(!o.opts.unevaluated)return;let E=(T=r?.validate)===null||T===void 0?void 0:T.evaluated;if(o.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(o.props=Zo.mergeEvaluated.props(s,E.props,o.props));else{let P=s.var("props",(0,Je._)`${S}.evaluated.props`);o.props=Zo.mergeEvaluated.props(s,P,o.props,Je.Name)}if(o.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(o.items=Zo.mergeEvaluated.items(s,E.items,o.items));else{let P=s.var("items",(0,Je._)`${S}.evaluated.items`);o.items=Zo.mergeEvaluated.items(s,P,o.items,Je.Name)}}}wr.callRef=Qo;wr.default=hT});var Um=U(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});var fT=Cm(),mT=jm(),gT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",fT.default,mT.default];gc.default=gT});var Dm=U(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});var Xo=ee(),rr=Xo.operators,ei={maximum:{okStr:"<=",ok:rr.LTE,fail:rr.GT},minimum:{okStr:">=",ok:rr.GTE,fail:rr.LT},exclusiveMaximum:{okStr:"<",ok:rr.LT,fail:rr.GTE},exclusiveMinimum:{okStr:">",ok:rr.GT,fail:rr.LTE}},bT={message:({keyword:t,schemaCode:e})=>(0,Xo.str)`must be ${ei[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Xo._)`{comparison: ${ei[t].okStr}, limit: ${e}}`},yT={keyword:Object.keys(ei),type:"number",schemaType:"number",$data:!0,error:bT,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Xo._)`${r} ${ei[e].fail} ${n} || isNaN(${r})`)}};bc.default=yT});var qm=U(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var os=ee(),wT={message:({schemaCode:t})=>(0,os.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,os._)`{multipleOf: ${t}}`},vT={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wT,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,os._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,os._)`${i} !== parseInt(${i})`;t.fail$data((0,os._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};yc.default=vT});var zm=U(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});function Mm(t){let e=t.length,r=0,n=0,s;for(;n<e;)r++,s=t.charCodeAt(n++),s>=55296&&s<=56319&&n<e&&(s=t.charCodeAt(n),(s&64512)===56320&&n++);return r}wc.default=Mm;Mm.code='require("ajv/dist/runtime/ucs2length").default'});var Bm=U(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var vr=ee(),kT=de(),ST=zm(),_T={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,vr.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,vr._)`{limit: ${t}}`},$T={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:_T,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?vr.operators.GT:vr.operators.LT,i=s.opts.unicode===!1?(0,vr._)`${r}.length`:(0,vr._)`${(0,kT.useFunc)(t.gen,ST.default)}(${r})`;t.fail$data((0,vr._)`${i} ${o} ${n}`)}};vc.default=$T});var Fm=U(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var xT=lt(),TT=de(),Xr=ee(),RT={message:({schemaCode:t})=>(0,Xr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Xr._)`{pattern: ${t}}`},ET={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:RT,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,Xr._)`new RegExp`:(0,TT.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,Xr._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,Xr._)`!${p}`)}else{let l=(0,xT.usePattern)(t,s);t.fail$data((0,Xr._)`!${l}.test(${r})`)}}};kc.default=ET});var Hm=U(Sc=>{"use strict";Object.defineProperty(Sc,"__esModule",{value:!0});var is=ee(),PT={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,is.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,is._)`{limit: ${t}}`},AT={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:PT,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?is.operators.GT:is.operators.LT;t.fail$data((0,is._)`Object.keys(${r}).length ${s} ${n}`)}};Sc.default=AT});var Km=U(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var as=lt(),ls=ee(),IT=de(),CT={message:({params:{missingProperty:t}})=>(0,ls.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ls._)`{missingProperty: ${t}}`},OT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:CT,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let v=t.parentSchema.properties,{definedProperties:S}=t.it;for(let T of r)if(v?.[T]===void 0&&!S.has(T)){let E=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${T}" is not defined at "${E}" (strictRequired)`;(0,IT.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(ls.nil,g);else for(let v of r)(0,as.checkReportMissingProp)(t,v)}function p(){let v=e.let("missing");if(l||o){let S=e.let("valid",!0);t.block$data(S,()=>$(v,S)),t.ok(S)}else e.if((0,as.checkMissingProp)(t,r,v)),(0,as.reportMissingProp)(t,v),e.else()}function g(){e.forOf("prop",n,v=>{t.setParams({missingProperty:v}),e.if((0,as.noPropertyInData)(e,s,v,a.ownProperties),()=>t.error())})}function $(v,S){t.setParams({missingProperty:v}),e.forOf(v,n,()=>{e.assign(S,(0,as.propertyInData)(e,s,v,a.ownProperties)),e.if((0,ls.not)(S),()=>{t.error(),e.break()})},ls.nil)}}};_c.default=OT});var Vm=U($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var cs=ee(),NT={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,cs.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,cs._)`{limit: ${t}}`},LT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:NT,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?cs.operators.GT:cs.operators.LT;t.fail$data((0,cs._)`${r}.length ${s} ${n}`)}};$c.default=LT});var ti=U(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var Gm=Wl();Gm.code='require("ajv/dist/runtime/equal").default';xc.default=Gm});var Wm=U(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var Tc=Jn(),Ce=ee(),jT=de(),UT=ti(),DT={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}}`},qT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:DT,code(t){let{gen:e,data:r,$data:n,schema:s,parentSchema:o,schemaCode:i,it:a}=t;if(!n&&!s)return;let l=e.let("valid"),u=o.items?(0,Tc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,Ce._)`${i} === false`),t.ok(l);function p(){let S=e.let("i",(0,Ce._)`${r}.length`),T=e.let("j");t.setParams({i:S,j:T}),e.assign(l,!0),e.if((0,Ce._)`${S} > 1`,()=>(g()?$:v)(S,T))}function g(){return u.length>0&&!u.some(S=>S==="object"||S==="array")}function $(S,T){let E=e.name("item"),P=(0,Tc.checkDataTypes)(u,E,a.opts.strictNumbers,Tc.DataType.Wrong),O=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${S}--;`,()=>{e.let(E,(0,Ce._)`${r}[${S}]`),e.if(P,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${E} == "string"`,(0,Ce._)`${E} += "_"`),e.if((0,Ce._)`typeof ${O}[${E}] == "number"`,()=>{e.assign(T,(0,Ce._)`${O}[${E}]`),t.error(),e.assign(l,!1).break()}).code((0,Ce._)`${O}[${E}] = ${S}`)})}function v(S,T){let E=(0,jT.useFunc)(e,UT.default),P=e.name("outer");e.label(P).for((0,Ce._)`;${S}--;`,()=>e.for((0,Ce._)`${T} = ${S}; ${T}--;`,()=>e.if((0,Ce._)`${E}(${r}[${S}], ${r}[${T}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Rc.default=qT});var Jm=U(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var Ec=ee(),MT=de(),zT=ti(),BT={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ec._)`{allowedValue: ${t}}`},FT={keyword:"const",$data:!0,error:BT,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Ec._)`!${(0,MT.useFunc)(e,zT.default)}(${r}, ${s})`):t.fail((0,Ec._)`${o} !== ${r}`)}};Pc.default=FT});var Ym=U(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var ds=ee(),HT=de(),KT=ti(),VT={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ds._)`{allowedValues: ${t}}`},GT={keyword:"enum",schemaType:"array",$data:!0,error:VT,code(t){let{gen:e,data:r,$data:n,schema:s,schemaCode:o,it:i}=t;if(!n&&s.length===0)throw new Error("enum must have non-empty array");let a=s.length>=i.opts.loopEnum,l,u=()=>l??(l=(0,HT.useFunc)(e,KT.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,g);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let v=e.const("vSchema",o);p=(0,ds.or)(...s.map((S,T)=>$(v,T)))}t.pass(p);function g(){e.assign(p,!1),e.forOf("v",o,v=>e.if((0,ds._)`${u()}(${r}, ${v})`,()=>e.assign(p,!0).break()))}function $(v,S){let T=s[S];return typeof T=="object"&&T!==null?(0,ds._)`${u()}(${r}, ${v}[${S}])`:(0,ds._)`${r} === ${T}`}}};Ac.default=GT});var Zm=U(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var WT=Dm(),JT=qm(),YT=Bm(),ZT=Fm(),QT=Hm(),XT=Km(),eR=Vm(),tR=Wm(),rR=Jm(),nR=Ym(),sR=[WT.default,JT.default,YT.default,ZT.default,QT.default,XT.default,eR.default,tR.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rR.default,nR.default];Ic.default=sR});var Oc=U(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.validateAdditionalItems=void 0;var kr=ee(),Cc=de(),oR={message:({params:{len:t}})=>(0,kr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,kr._)`{limit: ${t}}`},iR={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:oR,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Cc.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}Qm(t,n)}};function Qm(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,kr._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,kr._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Cc.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,kr._)`${a} <= ${e.length}`);r.if((0,kr.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Cc.Type.Num},u),i.allErrors||r.if((0,kr.not)(u),()=>r.break())})}}us.validateAdditionalItems=Qm;us.default=iR});var Nc=U(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.validateTuple=void 0;var Xm=ee(),ri=de(),aR=lt(),lR={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return eg(t,"additionalItems",e);r.items=!0,!(0,ri.alwaysValidSchema)(r,e)&&t.ok((0,aR.validateArray)(t))}};function eg(t,e,r=t.schema){let{gen:n,parentSchema:s,data:o,keyword:i,it:a}=t;p(s),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ri.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),u=n.const("len",(0,Xm._)`${o}.length`);r.forEach((g,$)=>{(0,ri.alwaysValidSchema)(a,g)||(n.if((0,Xm._)`${u} > ${$}`,()=>t.subschema({keyword:i,schemaProp:$,dataProp:$},l)),t.ok(l))});function p(g){let{opts:$,errSchemaPath:v}=a,S=r.length,T=S===g.minItems&&(S===g.maxItems||g[e]===!1);if($.strictTuples&&!T){let E=`"${i}" is ${S}-tuple, but minItems or maxItems/${e} are not specified or different at path "${v}"`;(0,ri.checkStrictMode)(a,E,$.strictTuples)}}}ps.validateTuple=eg;ps.default=lR});var tg=U(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var cR=Nc(),dR={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,cR.validateTuple)(t,"items")};Lc.default=dR});var ng=U(jc=>{"use strict";Object.defineProperty(jc,"__esModule",{value:!0});var rg=ee(),uR=de(),pR=lt(),hR=Oc(),fR={message:({params:{len:t}})=>(0,rg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,rg._)`{limit: ${t}}`},mR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:fR,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,uR.alwaysValidSchema)(n,e)&&(s?(0,hR.validateAdditionalItems)(t,s):t.ok((0,pR.validateArray)(t)))}};jc.default=mR});var sg=U(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var dt=ee(),ni=de(),gR={message:({params:{min:t,max:e}})=>e===void 0?(0,dt.str)`must contain at least ${t} valid item(s)`:(0,dt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dt._)`{minContains: ${t}}`:(0,dt._)`{minContains: ${t}, maxContains: ${e}}`},bR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:gR,code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t,i,a,{minContains:l,maxContains:u}=n;o.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=e.const("len",(0,dt._)`${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,r)){let T=(0,dt._)`${p} >= ${i}`;a!==void 0&&(T=(0,dt._)`${T} && ${p} <= ${a}`),t.pass(T);return}o.items=!0;let g=e.name("valid");a===void 0&&i===1?v(g,()=>e.if(g,()=>e.break())):i===0?(e.let(g,!0),a!==void 0&&e.if((0,dt._)`${s}.length > 0`,$)):(e.let(g,!1),$()),t.result(g,()=>t.reset());function $(){let T=e.name("_valid"),E=e.let("count",0);v(T,()=>e.if(T,()=>S(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 S(T){e.code((0,dt._)`${T}++`),a===void 0?e.if((0,dt._)`${T} >= ${i}`,()=>e.assign(g,!0).break()):(e.if((0,dt._)`${T} > ${a}`,()=>e.assign(g,!1).break()),i===1?e.assign(g,!0):e.if((0,dt._)`${T} >= ${i}`,()=>e.assign(g,!0)))}}};Uc.default=bR});var ag=U($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.validateSchemaDeps=$t.validatePropertyDeps=$t.error=void 0;var Dc=ee(),yR=de(),hs=lt();$t.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Dc.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Dc._)`{property: ${t},
1869
- missingProperty: ${n},
1859
+ `});import*as th from"zod/v3";import*as dn from"zod/v4-mini";function kt(t){return!!t._zod}function un(t){let e=Object.values(t);if(e.length===0)return dn.object({});let n=e.every(kt),r=e.every(s=>!kt(s));if(n)return dn.object(t);if(r)return th.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Kt(t,e){return kt(t)?dn.safeParse(t,e):t.safeParse(e)}async function Js(t,e){return kt(t)?await dn.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 jn(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 un(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 ok(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function Ys(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 ${ok(e.path)}`:e.message).join(`
1860
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function nh(t){return t.description}function rh(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 Dn(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 Rr=j(()=>{});import*as c from"zod/v4";function vh(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function kh(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var _a,sh,Gt,Xs,xe,oh,ih,RI,ik,ak,$a,Xe,Er,ah,Pe,st,ot,Ae,Qs,lh,xa,ch,dh,Ta,Pr,H,Ra,uh,ph,EI,eo,lk,to,ck,Ar,Un,hh,dk,uk,pk,hk,fk,mk,Ea,gk,bk,Pa,no,yk,wk,ro,vk,Ir,Cr,kk,Or,Mn,Sk,Nr,so,oo,io,PI,ao,lo,co,fh,mh,gh,Aa,bh,Lr,zn,yh,_k,uo,$k,po,xk,Ia,Tk,ho,Rk,Ek,Pk,Ak,Ik,Ck,Ok,Nk,Lk,jk,fo,Dk,Uk,mo,Ca,Oa,Na,Mk,zk,qk,La,Bk,Fk,Hk,Kk,Vk,wh,go,Gk,bo,AI,Wk,qn,Jk,II,jr,Yk,ja,Zk,Xk,Qk,eS,tS,nS,rS,Zs,sS,oS,iS,Dr,Da,aS,lS,cS,dS,uS,pS,hS,fS,mS,gS,bS,yS,wS,vS,kS,SS,_S,$S,Bn,xS,TS,RS,yo,ES,PS,AS,Ua,IS,CI,OI,NI,LI,jI,DI,z,Sa,Fn=j(()=>{_a="2025-11-25",sh=[_a,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Gt="io.modelcontextprotocol/related-task",Xs="2.0",xe=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),oh=c.union([c.string(),c.number().int()]),ih=c.string(),RI=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),ik=c.object({ttl:c.number().optional()}),ak=c.object({taskId:c.string()}),$a=c.looseObject({progressToken:oh.optional(),[Gt]:ak.optional()}),Xe=c.object({_meta:$a.optional()}),Er=Xe.extend({task:ik.optional()}),ah=t=>Er.safeParse(t).success,Pe=c.object({method:c.string(),params:Xe.loose().optional()}),st=c.object({_meta:$a.optional()}),ot=c.object({method:c.string(),params:st.loose().optional()}),Ae=c.looseObject({_meta:$a.optional()}),Qs=c.union([c.string(),c.number().int()]),lh=c.object({jsonrpc:c.literal(Xs),id:Qs,...Pe.shape}).strict(),xa=t=>lh.safeParse(t).success,ch=c.object({jsonrpc:c.literal(Xs),...ot.shape}).strict(),dh=t=>ch.safeParse(t).success,Ta=c.object({jsonrpc:c.literal(Xs),id:Qs,result:Ae}).strict(),Pr=t=>Ta.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"})(H||(H={}));Ra=c.object({jsonrpc:c.literal(Xs),id:Qs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),uh=t=>Ra.safeParse(t).success,ph=c.union([lh,ch,Ta,Ra]),EI=c.union([Ta,Ra]),eo=Ae.strict(),lk=st.extend({requestId:Qs.optional(),reason:c.string().optional()}),to=ot.extend({method:c.literal("notifications/cancelled"),params:lk}),ck=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Ar=c.object({icons:c.array(ck).optional()}),Un=c.object({name:c.string(),title:c.string().optional()}),hh=Un.extend({...Un.shape,...Ar.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),dk=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),uk=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:dk.optional(),url:xe.optional()}),c.record(c.string(),c.unknown()).optional())),pk=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()}),hk=c.looseObject({list:xe.optional(),cancel:xe.optional(),requests:c.looseObject({tools:c.looseObject({call:xe.optional()}).optional()}).optional()}),fk=c.object({experimental:c.record(c.string(),xe).optional(),sampling:c.object({context:xe.optional(),tools:xe.optional()}).optional(),elicitation:uk.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:pk.optional(),extensions:c.record(c.string(),xe).optional()}),mk=Xe.extend({protocolVersion:c.string(),capabilities:fk,clientInfo:hh}),Ea=Pe.extend({method:c.literal("initialize"),params:mk}),gk=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:hk.optional(),extensions:c.record(c.string(),xe).optional()}),bk=Ae.extend({protocolVersion:c.string(),capabilities:gk,serverInfo:hh,instructions:c.string().optional()}),Pa=ot.extend({method:c.literal("notifications/initialized"),params:st.optional()}),no=Pe.extend({method:c.literal("ping"),params:Xe.optional()}),yk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),wk=c.object({...st.shape,...yk.shape,progressToken:oh}),ro=ot.extend({method:c.literal("notifications/progress"),params:wk}),vk=Xe.extend({cursor:ih.optional()}),Ir=Pe.extend({params:vk.optional()}),Cr=Ae.extend({nextCursor:ih.optional()}),kk=c.enum(["working","input_required","completed","failed","cancelled"]),Or=c.object({taskId:c.string(),status:kk,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:Or}),Sk=st.merge(Or),Nr=ot.extend({method:c.literal("notifications/tasks/status"),params:Sk}),so=Pe.extend({method:c.literal("tasks/get"),params:Xe.extend({taskId:c.string()})}),oo=Ae.merge(Or),io=Pe.extend({method:c.literal("tasks/result"),params:Xe.extend({taskId:c.string()})}),PI=Ae.loose(),ao=Ir.extend({method:c.literal("tasks/list")}),lo=Cr.extend({tasks:c.array(Or)}),co=Pe.extend({method:c.literal("tasks/cancel"),params:Xe.extend({taskId:c.string()})}),fh=Ae.merge(Or),mh=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),gh=mh.extend({text:c.string()}),Aa=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bh=mh.extend({blob:Aa}),Lr=c.enum(["user","assistant"]),zn=c.object({audience:c.array(Lr).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),yh=c.object({...Un.shape,...Ar.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:zn.optional(),_meta:c.optional(c.looseObject({}))}),_k=c.object({...Un.shape,...Ar.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:zn.optional(),_meta:c.optional(c.looseObject({}))}),uo=Ir.extend({method:c.literal("resources/list")}),$k=Cr.extend({resources:c.array(yh)}),po=Ir.extend({method:c.literal("resources/templates/list")}),xk=Cr.extend({resourceTemplates:c.array(_k)}),Ia=Xe.extend({uri:c.string()}),Tk=Ia,ho=Pe.extend({method:c.literal("resources/read"),params:Tk}),Rk=Ae.extend({contents:c.array(c.union([gh,bh]))}),Ek=ot.extend({method:c.literal("notifications/resources/list_changed"),params:st.optional()}),Pk=Ia,Ak=Pe.extend({method:c.literal("resources/subscribe"),params:Pk}),Ik=Ia,Ck=Pe.extend({method:c.literal("resources/unsubscribe"),params:Ik}),Ok=st.extend({uri:c.string()}),Nk=ot.extend({method:c.literal("notifications/resources/updated"),params:Ok}),Lk=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),jk=c.object({...Un.shape,...Ar.shape,description:c.optional(c.string()),arguments:c.optional(c.array(Lk)),_meta:c.optional(c.looseObject({}))}),fo=Ir.extend({method:c.literal("prompts/list")}),Dk=Cr.extend({prompts:c.array(jk)}),Uk=Xe.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),mo=Pe.extend({method:c.literal("prompts/get"),params:Uk}),Ca=c.object({type:c.literal("text"),text:c.string(),annotations:zn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Oa=c.object({type:c.literal("image"),data:Aa,mimeType:c.string(),annotations:zn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Na=c.object({type:c.literal("audio"),data:Aa,mimeType:c.string(),annotations:zn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Mk=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()}),zk=c.object({type:c.literal("resource"),resource:c.union([gh,bh]),annotations:zn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),qk=yh.extend({type:c.literal("resource_link")}),La=c.union([Ca,Oa,Na,qk,zk]),Bk=c.object({role:Lr,content:La}),Fk=Ae.extend({description:c.string().optional(),messages:c.array(Bk)}),Hk=ot.extend({method:c.literal("notifications/prompts/list_changed"),params:st.optional()}),Kk=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),Vk=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),wh=c.object({...Un.shape,...Ar.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:Kk.optional(),execution:Vk.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),go=Ir.extend({method:c.literal("tools/list")}),Gk=Cr.extend({tools:c.array(wh)}),bo=Ae.extend({content:c.array(La).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),AI=bo.or(Ae.extend({toolResult:c.unknown()})),Wk=Er.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),qn=Pe.extend({method:c.literal("tools/call"),params:Wk}),Jk=ot.extend({method:c.literal("notifications/tools/list_changed"),params:st.optional()}),II=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),jr=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Yk=Xe.extend({level:jr}),ja=Pe.extend({method:c.literal("logging/setLevel"),params:Yk}),Zk=st.extend({level:jr,logger:c.string().optional(),data:c.unknown()}),Xk=ot.extend({method:c.literal("notifications/message"),params:Zk}),Qk=c.object({name:c.string().optional()}),eS=c.object({hints:c.array(Qk).optional(),costPriority:c.number().min(0).max(1).optional(),speedPriority:c.number().min(0).max(1).optional(),intelligencePriority:c.number().min(0).max(1).optional()}),tS=c.object({mode:c.enum(["auto","required","none"]).optional()}),nS=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(La).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),rS=c.discriminatedUnion("type",[Ca,Oa,Na]),Zs=c.discriminatedUnion("type",[Ca,Oa,Na,Mk,nS]),sS=c.object({role:Lr,content:c.union([Zs,c.array(Zs)]),_meta:c.record(c.string(),c.unknown()).optional()}),oS=Er.extend({messages:c.array(sS),modelPreferences:eS.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(wh).optional(),toolChoice:tS.optional()}),iS=Pe.extend({method:c.literal("sampling/createMessage"),params:oS}),Dr=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Lr,content:rS}),Da=Ae.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Lr,content:c.union([Zs,c.array(Zs)])}),aS=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),lS=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()}),cS=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()}),dS=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),uS=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()}),pS=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()}),hS=c.union([dS,uS]),fS=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()}),mS=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()}),gS=c.union([fS,mS]),bS=c.union([pS,hS,gS]),yS=c.union([bS,aS,lS,cS]),wS=Er.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),yS),required:c.array(c.string()).optional()})}),vS=Er.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),kS=c.union([wS,vS]),SS=Pe.extend({method:c.literal("elicitation/create"),params:kS}),_S=st.extend({elicitationId:c.string()}),$S=ot.extend({method:c.literal("notifications/elicitation/complete"),params:_S}),Bn=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())}),xS=c.object({type:c.literal("ref/resource"),uri:c.string()}),TS=c.object({type:c.literal("ref/prompt"),name:c.string()}),RS=Xe.extend({ref:c.union([TS,xS]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),yo=Pe.extend({method:c.literal("completion/complete"),params:RS});ES=Ae.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),PS=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),AS=Pe.extend({method:c.literal("roots/list"),params:Xe.optional()}),Ua=Ae.extend({roots:c.array(PS)}),IS=ot.extend({method:c.literal("notifications/roots/list_changed"),params:st.optional()}),CI=c.union([no,Ea,yo,ja,mo,fo,uo,po,ho,Ak,Ck,qn,go,so,io,ao,co]),OI=c.union([to,ro,Pa,IS,Nr]),NI=c.union([eo,Dr,Da,Bn,Ua,oo,lo,Mn]),LI=c.union([no,iS,SS,AS,so,io,ao,co]),jI=c.union([to,ro,Xk,Nk,Ek,Jk,Hk,Nr,$S]),DI=c.union([eo,bk,ES,Fk,Dk,$k,xk,Rk,bo,Gk,oo,lo,Mn]),z=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===H.UrlElicitationRequired&&r){let s=r;if(s.elicitations)return new Sa(s.elicitations,n)}return new t(e,n,r)}},Sa=class extends z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(H.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Wt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Sh=j(()=>{});var $h,_h,xh,wo=j(()=>{$h=Symbol("Let zodToJsonSchema decide on which parser to use"),_h={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"},xh=t=>typeof t=="string"?{..._h,name:t}:{..._h,...t}});var Th,Ma=j(()=>{wo();Th=t=>{let e=xh(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 za(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ie(t,e,n,r,s){t[e]=n,za(t,e,r,s)}var Jt=j(()=>{});var vo,ko=j(()=>{vo=(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"?vo(e,t.currentPath):e.join("/")}}var it=j(()=>{ko()});import{ZodFirstPartyTypeKind as CS}from"zod/v3";function Rh(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==CS.ZodAny&&(n.items=W(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 qa=j(()=>{Jt();$e()});function Eh(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 Ba=j(()=>{Jt()});function Ph(){return{type:"boolean"}}var Fa=j(()=>{});function So(t,e){return W(t.type._def,e)}var _o=j(()=>{$e()});var Ah,Ha=j(()=>{$e();Ah=(t,e)=>W(t.innerType._def,e)});function Ka(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,o)=>Ka(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 OS(t,e)}}var OS,Va=j(()=>{Jt();OS=(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 Ih(t,e){return{...W(t.innerType._def,e),default:t.defaultValue()}}var Ga=j(()=>{$e()});function Ch(t,e){return e.effectStrategy==="input"?W(t.schema._def,e):we(e)}var Wa=j(()=>{$e();it()});function Oh(t){return{type:"string",enum:Array.from(t.values)}}var Ja=j(()=>{});function Nh(t,e){let n=[W(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),W(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(NS(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 NS,Ya=j(()=>{$e();NS=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Lh(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 Za=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":qe(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":qe(n,r.regex,r.message,e);break;case"cuid":qe(n,ht.cuid,r.message,e);break;case"cuid2":qe(n,ht.cuid2,r.message,e);break;case"startsWith":qe(n,RegExp(`^${Qa(r.value,e)}`),r.message,e);break;case"endsWith":qe(n,RegExp(`${Qa(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":{qe(n,RegExp(Qa(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":qe(n,ht.base64url,r.message,e);break;case"jwt":qe(n,ht.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&qe(n,ht.ipv4Cidr,r.message,e),r.version!=="v4"&&qe(n,ht.ipv6Cidr,r.message,e);break}case"emoji":qe(n,ht.emoji(),r.message,e);break;case"ulid":{qe(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":{qe(n,ht.base64,r.message,e);break}}break}case"nanoid":qe(n,ht.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Qa(t,e){return e.patternStrategy==="escape"?jS(t):t}function jS(t){let e="";for(let n=0;n<t.length;n++)LS.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 qe(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:jh(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ie(t,"pattern",jh(e,r),n,r)}function jh(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
1861
+ ]))`;continue}else if(r[l]==="$"){s+=`($|(?=[\r
1862
+ ]))`;continue}}if(n.s&&r[l]==="."){s+=i?`${r[l]}\r
1863
+ `:`[${r[l]}\r
1864
+ ]`;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 Xa,ht,LS,xo=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:()=>(Xa===void 0&&(Xa=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Xa),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-_]*$/};LS=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Ur}from"zod/v3";function To(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===Ur.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((r,s)=>({...r,[s]:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??we(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===Ur.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===Ur.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Ur.ZodBranded&&t.keyType._def.type._def.typeName===Ur.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...s}=So(t.keyType._def,e);return{...n,propertyNames:s}}}return n}var Ro=j(()=>{$e();xo();_o();it()});function Dh(t,e){if(e.mapStrategy==="record")return To(t,e);let n=W(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||we(e),r=W(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 el=j(()=>{$e();Ro();it()});function Uh(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 tl=j(()=>{});function Mh(t){return t.target==="openAi"?void 0:{not:we({...t,currentPath:[...t.currentPath,"not"]})}}var nl=j(()=>{it()});function zh(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var rl=j(()=>{});function Bh(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 Mr&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((s,o)=>{let i=Mr[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 Mr,qh,Eo=j(()=>{$e();Mr={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)=>W(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 Fh(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:Mr[t.innerType._def.typeName],nullable:!0}:{type:[Mr[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=W(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}var sl=j(()=>{$e();Eo()});function Hh(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",za(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 ol=j(()=>{Jt()});function Kh(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=US(l);u&&n&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=W(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=DS(t,e);return i!==void 0&&(r.additionalProperties=i),r}function DS(t,e){if(t.catchall._def.typeName!=="ZodNever")return W(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 US(t){try{return t.isOptional()}catch{return!0}}var il=j(()=>{$e()});var Vh,al=j(()=>{$e();it();Vh=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return W(t.innerType._def,e);let n=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:we(e)},n]}:we(e)}});var Gh,ll=j(()=>{$e();Gh=(t,e)=>{if(e.pipeStrategy==="input")return W(t.in._def,e);if(e.pipeStrategy==="output")return W(t.out._def,e);let n=W(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=W(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(s=>s!==void 0)}}});function Wh(t,e){return W(t.type._def,e)}var cl=j(()=>{$e()});function Jh(t,e){let r={type:"array",uniqueItems:!0,items:W(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 dl=j(()=>{Jt();$e()});function Yh(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>W(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:W(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>W(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}var ul=j(()=>{$e()});function Zh(t){return{not:we(t)}}var pl=j(()=>{it()});function Xh(t){return we(t)}var hl=j(()=>{it()});var Qh,fl=j(()=>{$e();Qh=(t,e)=>W(t.innerType._def,e)});import{ZodFirstPartyTypeKind as oe}from"zod/v3";var ef,ml=j(()=>{it();qa();Ba();Fa();_o();Ha();Va();Ga();Wa();Ja();Ya();Za();el();tl();nl();rl();sl();ol();il();al();ll();cl();Ro();dl();xo();ul();pl();Eo();hl();fl();ef=(t,e,n)=>{switch(e){case oe.ZodString:return $o(t,n);case oe.ZodNumber:return Hh(t,n);case oe.ZodObject:return Kh(t,n);case oe.ZodBigInt:return Eh(t,n);case oe.ZodBoolean:return Ph();case oe.ZodDate:return Ka(t,n);case oe.ZodUndefined:return Zh(n);case oe.ZodNull:return zh(n);case oe.ZodArray:return Rh(t,n);case oe.ZodUnion:case oe.ZodDiscriminatedUnion:return Bh(t,n);case oe.ZodIntersection:return Nh(t,n);case oe.ZodTuple:return Yh(t,n);case oe.ZodRecord:return To(t,n);case oe.ZodLiteral:return Lh(t,n);case oe.ZodEnum:return Oh(t);case oe.ZodNativeEnum:return Uh(t);case oe.ZodNullable:return Fh(t,n);case oe.ZodOptional:return Vh(t,n);case oe.ZodMap:return Dh(t,n);case oe.ZodSet:return Jh(t,n);case oe.ZodLazy:return()=>t.getter()._def;case oe.ZodPromise:return Wh(t,n);case oe.ZodNaN:case oe.ZodNever:return Mh(n);case oe.ZodEffects:return Ch(t,n);case oe.ZodAny:return we(n);case oe.ZodUnknown:return Xh(n);case oe.ZodDefault:return Ih(t,n);case oe.ZodBranded:return So(t,n);case oe.ZodReadonly:return Qh(t,n);case oe.ZodCatch:return Ah(t,n);case oe.ZodPipeline:return Gh(t,n);case oe.ZodFunction:case oe.ZodVoid:case oe.ZodSymbol:return;default:return(r=>{})(e)}}});function W(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==$h)return a}if(r&&!n){let a=MS(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=ef(t,t.typeName,e),i=typeof o=="function"?W(o(),e):o;if(i&&zS(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var MS,zS,$e=j(()=>{wo();ml();ko();it();MS=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:vo(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}},zS=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n)});var tf=j(()=>{});var gl,bl=j(()=>{$e();Ma();it();gl=(t,e)=>{let n=Th(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:W(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=W(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 nf=j(()=>{wo();Ma();Jt();ko();$e();tf();it();qa();Ba();Fa();_o();Ha();Va();Ga();Wa();Ja();Ya();Za();el();tl();nl();rl();sl();ol();il();al();ll();cl();fl();Ro();dl();xo();ul();pl();Eo();hl();ml();bl();bl()});import*as rf from"zod/v4-mini";function qS(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function yl(t,e){return kt(t)?rf.toJSONSchema(t,{target:qS(e?.target),io:e?.pipeStrategy??"input"}):gl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function wl(t){let n=Vt(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Dn(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function vl(t,e){let n=Kt(t,e);if(!n.success)throw n.error;return n.data}var kl=j(()=>{Rr();nf()});function sf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function of(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];sf(i)&&sf(o)?n[s]={...i,...o}:n[s]=o}return n}var BS,Po,af=j(()=>{Rr();Fn();Sh();kl();BS=6e4,Po=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(to,n=>{this._oncancel(n)}),this.setNotificationHandler(ro,n=>{this._onprogress(n)}),this.setRequestHandler(no,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(so,async(n,r)=>{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(H.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(io,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 g=l,$=new z(g.error.code,g.error.message,g.error.data);p($)}else{let g=a.type==="response"?"Response":"Error";this._onerror(new Error(`${g} 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 z(H.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(ao,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 z(H.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(co,async(n,r)=>{try{let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(H.InvalidParams,`Task not found: ${n.params.taskId}`);if(Wt(s.status))throw new z(H.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 z(H.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof z?s:new z(H.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),z.fromError(H.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),Pr(o)||uh(o)?this._onresponse(o):xa(o)?this._onrequest(o,i):dh(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=z.fromError(H.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:H.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:p,timestamp:Date.now()},s?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):s?.send(p).catch(g=>this._onerror(new Error(`Failed to send an error response: ${g}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=ah(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 g={relatedRequestId:e.id};o&&(g.relatedTask={taskId:o}),await this.notification(p,g)},sendRequest:async(p,g,$)=>{if(i.signal.aborted)throw new z(H.ConnectionClosed,"Request was cancelled");let v={...$,relatedRequestId:e.id};o&&!v.relatedTask&&(v.relatedTask={taskId:o});let S=v.relatedTask?.taskId??o;return S&&l&&await l.updateTaskStatus(S,"input_required"),await this.request(p,g,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 g={result:p,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:g,timestamp:Date.now()},s?.sessionId):await s?.send(g)},async p=>{if(i.signal.aborted)return;let g={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(p.code)?p.code:H.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:g,timestamp:Date.now()},s?.sessionId):await s?.send(g)}).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),Pr(e))r(e);else{let i=new z(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(Pr(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),Pr(e))s(e);else{let i=z.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 z?i:new z(H.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 z(H.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 z(H.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(H.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 z?i:new z(H.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 g=O=>{p(O)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(O){g(O);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 S=O=>{this._responseHandlers.delete($),this._progressHandlers.delete($),this._cleanupTimeout($),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:$,reason:String(O)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(re=>this._onerror(new Error(`Failed to send cancellation: ${re}`)));let U=O instanceof z?O:new z(H.RequestTimeout,String(O));p(U)};this._responseHandlers.set($,O=>{if(!r?.signal?.aborted){if(O instanceof Error)return p(O);try{let U=Kt(n,O.result);U.success?u(U.data):p(U.error)}catch(U){p(U)}}}),r?.signal?.addEventListener("abort",()=>{S(r?.signal?.reason)});let T=r?.timeout??BS,E=()=>S(z.fromError(H.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout($,T,r?.maxTotalTimeout,E,r?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let O=U=>{let re=this._responseHandlers.get($);re?re(U):this._onerror(new Error(`Response handler missing for side-channeled request ${$}`))};this._requestResolvers.set($,O),this._enqueueTaskMessage(P,{type:"request",message:v,timestamp:Date.now()}).catch(U=>{this._cleanupTimeout($),p(U)})}else this._transport.send(v,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(O=>{this._cleanupTimeout($),p(O)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},oo,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},lo,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},fh,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=wl(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(s,o)=>{let i=vl(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=wl(e);this._notificationHandlers.set(r,s=>{let o=vl(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"&&xa(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new z(H.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 z(H.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,r);n.addEventListener("abort",()=>{clearTimeout(i),o(new z(H.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 z(H.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=Nr.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 z(H.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(Wt(a.status))throw new z(H.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=Nr.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Wt(l.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>r.listTasks(s,n)}}}});var Br=D(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 zr=class{};pe._CodeOrName=zr;pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var pn=class extends zr{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=pn;var at=class extends zr{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 pn&&(n[r.str]=(n[r.str]||0)+1),n),{})}};pe._Code=at;pe.nil=new at("");function lf(t,...e){let n=[t[0]],r=0;for(;r<e.length;)_l(n,e[r]),n.push(t[++r]);return new at(n)}pe._=lf;var Sl=new at("+");function cf(t,...e){let n=[qr(t[0])],r=0;for(;r<e.length;)n.push(Sl),_l(n,e[r]),n.push(Sl,qr(t[++r]));return FS(n),new at(n)}pe.str=cf;function _l(t,e){e instanceof at?t.push(...e._items):e instanceof pn?t.push(e):t.push(VS(e))}pe.addCodeArg=_l;function FS(t){let e=1;for(;e<t.length-1;){if(t[e]===Sl){let n=HS(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function HS(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof pn||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 pn))return`"${t}${e.slice(1)}`}function KS(t,e){return e.emptyStr()?t:t.emptyStr()?e:cf`${t}${e}`}pe.strConcat=KS;function VS(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:qr(Array.isArray(t)?t.join(","):t)}function GS(t){return new at(qr(t))}pe.stringify=GS;function qr(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}pe.safeStringify=qr;function WS(t){return typeof t=="string"&&pe.IDENTIFIER.test(t)?new at(`.${t}`):lf`[${t}]`}pe.getProperty=WS;function JS(t){if(typeof t=="string"&&pe.IDENTIFIER.test(t))return new at(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}pe.getEsmExportName=JS;function YS(t){return new at(t.toString())}pe.regexpCode=YS});var Tl=D(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.ValueScope=Ge.ValueScopeName=Ge.Scope=Ge.varKinds=Ge.UsedValueState=void 0;var Ve=Br(),$l=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ao;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ao||(Ge.UsedValueState=Ao={}));Ge.varKinds={const:new Ve.Name("const"),let:new Ve.Name("let"),var:new Ve.Name("var")};var Io=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=Io;var Co=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=Co;var ZS=(0,Ve._)`\n`,xl=class extends Io{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?ZS:Ve.nil}}get(){return this._scope}name(e){return new Co(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,Ao.Started);let p=n(u);if(p){let g=this.opts.es5?Ge.varKinds.var:Ge.varKinds.const;o=(0,Ve._)`${o}${g} ${u} = ${p};${this.opts._n}`}else if(p=s?.(u))o=(0,Ve._)`${o}${p}${this.opts._n}`;else throw new $l(u);l.set(u,Ao.Completed)})}return o}};Ge.ValueScope=xl});var ee=D(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=Br(),mt=Tl(),Yt=Br();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 jo=Tl();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return jo.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return jo.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return jo.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return jo.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}},Rl=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=Kn(this.rhs,e,n)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},Oo=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=Kn(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return Lo(e,this.rhs)}},El=class extends Oo{constructor(e,n,r,s){super(e,r,s),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Pl=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Al=class extends Ct{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Il=class extends Ct{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Cl=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=Kn(this.code,e,n),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},Fr=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)||(XS(e,o.names),r.splice(s,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>mn(e,n.names),{})}},Ot=class extends Fr{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ol=class extends Fr{},Hn=class extends Ot{};Hn.kind="else";var hn=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 Hn(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(df(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=Kn(this.condition,e,n),this}get names(){let e=super.names;return Lo(e,this.condition),this.else&&mn(e,this.else.names),e}};hn.kind="if";var fn=class extends Ot{};fn.kind="for";var Nl=class extends fn{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=Kn(this.iteration,e,n),this}get names(){return mn(super.names,this.iteration.names)}},Ll=class extends fn{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=Lo(super.names,this.from);return Lo(e,this.to)}},No=class extends fn{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=Kn(this.iterable,e,n),this}get names(){return mn(super.names,this.iterable.names)}},Hr=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)}};Hr.kind="func";var Kr=class extends Fr{render(e){return"return "+super.render(e)}};Kr.kind="return";var jl=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&&mn(e,this.catch.names),this.finally&&mn(e,this.finally.names),e}},Vr=class extends Ot{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Vr.kind="catch";var Gr=class extends Ot{render(e){return"finally"+super.render(e)}};Gr.kind="finally";var Dl=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
1865
+ `:""},this._extScope=e,this._scope=new mt.Scope({parent:e}),this._nodes=[new Ol]}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 Rl(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 Oo(e,n,r))}add(e,n){return this._leafNode(new El(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new Cl(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 hn(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 hn(e))}else(){return this._elseNode(new Hn)}endIf(){return this._endBlockNode(hn,Hn)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Nl(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 Ll(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 No("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 No("in",s,o,n),()=>r(o))}endFor(){return this._endBlockNode(fn)}label(e){return this._leafNode(new Pl(e))}break(e){return this._leafNode(new Al(e))}return(e){let n=new Kr;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Kr)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new jl;if(this._blockNode(s),this.code(e),n){let o=this.name("e");this._currNode=s.catch=new Vr(o),n(o)}return r&&(this._currNode=s.finally=new Gr,this.code(r)),this._endBlockNode(Vr,Gr)}throw(e){return this._leafNode(new Il(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 Hr(e,n,r)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Hr)}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 hn))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=Dl;function mn(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function Lo(t,e){return e instanceof ae._CodeOrName?mn(t,e.names):t}function Kn(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 XS(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function df(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${Ul(t)}`}te.not=df;var QS=uf(te.operators.AND);function e_(...t){return t.reduce(QS)}te.and=e_;var t_=uf(te.operators.OR);function n_(...t){return t.reduce(t_)}te.or=n_;function uf(t){return(e,n)=>e===ae.nil?n:n===ae.nil?e:(0,ae._)`${Ul(e)} ${t} ${Ul(n)}`}function Ul(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var de=D(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(),r_=Br();function s_(t){let e={};for(let n of t)e[n]=!0;return e}ne.toHash=s_;function o_(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ff(t,e),!mf(e,t.self.RULES.all))}ne.alwaysValidSchema=o_;function ff(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]||yf(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=ff;function mf(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}ne.schemaHasRules=mf;function i_(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=i_;function a_({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=a_;function l_(t){return gf(decodeURIComponent(t))}ne.unescapeFragment=l_;function c_(t){return encodeURIComponent(zl(t))}ne.escapeFragment=c_;function zl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=zl;function gf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=gf;function d_(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}ne.eachItem=d_;function pf({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:pf({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} || {}`),ql(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:bf}),items:pf({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 bf(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,ge._)`{}`);return e!==void 0&&ql(t,n,e),n}ne.evaluatedPropsToName=bf;function ql(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(r)}`,!0))}ne.setEvaluated=ql;var hf={};function u_(t,e){return t.scopeValue("func",{ref:e,code:hf[e.code]||(hf[e.code]=new r_._Code(e.code))})}ne.useFunc=u_;var Ml;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ml||(ne.Type=Ml={}));function p_(t,e,n){if(t instanceof ge.Name){let r=e===Ml.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():"/"+zl(t)}ne.getErrorPath=p_;function yf(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=yf});var Nt=D(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var Oe=ee(),h_={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")};Bl.default=h_});var Wr=D(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(),Do=de(),Be=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 f_(t,e=Ne.keywordError,n,r){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,l=kf(t,e,n);r??(i||a)?wf(o,l):vf(s,(0,ue._)`[${l}]`)}Ne.reportError=f_;function m_(t,e=Ne.keywordError,n){let{it:r}=t,{gen:s,compositeRule:o,allErrors:i}=r,a=kf(t,e,n);wf(s,a),o||i||vf(r,Be.default.vErrors)}Ne.reportExtraError=m_;function g_(t,e){t.assign(Be.default.errors,e),t.if((0,ue._)`${Be.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ue._)`${Be.default.vErrors}.length`,e),()=>t.assign(Be.default.vErrors,null)))}Ne.resetErrorsCount=g_;function b_({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,Be.default.errors,a=>{t.const(i,(0,ue._)`${Be.default.vErrors}[${a}]`),t.if((0,ue._)`${i}.instancePath === undefined`,()=>t.assign((0,ue._)`${i}.instancePath`,(0,ue.strConcat)(Be.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=b_;function wf(t,e){let n=t.const("err",e);t.if((0,ue._)`${Be.default.vErrors} === null`,()=>t.assign(Be.default.vErrors,(0,ue._)`[${n}]`),(0,ue._)`${Be.default.vErrors}.push(${n})`),t.code((0,ue._)`${Be.default.errors}++`)}function vf(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 gn={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 kf(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,ue._)`{}`:y_(t,e,n)}function y_(t,e,n={}){let{gen:r,it:s}=t,o=[w_(s,n),v_(t,n)];return k_(t,e,o),r.object(...o)}function w_({errorPath:t},{instancePath:e}){let n=e?(0,ue.str)`${t}${(0,Do.getErrorPath)(e,Do.Type.Str)}`:t;return[Be.default.instancePath,(0,ue.strConcat)(Be.default.instancePath,n)]}function v_({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,Do.getErrorPath)(n,Do.Type.Str)}`),[gn.schemaPath,s]}function k_(t,{params:e,message:n},r){let{keyword:s,data:o,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:g}=a;r.push([gn.keyword,s],[gn.params,typeof e=="function"?e(t):e||(0,ue._)`{}`]),l.messages&&r.push([gn.message,typeof n=="function"?n(t):n]),l.verbose&&r.push([gn.schema,i],[gn.parentSchema,(0,ue._)`${p}${g}`],[Be.default.data,o]),u&&r.push([gn.propertyName,u])}});var _f=D(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.boolOrEmptySchema=Vn.topBoolOrEmptySchema=void 0;var S_=Wr(),__=ee(),$_=Nt(),x_={message:"boolean schema is false"};function T_(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Sf(t,!1):typeof n=="object"&&n.$async===!0?e.return($_.default.data):(e.assign((0,__._)`${r}.errors`,null),e.return(!0))}Vn.topBoolOrEmptySchema=T_;function R_(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Sf(t)):n.var(e,!0)}Vn.boolOrEmptySchema=R_;function Sf(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,S_.reportError)(s,x_,void 0,e)}});var Fl=D(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.getRules=Gn.isJSONType=void 0;var E_=["string","number","integer","boolean","null","object","array"],P_=new Set(E_);function A_(t){return typeof t=="string"&&P_.has(t)}Gn.isJSONType=A_;function I_(){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:{}}}Gn.getRules=I_});var Hl=D(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.shouldUseRule=Zt.shouldUseGroup=Zt.schemaHasRulesForType=void 0;function C_({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&$f(t,r)}Zt.schemaHasRulesForType=C_;function $f(t,e){return e.rules.some(n=>xf(t,n))}Zt.shouldUseGroup=$f;function xf(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=xf});var Jr=D(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 O_=Fl(),N_=Hl(),L_=Wr(),X=ee(),Tf=de(),Wn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Wn||(Le.DataType=Wn={}));function j_(t){let e=Rf(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=j_;function Rf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(O_.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Le.getJSONTypes=Rf;function D_(t,e){let{gen:n,data:r,opts:s}=t,o=U_(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,N_.schemaHasRulesForType)(t,e[0]));if(i){let a=Vl(e,r,s.strictNumbers,Wn.Wrong);n.if(a,()=>{o.length?M_(t,e,o):Gl(t)})}return i}Le.coerceAndCheckDataType=D_;var Ef=new Set(["string","number","integer","boolean","null"]);function U_(t,e){return e?t.filter(n=>Ef.has(n)||e==="array"&&n==="array"):[]}function M_(t,e,n){let{gen:r,data:s,opts:o}=t,i=r.let("dataType",(0,X._)`typeof ${s}`),a=r.let("coerced",(0,X._)`undefined`);o.coerceTypes==="array"&&r.if((0,X._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>r.assign(s,(0,X._)`${s}[0]`).assign(i,(0,X._)`typeof ${s}`).if(Vl(e,s,o.strictNumbers),()=>r.assign(a,s))),r.if((0,X._)`${a} !== undefined`);for(let u of n)(Ef.has(u)||u==="array"&&o.coerceTypes==="array")&&l(u);r.else(),Gl(t),r.endIf(),r.if((0,X._)`${a} !== undefined`,()=>{r.assign(s,a),z_(t,a)});function l(u){switch(u){case"string":r.elseIf((0,X._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,X._)`"" + ${s}`).elseIf((0,X._)`${s} === null`).assign(a,(0,X._)`""`);return;case"number":r.elseIf((0,X._)`${i} == "boolean" || ${s} === null
1866
+ || (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,X._)`+${s}`);return;case"integer":r.elseIf((0,X._)`${i} === "boolean" || ${s} === null
1867
+ || (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,X._)`+${s}`);return;case"boolean":r.elseIf((0,X._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,X._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":r.elseIf((0,X._)`${s} === "" || ${s} === 0 || ${s} === false`),r.assign(a,null);return;case"array":r.elseIf((0,X._)`${i} === "string" || ${i} === "number"
1868
+ || ${i} === "boolean" || ${s} === null`).assign(a,(0,X._)`[${s}]`)}}}function z_({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,X._)`${e} !== undefined`,()=>t.assign((0,X._)`${e}[${n}]`,r))}function Kl(t,e,n,r=Wn.Correct){let s=r===Wn.Correct?X.operators.EQ:X.operators.NEQ,o;switch(t){case"null":return(0,X._)`${e} ${s} null`;case"array":o=(0,X._)`Array.isArray(${e})`;break;case"object":o=(0,X._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,X._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,X._)`typeof ${e} ${s} ${t}`}return r===Wn.Correct?o:(0,X.not)(o);function i(a=X.nil){return(0,X.and)((0,X._)`typeof ${e} == "number"`,a,n?(0,X._)`isFinite(${e})`:X.nil)}}Le.checkDataType=Kl;function Vl(t,e,n,r){if(t.length===1)return Kl(t[0],e,n,r);let s,o=(0,Tf.toHash)(t);if(o.array&&o.object){let i=(0,X._)`typeof ${e} != "object"`;s=o.null?i:(0,X._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=X.nil;o.number&&delete o.integer;for(let i in o)s=(0,X.and)(s,Kl(i,e,n,r));return s}Le.checkDataTypes=Vl;var q_={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,X._)`{type: ${t}}`:(0,X._)`{type: ${e}}`};function Gl(t){let e=B_(t);(0,L_.reportError)(e,q_)}Le.reportTypeError=Gl;function B_(t){let{gen:e,data:n,schema:r}=t,s=(0,Tf.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:s,schemaValue:s,parentSchema:r,params:{},it:t}}});var Af=D(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.assignDefaults=void 0;var Jn=ee(),F_=de();function H_(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let s in n)Pf(t,s,n[s].default);else e==="array"&&Array.isArray(r)&&r.forEach((s,o)=>Pf(t,o,s.default))}Uo.assignDefaults=H_;function Pf(t,e,n){let{gen:r,compositeRule:s,data:o,opts:i}=t;if(n===void 0)return;let a=(0,Jn._)`${o}${(0,Jn.getProperty)(e)}`;if(s){(0,F_.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,Jn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,Jn._)`${l} || ${a} === null || ${a} === ""`),r.if(l,(0,Jn._)`${a} = ${(0,Jn.stringify)(n)}`)}});var lt=D(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(),Wl=de(),Xt=Nt(),K_=de();function V_(t,e){let{gen:n,data:r,it:s}=t;n.if(Yl(n,r,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,be._)`${e}`},!0),t.error()})}fe.checkReportMissingProp=V_;function G_({gen:t,data:e,it:{opts:n}},r,s){return(0,be.or)(...r.map(o=>(0,be.and)(Yl(t,e,o,n.ownProperties),(0,be._)`${s} = ${o}`)))}fe.checkMissingProp=G_;function W_(t,e){t.setParams({missingProperty:e},!0),t.error()}fe.reportMissingProp=W_;function If(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,be._)`Object.prototype.hasOwnProperty`})}fe.hasPropFunc=If;function Jl(t,e,n){return(0,be._)`${If(t)}.call(${e}, ${n})`}fe.isOwnProperty=Jl;function J_(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} !== undefined`;return r?(0,be._)`${s} && ${Jl(t,e,n)}`:s}fe.propertyInData=J_;function Yl(t,e,n,r){let s=(0,be._)`${e}${(0,be.getProperty)(n)} === undefined`;return r?(0,be.or)(s,(0,be.not)(Jl(t,e,n))):s}fe.noPropertyInData=Yl;function Cf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}fe.allSchemaProperties=Cf;function Y_(t,e){return Cf(e).filter(n=>!(0,Wl.alwaysValidSchema)(t,e[n]))}fe.schemaProperties=Y_;function Z_({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,g=[[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&&g.push([Xt.default.dynamicAnchors,Xt.default.dynamicAnchors]);let $=(0,be._)`${p}, ${n.object(...g)}`;return l!==be.nil?(0,be._)`${a}.call(${l}, ${$})`:(0,be._)`${a}(${$})`}fe.callValidateCode=Z_;var X_=(0,be._)`new RegExp`;function Q_({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"?X_:(0,K_.useFunc)(t,s)}(${n}, ${r})`})}fe.usePattern=Q_;function e$(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:Wl.Type.Num},o),e.if((0,be.not)(o),a)})}}fe.validateArray=e$;function t$(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,Wl.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=t$});var Lf=D(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.validateKeywordUsage=St.validSchemaType=St.funcKeywordCode=St.macroKeywordCode=void 0;var Fe=ee(),bn=Nt(),n$=lt(),r$=Wr();function s$(t,e){let{gen:n,keyword:r,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),l=Nf(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:Fe.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}St.macroKeywordCode=s$;function o$(t,e){var n;let{gen:r,keyword:s,schema:o,parentSchema:i,$data:a,it:l}=t;a$(l,e);let u=!a&&e.compile?e.compile.call(l.self,o,i,l):e.validate,p=Nf(r,s,u),g=r.let("valid");t.block$data(g,$),t.ok((n=e.valid)!==null&&n!==void 0?n:g);function $(){if(e.errors===!1)T(),e.modifying&&Of(t),E(()=>t.error());else{let P=e.async?v():S();e.modifying&&Of(t),E(()=>i$(t,P))}}function v(){let P=r.let("ruleErrs",null);return r.try(()=>T((0,Fe._)`await `),O=>r.assign(g,!1).if((0,Fe._)`${O} instanceof ${l.ValidationError}`,()=>r.assign(P,(0,Fe._)`${O}.errors`),()=>r.throw(O))),P}function S(){let P=(0,Fe._)`${p}.errors`;return r.assign(P,null),T(Fe.nil),P}function T(P=e.async?(0,Fe._)`await `:Fe.nil){let O=l.opts.passContext?bn.default.this:bn.default.self,U=!("compile"in e&&!a||e.schema===!1);r.assign(g,(0,Fe._)`${P}${(0,n$.callValidateCode)(t,p,O,U)}`,e.modifying)}function E(P){var O;r.if((0,Fe.not)((O=e.valid)!==null&&O!==void 0?O:g),P)}}St.funcKeywordCode=o$;function Of(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Fe._)`${r.parentData}[${r.parentDataProperty}]`))}function i$(t,e){let{gen:n}=t;n.if((0,Fe._)`Array.isArray(${e})`,()=>{n.assign(bn.default.vErrors,(0,Fe._)`${bn.default.vErrors} === null ? ${e} : ${bn.default.vErrors}.concat(${e})`).assign(bn.default.errors,(0,Fe._)`${bn.default.vErrors}.length`),(0,r$.extendErrors)(t)},()=>t.error())}function a$({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Nf(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,Fe.stringify)(n)})}function l$(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}St.validSchemaType=l$;function c$({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=c$});var Df=D(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.extendSubschemaMode=Qt.extendSubschemaData=Qt.getSubschema=void 0;var _t=ee(),jf=de();function d$(t,{keyword:e,schemaProp:n,schema:r,schemaPath:s,errSchemaPath:o,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,_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,jf.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')}Qt.getSubschema=d$;function u$(t,e,{dataProp:n,dataPropType:r,data:s,dataTypes:o,propertyName:i}){if(s!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:p,opts:g}=e,$=a.let("data",(0,_t._)`${e.data}${(0,_t.getProperty)(n)}`,!0);l($),t.errorPath=(0,_t.str)`${u}${(0,jf.getErrorPath)(n,r,g.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]}}Qt.extendSubschemaData=u$;function p$(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}Qt.extendSubschemaMode=p$});var Zl=D((QN,Uf)=>{"use strict";Uf.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 zf=D((eL,Mf)=>{"use strict";var en=Mf.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(){};Mo(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 Mo(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 g=r[p];if(Array.isArray(g)){if(p in en.arrayKeywords)for(var $=0;$<g.length;$++)Mo(t,e,n,g[$],s+"/"+p+"/"+$,o,s,p,r,$)}else if(p in en.propsKeywords){if(g&&typeof g=="object")for(var v in g)Mo(t,e,n,g[v],s+"/"+p+"/"+h$(v),o,s,p,r,v)}else(p in en.keywords||t.allKeys&&!(p in en.skipKeywords))&&Mo(t,e,n,g,s+"/"+p,o,s,p,r)}n(r,s,o,i,a,l,u)}}function h$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Yr=D(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.getSchemaRefs=We.resolveUrl=We.normalizeId=We._getFullPath=We.getFullPath=We.inlineRef=void 0;var f$=de(),m$=Zl(),g$=zf(),b$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function y$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Xl(t):e?qf(t)<=e:!1}We.inlineRef=y$;var w$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Xl(t){for(let e in t){if(w$.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Xl)||typeof n=="object"&&Xl(n))return!0}return!1}function qf(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!b$.has(n)&&(typeof t[n]=="object"&&(0,f$.eachItem)(t[n],r=>e+=qf(r)),e===1/0))return 1/0}return e}function Bf(t,e="",n){n!==!1&&(e=Yn(e));let r=t.parse(e);return Ff(t,r)}We.getFullPath=Bf;function Ff(t,e){return t.serialize(e).split("#")[0]+"#"}We._getFullPath=Ff;var v$=/#\/?$/;function Yn(t){return t?t.replace(v$,""):""}We.normalizeId=Yn;function k$(t,e,n){return n=Yn(n),t.resolve(e,n)}We.resolveUrl=k$;var S$=/^[a-z_][-a-z0-9._]*$/i;function _$(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,s=Yn(t[n]||e),o={"":s},i=Bf(r,s,!1),a={},l=new Set;return g$(t,{allKeys:!0},(g,$,v,S)=>{if(S===void 0)return;let T=i+$,E=o[S];typeof g[n]=="string"&&(E=P.call(this,g[n])),O.call(this,g.$anchor),O.call(this,g.$dynamicAnchor),o[$]=E;function P(U){let re=this.opts.uriResolver.resolve;if(U=Yn(E?re(E,U):U),l.has(U))throw p(U);l.add(U);let Y=this.refs[U];return typeof Y=="string"&&(Y=this.refs[Y]),typeof Y=="object"?u(g,Y.schema,U):U!==Yn(T)&&(U[0]==="#"?(u(g,a[U],U),a[U]=g):this.refs[U]=T),U}function O(U){if(typeof U=="string"){if(!S$.test(U))throw new Error(`invalid anchor "${U}"`);P.call(this,`#${U}`)}}}),a;function u(g,$,v){if($!==void 0&&!m$(g,$))throw p(v)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}We.getSchemaRefs=_$});var Qr=D(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.getData=tn.KeywordCxt=tn.validateFunctionCode=void 0;var Wf=_f(),Hf=Jr(),ec=Hl(),zo=Jr(),$$=Af(),Xr=Lf(),Ql=Df(),q=ee(),Z=Nt(),x$=Yr(),Lt=de(),Zr=Wr();function T$(t){if(Zf(t)&&(Xf(t),Yf(t))){P$(t);return}Jf(t,()=>(0,Wf.topBoolOrEmptySchema)(t))}tn.validateFunctionCode=T$;function Jf({gen:t,validateName:e,schema:n,schemaEnv:r,opts:s},o){s.code.es5?t.func(e,(0,q._)`${Z.default.data}, ${Z.default.valCxt}`,r.$async,()=>{t.code((0,q._)`"use strict"; ${Kf(n,s)}`),E$(t,s),t.code(o)}):t.func(e,(0,q._)`${Z.default.data}, ${R$(s)}`,r.$async,()=>t.code(Kf(n,s)).code(o))}function R$(t){return(0,q._)`{${Z.default.instancePath}="", ${Z.default.parentData}, ${Z.default.parentDataProperty}, ${Z.default.rootData}=${Z.default.data}${t.dynamicRef?(0,q._)`, ${Z.default.dynamicAnchors}={}`:q.nil}}={}`}function E$(t,e){t.if(Z.default.valCxt,()=>{t.var(Z.default.instancePath,(0,q._)`${Z.default.valCxt}.${Z.default.instancePath}`),t.var(Z.default.parentData,(0,q._)`${Z.default.valCxt}.${Z.default.parentData}`),t.var(Z.default.parentDataProperty,(0,q._)`${Z.default.valCxt}.${Z.default.parentDataProperty}`),t.var(Z.default.rootData,(0,q._)`${Z.default.valCxt}.${Z.default.rootData}`),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,q._)`${Z.default.valCxt}.${Z.default.dynamicAnchors}`)},()=>{t.var(Z.default.instancePath,(0,q._)`""`),t.var(Z.default.parentData,(0,q._)`undefined`),t.var(Z.default.parentDataProperty,(0,q._)`undefined`),t.var(Z.default.rootData,Z.default.data),e.dynamicRef&&t.var(Z.default.dynamicAnchors,(0,q._)`{}`)})}function P$(t){let{schema:e,opts:n,gen:r}=t;Jf(t,()=>{n.$comment&&e.$comment&&em(t),N$(t),r.let(Z.default.vErrors,null),r.let(Z.default.errors,0),n.unevaluated&&A$(t),Qf(t),D$(t)})}function A$(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,q._)`${n}.evaluated`),e.if((0,q._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,q._)`${t.evaluated}.props`,(0,q._)`undefined`)),e.if((0,q._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,q._)`${t.evaluated}.items`,(0,q._)`undefined`))}function Kf(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,q._)`/*# sourceURL=${n} */`:q.nil}function I$(t,e){if(Zf(t)&&(Xf(t),Yf(t))){C$(t,e);return}(0,Wf.boolOrEmptySchema)(t,e)}function Yf({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 Zf(t){return typeof t.schema!="boolean"}function C$(t,e){let{schema:n,gen:r,opts:s}=t;s.$comment&&n.$comment&&em(t),L$(t),j$(t);let o=r.const("_errs",Z.default.errors);Qf(t,o),r.var(e,(0,q._)`${o} === ${Z.default.errors}`)}function Xf(t){(0,Lt.checkUnknownRules)(t),O$(t)}function Qf(t,e){if(t.opts.jtd)return Vf(t,[],!1,e);let n=(0,Hf.getSchemaTypes)(t.schema),r=(0,Hf.coerceAndCheckDataType)(t,n);Vf(t,n,!r,e)}function O$(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 N$(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 L$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,x$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function j$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function em({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:s}){let o=n.$comment;if(s.$comment===!0)t.code((0,q._)`${Z.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,q.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,q._)`${Z.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function D$(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:s,opts:o}=t;n.$async?e.if((0,q._)`${Z.default.errors} === 0`,()=>e.return(Z.default.data),()=>e.throw((0,q._)`new ${s}(${Z.default.vErrors})`)):(e.assign((0,q._)`${r}.errors`,Z.default.vErrors),o.unevaluated&&U$(t),e.return((0,q._)`${Z.default.errors} === 0`))}function U$({gen:t,evaluated:e,props:n,items:r}){n instanceof q.Name&&t.assign((0,q._)`${e}.props`,n),r instanceof q.Name&&t.assign((0,q._)`${e}.items`,r)}function Vf(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(()=>nm(t,"$ref",p.all.$ref.definition));return}l.jtd||M$(t,e),s.block(()=>{for(let $ of p.rules)g($);g(p.post)});function g($){(0,ec.shouldUseGroup)(o,$)&&($.type?(s.if((0,zo.checkDataType)($.type,i,l.strictNumbers)),Gf(t,$),e.length===1&&e[0]===$.type&&n&&(s.else(),(0,zo.reportTypeError)(t)),s.endIf()):Gf(t,$),a||s.if((0,q._)`${Z.default.errors} === ${r||0}`))}}function Gf(t,e){let{gen:n,schema:r,opts:{useDefaults:s}}=t;s&&(0,$$.assignDefaults)(t,e.type),n.block(()=>{for(let o of e.rules)(0,ec.shouldUseRule)(r,o)&&nm(t,o.keyword,o.definition,e.type)})}function M$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(z$(t,e),t.opts.allowUnionTypes||q$(t,e),B$(t,t.dataTypes))}function z$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{tm(t.dataTypes,n)||tc(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),H$(t,e)}}function q$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&tc(t,"use allowUnionTypes to allow union type keyword")}function B$(t,e){let n=t.self.RULES.all;for(let r in n){let s=n[r];if(typeof s=="object"&&(0,ec.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>F$(e,i))&&tc(t,`missing type "${o.join(",")}" for keyword "${r}"`)}}}function F$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function tm(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function H$(t,e){let n=[];for(let r of t.dataTypes)tm(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function tc(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Lt.checkStrictMode)(t,e,t.opts.strictTypes)}var qo=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",rm(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,q.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,q.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,q._)`${n} !== undefined && (${(0,q.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?Zr.reportExtraError:Zr.reportError)(this,this.def.error,n)}$dataError(){(0,Zr.reportError)(this,this.def.$dataError||Zr.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Zr.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=q.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=q.nil,n=q.nil){if(!this.$data)return;let{gen:r,schemaCode:s,schemaType:o,def:i}=this;r.if((0,q.or)((0,q._)`${s} === undefined`,n)),e!==q.nil&&r.assign(e,!0),(o.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==q.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:s,it:o}=this;return(0,q.or)(i(),a());function i(){if(r.length){if(!(n instanceof q.Name))throw new Error("ajv implementation error");let l=Array.isArray(r)?r:[r];return(0,q._)`${(0,zo.checkDataTypes)(l,n,o.opts.strictNumbers,zo.DataType.Wrong)}`}return q.nil}function a(){if(s.validateSchema){let l=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,q._)`!${l}(${n})`}return q.nil}}subschema(e,n){let r=(0,Ql.getSubschema)(this.it,e);(0,Ql.extendSubschemaData)(r,this.it,e),(0,Ql.extendSubschemaMode)(r,e);let s={...this.it,...r,items:void 0,props:void 0};return I$(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,q.Name)),!0}};tn.KeywordCxt=qo;function nm(t,e,n,r){let s=new qo(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 K$=/^\/(?:[^~]|~0|~1)*$/,V$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function rm(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let s,o;if(t==="")return Z.default.rootData;if(t[0]==="/"){if(!K$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Z.default.rootData}else{let u=V$.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,q._)`${o}${(0,q.getProperty)((0,Lt.unescapeJsonPointer)(u))}`,i=(0,q._)`${i} && ${o}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}tn.getData=rm});var Bo=D(rc=>{"use strict";Object.defineProperty(rc,"__esModule",{value:!0});var nc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};rc.default=nc});var es=D(ic=>{"use strict";Object.defineProperty(ic,"__esModule",{value:!0});var sc=Yr(),oc=class extends Error{constructor(e,n,r,s){super(s||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,sc.resolveUrl)(e,n,r),this.missingSchema=(0,sc.normalizeId)((0,sc.getFullPath)(e,this.missingRef))}};ic.default=oc});var Ho=D(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.resolveSchema=ct.getCompilingSchema=ct.resolveRef=ct.compileSchema=ct.SchemaEnv=void 0;var gt=ee(),G$=Bo(),yn=Nt(),bt=Yr(),sm=de(),W$=Qr(),Zn=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={}}};ct.SchemaEnv=Zn;function lc(t){let e=om.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:G$.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:yn.default.data,parentData:yn.default.parentData,parentDataProperty:yn.default.parentDataProperty,dataNames:[yn.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,W$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(yn.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let v=new Function(`${yn.default.self}`,`${yn.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:g,scopeValues:i._values}),this.opts.unevaluated){let{props:S,items:T}=u;v.evaluated={props:S instanceof gt.Name?void 0:S,items:T instanceof gt.Name?void 0:T,dynamicProps:S instanceof gt.Name,dynamicItems:T instanceof gt.Name},v.source&&(v.source.evaluated=(0,gt.stringify)(v.evaluated))}return t.validate=v,t}catch(g){throw delete t.validate,delete t.validateName,p&&this.logger.error("Error compiling schema, function code:",p),g}finally{this._compilations.delete(t)}}ct.compileSchema=lc;function J$(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=X$.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 Zn({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[n]=Y$.call(this,o)}ct.resolveRef=J$;function Y$(t){return(0,bt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:lc.call(this,t)}function om(t){for(let e of this._compilations)if(Z$(e,t))return e}ct.getCompilingSchema=om;function Z$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function X$(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Fo.call(this,t,e)}function Fo(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 ac.call(this,n,t);let o=(0,bt.normalizeId)(r),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Fo.call(this,t,i);return typeof a?.schema!="object"?void 0:ac.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||lc.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 Zn({schema:a,schemaId:l,root:t,baseId:s})}return ac.call(this,n,i)}}ct.resolveSchema=Fo;var Q$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ac(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,sm.unescapeFragment)(a)];if(l===void 0)return;n=l;let u=typeof n=="object"&&n[this.opts.schemaId];!Q$.has(a)&&u&&(e=(0,bt.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof n!="boolean"&&n.$ref&&!(0,sm.schemaHasRulesButRef)(n,this.RULES)){let a=(0,bt.resolveUrl)(this.opts.uriResolver,e,n.$ref);o=Fo.call(this,r,a)}let{schemaId:i}=this.opts;if(o=o||new Zn({schema:n,schemaId:i,root:r,baseId:e}),o.schema!==o.root.schema)return o}});var im=D((iL,ex)=>{ex.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 uc=D((aL,pm)=>{"use strict";var tx=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),lm=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),cc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),cm=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),nx=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function dc(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 rx=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function am(t){return t.length=0,!0}function sx(t,e,n){if(t.length){let r=dc(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function ox(t){let e=0,n={error:!1,address:"",zone:""},r=[],s=[],o=!1,i=!1,a=sx;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=am}else{s.push(u);continue}}return s.length&&(a===am?n.zone=s.join(""):i?r.push(s.join("")):r.push(dc(s))),n.address=r.join(""),n}function dm(t){if(ix(t,":")<2)return{host:t,isIPV6:!1};let e=ox(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 ix(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function ax(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 lx={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},cx=/[@/?#:]/g,dx=/[@/?#]/g;function um(t,e){let n=e?dx:cx;return n.lastIndex=0,t.replace(n,r=>lx[r])}function ux(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(cc(s)){let o=s.toUpperCase(),i=String.fromCharCode(parseInt(o,16));e&&cm(i)?n+=i:n+="%"+o,r+=2;continue}}n+=t[r]}return n}function px(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(cc(r)){let s=r.toUpperCase(),o=String.fromCharCode(parseInt(s,16));o!=="."&&cm(o)?e+=o:e+="%"+s,n+=2;continue}}nx(t[n])?e+=t[n]:e+=escape(t[n])}return e}function hx(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(cc(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function fx(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!lm(n)){let r=dm(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=um(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}pm.exports={nonSimpleDomain:rx,recomposeAuthority:fx,reescapeHostDelimiters:um,normalizePercentEncoding:ux,normalizePathEncoding:px,escapePreservingEscapes:hx,removeDotSegments:ax,isIPv4:lm,isUUID:tx,normalizeIPv6:dm,stringArrayToHexStripped:dc}});var bm=D((lL,gm)=>{"use strict";var{isUUID:mx}=uc(),gx=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,bx=["http","https","ws","wss","urn","urn:uuid"];function yx(t){return bx.indexOf(t)!==-1}function pc(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 hm(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function fm(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 wx(t){return t.secure=pc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function vx(t){if((t.port===(pc(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 kx(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(gx);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=hc(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Sx(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=hc(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 _x(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!mx(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function $x(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var mm={scheme:"http",domainHost:!0,parse:hm,serialize:fm},xx={scheme:"https",domainHost:mm.domainHost,parse:hm,serialize:fm},Ko={scheme:"ws",domainHost:!0,parse:wx,serialize:vx},Tx={scheme:"wss",domainHost:Ko.domainHost,parse:Ko.parse,serialize:Ko.serialize},Rx={scheme:"urn",parse:kx,serialize:Sx,skipNormalize:!0},Ex={scheme:"urn:uuid",parse:_x,serialize:$x,skipNormalize:!0},Vo={http:mm,https:xx,ws:Ko,wss:Tx,urn:Rx,"urn:uuid":Ex};Object.setPrototypeOf(Vo,null);function hc(t){return t&&(Vo[t]||Vo[t.toLowerCase()])||void 0}gm.exports={wsIsSecure:pc,SCHEMES:Vo,isValidSchemeName:yx,getSchemeHandler:hc}});var Sm=D((cL,Jo)=>{"use strict";var{normalizeIPv6:Px,removeDotSegments:ts,recomposeAuthority:Ax,normalizePercentEncoding:Ix,normalizePathEncoding:Cx,escapePreservingEscapes:Ox,reescapeHostDelimiters:Nx,isIPv4:Lx,nonSimpleDomain:jx}=uc(),{SCHEMES:Dx,getSchemeHandler:wm}=bm();function Ux(t,e){return typeof t=="string"?t=Kx(t,e):typeof t=="object"&&(t=Wo(wn(t,e),e)),t}function Mx(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:s,malformedAuthorityOrPort:o}=Go(t,r),{parsed:i,malformedAuthorityOrPort:a}=Go(e,r);if(o||a)throw new Error(s.error||i.error||"URI is malformed.");let l=vm(s,i,r,!0);return r.skipEscape=!0,wn(l,r)}function vm(t,e,n,r){let s={};return r||(t=Wo(wn(t,n),n),e=Wo(wn(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=ts(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=ts(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=ts(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=ts(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 zx(t,e,n){let r=ym(t,n),s=ym(e,n);return r!==void 0&&s!==void 0&&r.toLowerCase()===s.toLowerCase()}function wn(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=wm(r.scheme||n.scheme);o&&o.serialize&&o.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=Ix(n.path):(n.path=Ox(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&s.push(n.scheme,":");let i=Ax(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=ts(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 qx=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Bx=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,Fx=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function Hx(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 Go(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(Bx);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",s=!0);let a=t.match(Fx);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(qx);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=Hx(r,l);if(u!==void 0&&(r.error=r.error||u,s=!0),r.host)if(Lx(r.host)===!1){let $=Px(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=wm(n.scheme||r.scheme);if(!n.unicodeSupport&&(!p||!p.unicodeSupport)&&r.host&&(n.domainHost||p&&p.domainHost)&&o===!1&&jx(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(g){r.error=r.error||"Host's domain name can not be converted to ASCII: "+g}if((!p||p&&!p.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Nx(unescape(r.host),o))),r.path&&(r.path=Cx(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 Wo(t,e){return Go(t,e).parsed}function Kx(t,e){return km(t,e).normalized}function km(t,e){let{parsed:n,malformedAuthorityOrPort:r}=Go(t,e);return{normalized:r?t:wn(n,e),malformedAuthorityOrPort:r}}function ym(t,e){if(typeof t=="string"){let{normalized:n,malformedAuthorityOrPort:r}=km(t,e);return r?void 0:n}if(typeof t=="object")return wn(t,e)}var fc={SCHEMES:Dx,normalize:Ux,resolve:Mx,resolveComponent:vm,equal:zx,serialize:wn,parse:Wo};Jo.exports=fc;Jo.exports.default=fc;Jo.exports.fastUri=fc});var $m=D(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var _m=Sm();_m.code='require("ajv/dist/runtime/uri").default';mc.default=_m});var Cm=D(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 Vx=Qr();Object.defineProperty(Ie,"KeywordCxt",{enumerable:!0,get:function(){return Vx.KeywordCxt}});var Xn=ee();Object.defineProperty(Ie,"_",{enumerable:!0,get:function(){return Xn._}});Object.defineProperty(Ie,"str",{enumerable:!0,get:function(){return Xn.str}});Object.defineProperty(Ie,"stringify",{enumerable:!0,get:function(){return Xn.stringify}});Object.defineProperty(Ie,"nil",{enumerable:!0,get:function(){return Xn.nil}});Object.defineProperty(Ie,"Name",{enumerable:!0,get:function(){return Xn.Name}});Object.defineProperty(Ie,"CodeGen",{enumerable:!0,get:function(){return Xn.CodeGen}});var Gx=Bo(),Pm=es(),Wx=Fl(),ns=Ho(),Jx=ee(),rs=Yr(),Yo=Jr(),bc=de(),xm=im(),Yx=$m(),Am=(t,e)=>new RegExp(t,e);Am.code="new RegExp";var Zx=["removeAdditional","useDefaults","coerceTypes"],Xx=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Qx={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."},eT={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Tm=200;function tT(t){var e,n,r,s,o,i,a,l,u,p,g,$,v,S,T,E,P,O,U,re,Y,He,je,cr,jt;let Ze=t.strict,dr=(e=t.code)===null||e===void 0?void 0:e.optimize,bs=dr===!0||dr===void 0?1:dr||0,Dt=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:Am,_n=(s=t.uriResolver)!==null&&s!==void 0?s:Yx.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:Ze)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:Ze)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:Ze)!==null&&p!==void 0?p:"log",strictTuples:($=(g=t.strictTuples)!==null&&g!==void 0?g:Ze)!==null&&$!==void 0?$:"log",strictRequired:(S=(v=t.strictRequired)!==null&&v!==void 0?v:Ze)!==null&&S!==void 0?S:!1,code:t.code?{...t.code,optimize:bs,regExp:Dt}:{optimize:bs,regExp:Dt},loopRequired:(T=t.loopRequired)!==null&&T!==void 0?T:Tm,loopEnum:(E=t.loopEnum)!==null&&E!==void 0?E:Tm,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(O=t.messages)!==null&&O!==void 0?O:!0,inlineRefs:(U=t.inlineRefs)!==null&&U!==void 0?U:!0,schemaId:(re=t.schemaId)!==null&&re!==void 0?re:"$id",addUsedSchema:(Y=t.addUsedSchema)!==null&&Y!==void 0?Y:!0,validateSchema:(He=t.validateSchema)!==null&&He!==void 0?He:!0,validateFormats:(je=t.validateFormats)!==null&&je!==void 0?je:!0,unicodeRegExp:(cr=t.unicodeRegExp)!==null&&cr!==void 0?cr:!0,int32range:(jt=t.int32range)!==null&&jt!==void 0?jt:!0,uriResolver:_n}}var ss=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,...tT(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new Jx.ValueScope({scope:{},prefixes:Xx,es5:n,lines:r}),this.logger=aT(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,Wx.getRules)(),Rm.call(this,Qx,e,"NOT SUPPORTED"),Rm.call(this,eT,e,"DEPRECATED","warn"),this._metaOpts=oT.call(this),e.formats&&rT.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&sT.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),nT.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,s=xm;r==="id"&&(s={...xm},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,g){await o.call(this,p.$schema);let $=this._addSchema(p,g);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(g){if(!(g instanceof Pm.default))throw g;return a.call(this,g),await l.call(this,g.missingSchema),i.call(this,p)}}function a({missingSchema:p,missingRef:g}){if(this.refs[p])throw new Error(`AnySchema ${p} is loaded but ${g} cannot be resolved`)}async function l(p){let g=await u.call(this,p);this.refs[p]||await o.call(this,g.$schema),this.refs[p]||this.addSchema(g,p,n)}async function u(p){let g=this._loading[p];if(g)return g;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,rs.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=Em.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,s=new ns.SchemaEnv({schema:{},schemaId:r});if(n=ns.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=Em.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,rs.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(cT.call(this,r,n),!n)return(0,bc.eachItem)(r,o=>gc.call(this,o)),this;uT.call(this,n);let s={...n,type:(0,Yo.getJSONTypes)(n.type),schemaType:(0,Yo.getJSONTypes)(n.schemaType)};return(0,bc.eachItem)(r,s.type.length===0?o=>gc.call(this,o,s):o=>s.type.forEach(i=>gc.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]=Im(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,rs.normalizeId)(i||r);let u=rs.getSchemaRefs.call(this,e,r);return l=new ns.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):ns.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{ns.compileSchema.call(this,e)}finally{this.opts=n}}};ss.ValidationError=Gx.default;ss.MissingRefError=Pm.default;Ie.default=ss;function Rm(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 Em(t){return t=(0,rs.normalizeId)(t),this.schemas[t]||this.refs[t]}function nT(){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 rT(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function sT(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 oT(){let t={...this.opts};for(let e of Zx)delete t[e];return t}var iT={log(){},warn(){},error(){}};function aT(t){if(t===!1)return iT;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var lT=/^[a-z_$][a-z0-9_$:-]*$/i;function cT(t,e){let{RULES:n}=this;if((0,bc.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!lT.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function gc(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,Yo.getJSONTypes)(e.type),schemaType:(0,Yo.getJSONTypes)(e.schemaType)}};e.before?dT.call(this,i,a,e.before):i.rules.push(a),o.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(l=>this.addKeyword(l))}function dT(t,e,n){let r=t.rules.findIndex(s=>s.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function uT(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Im(e)),t.validateSchema=this.compile(e,!0))}var pT={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Im(t){return{anyOf:[t,pT]}}});var Om=D(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var hT={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};yc.default=hT});var Dm=D(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.callRef=vn.getValidate=void 0;var fT=es(),Nm=lt(),Je=ee(),Qn=Nt(),Lm=Ho(),Zo=de(),mT={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 g();let p=Lm.resolveRef.call(l,u,s,n);if(p===void 0)throw new fT.default(r.opts.uriResolver,s,n);if(p instanceof Lm.SchemaEnv)return $(p);return v(p);function g(){if(o===u)return Xo(t,i,o,o.$async);let S=e.scopeValue("root",{ref:u});return Xo(t,(0,Je._)`${S}.validate`,u,u.$async)}function $(S){let T=jm(t,S);Xo(t,T,S,S.$async)}function v(S){let T=e.scopeValue("schema",a.code.source===!0?{ref:S,code:(0,Je.stringify)(S)}:{ref:S}),E=e.name("valid"),P=t.subschema({schema:S,dataTypes:[],schemaPath:Je.nil,topSchemaRef:T,errSchemaPath:n},E);t.mergeEvaluated(P),t.ok(E)}}};function jm(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Je._)`${n.scopeValue("wrapper",{ref:e})}.validate`}vn.getValidate=jm;function Xo(t,e,n,r){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:l}=o,u=l.passContext?Qn.default.this:Je.nil;r?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let S=s.let("valid");s.try(()=>{s.code((0,Je._)`await ${(0,Nm.callValidateCode)(t,e,u)}`),v(e),i||s.assign(S,!0)},T=>{s.if((0,Je._)`!(${T} instanceof ${o.ValidationError})`,()=>s.throw(T)),$(T),i||s.assign(S,!1)}),t.ok(S)}function g(){t.result((0,Nm.callValidateCode)(t,e,u),()=>v(e),()=>$(e))}function $(S){let T=(0,Je._)`${S}.errors`;s.assign(Qn.default.vErrors,(0,Je._)`${Qn.default.vErrors} === null ? ${T} : ${Qn.default.vErrors}.concat(${T})`),s.assign(Qn.default.errors,(0,Je._)`${Qn.default.vErrors}.length`)}function v(S){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=Zo.mergeEvaluated.props(s,E.props,o.props));else{let P=s.var("props",(0,Je._)`${S}.evaluated.props`);o.props=Zo.mergeEvaluated.props(s,P,o.props,Je.Name)}if(o.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(o.items=Zo.mergeEvaluated.items(s,E.items,o.items));else{let P=s.var("items",(0,Je._)`${S}.evaluated.items`);o.items=Zo.mergeEvaluated.items(s,P,o.items,Je.Name)}}}vn.callRef=Xo;vn.default=mT});var Um=D(wc=>{"use strict";Object.defineProperty(wc,"__esModule",{value:!0});var gT=Om(),bT=Dm(),yT=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",gT.default,bT.default];wc.default=yT});var Mm=D(vc=>{"use strict";Object.defineProperty(vc,"__esModule",{value:!0});var Qo=ee(),nn=Qo.operators,ei={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}},wT={message:({keyword:t,schemaCode:e})=>(0,Qo.str)`must be ${ei[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Qo._)`{comparison: ${ei[t].okStr}, limit: ${e}}`},vT={keyword:Object.keys(ei),type:"number",schemaType:"number",$data:!0,error:wT,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Qo._)`${n} ${ei[e].fail} ${r} || isNaN(${n})`)}};vc.default=vT});var zm=D(kc=>{"use strict";Object.defineProperty(kc,"__esModule",{value:!0});var os=ee(),kT={message:({schemaCode:t})=>(0,os.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,os._)`{multipleOf: ${t}}`},ST={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:kT,code(t){let{gen:e,data:n,schemaCode:r,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,os._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,os._)`${i} !== parseInt(${i})`;t.fail$data((0,os._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};kc.default=ST});var Bm=D(Sc=>{"use strict";Object.defineProperty(Sc,"__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}Sc.default=qm;qm.code='require("ajv/dist/runtime/ucs2length").default'});var Fm=D(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});var kn=ee(),_T=de(),$T=Bm(),xT={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,kn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,kn._)`{limit: ${t}}`},TT={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:xT,code(t){let{keyword:e,data:n,schemaCode:r,it:s}=t,o=e==="maxLength"?kn.operators.GT:kn.operators.LT,i=s.opts.unicode===!1?(0,kn._)`${n}.length`:(0,kn._)`${(0,_T.useFunc)(t.gen,$T.default)}(${n})`;t.fail$data((0,kn._)`${i} ${o} ${r}`)}};_c.default=TT});var Hm=D($c=>{"use strict";Object.defineProperty($c,"__esModule",{value:!0});var RT=lt(),ET=de(),er=ee(),PT={message:({schemaCode:t})=>(0,er.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,er._)`{pattern: ${t}}`},AT={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:PT,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,er._)`new RegExp`:(0,ET.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,er._)`${u}(${o}, ${a}).test(${n})`),()=>e.assign(p,!1)),t.fail$data((0,er._)`!${p}`)}else{let l=(0,RT.usePattern)(t,s);t.fail$data((0,er._)`!${l}.test(${n})`)}}};$c.default=AT});var Km=D(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});var is=ee(),IT={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,is.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,is._)`{limit: ${t}}`},CT={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:IT,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxProperties"?is.operators.GT:is.operators.LT;t.fail$data((0,is._)`Object.keys(${n}).length ${s} ${r}`)}};xc.default=CT});var Vm=D(Tc=>{"use strict";Object.defineProperty(Tc,"__esModule",{value:!0});var as=lt(),ls=ee(),OT=de(),NT={message:({params:{missingProperty:t}})=>(0,ls.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ls._)`{missingProperty: ${t}}`},LT={keyword:"required",type:"object",schemaType:"array",$data:!0,error:NT,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:S}=t.it;for(let T of n)if(v?.[T]===void 0&&!S.has(T)){let E=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${T}" is not defined at "${E}" (strictRequired)`;(0,OT.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||o)t.block$data(ls.nil,g);else for(let v of n)(0,as.checkReportMissingProp)(t,v)}function p(){let v=e.let("missing");if(l||o){let S=e.let("valid",!0);t.block$data(S,()=>$(v,S)),t.ok(S)}else e.if((0,as.checkMissingProp)(t,n,v)),(0,as.reportMissingProp)(t,v),e.else()}function g(){e.forOf("prop",r,v=>{t.setParams({missingProperty:v}),e.if((0,as.noPropertyInData)(e,s,v,a.ownProperties),()=>t.error())})}function $(v,S){t.setParams({missingProperty:v}),e.forOf(v,r,()=>{e.assign(S,(0,as.propertyInData)(e,s,v,a.ownProperties)),e.if((0,ls.not)(S),()=>{t.error(),e.break()})},ls.nil)}}};Tc.default=LT});var Gm=D(Rc=>{"use strict";Object.defineProperty(Rc,"__esModule",{value:!0});var cs=ee(),jT={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,cs.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,cs._)`{limit: ${t}}`},DT={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:jT,code(t){let{keyword:e,data:n,schemaCode:r}=t,s=e==="maxItems"?cs.operators.GT:cs.operators.LT;t.fail$data((0,cs._)`${n}.length ${s} ${r}`)}};Rc.default=DT});var ti=D(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var Wm=Zl();Wm.code='require("ajv/dist/runtime/equal").default';Ec.default=Wm});var Jm=D(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});var Pc=Jr(),Ce=ee(),UT=de(),MT=ti(),zT={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}}`},qT={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:zT,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,Pc.getSchemaTypes)(o.items):[];t.block$data(l,p,(0,Ce._)`${i} === false`),t.ok(l);function p(){let S=e.let("i",(0,Ce._)`${n}.length`),T=e.let("j");t.setParams({i:S,j:T}),e.assign(l,!0),e.if((0,Ce._)`${S} > 1`,()=>(g()?$:v)(S,T))}function g(){return u.length>0&&!u.some(S=>S==="object"||S==="array")}function $(S,T){let E=e.name("item"),P=(0,Pc.checkDataTypes)(u,E,a.opts.strictNumbers,Pc.DataType.Wrong),O=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${S}--;`,()=>{e.let(E,(0,Ce._)`${n}[${S}]`),e.if(P,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${E} == "string"`,(0,Ce._)`${E} += "_"`),e.if((0,Ce._)`typeof ${O}[${E}] == "number"`,()=>{e.assign(T,(0,Ce._)`${O}[${E}]`),t.error(),e.assign(l,!1).break()}).code((0,Ce._)`${O}[${E}] = ${S}`)})}function v(S,T){let E=(0,UT.useFunc)(e,MT.default),P=e.name("outer");e.label(P).for((0,Ce._)`;${S}--;`,()=>e.for((0,Ce._)`${T} = ${S}; ${T}--;`,()=>e.if((0,Ce._)`${E}(${n}[${S}], ${n}[${T}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};Ac.default=qT});var Ym=D(Cc=>{"use strict";Object.defineProperty(Cc,"__esModule",{value:!0});var Ic=ee(),BT=de(),FT=ti(),HT={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ic._)`{allowedValue: ${t}}`},KT={keyword:"const",$data:!0,error:HT,code(t){let{gen:e,data:n,$data:r,schemaCode:s,schema:o}=t;r||o&&typeof o=="object"?t.fail$data((0,Ic._)`!${(0,BT.useFunc)(e,FT.default)}(${n}, ${s})`):t.fail((0,Ic._)`${o} !== ${n}`)}};Cc.default=KT});var Zm=D(Oc=>{"use strict";Object.defineProperty(Oc,"__esModule",{value:!0});var ds=ee(),VT=de(),GT=ti(),WT={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ds._)`{allowedValues: ${t}}`},JT={keyword:"enum",schemaType:"array",$data:!0,error:WT,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,VT.useFunc)(e,GT.default)),p;if(a||r)p=e.let("valid"),t.block$data(p,g);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let v=e.const("vSchema",o);p=(0,ds.or)(...s.map((S,T)=>$(v,T)))}t.pass(p);function g(){e.assign(p,!1),e.forOf("v",o,v=>e.if((0,ds._)`${u()}(${n}, ${v})`,()=>e.assign(p,!0).break()))}function $(v,S){let T=s[S];return typeof T=="object"&&T!==null?(0,ds._)`${u()}(${n}, ${v}[${S}])`:(0,ds._)`${n} === ${T}`}}};Oc.default=JT});var Xm=D(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});var YT=Mm(),ZT=zm(),XT=Fm(),QT=Hm(),eR=Km(),tR=Vm(),nR=Gm(),rR=Jm(),sR=Ym(),oR=Zm(),iR=[YT.default,ZT.default,XT.default,QT.default,eR.default,tR.default,nR.default,rR.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},sR.default,oR.default];Nc.default=iR});var jc=D(us=>{"use strict";Object.defineProperty(us,"__esModule",{value:!0});us.validateAdditionalItems=void 0;var Sn=ee(),Lc=de(),aR={message:({params:{len:t}})=>(0,Sn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Sn._)`{limit: ${t}}`},lR={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:aR,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Lc.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Qm(t,r)}};function Qm(t,e){let{gen:n,schema:r,data:s,keyword:o,it:i}=t;i.items=!0;let a=n.const("len",(0,Sn._)`${s}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Sn._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Lc.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Sn._)`${a} <= ${e.length}`);n.if((0,Sn.not)(u),()=>l(u)),t.ok(u)}function l(u){n.forRange("i",e.length,a,p=>{t.subschema({keyword:o,dataProp:p,dataPropType:Lc.Type.Num},u),i.allErrors||n.if((0,Sn.not)(u),()=>n.break())})}}us.validateAdditionalItems=Qm;us.default=lR});var Dc=D(ps=>{"use strict";Object.defineProperty(ps,"__esModule",{value:!0});ps.validateTuple=void 0;var eg=ee(),ni=de(),cR=lt(),dR={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return tg(t,"additionalItems",e);n.items=!0,!(0,ni.alwaysValidSchema)(n,e)&&t.ok((0,cR.validateArray)(t))}};function tg(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=ni.mergeEvaluated.items(r,n.length,a.items));let l=r.name("valid"),u=r.const("len",(0,eg._)`${o}.length`);n.forEach((g,$)=>{(0,ni.alwaysValidSchema)(a,g)||(r.if((0,eg._)`${u} > ${$}`,()=>t.subschema({keyword:i,schemaProp:$,dataProp:$},l)),t.ok(l))});function p(g){let{opts:$,errSchemaPath:v}=a,S=n.length,T=S===g.minItems&&(S===g.maxItems||g[e]===!1);if($.strictTuples&&!T){let E=`"${i}" is ${S}-tuple, but minItems or maxItems/${e} are not specified or different at path "${v}"`;(0,ni.checkStrictMode)(a,E,$.strictTuples)}}}ps.validateTuple=tg;ps.default=dR});var ng=D(Uc=>{"use strict";Object.defineProperty(Uc,"__esModule",{value:!0});var uR=Dc(),pR={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,uR.validateTuple)(t,"items")};Uc.default=pR});var sg=D(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var rg=ee(),hR=de(),fR=lt(),mR=jc(),gR={message:({params:{len:t}})=>(0,rg.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,rg._)`{limit: ${t}}`},bR={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gR,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:s}=n;r.items=!0,!(0,hR.alwaysValidSchema)(r,e)&&(s?(0,mR.validateAdditionalItems)(t,s):t.ok((0,fR.validateArray)(t)))}};Mc.default=bR});var og=D(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var dt=ee(),ri=de(),yR={message:({params:{min:t,max:e}})=>e===void 0?(0,dt.str)`must contain at least ${t} valid item(s)`:(0,dt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dt._)`{minContains: ${t}}`:(0,dt._)`{minContains: ${t}, maxContains: ${e}}`},wR={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:yR,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,dt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ri.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ri.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ri.alwaysValidSchema)(o,n)){let T=(0,dt._)`${p} >= ${i}`;a!==void 0&&(T=(0,dt._)`${T} && ${p} <= ${a}`),t.pass(T);return}o.items=!0;let g=e.name("valid");a===void 0&&i===1?v(g,()=>e.if(g,()=>e.break())):i===0?(e.let(g,!0),a!==void 0&&e.if((0,dt._)`${s}.length > 0`,$)):(e.let(g,!1),$()),t.result(g,()=>t.reset());function $(){let T=e.name("_valid"),E=e.let("count",0);v(T,()=>e.if(T,()=>S(E)))}function v(T,E){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:ri.Type.Num,compositeRule:!0},T),E()})}function S(T){e.code((0,dt._)`${T}++`),a===void 0?e.if((0,dt._)`${T} >= ${i}`,()=>e.assign(g,!0).break()):(e.if((0,dt._)`${T} > ${a}`,()=>e.assign(g,!1).break()),i===1?e.assign(g,!0):e.if((0,dt._)`${T} >= ${i}`,()=>e.assign(g,!0)))}}};zc.default=wR});var lg=D($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.validateSchemaDeps=$t.validatePropertyDeps=$t.error=void 0;var qc=ee(),vR=de(),hs=lt();$t.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,qc.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,qc._)`{property: ${t},
1869
+ missingProperty: ${r},
1870
1870
  depsCount: ${e},
1871
- deps: ${r}}`};var wR={keyword:"dependencies",type:"object",schemaType:"object",error:$t.error,code(t){let[e,r]=vR(t);og(t,e),ig(t,r)}};function vR({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let s=Array.isArray(t[n])?e:r;s[n]=t[n]}return[e,r]}function og(t,e=t.schema){let{gen:r,data:n,it:s}=t;if(Object.keys(e).length===0)return;let o=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,hs.propertyInData)(r,n,i,s.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),s.allErrors?r.if(l,()=>{for(let u of a)(0,hs.checkReportMissingProp)(t,u)}):(r.if((0,Dc._)`${l} && (${(0,hs.checkMissingProp)(t,a,o)})`),(0,hs.reportMissingProp)(t,o),r.else())}}$t.validatePropertyDeps=og;function ig(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,yR.alwaysValidSchema)(o,e[a])||(r.if((0,hs.propertyInData)(r,n,a,o.opts.ownProperties),()=>{let l=t.subschema({keyword:s,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}$t.validateSchemaDeps=ig;$t.default=wR});var cg=U(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});var lg=ee(),kR=de(),SR={message:"property name must be valid",params:({params:t})=>(0,lg._)`{propertyName: ${t.propertyName}}`},_R={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:SR,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,kR.alwaysValidSchema)(s,r))return;let o=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},o),e.if((0,lg.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};qc.default=_R});var zc=U(Mc=>{"use strict";Object.defineProperty(Mc,"__esModule",{value:!0});var si=lt(),yt=ee(),$R=Nt(),oi=de(),xR={message:"must NOT have additional properties",params:({params:t})=>(0,yt._)`{additionalProperty: ${t.additionalProperty}}`},TR={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:xR,code(t){let{gen:e,schema:r,parentSchema:n,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,oi.alwaysValidSchema)(i,r))return;let u=(0,si.allSchemaProperties)(n.properties),p=(0,si.allSchemaProperties)(n.patternProperties);g(),t.ok((0,yt._)`${o} === ${$R.default.errors}`);function g(){e.forIn("key",s,E=>{!u.length&&!p.length?S(E):e.if($(E),()=>S(E))})}function $(E){let P;if(u.length>8){let O=(0,oi.schemaRefOrVal)(i,n.properties,"properties");P=(0,si.isOwnProperty)(e,O,E)}else u.length?P=(0,yt.or)(...u.map(O=>(0,yt._)`${E} === ${O}`)):P=yt.nil;return p.length&&(P=(0,yt.or)(P,...p.map(O=>(0,yt._)`${(0,si.usePattern)(t,O)}.test(${E})`))),(0,yt.not)(P)}function v(E){e.code((0,yt._)`delete ${s}[${E}]`)}function S(E){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){v(E);return}if(r===!1){t.setParams({additionalProperty:E}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,oi.alwaysValidSchema)(i,r)){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,O){let D={keyword:"additionalProperties",dataProp:E,dataPropType:oi.Type.Str};O===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};Mc.default=TR});var pg=U(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var RR=Xn(),dg=lt(),Bc=de(),ug=zc(),ER={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:s,it:o}=t;o.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&ug.default.code(new RR.KeywordCxt(o,ug.default,"additionalProperties"));let i=(0,dg.allSchemaProperties)(r);for(let g of i)o.definedProperties.add(g);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Bc.mergeEvaluated.props(e,(0,Bc.toHash)(i),o.props));let a=i.filter(g=>!(0,Bc.alwaysValidSchema)(o,r[g]));if(a.length===0)return;let l=e.name("valid");for(let g of a)u(g)?p(g):(e.if((0,dg.propertyInData)(e,s,g,o.opts.ownProperties)),p(g),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(g),t.ok(l);function u(g){return o.opts.useDefaults&&!o.compositeRule&&r[g].default!==void 0}function p(g){t.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};Fc.default=ER});var gg=U(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var hg=lt(),ii=ee(),fg=de(),mg=de(),PR={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:s,it:o}=t,{opts:i}=o,a=(0,hg.allSchemaProperties)(r),l=a.filter(T=>(0,fg.alwaysValidSchema)(o,r[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 ii.Name)&&(o.props=(0,mg.evaluatedPropsToName)(e,o.props));let{props:g}=o;$();function $(){for(let T of a)u&&v(T),o.allErrors?S(T):(e.var(p,!0),S(T),e.if(p))}function v(T){for(let E in u)new RegExp(T).test(E)&&(0,fg.checkStrictMode)(o,`property ${E} matches pattern ${T} (use allowMatchingProperties)`)}function S(T){e.forIn("key",n,E=>{e.if((0,ii._)`${(0,hg.usePattern)(t,T)}.test(${E})`,()=>{let P=l.includes(T);P||t.subschema({keyword:"patternProperties",schemaProp:T,dataProp:E,dataPropType:mg.Type.Str},p),o.opts.unevaluated&&g!==!0?e.assign((0,ii._)`${g}[${E}]`,!0):!P&&!o.allErrors&&e.if((0,ii.not)(p),()=>e.break())})})}}};Hc.default=PR});var bg=U(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var AR=de(),IR={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,AR.alwaysValidSchema)(n,r)){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"}};Kc.default=IR});var yg=U(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var CR=lt(),OR={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:CR.validateUnion,error:{message:"must match a schema in anyOf"}};Vc.default=OR});var wg=U(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var ai=ee(),NR=de(),LR={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ai._)`{passingSchemas: ${t.passing}}`},jR={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:LR,code(t){let{gen:e,schema:r,parentSchema:n,it:s}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(s.opts.discriminator&&n.discriminator)return;let o=r,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){o.forEach((p,g)=>{let $;(0,NR.alwaysValidSchema)(s,p)?e.var(l,!0):$=t.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&e.if((0,ai._)`${l} && ${i}`).assign(i,!1).assign(a,(0,ai._)`[${a}, ${g}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,g),$&&t.mergeEvaluated($,ai.Name)})})}}};Gc.default=jR});var vg=U(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var UR=de(),DR={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let s=e.name("valid");r.forEach((o,i)=>{if((0,UR.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Wc.default=DR});var _g=U(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var li=ee(),Sg=de(),qR={message:({params:t})=>(0,li.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,li._)`{failingKeyword: ${t.ifClause}}`},MR={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:qR,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Sg.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=kg(n,"then"),o=kg(n,"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,li.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,g){return()=>{let $=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated($,i),g?e.assign(g,(0,li._)`${p}`):t.setParams({ifClause:p})}}}};function kg(t,e){let r=t.schema[e];return r!==void 0&&!(0,Sg.alwaysValidSchema)(t,r)}Jc.default=MR});var $g=U(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var zR=de(),BR={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,zR.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Yc.default=BR});var xg=U(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var FR=Oc(),HR=tg(),KR=Nc(),VR=ng(),GR=sg(),WR=ag(),JR=cg(),YR=zc(),ZR=pg(),QR=gg(),XR=bg(),eE=yg(),tE=wg(),rE=vg(),nE=_g(),sE=$g();function oE(t=!1){let e=[XR.default,eE.default,tE.default,rE.default,nE.default,sE.default,JR.default,YR.default,WR.default,ZR.default,QR.default];return t?e.push(HR.default,VR.default):e.push(FR.default,KR.default),e.push(GR.default),e}Zc.default=oE});var Tg=U(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var ke=ee(),iE={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},aE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:iE,code(t,e){let{gen:r,data:n,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;s?$():v();function $(){let S=r.scopeValue("formats",{ref:g.formats,code:l.code.formats}),T=r.const("fDef",(0,ke._)`${S}[${i}]`),E=r.let("fType"),P=r.let("format");r.if((0,ke._)`typeof ${T} == "object" && !(${T} instanceof RegExp)`,()=>r.assign(E,(0,ke._)`${T}.type || "string"`).assign(P,(0,ke._)`${T}.validate`),()=>r.assign(E,(0,ke._)`"string"`).assign(P,T)),t.fail$data((0,ke.or)(O(),D()));function O(){return l.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${P}`}function D(){let ne=p.$async?(0,ke._)`(${T}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,ke._)`${P}(${n})`,Y=(0,ke._)`(typeof ${P} == "function" ? ${ne} : ${P}.test(${n}))`;return(0,ke._)`${P} && ${P} !== true && ${E} === ${e} && !${Y}`}}function v(){let S=g.formats[o];if(!S){O();return}if(S===!0)return;let[T,E,P]=D(S);T===e&&t.pass(ne());function O(){if(l.strictSchema===!1){g.logger.warn(Y());return}throw new Error(Y());function Y(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function D(Y){let He=Y instanceof RegExp?(0,ke.regexpCode)(Y):l.code.formats?(0,ke._)`${l.code.formats}${(0,ke.getProperty)(o)}`:void 0,je=r.scopeValue("formats",{key:o,ref:Y,code:He});return typeof Y=="object"&&!(Y instanceof RegExp)?[Y.type||"string",Y.validate,(0,ke._)`${je}.validate`]:["string",Y,je]}function ne(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.async){if(!p.$async)throw new Error("async format in sync schema");return(0,ke._)`await ${P}(${n})`}return typeof E=="function"?(0,ke._)`${P}(${n})`:(0,ke._)`${P}.test(${n})`}}}};Qc.default=aE});var Rg=U(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var lE=Tg(),cE=[lE.default];Xc.default=cE});var Eg=U(en=>{"use strict";Object.defineProperty(en,"__esModule",{value:!0});en.contentVocabulary=en.metadataVocabulary=void 0;en.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];en.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Ag=U(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var dE=Um(),uE=Zm(),pE=xg(),hE=Rg(),Pg=Eg(),fE=[dE.default,uE.default,(0,pE.default)(),hE.default,Pg.metadataVocabulary,Pg.contentVocabulary];ed.default=fE});var Cg=U(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.DiscrError=void 0;var Ig;(function(t){t.Tag="tag",t.Mapping="mapping"})(Ig||(ci.DiscrError=Ig={}))});var Ng=U(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var tn=ee(),td=Cg(),Og=Ho(),mE=es(),gE=de(),bE={message:({params:{discrError:t,tagName:e}})=>t===td.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,tn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},yE={keyword:"discriminator",type:"object",schemaType:"object",error:bE,code(t){let{gen:e,data:r,schema:n,parentSchema:s,it:o}=t,{oneOf:i}=s;if(!o.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),u=e.const("tag",(0,tn._)`${r}${(0,tn.getProperty)(a)}`);e.if((0,tn._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:td.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let v=$();e.if(!1);for(let S in v)e.elseIf((0,tn._)`${u} === ${S}`),e.assign(l,g(v[S]));e.else(),t.error(!1,{discrError:td.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function g(v){let S=e.name("valid"),T=t.subschema({keyword:"oneOf",schemaProp:v},S);return t.mergeEvaluated(T,tn.Name),S}function $(){var v;let S={},T=P(s),E=!0;for(let ne=0;ne<i.length;ne++){let Y=i[ne];if(Y?.$ref&&!(0,gE.schemaHasRulesButRef)(Y,o.self.RULES)){let je=Y.$ref;if(Y=Og.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,je),Y instanceof Og.SchemaEnv&&(Y=Y.schema),Y===void 0)throw new mE.default(o.opts.uriResolver,o.baseId,je)}let He=(v=Y?.properties)===null||v===void 0?void 0:v[a];if(typeof He!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);E=E&&(T||P(Y)),O(He,ne)}if(!E)throw new Error(`discriminator: "${a}" must be required`);return S;function P({required:ne}){return Array.isArray(ne)&&ne.includes(a)}function O(ne,Y){if(ne.const)D(ne.const,Y);else if(ne.enum)for(let He of ne.enum)D(He,Y);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(ne,Y){if(typeof ne!="string"||ne in S)throw new Error(`discriminator: "${a}" values must be unique strings`);S[ne]=Y}}}};rd.default=yE});var Lg=U((ML,wE)=>{wE.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 sd=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 vE=Im(),kE=Ag(),SE=Ng(),jg=Lg(),_E=["/properties"],di="http://json-schema.org/draft-07/schema",rn=class extends vE.default{_addVocabularies(){super._addVocabularies(),kE.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(SE.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(jg,_E):jg;this.addMetaSchema(e,di,!1),this.refs["http://json-schema.org/schema"]=di}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(di)?di:void 0)}};ye.Ajv=rn;nd.exports=ye=rn;nd.exports.Ajv=rn;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=rn;var $E=Xn();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return $E.KeywordCxt}});var nn=ee();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return nn._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return nn.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return nn.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return nn.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return nn.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return nn.CodeGen}});var xE=Bo();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return xE.default}});var TE=es();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return TE.default}})});var Hg=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(Mg,ld),time:xt(id(!0),cd),"date-time":xt(Ug(!0),Bg),"iso-time":xt(id(),zg),"iso-date-time":xt(Ug(),Fg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:CE,"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:qE,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:OE,int32:{type:"number",validate:jE},int64:{type:"number",validate:UE},float:{type:"number",validate:qg},double:{type:"number",validate:qg},password:!0,binary:!0};Tt.fastFormats={...Tt.fullFormats,date:xt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ld),time:xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,cd),"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,Bg),"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,Fg),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 RE(t){return t%4===0&&(t%100!==0||t%400===0)}var EE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,PE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Mg(t){let e=EE.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n===2&&RE(r)?29:PE[n])}function ld(t,e){if(t&&e)return t>e?1:t<e?-1:0}var od=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function id(t){return function(r){let n=od.exec(r);if(!n)return!1;let s=+n[1],o=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,u=+(n[6]||0),p=+(n[7]||0);if(u>23||p>59||t&&!a)return!1;if(s<=23&&o<=59&&i<60)return!0;let g=o-p*l,$=s-u*l-(g<0?1:0);return($===23||$===-1)&&(g===59||g===-1)&&i<61}}function cd(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function zg(t,e){if(!(t&&e))return;let r=od.exec(t),n=od.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var ad=/t|\s/i;function Ug(t){let e=id(t);return function(n){let s=n.split(ad);return s.length===2&&Mg(s[0])&&e(s[1])}}function Bg(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Fg(t,e){if(!(t&&e))return;let[r,n]=t.split(ad),[s,o]=e.split(ad),i=ld(r,s);if(i!==void 0)return i||cd(n,o)}var AE=/\/|:/,IE=/^(?:[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 CE(t){return AE.test(t)&&IE.test(t)}var Dg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function OE(t){return Dg.lastIndex=0,Dg.test(t)}var NE=-(2**31),LE=2**31-1;function jE(t){return Number.isInteger(t)&&t<=LE&&t>=NE}function UE(t){return Number.isInteger(t)}function qg(){return!0}var DE=/[^\\]\\Z/;function qE(t){if(DE.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Kg=U(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.formatLimitDefinition=void 0;var ME=sd(),wt=ee(),nr=wt.operators,ui={formatMaximum:{okStr:"<=",ok:nr.LTE,fail:nr.GT},formatMinimum:{okStr:">=",ok:nr.GTE,fail:nr.LT},formatExclusiveMaximum:{okStr:"<",ok:nr.LT,fail:nr.GTE},formatExclusiveMinimum:{okStr:">",ok:nr.GT,fail:nr.LTE}},zE={message:({keyword:t,schemaCode:e})=>(0,wt.str)`should be ${ui[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wt._)`{comparison: ${ui[t].okStr}, limit: ${e}}`};sn.formatLimitDefinition={keyword:Object.keys(ui),type:"string",schemaType:"string",$data:!0,error:zE,code(t){let{gen:e,data:r,schemaCode:n,keyword:s,it:o}=t,{opts:i,self:a}=o;if(!i.validateFormats)return;let l=new ME.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"`,g(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 S=e.scopeValue("formats",{key:$,ref:v,code:i.code.formats?(0,wt._)`${i.code.formats}${(0,wt.getProperty)($)}`:void 0});t.fail$data(g(S))}function g($){return(0,wt._)`${$}.compare(${r}, ${n}) ${ui[s].fail} 0`}},dependencies:["format"]};var BE=t=>(t.addKeyword(sn.formatLimitDefinition),t);sn.default=BE});var Jg=U((fs,Wg)=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});var on=Hg(),FE=Kg(),dd=ee(),Vg=new dd.Name("fullFormats"),HE=new dd.Name("fastFormats"),ud=(t,e={keywords:!0})=>{if(Array.isArray(e))return Gg(t,e,on.fullFormats,Vg),t;let[r,n]=e.mode==="fast"?[on.fastFormats,HE]:[on.fullFormats,Vg],s=e.formats||on.formatNames;return Gg(t,s,r,n),e.keywords&&(0,FE.default)(t),t};ud.get=(t,e="full")=>{let n=(e==="fast"?on.fastFormats:on.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Gg(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,dd._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}Wg.exports=fs=ud;Object.defineProperty(fs,"__esModule",{value:!0});fs.default=ud});function KE(){let t=new Yg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Zg.default)(t),t}var Yg,Zg,pi,Qg=j(()=>{Yg=Td(sd(),1),Zg=Td(Jg(),1);pi=class{constructor(e){this._ajv=e??KE()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var hi,Xg=j(()=>{Br();hi=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let 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)),g=new Set(o.filter($=>$.type==="tool_result").map($=>$.toolUseId));if(p.size!==g.size||![...p].every($=>g.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},Un,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),s=e.mode??"form";switch(s){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let o=s==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:o},zr,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function eb(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function tb(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var rb=j(()=>{});var fi,nb=j(()=>{of();Br();Qg();Rn();Xg();rb();fi=class extends Po{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(jn.options.map((n,s)=>[n,s])),this.isMessageIgnored=(n,s)=>{let o=this._loggingLevels.get(s);return o?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new pi,this.setRequestHandler(xa,n=>this._oninitialize(n)),this.setNotificationHandler(Ta,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Oa,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=jn.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new hi(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=sf(this._capabilities,e)}setRequestHandler(e,r){let s=Vt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=jr(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(Mr,l);if(!p.success){let S=p.error instanceof Error?p.error.message:String(p.error);throw new M(H.InvalidParams,`Invalid tools/call request: ${S}`)}let{params:g}=p.data,$=await Promise.resolve(r(l,u));if(g.task){let S=Kt(Dr,$);if(!S.success){let T=S.error instanceof Error?S.error.message:String(S.error);throw new M(H.InvalidParams,`Invalid task creation result: ${T}`)}return S.data}let v=Kt(bo,$);if(!v.success){let S=v.error instanceof Error?v.error.message:String(v.error);throw new M(H.InvalidParams,`Invalid tools/call result: ${S}`)}return v.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){tb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&eb(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:nh.includes(r)?r:va,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"},eo)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],s=Array.isArray(n.content)?n.content:[n.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(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(s.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(u.size!==p.size||![...u].every(g=>p.has(g)))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},Na,r):this.request({method:"sampling/createMessage",params:e},Un,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let s=e;return this.request({method:"elicitation/create",params:s},zr,r)}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},zr,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new M(H.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof M?i:new M(H.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return o}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},La,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function pd(t){return!!t&&typeof t=="object"&&ob in t}function ib(t){return t[ob]?.complete}var ob,sb,ab=j(()=>{ob=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(sb||(sb={}))});var lb=j(()=>{});function GE(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"),!VE.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,s,o)=>o.indexOf(n)===s);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function WE(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function hd(t){let e=GE(t);return WE(t,e.warnings),e.isValid}var VE,cb=j(()=>{VE=/^[A-Za-z0-9._-]{1,128}$/});var mi,db=j(()=>{mi=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let s={taskSupport:"required",...r.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,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,s,r._meta,n)}}});import{ZodOptional as JE}from"zod";function hb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function fb(t){return"_def"in t||"_zod"in t||hb(t)}function fd(t){return typeof t!="object"||t===null||fb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(hb)}function ub(t){if(t){if(fd(t))return dr(t);if(!fb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function ZE(t){let e=Vt(t);return e?Object.entries(e).map(([r,n])=>{let s=th(n),o=rh(n);return{name:r,description:s,required:!o}}):[]}function sr(t){let r=Vt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=jr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function pb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var gi,YE,ms,mb=j(()=>{nb();Rn();yl();Br();ab();lb();cb();db();gi=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new fi(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new mi(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(sr(go)),this.server.assertCanSetRequestHandler(sr(Mr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(go,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let s=Lr(r.inputSchema);return s?ml(s,{strictUnions:!0,pipeStrategy:"input"}):YE})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=Lr(r.outputSchema);s&&(n.outputSchema=ml(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Mr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new M(H.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new M(H.InvalidParams,`Tool ${e.params.name} disabled`);let s=!!e.params.task,o=n.execution?.taskSupport,i="createTask"in n.handler;if((o==="required"||o==="optional")&&!i)throw new M(H.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new M(H.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(o==="optional"&&!s&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,a,r);return s||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof M&&n.code===H.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let o=Lr(e.inputSchema)??e.inputSchema,i=await Js(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=Ys(a);throw new M(H.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new M(H.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=Lr(e.outputSchema),o=await Js(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Ys(i);throw new M(H.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let s=e.handler;if("createTask"in s){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=s;return await Promise.resolve(a.createTask(r,i))}else{let a=s;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=s;return await Promise.resolve(i(r,n))}else{let i=s;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let s=await this.validateToolInput(e,r.params.arguments,r.params.name),o=e.handler,i={...n,taskStore:n.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 g=await n.taskStore.getTask(l);if(!g)throw new M(H.InternalError,`Task ${l} not found during polling`);u=g}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(sr(yo)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(yo,async e=>{switch(e.params.ref.type){case"ref/prompt":return wh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return vh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new M(H.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new M(H.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new M(H.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return ms;let o=Vt(n.argsSchema)?.[e.params.argument.name];if(!pd(o))return ms;let i=ib(o);if(!i)return ms;let a=await i(e.params.argument.value,e.params.context);return pb(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return ms;throw new M(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ms;let o=await s(e.params.argument.value,e.params.context);return pb(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(sr(uo)),this.server.assertCanSetRequestHandler(sr(po)),this.server.assertCanSetRequestHandler(sr(ho)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(uo,async(e,r)=>{let n=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(r);for(let a of i.resources)s.push({...o.metadata,...a})}return{resources:[...n,...s]}}),this.server.setRequestHandler(po,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(ho,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new M(H.InvalidParams,`Resource ${n} disabled`);return s.readCallback(n,r)}for(let o of Object.values(this._registeredResourceTemplates)){let i=o.resourceTemplate.uriTemplate.match(n.toString());if(i)return o.readCallback(n,i,r)}throw new M(H.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(sr(fo)),this.server.assertCanSetRequestHandler(sr(mo)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(fo,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?ZE(r.argsSchema):void 0}))})),this.server.setRequestHandler(mo,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new M(H.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new M(H.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=Lr(n.argsSchema),o=await Js(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",u=Ys(l);throw new M(H.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=o.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let s=n.callback;return await Promise.resolve(s(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let s;typeof n[0]=="object"&&(s=n.shift());let o=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,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,r,s,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,s){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let o=this._createRegisteredResource(e,n.title,r,n,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,n.title,r,n,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),o}}_createRegisteredResource(e,r,n,s,o){let i={name:e,title:r,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!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,s,o){let i={resourceTemplate:n,title:r,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=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,s,o){let i={title:r,description:n,argsSchema:s===void 0?void 0:dr(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=dr(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 JE?l._def?.innerType:l;return pd(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,l,u){hd(e);let p={title:r,description:n,inputSchema:ub(s),outputSchema:ub(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:g=>{typeof g.name<"u"&&g.name!==e&&(typeof g.name=="string"&&hd(g.name),delete this._registeredTools[e],g.name&&(this._registeredTools[g.name]=p)),typeof g.title<"u"&&(p.title=g.title),typeof g.description<"u"&&(p.description=g.description),typeof g.paramsSchema<"u"&&(p.inputSchema=dr(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=dr(g.outputSchema)),typeof g.callback<"u"&&(p.handler=g.callback),typeof g.annotations<"u"&&(p.annotations=g.annotations),typeof g._meta<"u"&&(p._meta=g._meta),typeof g.enabled<"u"&&(p.enabled=g.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,s,o,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(fd(l))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!fd(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,s,o,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){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}=r;return this._createRegisteredTool(e,s,o,i,a,l,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let s;r.length>1&&(s=r.shift());let o=r[0],i=this._createRegisteredPrompt(e,void 0,n,s,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:s,description:o,argsSchema:i}=r,a=this._createRegisteredPrompt(e,s,o,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},YE={type:"object",properties:{}};ms={completion:{values:[],hasMore:!1}}});function XE(t){return uh.parse(JSON.parse(t))}function gb(t){return JSON.stringify(t)+`
1872
- `}var QE,bi,bb=j(()=>{Br();QE=10*1024*1024,bi=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??QE}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(`
1873
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),XE(r)}clear(){this._buffer=void 0}}});import yb from"node:process";var yi,wb=j(()=>{bb();yi=class{constructor(e=yb.stdin,r=yb.stdout,n){this._stdin=e,this._stdout=r,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 bi({maxBufferSize:n?.maxBufferSize})}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=gb(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var vb,kb=j(()=>{vb=[]});var Ab={};xd(Ab,{AUTHORING_MCP_SERVER_NAME:()=>Tb,AUTHORING_MCP_SERVER_VERSION:()=>Rb,AUTHORING_RESOURCES:()=>n0,AUTHORING_TOOLS:()=>r0,AUTHORING_TOOLS_PUBLIC:()=>Pb,buildAuthoringMcpServer:()=>Eb,runAuthoringMcpServer:()=>s0});import{promises as e0}from"node:fs";import{resolve as Sb}from"node:path";import{z as B}from"zod";function xb(){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 t0(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(o=>o.hookId).filter(o=>typeof o=="string"):null}catch{return null}}async function Eb(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 r=t.grounding??{},n=await xb(),s=null;if(n)try{let v=await e();s={surface:"mcp-authoring",baseUrl:v.baseUrl,token:v.token}}catch{s=null}let o=n&&s?await n.loadActiveSources(s,r):[],i={...r,loadActiveSourcesImpl:async()=>o},a=[],l=[];if(n&&s){try{a=await n.listMcpPromptSkills(s,i)}catch{a=[]}try{l=(await n.listRecipesForSurface(s,i)).map(v=>({id:v.id,record_type:v.record_type,intent:v.intent}))}catch{l=[]}}let u=s?await t0(s,r):null,p=new gi({name:Tb,version:Rb},n?{instructions:n.renderAuthoringInstructions({baseUrl:s?.baseUrl??t.baseUrl??"this instance",sources:o,recipeIntents:l,promptNames:a.map(v=>v.id),deployedExtensions:u,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&s){let v=s;for(let S of a)p.registerPrompt(S.id,{title:S.name,description:S.description},async()=>{let T=await n.getMcpPromptSkill(v,S.id,r);if(!T)throw new Error(`unknown prompt: ${S.id}`);return{description:T.description,messages:[{role:"user",content:{type:"text",text:(T.prompts??[]).join(`
1874
-
1875
- `)}}]}})}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:S}=await e(),T=await fetch(`${v}/v1/catalog/records`,{headers:{Authorization:`Bearer ${S}`,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:B.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:B.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:S})=>{let{baseUrl:T,token:E}=await e(),P=S?`?source=${encodeURIComponent(S)}`:"",O=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(v)}${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(O.status===404)throw new Error(`unknown record type "${v}" \u2014 list them with catalog_get.`);if(!O.ok)throw new Error(`record anatomy fetch failed: ${O.status}`);return Se(await O.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:B.array(B.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:B.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:S})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({types:v.join(",")});S&&P.set("source",S);let O=await fetch(`${T}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(O.status===404)throw new Error(`none of those record types resolved: ${v.join(", ")} \u2014 list them with catalog_get.`);if(!O.ok)throw new Error(`common columns fetch failed: ${O.status}`);return Se(await O.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:v,token:S}=await e(),T=await fetch(`${v}/v1/catalog/census`,{headers:{Authorization:`Bearer ${S}`,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:B.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:B.enum(_b).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:B.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:S,limit:T})=>{let{baseUrl:E,token:P}=await e(),O=new URLSearchParams({q:v});S&&O.set("kind",S),T!==void 0&&O.set("limit",String(T));let D=await fetch(`${E}/v1/catalog/objects?${O}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return Se(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:B.enum(_b),externalId:B.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:v,externalId:S})=>{let{baseUrl:T,token:E}=await e(),P=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(v)}/${encodeURIComponent(S)}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${v}:${S} \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:B.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:B.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:v,limit:S})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({q:v});S!==void 0&&P.set("limit",String(S));let O=await fetch(`${T}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!O.ok)throw new Error(`kb search failed: ${O.status}`);return Se(await O.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:B.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:v})=>{let{baseUrl:S,token:T}=await e(),E=await fetch(`${S}/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:B.boolean().optional()}},async({recordsOnly:v})=>{let{baseUrl:S,token:T}=await e();return{content:[{type:"text",text:await ir({baseUrl:S,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:B.string(),event:B.string().optional(),template:B.enum(["require-field","enforce-format","blank"]).optional(),field:B.string().optional(),regex:B.string().optional(),source:B.string().optional(),id:B.string().optional()}},async v=>{let S=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:S.relativePath,content:S.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:B.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:B.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:B.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:B.string().optional().describe("Target record type (defaults to the trigger record type)."),event:B.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:B.string().optional()}},async v=>{let S=Bt("conduit",{recordType:v.recordType,source:v.source,to:v.to,toRecordType:v.toRecordType,event:v.event,id:v.id});return Se({path:S.relativePath,content:S.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:B.string().describe("The extension TS source."),samplesDir:B.string().optional().describe('Samples directory (default "samples").')}},async({source:v,samplesDir:S})=>{let T=Sb(process.cwd(),S??"samples"),E=await gn(T),P=await As(v,E.map(D=>D.fixture)),O=P.filter(D=>!D.pass).length;return Se({total:P.length,passed:P.length-O,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:B.string(),recordType:B.string(),event:B.string(),source:B.string().describe('Adapter id or "standalone".'),sourceCode:B.string().describe("The verbatim extension TS."),extensionKind:B.string().optional()}},async v=>{let{baseUrl:S,token:T}=await e(),P=await new F({baseUrl:S,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:B.string(),limit:B.number().int().positive().optional()}},async({id:v,limit:S})=>{let{baseUrl:T,token:E}=await e(),P=new F({baseUrl:T,token:E});return Se({id:v,logs:await P.logs(v,S)})}),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:S}=await e(),T=new F({baseUrl:v,token:S});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:B.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:B.string().optional().describe("Display name (defaults to the slug)."),description:B.string().optional().describe("Short description.")}},async({slug:v,name:S,description:T})=>{let{baseUrl:E,token:P}=await e(),O=new F({baseUrl:E,token:P});return Se(await O.appsCreate({slug:v,name:S,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:B.string().describe("App slug or id.")}},async({app:v})=>{let{baseUrl:S,token:T}=await e(),E=new F({baseUrl:S,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:B.string().describe("App slug or id."),files:B.record(B.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:B.string().optional().describe("Short note stored with the revision.")}},async({app:v,files:S,note:T})=>{let{baseUrl:E,token:P}=await e(),O=new F({baseUrl:E,token:P});return Se(await O.appsPush(v,S,{note:T}))});let g=B.object({name:B.string().describe("Field name (lowercase identifier)."),type:B.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:B.boolean().optional()}),$=B.object({slug:B.string().describe("Table slug; the physical table is cr_<slug>."),displayName:B.string().optional(),fields:B.array(g).describe("At least one field."),rowLevelOwner:B.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:S}=await e(),T=new F({baseUrl:v,token:S});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:B.array($),claimedBy:B.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:S})=>{let{baseUrl:T,token:E}=await e(),P=new F({baseUrl:T,token:E});return Se(await P.tablesPlan({tables:v,claimedBy:S}))}),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:B.array($),claimedBy:B.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:S})=>{let{baseUrl:T,token:E}=await e(),P=new F({baseUrl:T,token:E});return Se(await P.tablesApply({tables:v,claimedBy:S}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async v=>{let{baseUrl:S,token:T}=await e(),P=await(await fetch(`${S}/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:S,token:T}=await e(),E=await ir({baseUrl:S,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 S=Sb(process.cwd(),"samples"),T=[];try{T=(await e0.readdir(S)).filter(P=>P.endsWith(".json"))}catch{T=[]}let E=await gn(S);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 S=await xb(),T=[];if(S){let{baseUrl:E,token:P}=await e();T=await S.listRecipesForSurface({surface:"mcp-authoring",baseUrl:E,token:P},r)}return{contents:[{uri:v.href,mimeType:"application/json",text:JSON.stringify({recipes:T})}]}}),p}async function s0(t={}){let e=await Eb(t),r=new yi;await e.connect(r)}var _b,$b,Tb,Rb,Pb,r0,n0,Ib=j(()=>{mb();wb();ji();hn();Et();Ki();Ls();kb();_b=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Tb="turbobase-authoring",Rb="0.1.0";Pb=["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"],r0=[...Pb,...vb],n0=["catalog:///","types://all","samples:///","recipes:///"]});ji();hn();Et();Ki();import{spawn as vd}from"node:child_process";import{promises as se}from"node:fs";import{homedir as o0}from"node:os";import{basename as Ob,dirname as an,join as Ye,relative as vi,resolve as le,sep as wd}from"node:path";import{Command as i0}from"commander";Fi();import{promises as Jd}from"node:fs";function Gd(t,e){return e===t?"same-type-merge":"different-type-mint"}var Yd=4;function Vi(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Tr(t,"id"),r=Tr(t,"on"),n=Tr(t,"source"),s=Tr(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Tr(o,"source"),a=Tr(o,"recordType"),l=/cycleBudget\s*:\s*(\d+)/.exec(t);if(!e||!n||!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:r,fromSource:n,fromRecordType:s,toSource:i,toRecordType:a,cycleBudget:l?Number(l[1]):Yd}}function Tr(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function hy(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 Zd(t,e,r="fixture"){let n=e.name??r,s=[],o;try{o=Vi(t)}catch(l){return{fixtureName:n,conduit:my(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=hy(e),a=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Ps(t),p=!!(await mn(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 g=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${g} 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:n,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,wouldWriteBindings:[],logs:[]};let $=await mn(l,i,{member:"transform",timeoutMs:200}),v=$.effects.logs,S=$.effects.result;if(!S||typeof S!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let T=S,E=Gd(o.fromRecordType,o.toRecordType),{wouldWriteBindings:P,masterAction:O}=fy(o,E,e);return{fixtureName:n,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,transformResult:T,applyBranch:E,wouldWriteBindings:P,masterAction:O,logs:v}}catch(l){return{fixtureName:n,conduit:o,guards:s,whenPassed:!1,atlasResolutions:a,wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}}function fy(t,e,r){return e==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${r.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:r.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.toSource,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${t.toRecordType} master (source_system='${t.toSource}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.toSource,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"},{source:t.fromSource,externalId:r.externalId,role:"replica",why:"firing source bound onto the created master (supplementary lineage; best-effort, may collide in a 1\u2192N fan)"}]}}function my(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Yd}}async function Qd(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 Xd(t){let e=await Jd.readFile(t,"utf8");return JSON.parse(e)}function eu(t){return Jd.readFile(t,"utf8")}function tu(t,e){let r=t.conduit;if(t.error)return`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`;if(!e)return t.whenPassed?`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`:`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;let n=[];n.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),n.push(`conduit: ${r.id}`),n.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${r.toSource}.${r.toRecordType}${r.on?` on=${r.on}`:""}`),n.push(""),n.push("guards (dispatch order):");for(let s of t.guards){let o=s.status==="passed"?"\u2713":s.status==="failed"?"\u2717":"\u2298";n.push(` ${o} ${s.name} [${s.status}] \u2014 ${s.detail}`)}if(n.push(""),n.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)n.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let s of t.atlasResolutions)n.push(` ${s.key} \u2192 ${s.resolved===null?"null (no Atlas link \u2014 noted)":s.resolved}`);if(!t.whenPassed)return n.push(""),n.push("transform: SKIPPED (from.when gate did not fire)."),n.join(`
1876
- `);if(n.push(""),n.push("transform \u2192 patch:"),n.push(gy(JSON.stringify(t.transformResult?.patch??{},null,2)," ")),t.transformResult?.createdFrom&&n.push(` createdFrom: ${JSON.stringify(t.transformResult.createdFrom)}`),t.logs.length>0){n.push(""),n.push("conduit logs:");for(let s of t.logs)n.push(` [${s.level}] ${s.message}${s.meta?` ${JSON.stringify(s.meta)}`:""}`)}n.push(""),n.push(`apply-branch: ${t.applyBranch}`),n.push(` ${t.masterAction}`),n.push(""),n.push("bindings that WOULD be written (txn_source_link):");for(let s of t.wouldWriteBindings)n.push(` ${s.source} role=${s.role} external_id=${s.externalId??"null"} \u2014 ${s.why}`);return n.join(`
1877
- `)}function gy(t,e){return t.split(`
1878
- `).map(r=>e+r).join(`
1879
- `)}var by="2026-01-01",ru="2026-01-01T00:00:00.000Z";function yy(t,e){let r=t.trim().toLowerCase();return r==="boolean"||r==="bool"?!1:r==="smallint"||r==="integer"||r==="int"||r==="int2"||r==="int4"||r==="int8"||r==="bigint"||r==="serial"||r==="bigserial"?1:r==="numeric"||r==="decimal"||r==="real"||r==="double precision"||r==="float4"||r==="float8"||r==="money"?0:r==="date"?by:r.startsWith("timestamp")?ru:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:ru}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function wy(t){let e={};for(let r of t.columns)e[r.name]=yy(r.pgType,r.name);return e}function vy(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:wy(t)},expect:e.expect??"pass"}}function nu(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:vy(r,e)}))}import{promises as su}from"node:fs";import{join as ou,relative as ky,sep as Sy}from"node:path";var _y=67324752,$y=33639248,xy=101010256,Ty=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let r=e;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;t[e]=r>>>0}return t})();function Ry(t){let e=4294967295;for(let r=0;r<t.length;r++)e=Ty[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function Ey(t){let e=[];async function r(n){let s=await su.readdir(n,{withFileTypes:!0});for(let o of s){let i=ou(n,o.name);o.isDirectory()?await r(i):o.isFile()&&e.push(ky(t,i).split(Sy).join("/"))}}return await r(t),e.sort(),e}async function iu(t){let e=await Ey(t),r=[],n=[],s=0;for(let a of e){let l=Buffer.from(a,"utf8"),u=await su.readFile(ou(t,a)),p=Ry(u),g=Buffer.alloc(30+l.length);g.writeUInt32LE(_y,0),g.writeUInt16LE(20,4),g.writeUInt16LE(0,6),g.writeUInt16LE(0,8),g.writeUInt32LE(p,14),g.writeUInt32LE(u.length,18),g.writeUInt32LE(u.length,22),g.writeUInt16LE(l.length,26),l.copy(g,30),r.push(g,u);let $=Buffer.alloc(46+l.length);$.writeUInt32LE($y,0),$.writeUInt16LE(20,4),$.writeUInt16LE(20,6),$.writeUInt16LE(0,10),$.writeUInt32LE(p,16),$.writeUInt32LE(u.length,20),$.writeUInt32LE(u.length,24),$.writeUInt16LE(l.length,28),$.writeUInt32LE(s,42),l.copy($,46),n.push($),s+=g.length+u.length}let o=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(xy,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(o.length,12),i.writeUInt32LE(s,16),{buffer:Buffer.concat([...r,o,i]),fileCount:e.length}}function Py(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Is(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Ay(t){let e=au(t,"from"),r=au(t,"to");return{fromSource:e?Is(e,"source"):void 0,fromRecordType:e?Is(e,"recordType"):void 0,toSource:r?Is(r,"source"):void 0,toRecordType:r?Is(r,"recordType"):void 0}}function au(t,e){let r=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!r)return null;let n=0,s=r.index+r[0].length-1;for(let o=s;o<t.length;o+=1){let i=t[o];if(i==="{")n+=1;else if(i==="}"&&(n-=1,n===0))return t.slice(s+1,o)}return null}function Iy(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,s=null,o=r;for(;o<t.length;o+=1){let l=t[o];if(s){l==="\\"?o+=1:l===s&&(s=null);continue}if(l==="'"||l==='"'||l==="`"){s=l;continue}if(l==="("||l==="{"||l==="[")n+=1;else if(l===")"||l==="}"||l==="]"){if(n===0)break;n-=1}else if(l===","&&n===0)break}let i=t.slice(r,o),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function Cy(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function Oy(t){return/\bcreatedFrom\b/.test(t)}function lu(t){let e=Py(t),r=[];if(e==="hook")return{kind:e,warnings:r};let{fromSource:n,toSource:s,fromRecordType:o,toRecordType:i}=Ay(t);n&&s&&n===s&&r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${n}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});let a=Iy(t);if(a!==null){let u=/\bexternalId\b/.test(a),p=/\bfromSource\b/.test(a);!u&&!p&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}o&&i&&o!==i&&!Oy(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let l=Cy(t,"cycleBudget");return l!==void 0&&(l<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${l} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):l>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${l} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:r}}function cu(t,e,r={}){let n=r.warn??(a=>a),s=r.ok??(a=>a),o=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${s("ok")} \u2014 no warnings.`),i.join(`
1880
- `);for(let a of e.warnings)i.push(` ${n("WARN")} ${o(`[${a.rule}]`)} ${a.message}`),i.push(` ${o("\u2192 fix:")} ${a.fix}`);return i.push(`
1881
- lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
1882
- `)}function du(t){return t.cases.filter(e=>e.status==="failed").length}function yn(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Ny(t){let e=du(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${yn(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let s=` <testcase name="${yn(n.name)}"`;if(n.status==="passed"){r.push(`${s} />`);continue}r.push(`${s}>`);let o=n.detail??"failed",i=n.type?` type="${yn(n.type)}"`:"";r.push(` <failure${i} message="${yn(o)}">${yn(o)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
1871
+ deps: ${n}}`};var kR={keyword:"dependencies",type:"object",schemaType:"object",error:$t.error,code(t){let[e,n]=SR(t);ig(t,e),ag(t,n)}};function SR({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 ig(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,hs.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,hs.checkReportMissingProp)(t,u)}):(n.if((0,qc._)`${l} && (${(0,hs.checkMissingProp)(t,a,o)})`),(0,hs.reportMissingProp)(t,o),n.else())}}$t.validatePropertyDeps=ig;function ag(t,e=t.schema){let{gen:n,data:r,keyword:s,it:o}=t,i=n.name("valid");for(let a in e)(0,vR.alwaysValidSchema)(o,e[a])||(n.if((0,hs.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=ag;$t.default=kR});var dg=D(Bc=>{"use strict";Object.defineProperty(Bc,"__esModule",{value:!0});var cg=ee(),_R=de(),$R={message:"property name must be valid",params:({params:t})=>(0,cg._)`{propertyName: ${t.propertyName}}`},xR={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:$R,code(t){let{gen:e,schema:n,data:r,it:s}=t;if((0,_R.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,cg.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Bc.default=xR});var Hc=D(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var si=lt(),yt=ee(),TR=Nt(),oi=de(),RR={message:"must NOT have additional properties",params:({params:t})=>(0,yt._)`{additionalProperty: ${t.additionalProperty}}`},ER={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:RR,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,oi.alwaysValidSchema)(i,n))return;let u=(0,si.allSchemaProperties)(r.properties),p=(0,si.allSchemaProperties)(r.patternProperties);g(),t.ok((0,yt._)`${o} === ${TR.default.errors}`);function g(){e.forIn("key",s,E=>{!u.length&&!p.length?S(E):e.if($(E),()=>S(E))})}function $(E){let P;if(u.length>8){let O=(0,oi.schemaRefOrVal)(i,r.properties,"properties");P=(0,si.isOwnProperty)(e,O,E)}else u.length?P=(0,yt.or)(...u.map(O=>(0,yt._)`${E} === ${O}`)):P=yt.nil;return p.length&&(P=(0,yt.or)(P,...p.map(O=>(0,yt._)`${(0,si.usePattern)(t,O)}.test(${E})`))),(0,yt.not)(P)}function v(E){e.code((0,yt._)`delete ${s}[${E}]`)}function S(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,oi.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,O){let U={keyword:"additionalProperties",dataProp:E,dataPropType:oi.Type.Str};O===!1&&Object.assign(U,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(U,P)}}};Fc.default=ER});var hg=D(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var PR=Qr(),ug=lt(),Kc=de(),pg=Hc(),AR={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&&pg.default.code(new PR.KeywordCxt(o,pg.default,"additionalProperties"));let i=(0,ug.allSchemaProperties)(n);for(let g of i)o.definedProperties.add(g);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=Kc.mergeEvaluated.props(e,(0,Kc.toHash)(i),o.props));let a=i.filter(g=>!(0,Kc.alwaysValidSchema)(o,n[g]));if(a.length===0)return;let l=e.name("valid");for(let g of a)u(g)?p(g):(e.if((0,ug.propertyInData)(e,s,g,o.opts.ownProperties)),p(g),o.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(g),t.ok(l);function u(g){return o.opts.useDefaults&&!o.compositeRule&&n[g].default!==void 0}function p(g){t.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};Vc.default=AR});var bg=D(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var fg=lt(),ii=ee(),mg=de(),gg=de(),IR={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,fg.allSchemaProperties)(n),l=a.filter(T=>(0,mg.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 ii.Name)&&(o.props=(0,gg.evaluatedPropsToName)(e,o.props));let{props:g}=o;$();function $(){for(let T of a)u&&v(T),o.allErrors?S(T):(e.var(p,!0),S(T),e.if(p))}function v(T){for(let E in u)new RegExp(T).test(E)&&(0,mg.checkStrictMode)(o,`property ${E} matches pattern ${T} (use allowMatchingProperties)`)}function S(T){e.forIn("key",r,E=>{e.if((0,ii._)`${(0,fg.usePattern)(t,T)}.test(${E})`,()=>{let P=l.includes(T);P||t.subschema({keyword:"patternProperties",schemaProp:T,dataProp:E,dataPropType:gg.Type.Str},p),o.opts.unevaluated&&g!==!0?e.assign((0,ii._)`${g}[${E}]`,!0):!P&&!o.allErrors&&e.if((0,ii.not)(p),()=>e.break())})})}}};Gc.default=IR});var yg=D(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var CR=de(),OR={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,CR.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"}};Wc.default=OR});var wg=D(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var NR=lt(),LR={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:NR.validateUnion,error:{message:"must match a schema in anyOf"}};Jc.default=LR});var vg=D(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var ai=ee(),jR=de(),DR={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ai._)`{passingSchemas: ${t.passing}}`},UR={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:DR,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,g)=>{let $;(0,jR.alwaysValidSchema)(s,p)?e.var(l,!0):$=t.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&e.if((0,ai._)`${l} && ${i}`).assign(i,!1).assign(a,(0,ai._)`[${a}, ${g}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,g),$&&t.mergeEvaluated($,ai.Name)})})}}};Yc.default=UR});var kg=D(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var MR=de(),zR={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,MR.alwaysValidSchema)(r,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Zc.default=zR});var $g=D(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var li=ee(),_g=de(),qR={message:({params:t})=>(0,li.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,li._)`{failingKeyword: ${t.ifClause}}`},BR={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:qR,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,_g.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let s=Sg(r,"then"),o=Sg(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,li.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,g){return()=>{let $=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated($,i),g?e.assign(g,(0,li._)`${p}`):t.setParams({ifClause:p})}}}};function Sg(t,e){let n=t.schema[e];return n!==void 0&&!(0,_g.alwaysValidSchema)(t,n)}Xc.default=BR});var xg=D(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var FR=de(),HR={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,FR.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Qc.default=HR});var Tg=D(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var KR=jc(),VR=ng(),GR=Dc(),WR=sg(),JR=og(),YR=lg(),ZR=dg(),XR=Hc(),QR=hg(),eE=bg(),tE=yg(),nE=wg(),rE=vg(),sE=kg(),oE=$g(),iE=xg();function aE(t=!1){let e=[tE.default,nE.default,rE.default,sE.default,oE.default,iE.default,ZR.default,XR.default,YR.default,QR.default,eE.default];return t?e.push(VR.default,WR.default):e.push(KR.default,GR.default),e.push(JR.default),e}ed.default=aE});var Rg=D(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var ke=ee(),lE={message:({schemaCode:t})=>(0,ke.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ke._)`{format: ${t}}`},cE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:lE,code(t,e){let{gen:n,data:r,$data:s,schema:o,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;s?$():v();function $(){let S=n.scopeValue("formats",{ref:g.formats,code:l.code.formats}),T=n.const("fDef",(0,ke._)`${S}[${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)(O(),U()));function O(){return l.strictSchema===!1?ke.nil:(0,ke._)`${i} && !${P}`}function U(){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 S=g.formats[o];if(!S){O();return}if(S===!0)return;let[T,E,P]=U(S);T===e&&t.pass(re());function O(){if(l.strictSchema===!1){g.logger.warn(Y());return}throw new Error(Y());function Y(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function U(Y){let He=Y instanceof RegExp?(0,ke.regexpCode)(Y):l.code.formats?(0,ke._)`${l.code.formats}${(0,ke.getProperty)(o)}`:void 0,je=n.scopeValue("formats",{key:o,ref:Y,code:He});return typeof Y=="object"&&!(Y instanceof RegExp)?[Y.type||"string",Y.validate,(0,ke._)`${je}.validate`]:["string",Y,je]}function re(){if(typeof S=="object"&&!(S instanceof RegExp)&&S.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})`}}}};td.default=cE});var Eg=D(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var dE=Rg(),uE=[dE.default];nd.default=uE});var Pg=D(tr=>{"use strict";Object.defineProperty(tr,"__esModule",{value:!0});tr.contentVocabulary=tr.metadataVocabulary=void 0;tr.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];tr.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Ig=D(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var pE=Um(),hE=Xm(),fE=Tg(),mE=Eg(),Ag=Pg(),gE=[pE.default,hE.default,(0,fE.default)(),mE.default,Ag.metadataVocabulary,Ag.contentVocabulary];rd.default=gE});var Og=D(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.DiscrError=void 0;var Cg;(function(t){t.Tag="tag",t.Mapping="mapping"})(Cg||(ci.DiscrError=Cg={}))});var Lg=D(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var nr=ee(),sd=Og(),Ng=Ho(),bE=es(),yE=de(),wE={message:({params:{discrError:t,tagName:e}})=>t===sd.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,nr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},vE={keyword:"discriminator",type:"object",schemaType:"object",error:wE,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,nr._)`${n}${(0,nr.getProperty)(a)}`);e.if((0,nr._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:sd.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let v=$();e.if(!1);for(let S in v)e.elseIf((0,nr._)`${u} === ${S}`),e.assign(l,g(v[S]));e.else(),t.error(!1,{discrError:sd.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function g(v){let S=e.name("valid"),T=t.subschema({keyword:"oneOf",schemaProp:v},S);return t.mergeEvaluated(T,nr.Name),S}function $(){var v;let S={},T=P(s),E=!0;for(let re=0;re<i.length;re++){let Y=i[re];if(Y?.$ref&&!(0,yE.schemaHasRulesButRef)(Y,o.self.RULES)){let je=Y.$ref;if(Y=Ng.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,je),Y instanceof Ng.SchemaEnv&&(Y=Y.schema),Y===void 0)throw new bE.default(o.opts.uriResolver,o.baseId,je)}let He=(v=Y?.properties)===null||v===void 0?void 0:v[a];if(typeof He!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);E=E&&(T||P(Y)),O(He,re)}if(!E)throw new Error(`discriminator: "${a}" must be required`);return S;function P({required:re}){return Array.isArray(re)&&re.includes(a)}function O(re,Y){if(re.const)U(re.const,Y);else if(re.enum)for(let He of re.enum)U(He,Y);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function U(re,Y){if(typeof re!="string"||re in S)throw new Error(`discriminator: "${a}" values must be unique strings`);S[re]=Y}}}};od.default=vE});var jg=D((ZL,kE)=>{kE.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 ad=D((ye,id)=>{"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 SE=Cm(),_E=Ig(),$E=Lg(),Dg=jg(),xE=["/properties"],di="http://json-schema.org/draft-07/schema",rr=class extends SE.default{_addVocabularies(){super._addVocabularies(),_E.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword($E.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Dg,xE):Dg;this.addMetaSchema(e,di,!1),this.refs["http://json-schema.org/schema"]=di}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(di)?di:void 0)}};ye.Ajv=rr;id.exports=ye=rr;id.exports.Ajv=rr;Object.defineProperty(ye,"__esModule",{value:!0});ye.default=rr;var TE=Qr();Object.defineProperty(ye,"KeywordCxt",{enumerable:!0,get:function(){return TE.KeywordCxt}});var sr=ee();Object.defineProperty(ye,"_",{enumerable:!0,get:function(){return sr._}});Object.defineProperty(ye,"str",{enumerable:!0,get:function(){return sr.str}});Object.defineProperty(ye,"stringify",{enumerable:!0,get:function(){return sr.stringify}});Object.defineProperty(ye,"nil",{enumerable:!0,get:function(){return sr.nil}});Object.defineProperty(ye,"Name",{enumerable:!0,get:function(){return sr.Name}});Object.defineProperty(ye,"CodeGen",{enumerable:!0,get:function(){return sr.CodeGen}});var RE=Bo();Object.defineProperty(ye,"ValidationError",{enumerable:!0,get:function(){return RE.default}});var EE=es();Object.defineProperty(ye,"MissingRefError",{enumerable:!0,get:function(){return EE.default}})});var Kg=D(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,ud),time:xt(cd(!0),pd),"date-time":xt(Ug(!0),Fg),"iso-time":xt(cd(),Bg),"iso-date-time":xt(Ug(),Hg),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:NE,"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:qE,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:LE,int32:{type:"number",validate:UE},int64:{type:"number",validate:ME},float:{type:"number",validate:zg},double:{type:"number",validate:zg},password:!0,binary:!0};Tt.fastFormats={...Tt.fullFormats,date:xt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ud),time:xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,pd),"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,Fg),"iso-time":xt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Bg),"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,Hg),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 PE(t){return t%4===0&&(t%100!==0||t%400===0)}var AE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,IE=[0,31,28,31,30,31,30,31,31,30,31,30,31];function qg(t){let e=AE.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&&PE(n)?29:IE[r])}function ud(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ld=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function cd(t){return function(n){let r=ld.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 g=o-p*l,$=s-u*l-(g<0?1:0);return($===23||$===-1)&&(g===59||g===-1)&&i<61}}function pd(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 Bg(t,e){if(!(t&&e))return;let n=ld.exec(t),r=ld.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 dd=/t|\s/i;function Ug(t){let e=cd(t);return function(r){let s=r.split(dd);return s.length===2&&qg(s[0])&&e(s[1])}}function Fg(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function Hg(t,e){if(!(t&&e))return;let[n,r]=t.split(dd),[s,o]=e.split(dd),i=ud(n,s);if(i!==void 0)return i||pd(r,o)}var CE=/\/|:/,OE=/^(?:[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 NE(t){return CE.test(t)&&OE.test(t)}var Mg=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function LE(t){return Mg.lastIndex=0,Mg.test(t)}var jE=-(2**31),DE=2**31-1;function UE(t){return Number.isInteger(t)&&t<=DE&&t>=jE}function ME(t){return Number.isInteger(t)}function zg(){return!0}var zE=/[^\\]\\Z/;function qE(t){if(zE.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Vg=D(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.formatLimitDefinition=void 0;var BE=ad(),wt=ee(),rn=wt.operators,ui={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}},FE={message:({keyword:t,schemaCode:e})=>(0,wt.str)`should be ${ui[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wt._)`{comparison: ${ui[t].okStr}, limit: ${e}}`};or.formatLimitDefinition={keyword:Object.keys(ui),type:"string",schemaType:"string",$data:!0,error:FE,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 BE.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"`,g(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 S=e.scopeValue("formats",{key:$,ref:v,code:i.code.formats?(0,wt._)`${i.code.formats}${(0,wt.getProperty)($)}`:void 0});t.fail$data(g(S))}function g($){return(0,wt._)`${$}.compare(${n}, ${r}) ${ui[s].fail} 0`}},dependencies:["format"]};var HE=t=>(t.addKeyword(or.formatLimitDefinition),t);or.default=HE});var Yg=D((fs,Jg)=>{"use strict";Object.defineProperty(fs,"__esModule",{value:!0});var ir=Kg(),KE=Vg(),hd=ee(),Gg=new hd.Name("fullFormats"),VE=new hd.Name("fastFormats"),fd=(t,e={keywords:!0})=>{if(Array.isArray(e))return Wg(t,e,ir.fullFormats,Gg),t;let[n,r]=e.mode==="fast"?[ir.fastFormats,VE]:[ir.fullFormats,Gg],s=e.formats||ir.formatNames;return Wg(t,s,n,r),e.keywords&&(0,KE.default)(t),t};fd.get=(t,e="full")=>{let r=(e==="fast"?ir.fastFormats:ir.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Wg(t,e,n,r){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,hd._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}Jg.exports=fs=fd;Object.defineProperty(fs,"__esModule",{value:!0});fs.default=fd});function GE(){let t=new Zg.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Xg.default)(t),t}var Zg,Xg,pi,Qg=j(()=>{Zg=Pd(ad(),1),Xg=Pd(Yg(),1);pi=class{constructor(e){this._ajv=e??GE()}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 hi,eb=j(()=>{Fn();hi=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)),g=new Set(o.filter($=>$.type==="tool_result").map($=>$.toolUseId));if(p.size!==g.size||![...p].every($=>g.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},Bn,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 tb(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 nb(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 rb=j(()=>{});var fi,sb=j(()=>{af();Fn();Qg();Rr();eb();rb();fi=class extends Po{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(jr.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 pi,this.setRequestHandler(Ea,r=>this._oninitialize(r)),this.setNotificationHandler(Pa,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ja,async(r,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=jr.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new hi(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=of(this._capabilities,e)}setRequestHandler(e,n){let s=Vt(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o=Dn(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(qn,l);if(!p.success){let S=p.error instanceof Error?p.error.message:String(p.error);throw new z(H.InvalidParams,`Invalid tools/call request: ${S}`)}let{params:g}=p.data,$=await Promise.resolve(n(l,u));if(g.task){let S=Kt(Mn,$);if(!S.success){let T=S.error instanceof Error?S.error.message:String(S.error);throw new z(H.InvalidParams,`Invalid task creation result: ${T}`)}return S.data}let v=Kt(bo,$);if(!v.success){let S=v.error instanceof Error?v.error.message:String(v.error);throw new z(H.InvalidParams,`Invalid tools/call result: ${S}`)}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){nb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&tb(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:sh.includes(n)?n:_a,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"},eo)}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(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(s.filter(g=>g.type==="tool_result").map(g=>g.toolUseId));if(u.size!==p.size||![...u].every(g=>p.has(g)))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},Da,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},Bn,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},Bn,n);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new z(H.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(H.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},Ua,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 md(t){return!!t&&typeof t=="object"&&ib in t}function ab(t){return t[ib]?.complete}var ib,ob,lb=j(()=>{ib=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(ob||(ob={}))});var cb=j(()=>{});function JE(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"),!WE.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 YE(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 gd(t){let e=JE(t);return YE(t,e.warnings),e.isValid}var WE,db=j(()=>{WE=/^[A-Za-z0-9._-]{1,128}$/});var mi,ub=j(()=>{mi=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 ZE}from"zod";function fb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function mb(t){return"_def"in t||"_zod"in t||fb(t)}function bd(t){return typeof t!="object"||t===null||mb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(fb)}function pb(t){if(t){if(bd(t))return un(t);if(!mb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function QE(t){let e=Vt(t);return e?Object.entries(e).map(([n,r])=>{let s=nh(r),o=rh(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=Dn(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function hb(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var gi,XE,ms,gb=j(()=>{sb();Rr();kl();Fn();lb();cb();db();ub();gi=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 fi(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new mi(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(go)),this.server.assertCanSetRequestHandler(sn(qn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(go,()=>({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=jn(n.inputSchema);return s?yl(s,{strictUnions:!0,pipeStrategy:"input"}):XE})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let s=jn(n.outputSchema);s&&(r.outputSchema=yl(s,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(qn,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new z(H.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new z(H.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 z(H.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new z(H.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 z&&r.code===H.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=jn(e.inputSchema)??e.inputSchema,i=await Js(o,n);if(!i.success){let a="error"in i?i.error:"Unknown error",l=Ys(a);throw new z(H.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 z(H.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let s=jn(e.outputSchema),o=await Js(s,n.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Ys(i);throw new z(H.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 g=await r.taskStore.getTask(l);if(!g)throw new z(H.InternalError,`Task ${l} not found during polling`);u=g}return await r.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(sn(yo)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(yo,async e=>{switch(e.params.ref.type){case"ref/prompt":return vh(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return kh(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(H.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new z(H.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new z(H.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return ms;let o=Vt(r.argsSchema)?.[e.params.argument.name];if(!md(o))return ms;let i=ab(o);if(!i)return ms;let a=await i(e.params.argument.value,e.params.context);return hb(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 ms;throw new z(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=r.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return ms;let o=await s(e.params.argument.value,e.params.context);return hb(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(uo)),this.server.assertCanSetRequestHandler(sn(po)),this.server.assertCanSetRequestHandler(sn(ho)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(uo,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(po,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(ho,async(e,n)=>{let r=new URL(e.params.uri),s=this._registeredResources[r.toString()];if(s){if(!s.enabled)throw new z(H.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 z(H.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(sn(fo)),this.server.assertCanSetRequestHandler(sn(mo)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(fo,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?QE(n.argsSchema):void 0}))})),this.server.setRequestHandler(mo,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new z(H.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new z(H.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let s=jn(r.argsSchema),o=await Js(s,e.params.arguments);if(!o.success){let l="error"in o?o.error:"Unknown error",u=Ys(l);throw new z(H.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:un(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=un(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 ZE?l._def?.innerType:l;return md(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,s,o,i,a,l,u){gd(e);let p={title:n,description:r,inputSchema:pb(s),outputSchema:pb(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:g=>{typeof g.name<"u"&&g.name!==e&&(typeof g.name=="string"&&gd(g.name),delete this._registeredTools[e],g.name&&(this._registeredTools[g.name]=p)),typeof g.title<"u"&&(p.title=g.title),typeof g.description<"u"&&(p.description=g.description),typeof g.paramsSchema<"u"&&(p.inputSchema=un(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=un(g.outputSchema)),typeof g.callback<"u"&&(p.handler=g.callback),typeof g.annotations<"u"&&(p.annotations=g.annotations),typeof g._meta<"u"&&(p._meta=g._meta),typeof g.enabled<"u"&&(p.enabled=g.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(bd(l))s=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!bd(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()}},XE={type:"object",properties:{}};ms={completion:{values:[],hasMore:!1}}});function t0(t){return ph.parse(JSON.parse(t))}function bb(t){return JSON.stringify(t)+`
1872
+ `}var e0,bi,yb=j(()=>{Fn();e0=10*1024*1024,bi=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??e0}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(`
1873
+ `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),t0(n)}clear(){this._buffer=void 0}}});import wb from"node:process";var yi,vb=j(()=>{yb();yi=class{constructor(e=wb.stdin,n=wb.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 bi({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=bb(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}}});var kb,Sb=j(()=>{kb=[]});var Ib={};Ed(Ib,{AUTHORING_MCP_SERVER_NAME:()=>Rb,AUTHORING_MCP_SERVER_VERSION:()=>Eb,AUTHORING_RESOURCES:()=>o0,AUTHORING_TOOLS:()=>s0,AUTHORING_TOOLS_PUBLIC:()=>Ab,buildAuthoringMcpServer:()=>Pb,runAuthoringMcpServer:()=>i0});import{promises as n0}from"node:fs";import{resolve as _b}from"node:path";import{z as B}from"zod";function Tb(){return xb??=import("../mcp/grounding.js").then(e=>e,()=>null),xb}function Se(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function r0(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 Pb(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 Tb(),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 r0(s,n):null,p=new gi({name:Rb,version:Eb},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 S of a)p.registerPrompt(S.id,{title:S.name,description:S.description},async()=>{let T=await r.getMcpPromptSkill(v,S.id,n);if(!T)throw new Error(`unknown prompt: ${S.id}`);return{description:T.description,messages:[{role:"user",content:{type:"text",text:(T.prompts??[]).join(`
1874
+
1875
+ `)}}]}})}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:S}=await e(),T=await fetch(`${v}/v1/catalog/records`,{headers:{Authorization:`Bearer ${S}`,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:B.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:B.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:S})=>{let{baseUrl:T,token:E}=await e(),P=S?`?source=${encodeURIComponent(S)}`:"",O=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(v)}${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(O.status===404)throw new Error(`unknown record type "${v}" \u2014 list them with catalog_get.`);if(!O.ok)throw new Error(`record anatomy fetch failed: ${O.status}`);return Se(await O.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:B.array(B.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:B.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:S})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({types:v.join(",")});S&&P.set("source",S);let O=await fetch(`${T}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(O.status===404)throw new Error(`none of those record types resolved: ${v.join(", ")} \u2014 list them with catalog_get.`);if(!O.ok)throw new Error(`common columns fetch failed: ${O.status}`);return Se(await O.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:v,token:S}=await e(),T=await fetch(`${v}/v1/catalog/census`,{headers:{Authorization:`Bearer ${S}`,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:B.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:B.enum($b).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:B.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:S,limit:T})=>{let{baseUrl:E,token:P}=await e(),O=new URLSearchParams({q:v});S&&O.set("kind",S),T!==void 0&&O.set("limit",String(T));let U=await fetch(`${E}/v1/catalog/objects?${O}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!U.ok)throw new Error(`catalog object search failed: ${U.status}`);return Se(await U.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:B.enum($b),externalId:B.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:v,externalId:S})=>{let{baseUrl:T,token:E}=await e(),P=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(v)}/${encodeURIComponent(S)}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${v}:${S} \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:B.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:B.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:v,limit:S})=>{let{baseUrl:T,token:E}=await e(),P=new URLSearchParams({q:v});S!==void 0&&P.set("limit",String(S));let O=await fetch(`${T}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!O.ok)throw new Error(`kb search failed: ${O.status}`);return Se(await O.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:B.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:v})=>{let{baseUrl:S,token:T}=await e(),E=await fetch(`${S}/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:B.boolean().optional()}},async({recordsOnly:v})=>{let{baseUrl:S,token:T}=await e();return{content:[{type:"text",text:await an({baseUrl:S,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:B.string(),event:B.string().optional(),template:B.enum(["require-field","enforce-format","blank"]).optional(),field:B.string().optional(),regex:B.string().optional(),source:B.string().optional(),id:B.string().optional()}},async v=>{let S=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:S.relativePath,content:S.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:B.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:B.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:B.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:B.string().optional().describe("Target record type (defaults to the trigger record type)."),event:B.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:B.string().optional()}},async v=>{let S=Bt("conduit",{recordType:v.recordType,source:v.source,to:v.to,toRecordType:v.toRecordType,event:v.event,id:v.id});return Se({path:S.relativePath,content:S.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:B.string().describe("The extension TS source."),samplesDir:B.string().optional().describe('Samples directory (default "samples").')}},async({source:v,samplesDir:S})=>{let T=_b(process.cwd(),S??"samples"),E=await gr(T),P=await As(v,E.map(U=>U.fixture)),O=P.filter(U=>!U.pass).length;return Se({total:P.length,passed:P.length-O,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:B.string(),recordType:B.string(),event:B.string(),source:B.string().describe('Adapter id or "standalone".'),sourceCode:B.string().describe("The verbatim extension TS."),extensionKind:B.string().optional()}},async v=>{let{baseUrl:S,token:T}=await e(),P=await new F({baseUrl:S,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:B.string(),limit:B.number().int().positive().optional()}},async({id:v,limit:S})=>{let{baseUrl:T,token:E}=await e(),P=new F({baseUrl:T,token:E});return Se({id:v,logs:await P.logs(v,S)})}),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:S}=await e(),T=new F({baseUrl:v,token:S});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:B.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:B.string().optional().describe("Display name (defaults to the slug)."),description:B.string().optional().describe("Short description.")}},async({slug:v,name:S,description:T})=>{let{baseUrl:E,token:P}=await e(),O=new F({baseUrl:E,token:P});return Se(await O.appsCreate({slug:v,name:S,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:B.string().describe("App slug or id.")}},async({app:v})=>{let{baseUrl:S,token:T}=await e(),E=new F({baseUrl:S,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:B.string().describe("App slug or id."),files:B.record(B.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:B.string().optional().describe("Short note stored with the revision.")}},async({app:v,files:S,note:T})=>{let{baseUrl:E,token:P}=await e(),O=new F({baseUrl:E,token:P});return Se(await O.appsPush(v,S,{note:T}))});let g=B.object({name:B.string().describe("Field name (lowercase identifier)."),type:B.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:B.boolean().optional()}),$=B.object({slug:B.string().describe("Table slug; the physical table is cr_<slug>."),displayName:B.string().optional(),fields:B.array(g).describe("At least one field."),rowLevelOwner:B.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:S}=await e(),T=new F({baseUrl:v,token:S});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:B.array($),claimedBy:B.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:S})=>{let{baseUrl:T,token:E}=await e(),P=new F({baseUrl:T,token:E});return Se(await P.tablesPlan({tables:v,claimedBy:S}))}),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:B.array($),claimedBy:B.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:v,claimedBy:S})=>{let{baseUrl:T,token:E}=await e(),P=new F({baseUrl:T,token:E});return Se(await P.tablesApply({tables:v,claimedBy:S}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async v=>{let{baseUrl:S,token:T}=await e(),P=await(await fetch(`${S}/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:S,token:T}=await e(),E=await an({baseUrl:S,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 S=_b(process.cwd(),"samples"),T=[];try{T=(await n0.readdir(S)).filter(P=>P.endsWith(".json"))}catch{T=[]}let E=await gr(S);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 S=await Tb(),T=[];if(S){let{baseUrl:E,token:P}=await e();T=await S.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 i0(t={}){let e=await Pb(t),n=new yi;await e.connect(n)}var $b,xb,Rb,Eb,Ab,s0,o0,Cb=j(()=>{gb();vb();ji();hr();Et();Ki();Ls();Sb();$b=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Rb="turbobase-authoring",Eb="0.1.0";Ab=["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"],s0=[...Ab,...kb],o0=["catalog:///","types://all","samples:///","recipes:///"]});ji();hr();Et();Ki();import{spawn as _d}from"node:child_process";import{promises as se}from"node:fs";import{homedir as a0}from"node:os";import{basename as Lb,dirname as ar,join as Ye,relative as vi,resolve as le,sep as Sd}from"node:path";import{Command as l0}from"commander";Fi();import{promises as Xd}from"node:fs";function Yd(t,e){return e===t?"same-type-merge":"different-type-mint"}var Qd=4;function Vi(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Rn(t,"id"),n=Rn(t,"on"),r=Rn(t,"source"),s=Rn(t,"recordType"),o=/to\s*:\s*\{([^}]*)\}/.exec(t)?.[1]??"",i=Rn(o,"source"),a=Rn(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]):Qd}}function Rn(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function my(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 eu(t,e,n="fixture"){let r=e.name??n,s=[],o;try{o=Vi(t)}catch(l){return{fixtureName:r,conduit:by(),guards:s,whenPassed:!1,atlasResolutions:[],wouldWriteBindings:[],logs:[],error:l instanceof Error?l.message:String(l)}}let i=my(e),a=Object.entries(e.atlasLinks??{}).map(([l,u])=>({key:l,resolved:u}));try{let l=await Ps(t),p=!!(await mr(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 g=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${g} 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 mr(l,i,{member:"transform",timeoutMs:200}),v=$.effects.logs,S=$.effects.result;if(!S||typeof S!="object")throw new Error(`conduit ${o.id} transform returned no result (expected { patch, createdFrom? })`);let T=S,E=Yd(o.fromRecordType,o.toRecordType),{wouldWriteBindings:P,masterAction:O}=gy(o,E,e);return{fixtureName:r,conduit:o,guards:s,whenPassed:p,atlasResolutions:a,transformResult:T,applyBranch:E,wouldWriteBindings:P,masterAction:O,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 gy(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 by(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",cycleBudget:Qd}}async function tu(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 nu(t){let e=await Xd.readFile(t,"utf8");return JSON.parse(e)}function ru(t){return Xd.readFile(t,"utf8")}function su(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(`
1876
+ `);if(r.push(""),r.push("transform \u2192 patch:"),r.push(yy(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(`
1877
+ `)}function yy(t,e){return t.split(`
1878
+ `).map(n=>e+n).join(`
1879
+ `)}var wy="2026-01-01",ou="2026-01-01T00:00:00.000Z";function vy(t,e){let n=t.trim().toLowerCase();return n==="boolean"||n==="bool"?!1:n==="smallint"||n==="integer"||n==="int"||n==="int2"||n==="int4"||n==="int8"||n==="bigint"||n==="serial"||n==="bigserial"?1:n==="numeric"||n==="decimal"||n==="real"||n==="double precision"||n==="float4"||n==="float8"||n==="money"?0:n==="date"?wy:n.startsWith("timestamp")?ou:n.startsWith("time")?"00:00:00":n==="json"||n==="jsonb"?e&&/^cf_[a-z]{2}_/.test(e)?1074:e==="raw"||e==="attrs"?{id:"1074",lastModifiedDate:ou}:{}:n==="uuid"?"00000000-0000-0000-0000-000000000000":n==="array"||n.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function ky(t){let e={};for(let n of t.columns)e[n.name]=vy(n.pgType,n.name);return e}function Sy(t,e={}){let n=e.event??"before_save";return{name:`${t.recordType} ${n} (generated)`,context:{recordType:t.recordType,event:n,source:t.source,payload:ky(t)},expect:e.expect??"pass"}}function iu(t,e={}){return t.map(n=>({recordType:n.recordType,fixture:Sy(n,e)}))}import{promises as au}from"node:fs";import{join as lu,relative as _y,sep as $y}from"node:path";var xy=67324752,Ty=33639248,Ry=101010256,Ey=(()=>{let t=new Uint32Array(256);for(let e=0;e<256;e++){let n=e;for(let r=0;r<8;r++)n=n&1?3988292384^n>>>1:n>>>1;t[e]=n>>>0}return t})();function Py(t){let e=4294967295;for(let n=0;n<t.length;n++)e=Ey[(e^t[n])&255]^e>>>8;return(e^4294967295)>>>0}async function Ay(t){let e=[];async function n(r){let s=await au.readdir(r,{withFileTypes:!0});for(let o of s){let i=lu(r,o.name);o.isDirectory()?await n(i):o.isFile()&&e.push(_y(t,i).split($y).join("/"))}}return await n(t),e.sort(),e}async function cu(t){let e=await Ay(t),n=[],r=[],s=0;for(let a of e){let l=Buffer.from(a,"utf8"),u=await au.readFile(lu(t,a)),p=Py(u),g=Buffer.alloc(30+l.length);g.writeUInt32LE(xy,0),g.writeUInt16LE(20,4),g.writeUInt16LE(0,6),g.writeUInt16LE(0,8),g.writeUInt32LE(p,14),g.writeUInt32LE(u.length,18),g.writeUInt32LE(u.length,22),g.writeUInt16LE(l.length,26),l.copy(g,30),n.push(g,u);let $=Buffer.alloc(46+l.length);$.writeUInt32LE(Ty,0),$.writeUInt16LE(20,4),$.writeUInt16LE(20,6),$.writeUInt16LE(0,10),$.writeUInt32LE(p,16),$.writeUInt32LE(u.length,20),$.writeUInt32LE(u.length,24),$.writeUInt16LE(l.length,28),$.writeUInt32LE(s,42),l.copy($,46),r.push($),s+=g.length+u.length}let o=Buffer.concat(r),i=Buffer.alloc(22);return i.writeUInt32LE(Ry,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(o.length,12),i.writeUInt32LE(s,16),{buffer:Buffer.concat([...n,o,i]),fileCount:e.length}}function Iy(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":"hook"}function Is(t,e){let n=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return n?n[2]:void 0}function Cy(t){let e=du(t,"from"),n=du(t,"to");return{fromSource:e?Is(e,"source"):void 0,fromRecordType:e?Is(e,"recordType"):void 0,toSource:n?Is(n,"source"):void 0,toRecordType:n?Is(n,"recordType"):void 0}}function du(t,e){let n=new RegExp(`\\b${e}\\s*:\\s*\\{`).exec(t);if(!n)return null;let r=0,s=n.index+n[0].length-1;for(let o=s;o<t.length;o+=1){let i=t[o];if(i==="{")r+=1;else if(i==="}"&&(r-=1,r===0))return t.slice(s+1,o)}return null}function Oy(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let n=e.index+e[0].length,r=0,s=null,o=n;for(;o<t.length;o+=1){let l=t[o];if(s){l==="\\"?o+=1:l===s&&(s=null);continue}if(l==="'"||l==='"'||l==="`"){s=l;continue}if(l==="("||l==="{"||l==="[")r+=1;else if(l===")"||l==="}"||l==="]"){if(r===0)break;r-=1}else if(l===","&&r===0)break}let i=t.slice(n,o),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function Ny(t,e){let n=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return n?Number(n[1]):void 0}function Ly(t){return/\bcreatedFrom\b/.test(t)}function uu(t){let e=Iy(t),n=[];if(e==="hook")return{kind:e,warnings:n};let{fromSource:r,toSource:s,fromRecordType:o,toRecordType:i}=Cy(t);r&&s&&r===s&&n.push({rule:"same-source-conduit",message:`from.source and to.source are both '${r}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${o??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});let a=Oy(t);if(a!==null){let u=/\bexternalId\b/.test(a),p=/\bfromSource\b/.test(a);!u&&!p&&n.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}o&&i&&o!==i&&!Ly(t)&&n.push({rule:"missing-created-from",message:`this conduit bridges '${o}' \u2192 '${i}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${i} won't carry a lineage pointer back to its origin, so the reverse leg can't find it.`,fix:"Return `createdFrom: { source: ctx.fromSource, recordType: ctx.recordType, externalId: ctx.externalId }` from the transform so the counterpart is bound to the master by construction."});let l=Ny(t,"cycleBudget");return l!==void 0&&(l<1?n.push({rule:"cycle-budget-too-low",message:`cycleBudget=${l} is below 1 \u2014 the cycle fuse trips before the first hop (hop 0 >= budget), so this conduit can never fire.`,fix:"Set cycleBudget to at least 1 (the engine default is 4, a sane range is 1\u201320)."}):l>20&&n.push({rule:"cycle-budget-too-high",message:`cycleBudget=${l} is far above the 20 ceiling \u2014 the max-hop safety fuse is effectively disarmed, so a misconfigured conduit pair can bounce a record dozens of times before anything stops it.`,fix:"Lower cycleBudget into the 1\u201320 range (the engine default is 4); a legitimate chain rarely needs more than a handful of hops."})),{kind:e,warnings:n}}function pu(t,e,n={}){let r=n.warn??(a=>a),s=n.ok??(a=>a),o=n.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${s("ok")} \u2014 no warnings.`),i.join(`
1880
+ `);for(let a of e.warnings)i.push(` ${r("WARN")} ${o(`[${a.rule}]`)} ${a.message}`),i.push(` ${o("\u2192 fix:")} ${a.fix}`);return i.push(`
1881
+ lint: ${r(`${e.warnings.length} warning(s).`)}`),i.join(`
1882
+ `)}function hu(t){return t.cases.filter(e=>e.status==="failed").length}function yr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function jy(t){let e=hu(t),n=[];n.push('<?xml version="1.0" encoding="UTF-8"?>'),n.push(`<testsuite name="${yr(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let r of t.cases){let s=` <testcase name="${yr(r.name)}"`;if(r.status==="passed"){n.push(`${s} />`);continue}n.push(`${s}>`);let o=r.detail??"failed",i=r.type?` type="${yr(r.type)}"`:"";n.push(` <failure${i} message="${yr(o)}">${yr(o)}</failure>`),n.push(" </testcase>")}return n.push("</testsuite>"),`${n.join(`
1883
1883
  `)}
1884
- `}function Ly(t){let e={suite:t.name,tests:t.cases.length,failures:du(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
1885
- `}function Cs(t,e){return e==="junit"?Ny(t):Ly(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`},Rr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],et={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},uu=/\x1b\[[0-9;]*m/g;function Pt(t){return t.replace(uu,"").length}function Gi(t,e){return e<=0?1:Math.max(1,Math.ceil(Pt(t)/e))}function jy(){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 Wi=jy();function Ee(){return Wi}function Ji(t){Wi=t}function qe(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function tt(t,e){return Wi?`${t}${e}${Ke.reset}`:e}var f={bold:t=>tt(Ke.bold,t),dim:t=>tt(Ke.dim,t),red:t=>tt(Ke.red,t),green:t=>tt(Ke.green,t),yellow:t=>tt(Ke.yellow,t),blue:t=>tt(Ke.blue,t),magenta:t=>tt(Ke.magenta,t),cyan:t=>tt(Ke.cyan,t),grey:t=>tt(Ke.grey,t)};var ve={success:t=>`${f.green("\u2713")} ${t}`,error:t=>`${f.red("\u2716")} ${t}`,warn:t=>`${f.yellow("\u26A0")} ${t}`,info:t=>`${f.dim("\xB7")} ${t}`,step:t=>`${f.cyan("\u25B8")} ${t}`},qt={add:t=>f.green(`+ ${t}`),change:t=>f.yellow(`~ ${t}`),destroy:t=>f.red(`- ${t}`)},Uy=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Dy=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),qy=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Er(t){let e=t.toLowerCase();return Uy.has(e)?f.green(t):Dy.has(e)?f.red(t):qy.has(e)?f.yellow(t):t}function Mt(t,e=[]){let r=Math.max(Pt(t),...e.map(Pt),0),n=r+2,s=f.cyan(et.v),o=a=>` ${a}${" ".repeat(r-Pt(a))} `,i=[f.cyan(`${et.tl}${et.h.repeat(n)}${et.tr}`),`${s}${f.bold(o(t))}${s}`];if(e.length){i.push(`${f.cyan(et.ml)}${f.dim(et.h.repeat(n))}${f.cyan(et.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(f.cyan(`${et.bl}${et.h.repeat(n)}${et.br}`)),i.join(`
1886
- `)}function pt(t,e={}){let r=e.indent??" ",n=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((g,$)=>{let v=g??"";return $===u.length-1?v:v+" ".repeat(Math.max(0,i[$]-Pt(v)))});return r+p.join(n)},l=[];e.head&&(l.push(a(e.head.map(u=>f.bold(u)))),l.push(a(e.head.map((u,p)=>f.dim("\u2500".repeat(i[p]??Pt(u)))))));for(let u of t)l.push(a(u));return l.join(`
1887
- `)}function Yi(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(n=>tt(Ke.cyan,n)).join(`
1884
+ `}function Dy(t){let e={suite:t.name,tests:t.cases.length,failures:hu(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
1885
+ `}function Cs(t,e){return e==="junit"?jy(t):Dy(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`},En=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],et={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},fu=/\x1b\[[0-9;]*m/g;function Pt(t){return t.replace(fu,"").length}function Gi(t,e){return e<=0?1:Math.max(1,Math.ceil(Pt(t)/e))}function Uy(){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 Wi=Uy();function Ee(){return Wi}function Ji(t){Wi=t}function Me(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function tt(t,e){return Wi?`${t}${e}${Ke.reset}`:e}var f={bold:t=>tt(Ke.bold,t),dim:t=>tt(Ke.dim,t),red:t=>tt(Ke.red,t),green:t=>tt(Ke.green,t),yellow:t=>tt(Ke.yellow,t),blue:t=>tt(Ke.blue,t),magenta:t=>tt(Ke.magenta,t),cyan:t=>tt(Ke.cyan,t),grey:t=>tt(Ke.grey,t)};var ve={success:t=>`${f.green("\u2713")} ${t}`,error:t=>`${f.red("\u2716")} ${t}`,warn:t=>`${f.yellow("\u26A0")} ${t}`,info:t=>`${f.dim("\xB7")} ${t}`,step:t=>`${f.cyan("\u25B8")} ${t}`},Mt={add:t=>f.green(`+ ${t}`),change:t=>f.yellow(`~ ${t}`),destroy:t=>f.red(`- ${t}`)},My=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),zy=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),qy=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Pn(t){let e=t.toLowerCase();return My.has(e)?f.green(t):zy.has(e)?f.red(t):qy.has(e)?f.yellow(t):t}function zt(t,e=[]){let n=Math.max(Pt(t),...e.map(Pt),0),r=n+2,s=f.cyan(et.v),o=a=>` ${a}${" ".repeat(n-Pt(a))} `,i=[f.cyan(`${et.tl}${et.h.repeat(r)}${et.tr}`),`${s}${f.bold(o(t))}${s}`];if(e.length){i.push(`${f.cyan(et.ml)}${f.dim(et.h.repeat(r))}${f.cyan(et.mr)}`);for(let a of e)i.push(`${s}${o(a)}${s}`)}return i.push(f.cyan(`${et.bl}${et.h.repeat(r)}${et.br}`)),i.join(`
1886
+ `)}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((g,$)=>{let v=g??"";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=>f.bold(u)))),l.push(a(e.head.map((u,p)=>f.dim("\u2500".repeat(i[p]??Pt(u)))))));for(let u of t)l.push(a(u));return l.join(`
1887
+ `)}function Yi(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=>tt(Ke.cyan,r)).join(`
1888
1888
  `):e.join(`
1889
1889
  `)}
1890
- ${f.dim(` ${t}`)}`}var rt=t=>{process.stderr.write(t)};function Os(){return Ee()&&process.stderr.isTTY===!0}function pu(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${f.dim("\u2591".repeat(e-n))}`}async function J(t,e){let r=Os(),n=0,s;r&&(rt(_e.hideCursor),s=setInterval(()=>{rt(`${_e.col0}${_e.clearLine}${f.magenta(Rr[n++%Rr.length])} ${t}`)},80));let o=()=>{s&&clearInterval(s),r&&rt(`${_e.col0}${_e.clearLine}${_e.showCursor}`)};try{let i=await e();return o(),r&&rt(`${ve.success(t)}
1891
- `),i}catch(i){throw o(),r&&rt(`${ve.error(t)}
1892
- `),i}}function Zi(t){let e=0,r={stage:"queued"},n=!1,s=()=>{let l=f.magenta(Rr[e%Rr.length]),u=f.cyan(r.stage),p=r.runStatus?` ${f.dim(`(${r.runStatus})`)}`:"",g=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${t} ${f.dim("\u25B8")} ${u}${p} ${pu(r.percent)} ${g}`},o=()=>{rt(`${_e.col0}${_e.clearLine}${s()}`),n=!0},i=()=>{n&&rt(`${_e.col0}${_e.clearLine}`),n=!1};rt(_e.hideCursor);let a=setInterval(()=>{e+=1,o()},80);return{log(l){i(),rt(`${l}
1893
- `),o()},status(l){r=l,o()},done(l){clearInterval(a),i(),rt(_e.showCursor);let u=l.stage!=="failed",p=`${t} ${f.dim("\u25B8")} ${My(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;rt(`${u?ve.success(p):ve.error(p)}
1894
- `)},stop(){clearInterval(a),i(),rt(_e.showCursor)}}}function My(t){return t==="completed"?f.green(t):t==="failed"?f.red(t):f.cyan(t)}function Me(t,e,r={}){return new Promise((n,s)=>{let o=e.findIndex(T=>!T.disabled);if(o===-1){s(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:o,a=T=>{process.stderr.write(T)},l=process.stdin,u=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${f.bold(f.cyan("?"))} ${f.bold(t)}
1890
+ ${f.dim(` ${t}`)}`}var nt=t=>{process.stderr.write(t)};function Os(){return Ee()&&process.stderr.isTTY===!0}function mu(t,e=15){let n=Math.max(0,Math.min(100,t??0)),r=Math.round(n/100*e);return`${"\u2588".repeat(r)}${f.dim("\u2591".repeat(e-r))}`}async function J(t,e){let n=Os(),r=0,s;n&&(nt(_e.hideCursor),s=setInterval(()=>{nt(`${_e.col0}${_e.clearLine}${f.magenta(En[r++%En.length])} ${t}`)},80));let o=()=>{s&&clearInterval(s),n&&nt(`${_e.col0}${_e.clearLine}${_e.showCursor}`)};try{let i=await e();return o(),n&&nt(`${ve.success(t)}
1891
+ `),i}catch(i){throw o(),n&&nt(`${ve.error(t)}
1892
+ `),i}}function Zi(t){let e=0,n={stage:"queued"},r=!1,s=()=>{let l=f.magenta(En[e%En.length]),u=f.cyan(n.stage),p=n.runStatus?` ${f.dim(`(${n.runStatus})`)}`:"",g=`${String(Math.round(n.percent??0)).padStart(3)}%`;return`${l} ${t} ${f.dim("\u25B8")} ${u}${p} ${mu(n.percent)} ${g}`},o=()=>{nt(`${_e.col0}${_e.clearLine}${s()}`),r=!0},i=()=>{r&&nt(`${_e.col0}${_e.clearLine}`),r=!1};nt(_e.hideCursor);let a=setInterval(()=>{e+=1,o()},80);return{log(l){i(),nt(`${l}
1893
+ `),o()},status(l){n=l,o()},done(l){clearInterval(a),i(),nt(_e.showCursor);let u=l.stage!=="failed",p=`${t} ${f.dim("\u25B8")} ${By(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;nt(`${u?ve.success(p):ve.error(p)}
1894
+ `)},stop(){clearInterval(a),i(),nt(_e.showCursor)}}}function By(t){return t==="completed"?f.green(t):t==="failed"?f.red(t):f.cyan(t)}function ze(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(`${f.bold(f.cyan("?"))} ${f.bold(t)}
1895
1895
  `),a(`${f.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
1896
- `),a(_e.hideCursor);let p=0,g=()=>{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 O=e[P],D=P===i,ne=D?f.cyan("\u25B6"):" ",Y=O.disabled?f.grey(O.label):D?f.bold(f.cyan(O.label)):O.label,He=O.description?` ${f.dim(O.description)}`:"",je=` ${ne} ${Y}${He}`;a(`\r${je}
1896
+ `),a(_e.hideCursor);let p=0,g=()=>{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 O=e[P],U=P===i,re=U?f.cyan("\u25B6"):" ",Y=O.disabled?f.grey(O.label):U?f.bold(f.cyan(O.label)):O.label,He=O.description?` ${f.dim(O.description)}`:"",je=` ${re} ${Y}${He}`;a(`\r${je}
1897
1897
  `),E+=Gi(je,T)}p=E},$=()=>{l.removeListener("data",S),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}},S=T=>{let E=T.toString("utf8");if(E===""||E==="q"){$(),a(`
1898
1898
  `),s(new Error("aborted"));return}if(E==="\r"||E===`
1899
- `){let O=e[i];if(O.disabled)return;$(),n(O.value);return}if(E==="\x1B[A"||E==="k"){v(-1),g();return}if(E==="\x1B[B"||E==="j"){v(1),g();return}let P=Number(E);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,g())};l.on("data",S),g()})}function Ns(t,e){return`${Er(t)}${" ".repeat(Math.max(0,e-t.length))}`}var fu=t=>new Promise(e=>setTimeout(e,t));function hu(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",s=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Ns(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${s}${r}`}async function mu(t,e,r={}){let n=r.sink??(p=>{process.stdout.write(`${p}
1900
- `)}),s=r.sleep??fu,o=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,l="";for(let p of[...i].reverse())n(hu(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!r.follow)return a;let u=r.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<u;p+=1){await s(o);let g=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let $ of[...g].reverse())n(hu($)),a+=1,$.updatedAt>l&&(l=$.updatedAt)}return a}function zy(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Ns(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function gu(t,e={}){let r=e.sink??(s=>{process.stdout.write(`${s}
1901
- `)});if(e.retry){let s=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${s.id} \u2192 ${s.sourceSystem} (master ${s.masterTable}/${s.masterRowId}).`),{mode:"retry",id:s.id,retried:s.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let s of n)r(zy(s));return r(`
1902
- binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function By(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",s=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",o=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Ns(t.severity,5)} ${Ns(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${o}${e?` ${e}`:""}${s}`}async function bu(t,e={}){let r=e.sink??(P=>{process.stdout.write(`${P}
1903
- `)}),n=e.sleep??fu,s=e.intervalMs??2e3,{follow:o,maxPolls:i,json:a,sink:l,sleep:u,intervalMs:p,...g}=e,$=P=>{r(a?JSON.stringify(P):By(P))},v=await t.platformEvents({...g,limit:g.limit??100});if(v.length===0&&!o)return r("logs: no events matched."),0;let S=0,T="";for(let P of[...v].reverse())$(P),S+=1,P.ts>T&&(T=P.ts);if(!o)return S;let E=i??Number.POSITIVE_INFINITY;for(let P=0;P<E;P+=1){await n(s);let O=await t.platformEvents({...g,...T?{after:T,since:void 0}:{},limit:200});for(let D of[...O].reverse())$(D),S+=1,D.ts>T&&(T=D.ts)}return S}Ls();function wu(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var Qi=".github/workflows/turbobase-release-deploy.yml",Vy=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1899
+ `){let O=e[i];if(O.disabled)return;$(),r(O.value);return}if(E==="\x1B[A"||E==="k"){v(-1),g();return}if(E==="\x1B[B"||E==="j"){v(1),g();return}let P=Number(E);Number.isFinite(P)&&P>=1&&P<=e.length&&!e[P-1].disabled&&(i=P-1,g())};l.on("data",S),g()})}function Ns(t,e){return`${Pn(t)}${" ".repeat(Math.max(0,e-t.length))}`}var bu=t=>new Promise(e=>setTimeout(e,t));function gu(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}] ${Ns(t.state,9)} ${t.conduitId} \u2192 ${e}${r} hop=${t.hop}${s}${n}`}async function yu(t,e,n={}){let r=n.sink??(p=>{process.stdout.write(`${p}
1900
+ `)}),s=n.sleep??bu,o=n.intervalMs??2e3,i=await t.conduitEvents(e,{limit:n.limit??100});if(i.length===0&&!n.follow)return r(`logs: no conduit_event rows for ${e}.`),0;let a=0,l="";for(let p of[...i].reverse())r(gu(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!n.follow)return a;let u=n.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<u;p+=1){await s(o);let g=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let $ of[...g].reverse())r(gu($)),a+=1,$.updatedAt>l&&(l=$.updatedAt)}return a}function Fy(t){let e=t.externalId??"\u2014",n=t.createdByConduit?` via=${t.createdByConduit}`:"",r=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Ns(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${n}${r}`}async function wu(t,e={}){let n=e.sink??(s=>{process.stdout.write(`${s}
1901
+ `)});if(e.retry){let s=await t.retryBinding(e.retry);return n(`binding: re-enqueued fan-out for ${s.id} \u2192 ${s.sourceSystem} (master ${s.masterTable}/${s.masterRowId}).`),{mode:"retry",id:s.id,retried:s.retried}}let r=await t.bindings({status:e.status,limit:e.limit});if(r.length===0)return n(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let s of r)n(Fy(s));return n(`
1902
+ binding: ${r.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:r.length}}function Hy(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),n=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),r=t.occurrences>1?` x${t.occurrences}`:"",s=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",o=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Ns(t.severity,5)} ${Ns(t.outcome,8)} ${t.code}${r}${n?` ${n}`:""}${o}${e?` ${e}`:""}${s}`}async function vu(t,e={}){let n=e.sink??(P=>{process.stdout.write(`${P}
1903
+ `)}),r=e.sleep??bu,s=e.intervalMs??2e3,{follow:o,maxPolls:i,json:a,sink:l,sleep:u,intervalMs:p,...g}=e,$=P=>{n(a?JSON.stringify(P):Hy(P))},v=await t.platformEvents({...g,limit:g.limit??100});if(v.length===0&&!o)return n("logs: no events matched."),0;let S=0,T="";for(let P of[...v].reverse())$(P),S+=1,P.ts>T&&(T=P.ts);if(!o)return S;let E=i??Number.POSITIVE_INFINITY;for(let P=0;P<E;P+=1){await r(s);let O=await t.platformEvents({...g,...T?{after:T,since:void 0}:{},limit:200});for(let U of[...O].reverse())$(U),S+=1,U.ts>T&&(T=U.ts)}return S}Ls();function Su(t,e={}){return t.learningIngestError?{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`}:t.learningIngestTaskId?t.learningSourceRev===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof t.learningSourceRev=="number"?e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${t.learningSourceRev} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${t.learningSourceRev}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}:null}var Xi=".github/workflows/turbobase-release-deploy.yml",Wy=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
1904
1904
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
1905
1905
  #
1906
1906
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -2002,7 +2002,7 @@ jobs:
2002
2002
  --ref "\${{ github.sha }}" \\
2003
2003
  --project . \\
2004
2004
  --follow
2005
- `,Gy=".github/workflows/turbobase-app-deploy.yml",Wy=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2005
+ `,Jy=".github/workflows/turbobase-app-deploy.yml",Yy=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2006
2006
  # Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
2007
2007
  #
2008
2008
  # What ships from this repo, and when:
@@ -2220,14 +2220,14 @@ jobs:
2220
2220
  else
2221
2221
  echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
2222
2222
  fi
2223
- `;function vu(){return[{path:Qi,content:Vy}]}function ku(){return[{path:Gy,content:Wy}]}Ls();var Jy=[".mcp.json"];function $u(t,e=Jy){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2224
- `).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),s=e.filter(i=>!n.has(r(i)));return s.length===0?null:`${t===""||t.endsWith(`
2223
+ `;function _u(){return[{path:Xi,content:Wy}]}function $u(){return[{path:Jy,content:Yy}]}Ls();var Zy=[".mcp.json"];function Ru(t,e=Zy){let n=i=>i.replace(/^\//,""),r=new Set(t.split(`
2224
+ `).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(n)),s=e.filter(i=>!r.has(n(i)));return s.length===0?null:`${t===""||t.endsWith(`
2225
2225
  `)?t:`${t}
2226
2226
  `}
2227
2227
  # Added by the Turbobase scaffold.
2228
2228
  ${s.join(`
2229
2229
  `)}
2230
- `}var Yy=`# Turbobase Extensions \u2014 extension project
2230
+ `}var Xy=`# Turbobase Extensions \u2014 extension project
2231
2231
 
2232
2232
  This directory authors **Turbobase extensions** (hooks today; conduits later)
2233
2233
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -2296,8 +2296,8 @@ order is the signal, and it is the part the product team reads first.
2296
2296
 
2297
2297
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
2298
2298
  updating a test. It is checked into the repo so the whole team sees it.
2299
- `,Zy=JSON.stringify({mcpServers:{"turbobase-authoring":{type:"http",url:"__BASE_URL__/mcp/authoring",headers:{Authorization:"Bearer __PAT__"}},turbobase:{type:"http",url:"__BASE_URL__/mcp"}}},null,2)+`
2300
- `;function Qy(t){return`---
2299
+ `,Qy=JSON.stringify({mcpServers:{"turbobase-authoring":{type:"http",url:"__BASE_URL__/mcp/authoring",headers:{Authorization:"Bearer __PAT__"}},turbobase:{type:"http",url:"__BASE_URL__/mcp"}}},null,2)+`
2300
+ `;function ew(t){return`---
2301
2301
  name: generate-types
2302
2302
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
2303
2303
  ---
@@ -2308,7 +2308,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
2308
2308
 
2309
2309
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
2310
2310
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
2311
- `}var Xy=`---
2311
+ `}var tw=`---
2312
2312
  name: mock-test
2313
2313
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
2314
2314
  ---
@@ -2317,7 +2317,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
2317
2317
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
2318
2318
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
2319
2319
  fixture for each branch (a passing record and a rejecting record).
2320
- `,ew=`---
2320
+ `,nw=`---
2321
2321
  name: deploy
2322
2322
  description: Deploy a hook to your instance. Use only after mock-test is green.
2323
2323
  ---
@@ -2325,7 +2325,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
2325
2325
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
2326
2326
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
2327
2327
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
2328
- `;function tw(t){return`# ${t} \u2014 Turbobase app
2328
+ `;function rw(t){return`# ${t} \u2014 Turbobase app
2329
2329
 
2330
2330
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
2331
2331
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -2655,7 +2655,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
2655
2655
  review, so what you write reaches the knowledge base and the product team instead
2656
2656
  of evaporating at the end of the session. Keep the section headings exactly as
2657
2657
  they are \u2014 the ingest finds entries by heading, not by filename.
2658
- `}var Pr="customer",ar="email",rw="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",nw=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2658
+ `}var An="customer",ln="email",sw="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",ow=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
2659
2659
  //
2660
2660
  // It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
2661
2661
  // the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
@@ -2674,8 +2674,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
2674
2674
  // Pure and credentials-free: no secrets, no network, no Node builtins, one
2675
2675
  // concern per file, nothing factored into a shared module (the sandbox fences
2676
2676
  // every import except the SDK).
2677
- `;function sw(){let t=Bt("hook",{recordType:Pr,event:"before_save",template:"enforce-format",field:ar,regex:rw,id:`app:${Pr}:${ar}-format`,description:`Reject a ${Pr} write whose ${ar} is not an address.`}),e=(r,n,s)=>JSON.stringify({name:s,context:{recordType:Pr,event:"before_save",payload:r},expect:n},null,2)+`
2678
- `;return[{path:t.relativePath,content:`${nw}${t.content}`},{path:`samples/${Pr}.${ar}-ok.json`,content:e({company_name:"Acme Supply",[ar]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${Pr}.${ar}-malformed.json`,content:e({company_name:"Acme Supply",[ar]:"ada-at-example"},"reject","a malformed address is rejected")}]}var ow="---\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",iw=`---
2677
+ `;function iw(){let t=Bt("hook",{recordType:An,event:"before_save",template:"enforce-format",field:ln,regex:sw,id:`app:${An}:${ln}-format`,description:`Reject a ${An} write whose ${ln} is not an address.`}),e=(n,r,s)=>JSON.stringify({name:s,context:{recordType:An,event:"before_save",payload:n},expect:r},null,2)+`
2678
+ `;return[{path:t.relativePath,content:`${ow}${t.content}`},{path:`samples/${An}.${ln}-ok.json`,content:e({company_name:"Acme Supply",[ln]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${An}.${ln}-malformed.json`,content:e({company_name:"Acme Supply",[ln]:"ada-at-example"},"reject","a malformed address is rejected")}]}var aw="---\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",lw=`---
2679
2679
  name: ship-app
2680
2680
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
2681
2681
  ---
@@ -2718,7 +2718,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
2718
2718
  non-text, so images and fonts belong in the build pipeline or object storage, not
2719
2719
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
2720
2720
  project root and DO travel \u2014 deploy reads them.
2721
- `,aw=`---
2721
+ `,cw=`---
2722
2722
  name: business-rule-to-hook
2723
2723
  description: Decide where a rule belongs \u2014 a hook on the instance (enforced for every writer, reusable by every app) or the app's UI. Use whenever you are about to write a validation, threshold, or "you can't do that" check.
2724
2724
  ---
@@ -2786,7 +2786,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
2786
2786
  standing rules for every agent on the instance \u2014 see the record-learning skill.
2787
2787
  A rule enforced in code and nowhere written down gets re-litigated by the next
2788
2788
  person.
2789
- `;function lw(t){return`---
2789
+ `;function dw(t){return`---
2790
2790
  name: record-learning
2791
2791
  description: Append to INSTANCE-LEARNINGS.md or TURBOBASE-FEEDBACK.md. Use the MOMENT you establish a fact about how this instance is set up, or the platform costs you time \u2014 in the same change, not at the end of the task and not when asked.
2792
2792
  ---
@@ -2831,7 +2831,7 @@ the product team acts on first, so it is maintained with the entries.
2831
2831
 
2832
2832
  Do not reword the three headings. The deploy-side ingest recognises entries by
2833
2833
  heading, not by filename, so a renamed section is a finding nobody receives.
2834
- `}function cw(t){return`# What this instance's source system actually does
2834
+ `}function uw(t){return`# What this instance's source system actually does
2835
2835
 
2836
2836
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
2837
2837
  Written for the knowledge base, and **everything here is verified against real
@@ -2950,7 +2950,7 @@ finding has not been handed to the knowledge base yet.
2950
2950
  and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
2951
2951
  already live, which is worth reading before adding another rule. -->
2952
2952
 
2953
- `}function dw(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
2953
+ `}function pw(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
2954
2954
 
2955
2955
  Everything below cost time or produced a wrong result. Not speculation, and not
2956
2956
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -3030,7 +3030,7 @@ Expected / happened / cost / fix.
3030
3030
  and what it would replace. These are the highest-signal entries in the file:
3031
3031
  each one is a page downloading rows to fold that it could have asked for
3032
3032
  folded. -->
3033
- `}function uw(t,e){let r=e?`
3033
+ `}function hw(t,e){let n=e?`
3034
3034
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
3035
3035
  # --records focus a previous run stamped into the file, so a refresh never
3036
3036
  # narrows what an agent deliberately widened.
@@ -3048,7 +3048,7 @@ turbobase project grounding \${records:+--records "$records"} --query ${JSON.str
3048
3048
  set -euo pipefail
3049
3049
  turbobase project types -o ${t} >/dev/null \\
3050
3050
  || echo "turbobase: \\\`turbobase project types\\\` failed (its error is above) \u2014 ${t} was NOT refreshed." >&2
3051
- ${r}
3051
+ ${n}
3052
3052
  # ADOPT.md \u2014 what changed in the PLATFORM that this project has to act on.
3053
3053
  #
3054
3054
  # Incremental and MERGING: it fetches only what is newer than the version already
@@ -3061,8 +3061,8 @@ ${r}
3061
3061
  # surface unticked items at the start of a session.
3062
3062
  turbobase project adopt -o ADOPT.md >/dev/null \\
3063
3063
  || echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
3064
- `}var xu="Turbobase consultant",pw="turbobase-consultant",hw=`---
3065
- name: ${xu}
3064
+ `}var Eu="Turbobase consultant",fw="turbobase-consultant",mw=`---
3065
+ name: ${Eu}
3066
3066
  description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
3067
3067
  keep-coding-instructions: true
3068
3068
  ---
@@ -3135,8 +3135,8 @@ exists on purpose.
3135
3135
  - Do not show a stack trace. Say what broke and what you are doing about it.
3136
3136
  - Do not apologise repeatedly or pad with "great question".
3137
3137
  - Do not use a table when a sentence works.
3138
- `,fw=JSON.stringify({outputStyle:xu,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
3139
- `,mw=`#!/usr/bin/env bash
3138
+ `,gw=JSON.stringify({outputStyle:Eu,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"}]}]}},null,2)+`
3139
+ `,bw=`#!/usr/bin/env bash
3140
3140
  # PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
3141
3141
  #
3142
3142
  # Advisory only: exits 0 always, and adds a note for the agent when the edited
@@ -3153,7 +3153,7 @@ set -uo pipefail
3153
3153
  command -v node >/dev/null 2>&1 || exit 0
3154
3154
 
3155
3155
  exec node "$(dirname "$0")/check-rule-placement.mjs"
3156
- `,gw=String.raw`/**
3156
+ `,yw=String.raw`/**
3157
3157
  * Is the file that was just edited enforcing a business rule inside the SPA?
3158
3158
  *
3159
3159
  * Reads the PostToolUse payload on stdin, and when BOTH signals are present —
@@ -3222,7 +3222,7 @@ process.stdout.write(
3222
3222
  },
3223
3223
  }),
3224
3224
  );
3225
- `,bw=`---
3225
+ `,ww=`---
3226
3226
  name: roles-and-permissions
3227
3227
  description: Decide who can open a screen and who can change a record \u2014 declare roles in public/turbobase.json, gate the UI on capabilities, and turn a denial into a message that names the role to ask for. Use when adding a screen, a nav item, a write button, a role, or answering "who can see/do X".
3228
3228
  ---
@@ -3373,7 +3373,7 @@ a denial look like emptiness.
3373
3373
  - Does every write catch \`TurbobasePermissionError\`?
3374
3374
  - Did you run \`turbobase apps plan\`?
3375
3375
  - Did you tell the user their administrator still has to ASSIGN the role?
3376
- `,yw=`---
3376
+ `,vw=`---
3377
3377
  name: app-design
3378
3378
  description: How a Turbobase app should look and behave. Read the published design system first, then the display rules here that stop a working build showing wrong data. Use before building any screen.
3379
3379
  ---
@@ -3453,7 +3453,7 @@ The design system covers the look. Two rules it does not:
3453
3453
  Load it in the browser and check: does it render with ZERO rows, with ONE row,
3454
3454
  and with several hundred? Does it survive the query failing? Does tab reach every
3455
3455
  control, with a visible focus ring? A green \`npm run build\` proves none of these.
3456
- `,js="",Su=String.raw`{
3456
+ `,js="",xu=String.raw`{
3457
3457
  "_comment": [
3458
3458
  "Declarative sync config — part of this repo's desired state.",
3459
3459
  " turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
@@ -3475,7 +3475,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3475
3475
  "fields": [],
3476
3476
  "tables": []
3477
3477
  }
3478
- `,_u=String.raw`{
3478
+ `,Tu=String.raw`{
3479
3479
  "_comment": [
3480
3480
  "Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
3481
3481
  "Removing an entry does NOT remove the schedule unless you pass --prune.",
@@ -3491,51 +3491,51 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
3491
3491
  ],
3492
3492
  "schedules": []
3493
3493
  }
3494
- `,ww=t=>`node_modules/
3494
+ `,kw=t=>`node_modules/
3495
3495
 
3496
3496
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
3497
3497
  .mcp.json
3498
3498
 
3499
3499
  .DS_Store
3500
- `;function Xi(t={}){let e=Zy.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",s=r?{slug:t.appSlug}:void 0,o=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:ww(r)},{path:"INSTANCE-LEARNINGS.md",content:cw(s)},{path:"TURBOBASE-FEEDBACK.md",content:dw(s)},{path:".claude/settings.json",content:fw},{path:`.claude/output-styles/${pw}.md`,content:hw},{path:".claude/skills/generate-types/SKILL.md",content:Qy(n)},{path:".claude/skills/record-learning/SKILL.md",content:lw(s)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:aw},{path:".claude/hooks/session-start-refresh-types.sh",content:uw(n,s),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:mw,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:gw}];return r?[{path:"CLAUDE.md",content:tw(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:ow},{path:".claude/skills/ship-app/SKILL.md",content:iw},{path:".claude/skills/app-design/SKILL.md",content:yw},{path:".claude/skills/roles-and-permissions/SKILL.md",content:bw},...sw(),{path:"conduits/.gitkeep",content:js},{path:"turbobase/sync.json",content:Su},{path:"turbobase/schedules.json",content:_u},...ku()]:[{path:"CLAUDE.md",content:Yy},...o,{path:".claude/skills/mock-test/SKILL.md",content:Xy},{path:".claude/skills/deploy/SKILL.md",content:ew},{path:"hooks/.gitkeep",content:js},{path:"conduits/.gitkeep",content:js},{path:"samples/.gitkeep",content:js},{path:"turbobase/sync.json",content:Su},{path:"turbobase/schedules.json",content:_u}]}import{promises as ta}from"node:fs";import{join as At,resolve as Au}from"node:path";function Ru(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var wn="bundle.json",Us="turbobase";function Eu(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let s=l=>Array.isArray(l)?l:[],o=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:s(r.hooks),conduits:s(r.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(r.schedules)};return ea(a)}function ea(t){let e=r=>(n,s)=>r(n)<r(s)?-1:r(n)>r(s)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(Tu)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Tu)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Tu(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Pu(t,e){let r=(e??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(t??"").trim();return n?n!==r?{ok:!1,reason:`--confirm "${n}" does not match the target instance "${r}" \u2014 refusing to apply`}:{ok:!0}:{ok:!1,reason:`--confirm <slug> is required for promote (expected "${r}")`}}var Ms="hooks",zs="conduits",Ft="turbobase/sync.json",Ht="turbobase/schedules.json";function ra(t){let e=l=>{let u=new RegExp(`${l}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return u?u[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineHook\s*[<(]/.test(t);if(!r&&!n)return null;let s=e("id"),o=e("recordType");if(r){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 Ds(t){let e;try{e=await ta.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let s of await Ds(At(t,n.name)))r.push(`${n.name}/${s}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function qs(t,e){let r;try{r=await ta.readFile(t,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${e} is not valid JSON: ${n instanceof Error?n.message:String(n)}`)}}function vw(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function kw(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function Sw(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 Iu(t=process.cwd()){let e=Au(t),[r,n]=await Promise.all([Ds(At(e,Ms)),Ds(At(e,zs))]);if(r.length>0||n.length>0)return!0;let[s,o]=await Promise.all([qs(At(e,Ft),Ft).catch(()=>{}),qs(At(e,Ht),Ht).catch(()=>{})]);return s!==void 0||o!==void 0}async function Cu(t=process.cwd(),e={}){let r=Au(t),n=Ru(e.tenant),s=[],o=[];for(let l of[Ms,zs])for(let u of await Ds(At(r,l))){let p=`${l}/${u}`,g=await ta.readFile(At(r,l,u),"utf8"),$=ra(g);if(!$){/\bdefine(Hook|Conduit)\s*[<(]/.test(g)&&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:g};$.extensionKind==="conduit"?n.conduits.push(v):n.hooks.push(v),s.push(p)}let i=await qs(At(r,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:[])n.sync.fields.push(vw(u));for(let u of Array.isArray(l.tables)?l.tables:[])n.sync.tables.push(kw(u));s.push(Ft)}let a=await qs(At(r,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)n.schedules.push(Sw(u));s.push(Ht)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:ea(n),contributed:s,unparsed:o}}import{promises as oa}from"node:fs";import{resolve as Ew}from"node:path";var _w="For app developers \u2014 adopt these";function Ou(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 Nu(t,e){let r=Ou(t),n=Ou(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let s=0;s<3;s++){let o=(r.core[s]??0)-(n.core[s]??0);if(o!==0)return o}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function $w(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var oA=$w(_w);hn();Et();var xw=t=>new Promise(e=>setTimeout(e,t));function Lu(t){return t.stage==="completed"||t.stage==="failed"}function Tw(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function Rw(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let o=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(o)for(let i of o.split(`
3501
- `))r(i)}return n}async function na(t,e={}){let r=e.sink??($=>{process.stdout.write(`${$}
3502
- `)}),n=e.sleep??xw,s=e.intervalMs??2e3,o=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??($=>r(Tw($))),a=e.onPoll,l="",u="",p=$=>{a?.($),$.stage!==u&&i($),l=Rw($,l,r),u=$.stage},g=await t();if(p(g),Lu(g))return g;for(let $=0;$<o;$+=1)if(await n(s),g=await t(),p(g),Lu(g))return g;return g}var y=t=>{process.stdout.write(`${t}
3500
+ `;function Qi(t={}){let e=Qy.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:kw(n)},{path:"INSTANCE-LEARNINGS.md",content:uw(s)},{path:"TURBOBASE-FEEDBACK.md",content:pw(s)},{path:".claude/settings.json",content:gw},{path:`.claude/output-styles/${fw}.md`,content:mw},{path:".claude/skills/generate-types/SKILL.md",content:ew(r)},{path:".claude/skills/record-learning/SKILL.md",content:dw(s)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:cw},{path:".claude/hooks/session-start-refresh-types.sh",content:hw(r,s),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:bw,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:yw}];return n?[{path:"CLAUDE.md",content:rw(t.appSlug)},...o,{path:".claude/skills/preview-app/SKILL.md",content:aw},{path:".claude/skills/ship-app/SKILL.md",content:lw},{path:".claude/skills/app-design/SKILL.md",content:vw},{path:".claude/skills/roles-and-permissions/SKILL.md",content:ww},...iw(),{path:"conduits/.gitkeep",content:js},{path:"turbobase/sync.json",content:xu},{path:"turbobase/schedules.json",content:Tu},...$u()]:[{path:"CLAUDE.md",content:Xy},...o,{path:".claude/skills/mock-test/SKILL.md",content:tw},{path:".claude/skills/deploy/SKILL.md",content:nw},{path:"hooks/.gitkeep",content:js},{path:"conduits/.gitkeep",content:js},{path:"samples/.gitkeep",content:js},{path:"turbobase/sync.json",content:xu},{path:"turbobase/schedules.json",content:Tu}]}import{promises as ta}from"node:fs";import{join as At,resolve as Ou}from"node:path";function Au(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var wr="bundle.json",Ds="turbobase";function Iu(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 ea(a)}function ea(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(Pu)),tables:[...t.sync.tables].sort(e(n=>n.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Pu)),conduits:[...t.guardrails.conduits].sort(e(n=>n.conduitId))},schedules:[...t.schedules].sort(e(n=>n.name))}}function Pu(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Cu(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 zs="hooks",qs="conduits",Ft="turbobase/sync.json",Ht="turbobase/schedules.json";function na(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 ta.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 Ms(t,e){let n;try{n=await ta.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 Sw(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function _w(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function $w(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 Nu(t=process.cwd()){let e=Ou(t),[n,r]=await Promise.all([Us(At(e,zs)),Us(At(e,qs))]);if(n.length>0||r.length>0)return!0;let[s,o]=await Promise.all([Ms(At(e,Ft),Ft).catch(()=>{}),Ms(At(e,Ht),Ht).catch(()=>{})]);return s!==void 0||o!==void 0}async function Lu(t=process.cwd(),e={}){let n=Ou(t),r=Au(e.tenant),s=[],o=[];for(let l of[zs,qs])for(let u of await Us(At(n,l))){let p=`${l}/${u}`,g=await ta.readFile(At(n,l,u),"utf8"),$=na(g);if(!$){/\bdefine(Hook|Conduit)\s*[<(]/.test(g)&&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:g};$.extensionKind==="conduit"?r.conduits.push(v):r.hooks.push(v),s.push(p)}let i=await Ms(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(Sw(u));for(let u of Array.isArray(l.tables)?l.tables:[])r.sync.tables.push(_w(u));s.push(Ft)}let a=await Ms(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($w(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:ea(r),contributed:s,unparsed:o}}import{promises as oa}from"node:fs";import{resolve as Aw}from"node:path";var xw="For app developers \u2014 adopt these";function ju(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 Du(t,e){let n=ju(t),r=ju(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 Tw(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var aA=Tw(xw);hr();Et();var Rw=t=>new Promise(e=>setTimeout(e,t));function Uu(t){return t.stage==="completed"||t.stage==="failed"}function Ew(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function Pw(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(`
3501
+ `))n(i)}return r}async function ra(t,e={}){let n=e.sink??($=>{process.stdout.write(`${$}
3502
+ `)}),r=e.sleep??Rw,s=e.intervalMs??2e3,o=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??($=>n(Ew($))),a=e.onPoll,l="",u="",p=$=>{a?.($),$.stage!==u&&i($),l=Pw($,l,n),u=$.stage},g=await t();if(p(g),Uu(g))return g;for(let $=0;$<o;$+=1)if(await r(s),g=await t(),p(g),Uu(g))return g;return g}var y=t=>{process.stdout.write(`${t}
3503
3503
  `)},L=t=>{process.stderr.write(`${t}
3504
- `)};function w(t){L(f.red(`turbobase: ${t}`)),process.exit(1)}var vn=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function ju(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&Ji(!1)}async function V(t){let e=await ut(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Rt();if(t){let n=r.length?` Stored instances: ${r.map(s=>s.baseUrl).join(", ")}.`:"";w(`not signed in to ${Xe(t)}.${n} Run \`turbobase auth login --base-url ${Xe(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&w("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),qe())try{let n=await Me("Multiple instances stored \u2014 pick the active one:",r.map(o=>({value:o.baseUrl,label:o.baseUrl,description:`updated ${o.updatedAt}`})));await Rs(n);let s=await ut();if(s)return{baseUrl:s.baseUrl,token:s.token}}catch{}w(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function G(t,e,r){if(!(t instanceof X)||t.status!==403)return;t.body?.error==="approval_required"&&w(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),w(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function sa(t,e,r){let n=r?Number(r):void 0;if(Os()){let o=Zi(e),i;try{i=await na(t,{intervalMs:n,sink:a=>o.log(a),onStage:()=>{},onPoll:a=>o.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){o.stop(),w(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}o.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let s;try{s=await na(t,{sink:y,intervalMs:n})}catch(o){w(`${e} --follow failed: ${o instanceof Error?o.message:String(o)}`)}s.stage==="failed"&&w(`${e} failed${s.runStatus?` (${s.runStatus})`:""}.`),y(`${e} ${s.stage}.`)}var Pw=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function Aw(t){try{let e=await oa.readFile(t,"utf8");return Pw.exec(e)?.[1]??null}catch{return null}}var Iw=/GENERATED by `turbobase project adopt`/,Du=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,Cw=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Uu(t){let e=[],r=null;for(let n of t.split(`
3505
- `)){let s=Du.exec(n);if(s){r={version:s[1],items:[]},e.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let o=Cw.exec(n);if(o){let a=o[2].trim();r.items.push({key:a.replace(/\s+/g," "),done:o[1]!==" ",text:a,extra:[]});continue}let i=r.items[r.items.length-1];i&&n.trim()!==""&&i.extra.push(n)}return e}function Ow(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
3504
+ `)};function w(t){L(f.red(`turbobase: ${t}`)),process.exit(1)}var vr=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Mu(t,e){let n=e.json===!0||typeof e.reporter=="string";(t.color===!1||n)&&Ji(!1)}async function V(t){let e=await ut(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let n=await Rt();if(t){let r=n.length?` Stored instances: ${n.map(s=>s.baseUrl).join(", ")}.`:"";w(`not signed in to ${Qe(t)}.${r} Run \`turbobase auth login --base-url ${Qe(t)} --token tb_pat_\u2026\`.`)}if(n.length===0&&w("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Me())try{let r=await ze("Multiple instances stored \u2014 pick the active one:",n.map(o=>({value:o.baseUrl,label:o.baseUrl,description:`updated ${o.updatedAt}`})));await Rs(r);let s=await ut();if(s)return{baseUrl:s.baseUrl,token:s.token}}catch{}w(`multiple instances stored (${n.map(r=>r.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function G(t,e,n){if(!(t instanceof Q)||t.status!==403)return;t.body?.error==="approval_required"&&w(`${n} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),w(`${n} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function sa(t,e,n){let r=n?Number(n):void 0;if(Os()){let o=Zi(e),i;try{i=await ra(t,{intervalMs:r,sink:a=>o.log(a),onStage:()=>{},onPoll:a=>o.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){o.stop(),w(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}o.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let s;try{s=await ra(t,{sink:y,intervalMs:r})}catch(o){w(`${e} --follow failed: ${o instanceof Error?o.message:String(o)}`)}s.stage==="failed"&&w(`${e} failed${s.runStatus?` (${s.runStatus})`:""}.`),y(`${e} ${s.stage}.`)}var Iw=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function Cw(t){try{let e=await oa.readFile(t,"utf8");return Iw.exec(e)?.[1]??null}catch{return null}}var Ow=/GENERATED by `turbobase project adopt`/,qu=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,Nw=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function zu(t){let e=[],n=null;for(let r of t.split(`
3505
+ `)){let s=qu.exec(r);if(s){n={version:s[1],items:[]},e.push(n);continue}if(/^#{1,6}[ \t]/.test(r)){n=null;continue}if(!n)continue;let o=Nw.exec(r);if(o){let a=o[2].trim();n.items.push({key:a.replace(/\s+/g," "),done:o[1]!==" ",text:a,extra:[]});continue}let i=n.items[n.items.length-1];i&&r.trim()!==""&&i.extra.push(r)}return e}function Lw(t){let e=t.items.map(n=>[`- [${n.done?"x":" "}] ${n.text}`,...n.extra].join(`
3506
3506
  `)).join(`
3507
3507
  `);return`## v${t.version}
3508
3508
 
3509
- ${e}`}function Nw(t,e){let r=Uu(t);if(r.length===0&&!Iw.test(t))return null;let n=new Map(r.map(p=>[p.version,p])),s=[],o=0;for(let p of Uu(e)){let g=n.get(p.version);n.delete(p.version);let $=new Set(p.items.map(S=>S.key)),v=p.items.map(S=>{let T=g?.items.find(E=>E.key===S.key);return T?{...S,done:T.done,extra:T.extra}:S});for(let S of g?.items??[])$.has(S.key)||S.done||(v.push(S),o+=1);s.push({version:p.version,items:v})}for(let p of n.values()){let g=p.items.filter($=>!$.done);g.length!==0&&(o+=g.length,s.push({version:p.version,items:g}))}s.sort((p,g)=>Nu(g.version,p.version));let i=e.split(`
3510
- `),a=i.findIndex(p=>Du.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
3509
+ ${e}`}function jw(t,e){let n=zu(t);if(n.length===0&&!Ow.test(t))return null;let r=new Map(n.map(p=>[p.version,p])),s=[],o=0;for(let p of zu(e)){let g=r.get(p.version);r.delete(p.version);let $=new Set(p.items.map(S=>S.key)),v=p.items.map(S=>{let T=g?.items.find(E=>E.key===S.key);return T?{...S,done:T.done,extra:T.extra}:S});for(let S of g?.items??[])$.has(S.key)||S.done||(v.push(S),o+=1);s.push({version:p.version,items:v})}for(let p of r.values()){let g=p.items.filter($=>!$.done);g.length!==0&&(o+=g.length,s.push({version:p.version,items:g}))}s.sort((p,g)=>Du(g.version,p.version));let i=e.split(`
3510
+ `),a=i.findIndex(p=>qu.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
3511
3511
  `).replace(/\s+$/,"");return{markdown:s.length===0?`${l}
3512
3512
  `:`${l}
3513
3513
 
3514
- ${s.map(Ow).join(`
3514
+ ${s.map(Lw).join(`
3515
3515
 
3516
3516
  `)}
3517
- `,carried:o}}function qu(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:r,token:n}=await V(e.baseUrl),s=Ew(process.cwd(),e.out),o=e.since?.trim()||await Aw(s),i=new URLSearchParams;o&&i.set("since",o);let a=i.toString(),l=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,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(`${r} 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 g=u.currentVersion??u.releases[0]?.version??"",$=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${g}. Re-run to refresh; delete this file once every line is done. -->
3518
-
3519
- `,v=await oa.readFile(s,"utf8").catch(()=>null),S=u.markdown,T=0;if(v!==null&&v.trim()!==""){let E=Nw(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>\`.`),S=E.markdown,T=E.carried}await oa.writeFile(s,$+S,"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 kn=["suggested_kb_edit","kb_correction"];var Lw=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function jw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var yA=new Map(Lw.map(t=>[jw(t.heading),t]));var wA=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 Uw(t){return t.diff??!!t.dryRun}var Dw={update_page:"append to the existing page",new_page:"create a NEW page"},It=(t,e)=>` ${f.dim(t.padEnd(11))}${e}`,zu=t=>t.ownerEmail??t.ownerId;function Ar(t){return!t.needsPageRef&&!t.blockedBy}var Bs=t=>f.green(t?` + ${t}`:" +"),qw=t=>f.red(t?` - ${t}`:" -"),lr=t=>f.dim(` ${t}`),Mw=` ${f.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,ia=80;function zw(t){let e=[Mw];t.target?(e.push(lr(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(qw(`visibility: ${t.target.visibility}`)),e.push(Bs("visibility: admin"))):e.push(lr(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(lr("title, slug, evidence: untouched")),e.push(lr("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(lr("turbobase.document \xB7 new")),e.push(Bs(`title: ${t.pageTitle}`)),e.push(Bs("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(lr('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(lr('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3520
- `);for(let n of r.slice(0,ia))e.push(Bs(n?` ${n}`:""));return r.length>ia&&e.push(f.yellow(` \u2026 ${r.length-ia} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function Bw(t,e={}){let r=[];return t.forEach((n,s)=>{let{target:o,entries:i}=n;if(r.push(`${String(s+1).padStart(2)}. ${f.bold(n.pageTitle)}`),r.push(It("page",o?`${o.title} (${o.slug}) [${o.visibility}]`:f.dim("new \u2014 no existing page matches"))),r.push(It("action",Ar(n)?Dw[n.action]:f.red("SKIP \u2014 nothing is written"))),n.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];r.push(It("unresolved",f.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.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?` ${f.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${f.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${f.dim("\xB7")} ${a.title.trim()}${u}${l}`)}),r.push(It("confidence",n.withdraws?f.red("WITHDRAWN from readers (text untouched)"):f.dim("untouched"))),n.supersedes&&r.push(It("supersedes",f.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(It("blocked",f.red(`unpublished work on this page belongs to ${zu(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(It("ambiguous",f.yellow(`${n.alsoMatched.length} other page(s) match this ref: ${n.alsoMatched.map(a=>a.slug).join(", ")}`))),(n.similarTo?.length??0)>0){let a=(n.similarTo??[]).map(l=>{let u=t.findIndex(g=>g.key===l),p=u>=0?t[u]:void 0;return p?`#${u+1} "${p.pageTitle}"`:l});r.push(It("similar",f.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&Ar(n)&&r.push(...zw(n)),r.push("")}),r}function Fw(t){let e=u=>t.filter(u).length,r=t.reduce((u,p)=>u+p.entries.length,0),n=e(u=>u.withdraws),s=e(u=>u.blockedBy!=null),o=e(u=>u.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(Ar)} page(s)`,`${e(u=>u.action==="update_page"&&Ar(u))} appended`,`${e(u=>u.action==="new_page"&&Ar(u))} created (unpublished)`,...o>0?[f.red(`${o} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?f.red(`${n} page(s) WITHDRAWN from readers`):f.dim("no page withdrawn"),l=s>0?` \xB7 ${f.red(`${s} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function Hw(t,e){let r=new Map(e.map(s=>[s.key,s])),n=[];for(let s of t){let o=r.get(s.key),i=s.pageTitle||o?.pageTitle||s.key;if(s.skipped==="blocked_by_draft_owner"){n.push(`${f.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))];n.push(`${f.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(u=>`"${u}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(s.skipped){n.push(`${f.yellow("skipped")} ${i} \u2014 ${s.skipped.replace(/_/g," ")}`);continue}let a=s.created?f.green("created "):f.green("appended");n.push(`${a} ${i} \u2014 ${s.appliedEntryIds.length} finding(s) \u2192 page ${f.bold(s.documentId??"?")}`+(s.created?f.dim(" (unpublished)"):"")),s.confidence==="downgraded"?n.push(` ${f.red("withdrawn from readers:")} ${i}`):s.confidence==="already_withdrawn"?n.push(` ${f.dim("page was already unpublished \u2014 left as is")}`):s.confidence==="missing"&&n.push(` ${f.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Mu(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.")}G(t,"extensions:deploy","learnings push-kb")}async function Sn(t,e){let r;try{r=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(s){return s instanceof X&&s.status===404?L(f.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):L(f.yellow(`could not re-read the pushed markdown: ${Kw(s)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return L(f.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),r;let n=[`${r.filesScanned} file(s) scanned`];return r.docsIngested>0&&n.push(`${r.docsIngested} changed`),r.docsUnchanged>0&&n.push(`${r.docsUnchanged} unchanged`),n.push(`${r.entriesAdded} new finding(s)`),r.entriesDuplicate>0&&n.push(`${r.entriesDuplicate} already known`),r.parseSkipped>0&&n.push(f.yellow(`${r.parseSkipped} unparseable`)),L(f.dim(n.join(" \xB7 "))),r}function Kw(t){return t instanceof Error?t.message:String(t)}async function Bu(t,e=r=>new F(r)){t.section&&!kn.includes(t.section.trim())&&w(`unknown --section "${t.section}" \u2014 expected one of ${kn.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let r=await V(t.baseUrl),n=e(r),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 Sn(n,t.app),i;try{i=await J("reading the pending queue",()=>n.learningsPending(s))}catch(u){Mu(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(Bw(i.items,{diff:Uw(t)}).join(`
3521
- `)),y(Fw(i.items)),t.dryRun){L(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(Ar);if(a.length===0){L(f.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let l=a.reduce((u,p)=>u+p.entries.length,0);if(!t.yes){if(!qe()){L(f.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Me(`Push ${l} finding(s) into the knowledge base as ${a.length} page(s)?`,[{value:"yes",label:"Yes \u2014 push to the knowledge base",description:"pages land unpublished; corrections withdraw the pages listed above"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let u=await J("writing pages",()=>n.learningsPushKb(i.planToken,s));y(Hw(u.applied,i.items).join(`
3522
- `))}catch(u){if(u instanceof X&&u.status===409){L(f.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${vn} kb push\` to review the current plan.`),process.exitCode=2;return}Mu(u),L(f.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}Et();var Ir=t=>new F(t);async function Cr(t,e){let r=await V(t.baseUrl);return e(r)}async function Fs(t,e,r,n){return n.yes?!0:qe()?await Me(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function Vw(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function Fu(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function Gw(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)),r=[];for(let o of t.items)r.push(`${Fu(f.bold(o.slug),e)} ${Fu(Vw(o),10)} ${f.dim(o.path)}`);r.push("");let n=t.items.filter(o=>o.visibility==="published"&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function Hu(t,e=Ir){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&w(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Cr(t,e),s;try{s=await J("reading the knowledge base",()=>n.docsList(r))}catch(o){G(o,"docs:publish","read the knowledge base"),w(`could not read the knowledge base: ${o instanceof Error?o.message:String(o)}`)}y(Gw(s).join(`
3523
- `))}async function Ku(t,e,r=Ir){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&w("name at least one page slug. `turbobase kb list` shows them.");let s=await Cr(e,r);if(!await Fs(`Publish ${n.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await J("publishing",()=>s.docsPublish(n))}catch(l){G(l,"docs:publish","publish a page"),w(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);y(f.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(f.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Vu(t,e,r=Ir){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&w("name at least one page slug. `turbobase kb list` shows them.");let s=await Cr(e,r);if(!await Fs(`Hide ${n.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>s.docsUnpublish(n))}catch(l){G(l,"docs:publish","unpublish a page"),w(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);y(f.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(f.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Gu(t,e=Ir){let r=await Cr(t,e),n;try{n=await J("reading the releases",()=>r.docsVersions())}catch(s){G(s,"docs:publish","read the knowledge-base releases"),w(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(n.items.length===0){y("no releases yet \u2014 nothing has been published.");return}for(let s of n.items){let o=s.is_current?f.green("current"):f.dim(" ");y(`v${String(s.version_no).padEnd(4)} ${o} ${s.published_at} ${s.node_count} page(s)${s.published_by?` ${f.dim(s.published_by)}`:""}`),s.release_note&&y(` ${f.dim(s.release_note)}`)}}async function Wu(t,e,r=Ir){let n=Number(t);(!Number.isInteger(n)||n<1)&&w(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let s=await Cr(e,r);if(await Fs(`Roll the knowledge base back to release v${n}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await J("rolling back",()=>s.docsRollback(n));y(f.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){G(i,"docs:publish","roll the knowledge base back"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Ju(t,e,r=Ir){let n=(t??"").trim();n||w("name the page slug to delete. `turbobase kb list` shows them.");let s=await Cr(e,r);if(await Fs(`Delete "${n}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await J("deleting",()=>s.docsDelete(n));y(f.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){G(i,"docs:publish","delete a page"),w(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Et();function Ww(t){return t.diff??!!t.dryRun}function Jw(t,e){let r=[];return t.forEach((n,s)=>{let o=n.action==="new_rule"?f.green("new rule"):f.yellow("amend rule"),i=n.targetPublished?` ${f.yellow("[currently live]")}`:"";r.push(`${s+1}. ${o} ${f.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${f.dim(n.description)}`);for(let a of n.entries)r.push(` ${f.dim("\xB7")} ${f.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
3524
- `))r.push(` ${f.dim("|")} ${a}`)}r.push("")}),r}function Yw(t){let e=t.reduce((s,o)=>s+o.entries.length,0),r=t.filter(s=>s.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(f.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Yu(t,e=r=>new F(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let r=await V(t.baseUrl),n=e(r),s={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},o=await Sn(n,t.app),i;try{i=await J("reading the pending rules",()=>n.rulesPending(s))}catch(l){G(l,"extensions:deploy","read the pending rules"),w(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&o&&o.entriesDuplicate>0){L(`nothing pending \u2014 all ${o.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}L(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(y(Jw(i.items,{diff:Ww(t)}).join(`
3525
- `)),y(Yw(i.items)),t.dryRun){L(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!qe()){L(f.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Me(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await J("writing the rules",()=>n.rulesPush(i.planToken,s))}catch(l){l instanceof X&&l.status===409&&w("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),w(`push failed: ${l instanceof Error?l.message:String(l)}`)}y(f.green(`wrote ${i.items.length} draft rule(s).`)),L(f.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Et();var Zw=["proposed","active","rejected"],Qw=["mechanic","operator","learning","code-baseline"],Hs=t=>new F(t);async function Ks(t,e){let r=await V(t.baseUrl);return e(r)}function Zu(t,e,r){if(!t)return;let n=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);if(n.length!==0){for(let s of n)e.includes(s)||w(`${r}: unknown value '${s}' \u2014 expected one of ${e.join(", ")}.`);return n}}function Xw(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&w("--limit must be a positive number."),Math.floor(e)}function ep(t){let e=Zu(t.status,Zw,"--status"),r=Zu(t.provenance,Qw,"--provenance"),n=Xw(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function Qu(t){return!!(t.provenance?.length||t.recordType||t.source)}var tp=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function ev(t){return t.status==="active"?f.green("active"):t.status==="rejected"?f.dim("rejected"):f.yellow("proposed")}function tv(t){return t.message?t.message:t.kind&&t.field?f.dim(`${t.kind} ${t.field}`):t.kind?f.dim(t.kind):f.dim("(no description)")}function rp(t){return[t.hookId,ev(t),t.provenance==="learning"?f.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),tv(t)]}async function np(t={},e=Hs){let r=await Ks(t,e),n=ep(t),s;try{s=await r.proposals(n)}catch(i){G(i,"extensions:deploy","list hook proposals"),w(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return y(JSON.stringify(s,null,2));if(s.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return y(`no ${i} hook proposals.
3526
- `+f.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}y(pt(s.map(rp),{head:tp})),y(f.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let o=s.filter(i=>i.provenance==="learning"&&i.status==="proposed");o.length>0&&y(f.dim(` ${o.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function rv(t,e,r){return r.yes?!0:qe()?await Me(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function nv(t){return!(t instanceof X)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function aa(t,e){nv(t)&&G(t,"extensions:deploy",e)}function la(t,e){let r=e instanceof X?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,o=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(ve.error(`${f.bold(t)} \u2014 ${o}`))}async function Xu(t,e){try{let r=await t.proposalPromote(e);return y(ve.success(`${f.bold(e)} ${f.dim(`${r.previousStatus} \u2192`)} ${f.green(r.status)}`)),!0}catch(r){return aa(r,"promote a hook proposal"),la(e,r),!1}}async function sp(t,e={},r=Hs){!e.auto&&t.length===0&&w("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&w("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&w("promote: --apply / --all only mean something with --auto.");let n=await Ks(e,r);if(!e.auto){let p=0;for(let g of t)await Xu(n,g)&&(p+=1);p>0&&y(f.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let s=ep({...e,status:e.status??"proposed"});s.provenance?.includes("learning")&&w("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),s.status?.some(p=>p!=="proposed")&&w("promote --auto: only `--status proposed` rows can be armed in bulk.");let o;try{o=await n.proposals(s)}catch(p){G(p,"extensions:deploy","list hook proposals"),w(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=o.filter(p=>p.provenance==="learning"),a=o.filter(p=>p.provenance!=="learning");if(e.json&&(y(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(y(`nothing to promote${Qu(s)?" for that filter":""}.`),i.length>0&&y(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(y(e.apply?`promoting ${f.bold(String(a.length))} hook proposal(s):`:`${f.bold("dry run")} \u2014 would promote ${f.bold(String(a.length))} hook proposal(s):`),y(pt(a.map(rp),{head:tp})),i.length>0&&y(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){y(""),y(ve.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Qu(s)&&!e.all&&w(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await rv(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let u=0;for(let p of a)await Xu(n,p.hookId)&&(u+=1);y(f.dim(` ${u}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),u<a.length&&(process.exitCode=1)}async function op(t,e={},r=Hs){t.length===0&&w("retract: name at least one proposal id.");let n=await Ks(e,r),s=0;for(let o of t)try{let i=await n.proposalRetract(o);y(ve.success(`${f.bold(o)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.yellow(i.status)}`)),s+=1}catch(i){aa(i,"retract a hook proposal"),la(o,i)}s>0&&y(f.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),s<t.length&&(process.exitCode=1)}async function ip(t,e={},r=Hs){t.length===0&&w("reject: name at least one proposal id.");let n=await Ks(e,r),s=0;for(let o of t)try{let i=await n.proposalReject(o,e.reason);y(ve.success(`${f.bold(o)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.dim(i.status)}`)),s+=1}catch(i){aa(i,"reject a hook proposal"),la(o,i)}s<t.length&&(process.exitCode=1)}Et();var Or=t=>new F(t);async function Nr(t,e){let r=await V(t.baseUrl);return e(r)}async function Vs(t,e,r,n){return n.yes?!0:qe()?await Me(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function sv(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function ap(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function ov(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(o=>o.slug.length)),r=[];for(let o of t.items)r.push(`${ap(f.bold(o.slug),e)} ${ap(sv(o),10)} ${o.surfaces.join(",")||f.dim("none")}`),o.description&&r.push(` ${f.dim(o.description)}`);r.push("");let n=t.items.filter(o=>o.visibility==="published"&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function lp(t,e=Or){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&w(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Nr(t,e),s;try{s=await J("reading the skills",()=>n.skillsList(r))}catch(o){G(o,"skills:publish","read the instance skills"),w(`could not read the skills: ${o instanceof Error?o.message:String(o)}`)}y(ov(s).join(`
3527
- `))}async function cp(t,e,r=Or){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let s=await Nr(e,r);if(!await Vs(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await J("publishing",()=>s.skillsPublish(n))}catch(a){G(a,"skills:publish","publish a skill"),w(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(f.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function dp(t,e,r=Or){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&w("name at least one skill slug. `turbobase skills list` shows them.");let s=await Nr(e,r);if(!await Vs(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>s.skillsUnpublish(n))}catch(a){G(a,"skills:publish","unpublish a skill"),w(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(f.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function up(t,e,r=Or){let n=Number(t);(!Number.isInteger(n)||n<1)&&w(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let s=await Nr(e,r);if(await Vs(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>s.skillsRollback(n));y(f.green(`rolled back to v${i.version.version_no}.`))}catch(i){G(i,"skills:publish","roll back a skills release"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function pp(t,e=Or){let r=await Nr(t,e),n;try{n=await J("reading the releases",()=>r.skillsReleases())}catch(s){G(s,"skills:publish","read the skills releases"),w(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(n.items.length===0){L("no releases yet.");return}for(let s of n.items){let o=s.is_current?f.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";y(`${o} v${s.version_no} ${s.skill_count} skill(s) ${f.dim(s.published_at)}${s.published_by?f.dim(` by ${s.published_by}`):""}${f.dim(i)}`)}}async function hp(t,e,r=Or){let n=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];n.length===0&&w("name at least one skill to delete. `turbobase skills list` shows the slugs.");let s=await Nr(e,r);if(!await Vs(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
3528
- ${n.join(`
3529
- `)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",e))return;let i=[],a=[];for(let u of n)try{i.push(await J(`deleting ${u}`,()=>s.skillsDelete(u)))}catch(p){if(p instanceof X&&p.status===404){a.push(u);continue}i.length>0&&L(f.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),G(p,"skills:publish","delete a skill"),w(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(f.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(f.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(f.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as fp}from"node:fs";import{join as iv,relative as av,resolve as lv,sep as cv}from"node:path";var dv=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),uv=new Set([".mcp.json",".env"]);function pv(t){return uv.has(t)||t.startsWith(".env.")&&t!==".env.example"}function hv(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function fv(t){return t.includes(0)}async function mp(t){let e=lv(t),r={},n=[],s=[],o=[];async function i(a){let l=await fp.readdir(a,{withFileTypes:!0});for(let u of l){let p=iv(a,u.name);if(dv.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=av(e,p).split(cv).join("/");if(pv(u.name)){s.push(g);continue}let $=await fp.readFile(p);if(!hv($)){n.push(g);continue}fv($)&&o.push(g),r[g]=$.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:s,unstorable:o}}import{randomBytes as mv}from"node:crypto";var gv="/_tb/app-assets",bv=16,yv=/^[0-9a-f]{32}$/;function gp(){return mv(bv).toString("hex")}function wv(t){return yv.test(t)}function bp(t){if(!wv(t))throw new Error(`not a build id: ${t}`);return`${gv}/${t}/`}var yp=7;import Gs from"node:fs/promises";import _n from"node:path";var ca={esbuild:"0.28.1","isolated-vm":"6.1.2"},da="@turbobase/isolated-vm-prebuilds";function ua(t,e){return`${t}-${e}`}function pa(t=process.versions){return`abi${t.modules}`}var wp=["darwin-x64","win32-arm64"];async function vp(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=ua(e,r),s=_n.join(t.home,"node_modules"),o=_n.join(s,...da.split("/"),"prebuilds",n),i=_n.join(s,"isolated-vm","prebuilds",n),a;try{a=await Gs.readdir(o)}catch{return[]}let l=[];await Gs.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=_n.join(i,u);try{await Gs.copyFile(_n.join(o,u),p,Gs.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as vv}from"node:os";import{join as kp}from"node:path";import{promises as ha}from"node:fs";function _p(){let t=process.env.TURBOBASE_HOME??kp(vv(),".turbobase");return{dir:t,file:kp(t,"sandboxes.json")}}var kv={s:1e3,m:6e4,h:36e5,d:864e5};function Sv(t){let e=/^\s*(\d+)\s*([smhd])\s*$/.exec(t);if(!e)throw new Error(`invalid --ttl '${t}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${t}': duration must be a positive integer.`);return r*kv[e[2]]}function _v(t,e=Date.now()){return new Date(e+Sv(t)).toISOString()}function $v(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function xv(t){let e=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(t);if(!e)throw new Error(`invalid --sample '${t}': expected a percent like 2% (or a bare number).`);let r=Number(e[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${t}': percent must be between 0 and 100.`);return r/100}function Tv(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let s=0;s<t.length;s+=r)n.push(t[s]);return n}var Rv="[REDACTED]",$n=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},fa=class extends Error{table;column;constructor(e,r,n){super(`Refusing to copy ${e}.${r} into a sandbox: ${n}. A sandbox must never hold un-redacted PII \u2014 classify the column 'safe' (non-PII) or let redaction mask it, then retry.`),this.name="UnredactedPiiError",this.table=e,this.column=r}};function Ev(t,e,r){let n={};for(let[s,o]of Object.entries(e)){let i=r[s];if(i===void 0)throw new fa(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?n[s]=o==null?o:Rv:n[s]=o}return n}function Pv(t,e,r){return e.map(n=>Ev(t,n,r))}var Sp=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Av=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function Iv(t){let e=t.trim();try{let s=new URL(e);if(s.hostname)return s.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function ma(t){if(!t||!t.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let e=t.toLowerCase();for(let n of Av)if(e.includes(n))throw new Error(`local-only guard: target '${t}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=Iv(t);if(!Sp.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Sp].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function Cv(t,e=Ov){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Ov(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Nv(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Lv(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function ga(){let{file:t}=_p();try{let e=await ha.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function $p(t){let{dir:e,file:r}=_p();await ha.mkdir(e,{recursive:!0}),await ha.writeFile(r,`${JSON.stringify(t,null,2)}
3530
- `,{mode:384})}async function jv(t){let e=await ga();e.push(t),await $p(e)}async function xp(t){let e=await ga(),r=e.findIndex(s=>s.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await $p(e),n??null}async function Ws(){return ga()}function ba(t,e=Date.now()){let r=[],n=[];for(let s of t)$v(s.expiresAt,e)?n.push(s):r.push(s);return{active:r,expired:n}}async function Tp(t,e){ma(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new $n(r);let n=xv(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Cv(u)))(e.fromTenant),i=Nv(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=Tv(u.rows,n),g=Pv(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:_v(e.ttl,s),sampleFraction:n,url:Lv(o,e.baseUrl)};return await jv(l),l}async function Rp(t,e){ma(t.target());let n=(await Ws()).find(s=>s.name===e);return n?(await t.dropDatabase(n.database),await xp(e),n):null}async function ya(t,e=Date.now()){ma(t.target());let r=await Ws(),{expired:n}=ba(r,e),s=[];for(let o of n){try{await t.dropDatabase(o.database)}catch{continue}await xp(o.name),s.push(o)}return s}var xn={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"}},tI=Object.keys(xn).filter(t=>xn[t].mintable);var sI=xn.pat.prefix,Uv=Object.entries(xn).map(([t,e])=>[e.prefix,t]),Dv=/^[A-Za-z0-9_-]{20,}$/;function qv(t){if(typeof t!="string")return null;for(let[e,r]of Uv)if(t.startsWith(e)&&Dv.test(t.slice(e.length)))return r;return null}function Ep(t){return qv(t)==="pat"}hn();var Mv=8e3,zv={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 Bv(t){return zv[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Fv(t,e,r=fetch){let n;try{n=await r(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(Mv)})}catch(o){return{state:"unreachable",detail:o instanceof Error?o.message:String(o)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let o=await n.json().catch(()=>null);return{state:"rejected",reason:typeof o?.reason=="string"&&o.reason?o.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Pp(t){return t.state==="accepted"?Ee()?f.green("accepted"):"accepted":t.state==="rejected"?Ee()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ee()?f.yellow("unreachable"):"unreachable"}async function Ap(t={},e=fetch){let r=await Rt(),{file:n}=Ts();if(r.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${n}.`));return}let s=await ut(),o=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!s&&i.baseUrl===s.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Fv(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?f.green("*"):" ",f.bold(i.baseUrl),Pp(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${Pp(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${n}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${Bv(i.check.reason)}.`)),L(f.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function a0(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`."),qe()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Me(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{w("cancelled.")}}async function l0(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(s){return{ok:!1,kind:"unreachable",detail:s instanceof Error?s.message:String(s)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function c0(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 d0(t,e,r){let n=await Fd({baseUrl:t,token:e}),s=(await Rt()).length-1;if(y(`signed in to ${n.baseUrl} \u2014 now the active instance`+(s>0?` (${s} other${s===1?"":"s"} stored; commands default here).`:".")),c0(n.baseUrl),!r)return;let o=await l0(n.baseUrl,e);o.ok||(o.kind==="wrong-host"?(L(`warning: ${n.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: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${o.detail}). Stored anyway.`))}async function u0(t){let e=await bn(t),r=ra(e);if(!r){let n=/\bdefineConduit\s*[<(]/.test(e);w(n?`could not parse id/on/from.source/from.recordType from ${t} \u2014 is it a defineConduit({...}) file?`:`could not parse id/recordType/event from ${t} \u2014 is it a defineHook({...}) file?`)}return{...r,sourceCode:e}}async function ln(t,e,r,n){try{return await se.access(t),"skipped"}catch{}return await se.mkdir(an(t),{recursive:!0}),await se.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await se.chmod(t,n),"wrote"}async function Cb(t,e){if(Ob(t)!==".gitignore")return ln(t,e.content,e.executable,e.mode);let r=await se.readFile(t,"utf8").catch(()=>null);if(r===null)return ln(t,e.content,e.executable,e.mode);let n=$u(r);return n===null?"skipped":(await se.writeFile(t,n,"utf8"),"merged")}function md(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function wi(t){process.exit(t)}function p0(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",s=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:s,type:n}})}}function h0(t,e){let r=e.warnings.length===0?[{name:`${t} (${e.kind})`,status:"passed"}]:e.warnings.map(n=>({name:`${t}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${t}`,cases:r}}function f0(t){let e=[];if(t.error)return e.push({name:`replay ${t.fixtureName}`,status:"failed",type:"error",detail:t.error}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e};for(let r of t.guards)e.push(r.status==="failed"?{name:`guard: ${r.name}`,status:"failed",type:r.name,detail:r.detail}:{name:`guard: ${r.name}`,status:"passed",detail:r.status==="skipped-offline"?`skipped-offline: ${r.detail}`:void 0});return t.whenPassed&&t.applyBranch&&e.push({name:`apply-branch: ${t.applyBranch}`,status:"passed",detail:`${t.masterAction??""} (${t.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${t.fixtureName}`,cases:e}}function kd({includeInternal:t=!0}={}){let e=new i0;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.6.5").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Yi()}
3531
- `),e.hook("preAction",(d,h)=>{ju(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),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.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=Xe(d.baseUrl);d.token||w(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
3532
- ${vn} auth login --base-url ${h} --token tb_pat_\u2026`),Ep(d.token)||w("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await d0(h,d.token,d.verify)}),r.command("status").description("Show every stored sign-in, where its token was read from, and whether the instance still accepts it.").option("--no-probe","List the stored sign-ins without asking each instance about its token.").action(async d=>Ap({probe:d.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async d=>{let h=d??await a0("Pick the active instance:"),b=await Rs(h);if(!b){let x=await Rt();w(`no stored sign-in for ${Xe(h)}.`+(x.length?` Stored: ${x.map(k=>k.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${Xe(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${b.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let x=await Rt();for(let k of x)await qi(k.baseUrl);y(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let h=await qi(d.baseUrl);h||w(d.baseUrl?`no stored sign-in for ${Xe(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}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:h,token:b}=await V(d.baseUrl),x;try{x=await ir({baseUrl:h,token:b,recordsOnly:d.recordsOnly})}catch(m){let _=m instanceof Error?m.message:String(m);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 ir({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 k=le(process.cwd(),d.out);await se.writeFile(k,x,"utf8"),y(`wrote ${k} (${x.split(`
3533
- `).length} lines).`)}),qu(n),n.command("grounding").description("Write the instance's grounding brief (source primer + record anatomy + KB retrieval) to a file for agent sessions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--records <list>","Comma-separated record types to focus, e.g. purchaseOrder,itemReceipt.").option("--query <text>","Retrieval question for the knowledge base (e.g. what the app is about).").option("-o, --out <file>","Output file","INSTANCE.md").action(async d=>{let{baseUrl:h,token:b}=await V(d.baseUrl),x=new URLSearchParams;d.records&&x.set("records",d.records),d.query&&x.set("query",d.query);let k=x.toString(),m=await fetch(`${h}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});m.ok||w(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${m.status}`);let R=((await m.json()).markdown??"").trim(),A=le(process.cwd(),d.out),I=d.records?` records=${d.records}`:"",C=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${I} \u2014 do not edit; re-run to refresh. -->
3517
+ `,carried:o}}function Bu(t){t.command("adopt").description("Write the instance's app-developer adopt notes (what changed that this project must act on) to a file.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--since <version>","Only notes newer than this version. Defaults to the version recorded in ADOPT.md; omit both to get everything.").option("-o, --out <file>","Output file","ADOPT.md").action(async e=>{let{baseUrl:n,token:r}=await V(e.baseUrl),s=Aw(process.cwd(),e.out),o=e.since?.trim()||await Cw(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 g=u.currentVersion??u.releases[0]?.version??"",$=`<!-- GENERATED by \`turbobase project adopt\` against ${n} \u2014 adopted-through=${g}. Re-run to refresh; delete this file once every line is done. -->
3518
+
3519
+ `,v=await oa.readFile(s,"utf8").catch(()=>null),S=u.markdown,T=0;if(v!==null&&v.trim()!==""){let E=jw(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>\`.`),S=E.markdown,T=E.carried}await oa.writeFile(s,$+S,"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 kr=["suggested_kb_edit","kb_correction"];var Dw=[{heading:"Suggested KB edits",section:"suggested_kb_edit",ranked:!1},{heading:"Knowledge-base corrections",section:"kb_correction",ranked:!1},{heading:"What would have helped most, in order",section:"platform_feedback",ranked:!0},{heading:"Platform asks",section:"platform_feedback",ranked:!1},{heading:"Requested rollups",section:"platform_feedback",ranked:!1},{heading:"Agent rules",section:"agent_rule",ranked:!1}];function Uw(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var vA=new Map(Dw.map(t=>[Uw(t.heading),t]));var kA=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 Mw(t){return t.diff??!!t.dryRun}var zw={update_page:"append to the existing page",new_page:"create a NEW page"},It=(t,e)=>` ${f.dim(t.padEnd(11))}${e}`,Hu=t=>t.ownerEmail??t.ownerId;function In(t){return!t.needsPageRef&&!t.blockedBy}var Bs=t=>f.green(t?` + ${t}`:" +"),qw=t=>f.red(t?` - ${t}`:" -"),cn=t=>f.dim(` ${t}`),Bw=` ${f.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,ia=80;function Fw(t){let e=[Bw];t.target?(e.push(cn(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(qw(`visibility: ${t.target.visibility}`)),e.push(Bs("visibility: admin"))):e.push(cn(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(cn("title, slug, evidence: untouched")),e.push(cn("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(cn("turbobase.document \xB7 new")),e.push(Bs(`title: ${t.pageTitle}`)),e.push(Bs("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(cn('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(cn('appended under "## From app developers":'));let n=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
3520
+ `);for(let r of n.slice(0,ia))e.push(Bs(r?` ${r}`:""));return n.length>ia&&e.push(f.yellow(` \u2026 ${n.length-ia} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function Hw(t,e={}){let n=[];return t.forEach((r,s)=>{let{target:o,entries:i}=r;if(n.push(`${String(s+1).padStart(2)}. ${f.bold(r.pageTitle)}`),n.push(It("page",o?`${o.title} (${o.slug}) [${o.visibility}]`:f.dim("new \u2014 no existing page matches"))),n.push(It("action",In(r)?zw[r.action]:f.red("SKIP \u2014 nothing is written"))),r.needsPageRef){let a=[...new Set(i.map(l=>l.kb_page_ref?.trim()).filter(l=>!!l))];n.push(It("unresolved",f.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(n.push(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?` ${f.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${f.dim(`(${a.kb_page_ref})`)}`:"";n.push(` ${f.dim("\xB7")} ${a.title.trim()}${u}${l}`)}),n.push(It("confidence",r.withdraws?f.red("WITHDRAWN from readers (text untouched)"):f.dim("untouched"))),r.supersedes&&n.push(It("supersedes",f.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),r.blockedBy&&n.push(It("blocked",f.red(`unpublished work on this page belongs to ${Hu(r.blockedBy)} \u2014 this page will be SKIPPED`))),r.alsoMatched.length>0&&n.push(It("ambiguous",f.yellow(`${r.alsoMatched.length} other page(s) match this ref: ${r.alsoMatched.map(a=>a.slug).join(", ")}`))),(r.similarTo?.length??0)>0){let a=(r.similarTo??[]).map(l=>{let u=t.findIndex(g=>g.key===l),p=u>=0?t[u]:void 0;return p?`#${u+1} "${p.pageTitle}"`:l});n.push(It("similar",f.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&In(r)&&n.push(...Fw(r)),n.push("")}),n}function Kw(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(In)} page(s)`,`${e(u=>u.action==="update_page"&&In(u))} appended`,`${e(u=>u.action==="new_page"&&In(u))} created (unpublished)`,...o>0?[f.red(`${o} SKIPPED \u2014 correction with no page to correct`)]:[]],a=r>0?f.red(`${r} page(s) WITHDRAWN from readers`):f.dim("no page withdrawn"),l=s>0?` \xB7 ${f.red(`${s} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function Vw(t,e){let n=new Map(e.map(s=>[s.key,s])),r=[];for(let s of t){let o=n.get(s.key),i=s.pageTitle||o?.pageTitle||s.key;if(s.skipped==="blocked_by_draft_owner"){r.push(`${f.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${s.blockedBy?Hu(s.blockedBy):"another editor"}; its findings stay pending`);continue}if(s.skipped==="unresolved_page_ref"){let l=[...new Set((o?.entries??[]).map(u=>u.kb_page_ref?.trim()).filter(u=>!!u))];r.push(`${f.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(u=>`"${u}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(s.skipped){r.push(`${f.yellow("skipped")} ${i} \u2014 ${s.skipped.replace(/_/g," ")}`);continue}let a=s.created?f.green("created "):f.green("appended");r.push(`${a} ${i} \u2014 ${s.appliedEntryIds.length} finding(s) \u2192 page ${f.bold(s.documentId??"?")}`+(s.created?f.dim(" (unpublished)"):"")),s.confidence==="downgraded"?r.push(` ${f.red("withdrawn from readers:")} ${i}`):s.confidence==="already_withdrawn"?r.push(` ${f.dim("page was already unpublished \u2014 left as is")}`):s.confidence==="missing"&&r.push(` ${f.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return r}function Fu(t){if(t instanceof Q){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.")}G(t,"extensions:deploy","learnings push-kb")}async function Sr(t,e){let n;try{n=await J("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(s){return s instanceof Q&&s.status===404?L(f.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):L(f.yellow(`could not re-read the pushed markdown: ${Gw(s)} \u2014 planning anyway.`)),null}if(n.filesScanned===0)return L(f.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),n;let r=[`${n.filesScanned} file(s) scanned`];return n.docsIngested>0&&r.push(`${n.docsIngested} changed`),n.docsUnchanged>0&&r.push(`${n.docsUnchanged} unchanged`),r.push(`${n.entriesAdded} new finding(s)`),n.entriesDuplicate>0&&r.push(`${n.entriesDuplicate} already known`),n.parseSkipped>0&&r.push(f.yellow(`${n.parseSkipped} unparseable`)),L(f.dim(r.join(" \xB7 "))),n}function Gw(t){return t instanceof Error?t.message:String(t)}async function Ku(t,e=n=>new F(n)){t.section&&!kr.includes(t.section.trim())&&w(`unknown --section "${t.section}" \u2014 expected one of ${kr.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let n=await V(t.baseUrl),r=e(n),s={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},o=await Sr(r,t.app),i;try{i=await J("reading the pending queue",()=>r.learningsPending(s))}catch(u){Fu(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(Hw(i.items,{diff:Mw(t)}).join(`
3521
+ `)),y(Kw(i.items)),t.dryRun){L(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(In);if(a.length===0){L(f.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let l=a.reduce((u,p)=>u+p.entries.length,0);if(!t.yes){if(!Me()){L(f.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await ze(`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(Vw(u.applied,i.items).join(`
3522
+ `))}catch(u){if(u instanceof Q&&u.status===409){L(f.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${vr} kb push\` to review the current plan.`),process.exitCode=2;return}Fu(u),L(f.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}Et();var Cn=t=>new F(t);async function On(t,e){let n=await V(t.baseUrl);return e(n)}async function Fs(t,e,n,r){return r.yes?!0:Me()?await ze(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function Ww(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function Vu(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function Jw(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(`${Vu(f.bold(o.slug),e)} ${Vu(Ww(o),10)} ${f.dim(o.path)}`);n.push("");let r=t.items.filter(o=>o.visibility==="published"&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return n.push(`${t.items.length} page(s) \xB7 ${r} readable \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),n}async function Gu(t,e=Cn){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 On(t,e),s;try{s=await J("reading the knowledge base",()=>r.docsList(n))}catch(o){G(o,"docs:publish","read the knowledge base"),w(`could not read the knowledge base: ${o instanceof Error?o.message:String(o)}`)}y(Jw(s).join(`
3523
+ `))}async function Wu(t,e,n=Cn){let r=[...new Set(t.map(l=>l.trim()).filter(Boolean))];r.length===0&&w("name at least one page slug. `turbobase kb list` shows them.");let s=await On(e,n);if(!await Fs(`Publish ${r.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",e))return;let i;try{i=await J("publishing",()=>s.docsPublish(r))}catch(l){G(l,"docs:publish","publish a page"),w(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);y(f.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(f.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Ju(t,e,n=Cn){let r=[...new Set(t.map(l=>l.trim()).filter(Boolean))];r.length===0&&w("name at least one page slug. `turbobase kb list` shows them.");let s=await On(e,n);if(!await Fs(`Hide ${r.length} page(s) from readers?`,"Yes \u2014 unpublish them","they drop out of the reader snapshot immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>s.docsUnpublish(r))}catch(l){G(l,"docs:publish","unpublish a page"),w(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);y(f.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(f.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(f.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function Yu(t,e=Cn){let n=await On(t,e),r;try{r=await J("reading the releases",()=>n.docsVersions())}catch(s){G(s,"docs:publish","read the knowledge-base releases"),w(`could not read the releases: ${s instanceof Error?s.message:String(s)}`)}if(r.items.length===0){y("no releases yet \u2014 nothing has been published.");return}for(let s of r.items){let o=s.is_current?f.green("current"):f.dim(" ");y(`v${String(s.version_no).padEnd(4)} ${o} ${s.published_at} ${s.node_count} page(s)${s.published_by?` ${f.dim(s.published_by)}`:""}`),s.release_note&&y(` ${f.dim(s.release_note)}`)}}async function Zu(t,e,n=Cn){let r=Number(t);(!Number.isInteger(r)||r<1)&&w(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let s=await On(e,n);if(await Fs(`Roll the knowledge base back to release v${r}?`,"Yes \u2014 roll it back","every reader sees that release\u2019s content until something is published again",e))try{let i=await J("rolling back",()=>s.docsRollback(r));y(f.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){G(i,"docs:publish","roll the knowledge base back"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Xu(t,e,n=Cn){let r=(t??"").trim();r||w("name the page slug to delete. `turbobase kb list` shows them.");let s=await On(e,n);if(await Fs(`Delete "${r}"?`,"Yes \u2014 delete it","it drops out of the tree and every reader release; its subtree goes with it, and it stays restorable from the editor\u2019s trash",e))try{let i=await J("deleting",()=>s.docsDelete(r));y(f.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){G(i,"docs:publish","delete a page"),w(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}Et();function Yw(t){return t.diff??!!t.dryRun}function Zw(t,e){let n=[];return t.forEach((r,s)=>{let o=r.action==="new_rule"?f.green("new rule"):f.yellow("amend rule"),i=r.targetPublished?` ${f.yellow("[currently live]")}`:"";n.push(`${s+1}. ${o} ${f.bold(r.slug)}${i}`),n.push(` ${r.name}`),r.description&&n.push(` ${f.dim(r.description)}`);for(let a of r.entries)n.push(` ${f.dim("\xB7")} ${f.dim(a.app_slug)} ${a.title}`);if(e.diff){n.push("");for(let a of r.bodyMarkdown.split(`
3524
+ `))n.push(` ${f.dim("|")} ${a}`)}n.push("")}),n}function Xw(t){let e=t.reduce((s,o)=>s+o.entries.length,0),n=t.filter(s=>s.targetPublished).length,r=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return n>0&&r.push(f.yellow(`${n} amend a rule that is currently live`)),r.join(" \xB7 ")}async function Qu(t,e=n=>new F(n)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&w("--limit must be a positive integer.");let n=await V(t.baseUrl),r=e(n),s={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},o=await Sr(r,t.app),i;try{i=await J("reading the pending rules",()=>r.rulesPending(s))}catch(l){G(l,"extensions:deploy","read the pending rules"),w(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&o&&o.entriesDuplicate>0){L(`nothing pending \u2014 all ${o.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}L(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(y(Zw(i.items,{diff:Yw(t)}).join(`
3525
+ `)),y(Xw(i.items)),t.dryRun){L(f.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!Me()){L(f.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await ze(`Push ${a} finding(s) as ${i.items.length} draft rule(s)?`,[{value:"yes",label:"Yes \u2014 write them as draft rules",description:"they land as DRAFTS; an admin publishes them before anything is injected"},{value:"no",label:"No \u2014 leave the queue untouched"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await J("writing the rules",()=>r.rulesPush(i.planToken,s))}catch(l){l instanceof Q&&l.status===409&&w("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),w(`push failed: ${l instanceof Error?l.message:String(l)}`)}y(f.green(`wrote ${i.items.length} draft rule(s).`)),L(f.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}Et();var Qw=["proposed","active","rejected"],ev=["mechanic","operator","learning","code-baseline"],Hs=t=>new F(t);async function Ks(t,e){let n=await V(t.baseUrl);return e(n)}function ep(t,e,n){if(!t)return;let r=t.split(",").map(s=>s.trim()).filter(s=>s.length>0);if(r.length!==0){for(let s of r)e.includes(s)||w(`${n}: unknown value '${s}' \u2014 expected one of ${e.join(", ")}.`);return r}}function tv(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&w("--limit must be a positive number."),Math.floor(e)}function rp(t){let e=ep(t.status,Qw,"--status"),n=ep(t.provenance,ev,"--provenance"),r=tv(t.limit);return{...e?{status:e}:{},...n?{provenance:n}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...r?{limit:r}:{}}}function tp(t){return!!(t.provenance?.length||t.recordType||t.source)}var sp=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function nv(t){return t.status==="active"?f.green("active"):t.status==="rejected"?f.dim("rejected"):f.yellow("proposed")}function rv(t){return t.message?t.message:t.kind&&t.field?f.dim(`${t.kind} ${t.field}`):t.kind?f.dim(t.kind):f.dim("(no description)")}function op(t){return[t.hookId,nv(t),t.provenance==="learning"?f.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),rv(t)]}async function ip(t={},e=Hs){let n=await Ks(t,e),r=rp(t),s;try{s=await n.proposals(r)}catch(i){G(i,"extensions:deploy","list hook proposals"),w(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return y(JSON.stringify(s,null,2));if(s.length===0){let i=r.status?.length?r.status.join("/"):"proposed";return y(`no ${i} hook proposals.
3526
+ `+f.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}y(pt(s.map(op),{head:sp})),y(f.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let o=s.filter(i=>i.provenance==="learning"&&i.status==="proposed");o.length>0&&y(f.dim(` ${o.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function sv(t,e,n){return n.yes?!0:Me()?await ze(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function ov(t){return!(t instanceof Q)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function aa(t,e){ov(t)&&G(t,"extensions:deploy",e)}function la(t,e){let n=e instanceof Q?e.body:void 0,r=n?.error==="forbidden"?n.reason??n.error:n?.error,o=r?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[r]??r:e instanceof Error?e.message:String(e);L(ve.error(`${f.bold(t)} \u2014 ${o}`))}async function np(t,e){try{let n=await t.proposalPromote(e);return y(ve.success(`${f.bold(e)} ${f.dim(`${n.previousStatus} \u2192`)} ${f.green(n.status)}`)),!0}catch(n){return aa(n,"promote a hook proposal"),la(e,n),!1}}async function ap(t,e={},n=Hs){!e.auto&&t.length===0&&w("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&w("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&w("promote: --apply / --all only mean something with --auto.");let r=await Ks(e,n);if(!e.auto){let p=0;for(let g of t)await np(r,g)&&(p+=1);p>0&&y(f.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let s=rp({...e,status:e.status??"proposed"});s.provenance?.includes("learning")&&w("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),s.status?.some(p=>p!=="proposed")&&w("promote --auto: only `--status proposed` rows can be armed in bulk.");let o;try{o=await r.proposals(s)}catch(p){G(p,"extensions:deploy","list hook proposals"),w(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=o.filter(p=>p.provenance==="learning"),a=o.filter(p=>p.provenance!=="learning");if(e.json&&(y(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(y(`nothing to promote${tp(s)?" for that filter":""}.`),i.length>0&&y(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(y(e.apply?`promoting ${f.bold(String(a.length))} hook proposal(s):`:`${f.bold("dry run")} \u2014 would promote ${f.bold(String(a.length))} hook proposal(s):`),y(pt(a.map(op),{head:sp})),i.length>0&&y(f.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){y(""),y(ve.info("nothing was changed. Re-run with --apply to arm these."));return}if(!tp(s)&&!e.all&&w(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await sv(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,e))return;let u=0;for(let p of a)await np(r,p.hookId)&&(u+=1);y(f.dim(` ${u}/${a.length} armed \u2014 the loader compiles them on its next reload. Undo one with \`turbobase ext proposals retract <id>\`.`)),u<a.length&&(process.exitCode=1)}async function lp(t,e={},n=Hs){t.length===0&&w("retract: name at least one proposal id.");let r=await Ks(e,n),s=0;for(let o of t)try{let i=await r.proposalRetract(o);y(ve.success(`${f.bold(o)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.yellow(i.status)}`)),s+=1}catch(i){aa(i,"retract a hook proposal"),la(o,i)}s>0&&y(f.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),s<t.length&&(process.exitCode=1)}async function cp(t,e={},n=Hs){t.length===0&&w("reject: name at least one proposal id.");let r=await Ks(e,n),s=0;for(let o of t)try{let i=await r.proposalReject(o,e.reason);y(ve.success(`${f.bold(o)} ${f.dim(`${i.previousStatus} \u2192`)} ${f.dim(i.status)}`)),s+=1}catch(i){aa(i,"reject a hook proposal"),la(o,i)}s<t.length&&(process.exitCode=1)}Et();var Nn=t=>new F(t);async function Ln(t,e){let n=await V(t.baseUrl);return e(n)}async function Vs(t,e,n,r){return r.yes?!0:Me()?await ze(t,[{value:"yes",label:e,description:n},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(L("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(L(f.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function iv(t){return t.visibility!=="published"?f.dim("draft"):t.in_current_release?f.green("live"):f.yellow("unreleased")}function dp(t,e){let n=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-n))}function av(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(o=>o.slug.length)),n=[];for(let o of t.items)n.push(`${dp(f.bold(o.slug),e)} ${dp(iv(o),10)} ${o.surfaces.join(",")||f.dim("none")}`),o.description&&n.push(` ${f.dim(o.description)}`);n.push("");let r=t.items.filter(o=>o.visibility==="published"&&o.in_current_release).length,s=t.items.filter(o=>o.visibility!=="published").length;return n.push(`${t.items.length} skill(s) \xB7 ${r} injected \xB7 ${s} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),n}async function up(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 skills",()=>r.skillsList(n))}catch(o){G(o,"skills:publish","read the instance skills"),w(`could not read the skills: ${o instanceof Error?o.message:String(o)}`)}y(av(s).join(`
3527
+ `))}async function pp(t,e,n=Nn){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 Ln(e,n);if(!await Vs(`Publish ${r.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",e))return;let i;try{i=await J("publishing",()=>s.skillsPublish(r))}catch(a){G(a,"skills:publish","publish a skill"),w(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(f.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function hp(t,e,n=Nn){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 Ln(e,n);if(!await Vs(`Move ${r.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",e))return;let i;try{i=await J("unpublishing",()=>s.skillsUnpublish(r))}catch(a){G(a,"skills:publish","unpublish a skill"),w(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(f.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(f.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(f.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function fp(t,e,n=Nn){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 Ln(e,n);if(await Vs(`Roll the skills back to release v${r}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",e))try{let i=await J("rolling back",()=>s.skillsRollback(r));y(f.green(`rolled back to v${i.version.version_no}.`))}catch(i){G(i,"skills:publish","roll back a skills release"),w(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function mp(t,e=Nn){let n=await Ln(t,e),r;try{r=await J("reading the releases",()=>n.skillsReleases())}catch(s){G(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?f.green("*"):" ",i=s.release_note?` \u2014 ${s.release_note}`:"";y(`${o} v${s.version_no} ${s.skill_count} skill(s) ${f.dim(s.published_at)}${s.published_by?f.dim(` by ${s.published_by}`):""}${f.dim(i)}`)}}async function gp(t,e,n=Nn){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 Ln(e,n);if(!await Vs(r.length===1?`Delete the skill '${r[0]}'?`:`Delete ${r.length} skills?
3528
+ ${r.join(`
3529
+ `)}`,"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 Q&&p.status===404){a.push(u);continue}i.length>0&&L(f.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),G(p,"skills:publish","delete a skill"),w(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(f.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(f.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(f.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as bp}from"node:fs";import{join as lv,relative as cv,resolve as dv,sep as uv}from"node:path";var pv=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),hv=new Set([".mcp.json",".env"]);function fv(t){return hv.has(t)||t.startsWith(".env.")&&t!==".env.example"}function mv(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function gv(t){return t.includes(0)}async function yp(t){let e=dv(t),n={},r=[],s=[],o=[];async function i(a){let l=await bp.readdir(a,{withFileTypes:!0});for(let u of l){let p=lv(a,u.name);if(pv.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=cv(e,p).split(uv).join("/");if(fv(u.name)){s.push(g);continue}let $=await bp.readFile(p);if(!mv($)){r.push(g);continue}gv($)&&o.push(g),n[g]=$.toString("utf8")}}return await i(e),{files:n,skipped:r,secrets:s,unstorable:o}}import{randomBytes as bv}from"node:crypto";var yv="/_tb/app-assets",wv=16,vv=/^[0-9a-f]{32}$/;function wp(){return bv(wv).toString("hex")}function kv(t){return vv.test(t)}function vp(t){if(!kv(t))throw new Error(`not a build id: ${t}`);return`${yv}/${t}/`}var kp=7;da();var ua=50*1024*1024;import Gs from"node:fs/promises";import _r from"node:path";var pa={esbuild:"0.28.1","isolated-vm":"6.1.2"},ha="@turbobase/isolated-vm-prebuilds";function fa(t,e){return`${t}-${e}`}function ma(t=process.versions){return`abi${t.modules}`}var Sp=["darwin-x64","win32-arm64"];async function _p(t){let e=t.platform??process.platform,n=t.arch??process.arch,r=fa(e,n),s=_r.join(t.home,"node_modules"),o=_r.join(s,...ha.split("/"),"prebuilds",r),i=_r.join(s,"isolated-vm","prebuilds",r),a;try{a=await Gs.readdir(o)}catch{return[]}let l=[];await Gs.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=_r.join(i,u);try{await Gs.copyFile(_r.join(o,u),p,Gs.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as Sv}from"node:os";import{join as $p}from"node:path";import{promises as ga}from"node:fs";function Tp(){let t=process.env.TURBOBASE_HOME??$p(Sv(),".turbobase");return{dir:t,file:$p(t,"sandboxes.json")}}var _v={s:1e3,m:6e4,h:36e5,d:864e5};function $v(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*_v[e[2]]}function xv(t,e=Date.now()){return new Date(e+$v(t)).toISOString()}function Tv(t,e=Date.now()){let n=Date.parse(t);return Number.isNaN(n)?!0:n<=e}function Rv(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 Ev(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 Pv="[REDACTED]",$r=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},ba=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 Av(t,e,n){let r={};for(let[s,o]of Object.entries(e)){let i=n[s];if(i===void 0)throw new ba(t,s,"column has no PII classification (unknown = unsafe)");i==="pii"?r[s]=o==null?o:Pv:r[s]=o}return r}function Iv(t,e,n){return e.map(r=>Av(t,r,n))}var xp=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),Cv=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function Ov(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 ya(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 Cv)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=Ov(t);if(!xp.has(n))throw new Error(`local-only guard: target host '${n}' is not a recognised local Postgres (${[...xp].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function Nv(t,e=Lv){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function Lv(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function jv(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function Dv(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function wa(){let{file:t}=Tp();try{let e=await ga.readFile(t,"utf8"),n=JSON.parse(e);return Array.isArray(n)?n:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Rp(t){let{dir:e,file:n}=Tp();await ga.mkdir(e,{recursive:!0}),await ga.writeFile(n,`${JSON.stringify(t,null,2)}
3530
+ `,{mode:384})}async function Uv(t){let e=await wa();e.push(t),await Rp(e)}async function Ep(t){let e=await wa(),n=e.findIndex(s=>s.name===t);if(n===-1)return null;let[r]=e.splice(n,1);return await Rp(e),r??null}async function Ws(){return wa()}function va(t,e=Date.now()){let n=[],r=[];for(let s of t)Tv(s.expiresAt,e)?r.push(s):n.push(s);return{active:n,expired:r}}async function Pp(t,e){ya(t.target());let n=t.dataCopyUnavailable?.();if(n)throw new $r(n);let r=Rv(e.sample),s=e.now??Date.now(),o=(e.nameGen??(u=>Nv(u)))(e.fromTenant),i=jv(o);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=Ev(u.rows,r),g=Iv(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:o,fromTenant:e.fromTenant,database:i,createdAt:new Date(s).toISOString(),expiresAt:xv(e.ttl,s),sampleFraction:r,url:Dv(o,e.baseUrl)};return await Uv(l),l}async function Ap(t,e){ya(t.target());let r=(await Ws()).find(s=>s.name===e);return r?(await t.dropDatabase(r.database),await Ep(e),r):null}async function ka(t,e=Date.now()){ya(t.target());let n=await Ws(),{expired:r}=va(n,e),s=[];for(let o of r){try{await t.dropDatabase(o.database)}catch{continue}await Ep(o.name),s.push(o)}return s}var xr={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"}},hI=Object.keys(xr).filter(t=>xr[t].mintable);var gI=xr.pat.prefix,Mv=Object.entries(xr).map(([t,e])=>[e.prefix,t]),zv=/^[A-Za-z0-9_-]{20,}$/;function qv(t){if(typeof t!="string")return null;for(let[e,n]of Mv)if(t.startsWith(e)&&zv.test(t.slice(e.length)))return n;return null}function Ip(t){return qv(t)==="pat"}hr();var Bv=8e3,Fv={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 Hv(t){return Fv[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Kv(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(Bv)})}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 Cp(t){return t.state==="accepted"?Ee()?f.green("accepted"):"accepted":t.state==="rejected"?Ee()?f.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Ee()?f.yellow("unreachable"):"unreachable"}async function Op(t={},e=fetch){let n=await Rt(),{file:r}=Ts();if(n.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(f.dim(`no sign-ins stored in ${r}.`));return}let s=await 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 Kv(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?f.green("*"):" ",f.bold(i.baseUrl),Cp(i.check),f.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of o)y(`${i.active?"* ":" "}${i.baseUrl} ${Cp(i.check)} (updated ${i.updatedAt})`);L(f.dim(`tokens read from ${r}`));for(let i of o)i.check.state==="rejected"?(L(f.red(`${i.baseUrl}: ${Hv(i.check.reason)}.`)),L(f.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(f.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));s||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function c0(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`."),Me()||w("this command needs an explicit <base-url> in a non-interactive shell.");try{return await ze(t,e.map(n=>({value:n.baseUrl,label:n.baseUrl,description:`updated ${n.updatedAt}`})))}catch{w("cancelled.")}}async function d0(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 u0(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 p0(t,e,n){let r=await Vd({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).`:".")),u0(r.baseUrl),!n)return;let o=await d0(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 h0(t){let e=await br(t),n=na(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 lr(t,e,n,r){try{return await se.access(t),"skipped"}catch{}return await se.mkdir(ar(t),{recursive:!0}),await se.writeFile(t,e,{mode:r??(n?493:420)}),r!==void 0&&await se.chmod(t,r),"wrote"}async function Ob(t,e){if(Lb(t)!==".gitignore")return lr(t,e.content,e.executable,e.mode);let n=await se.readFile(t,"utf8").catch(()=>null);if(n===null)return lr(t,e.content,e.executable,e.mode);let r=Ru(n);return r===null?"skipped":(await se.writeFile(t,r,"utf8"),"merged")}function yd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;w(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function wi(t){process.exit(t)}function f0(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 m0(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 g0(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 Nb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function $d({includeInternal:t=!0}={}){let e=new l0;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.6.6").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${Yi()}
3531
+ `),e.hook("preAction",(d,h)=>{Mu(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:
3532
+ ${vr} auth login --base-url ${h} --token tb_pat_\u2026`),Ip(d.token)||w("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await p0(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=>Op({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 c0("Pick the active instance:"),b=await Rs(h);if(!b){let x=await Rt();w(`no stored sign-in for ${Qe(h)}.`+(x.length?` Stored: ${x.map(k=>k.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 k of x)await Mi(k.baseUrl);y(`removed ${x.length} stored sign-in${x.length===1?"":"s"}.`);return}let h=await Mi(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 V(d.baseUrl),x;try{x=await an({baseUrl:h,token:b,recordsOnly:d.recordsOnly})}catch(m){let _=m instanceof Error?m.message:String(m);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 an({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 k=le(process.cwd(),d.out);await se.writeFile(k,x,"utf8"),y(`wrote ${k} (${x.split(`
3533
+ `).length} lines).`)}),Bu(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 V(d.baseUrl),x=new URLSearchParams;d.records&&x.set("records",d.records),d.query&&x.set("query",d.query);let k=x.toString(),m=await fetch(`${h}/v1/catalog/grounding${k?`?${k}`:""}`,{headers:{Authorization:`Bearer ${b}`,Accept:"application/json"}});m.ok||w(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${m.status}`);let R=((await m.json()).markdown??"").trim(),A=le(process.cwd(),d.out),I=d.records?` records=${d.records}`:"",C=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${I} \u2014 do not edit; re-run to refresh. -->
3534
3534
 
3535
3535
  `;await se.writeFile(A,C+(R?`${R}
3536
3536
  `:`(no grounding available yet)
3537
- `),"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 (${kn.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=>Bu(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=>Hu(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)=>Ku(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)=>Vu(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=>Gu(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)=>Wu(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)=>Ju(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=>Yu(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=>lp(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)=>cp(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)=>dp(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=>pp(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)=>up(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)=>hp(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(k){w(k instanceof Error?k.message:String(k))}let b=le(process.cwd(),h.relativePath);await ln(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(k){w(k instanceof Error?k.message:String(k))}let b=le(process.cwd(),h.relativePath);await ln(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=md(h.reporter),x=await bn(le(process.cwd(),d)),k=le(process.cwd(),h.samples),m=await gn(k);m.length===0&&!b&&y(`no samples found under ${k} \u2014 add JSON fixtures to dry-run against.`);let _;try{_=await As(x,m.map(I=>I.fixture))}catch(I){w(`bundle failed: ${I instanceof Error?I.message:String(I)}`)}if(b){let I=p0(_);y(Cs(I,b)),wi(I.cases.some(C=>C.status==="failed")?1:0)}let R=0;for(let I of _){let C=I.pass?f.green("PASS"):f.red("FAIL");I.pass||(R+=1);let q=I.error?` (error: ${I.error})`:I.observed!==I.expected?` (expected ${I.expected}, observed ${I.observed})`:I.rejection?` (rejected: ${I.rejection.code??"rejected"})`:"";y(` ${C} ${I.name}${q}`)}let A=`${_.length-R}/${_.length} sample(s) passed.`;y(`
3538
- ${R===0?f.green(A):f.yellow(A)}`),wi(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 gd(),{baseUrl:R,token:A}=await V(h.baseUrl),I=new F({baseUrl:R,token:A});try{let C=await J(`applying bundle to ${h.to}`,()=>I.configApply(_,{prune:h.prune}));y(`applied bundle to ${h.to}: +${C.applied.add} ~${C.applied.change} -${C.applied.destroy}`+(C.backfillsQueued.length?` (${C.backfillsQueued.length} backfill(s) queued)`:""));let q=C.skippedDestroys??[];if(q.length>0){L(`${q.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let N of q)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(C){C instanceof X&&C.status===403&&w("apply forbidden (403) \u2014 the stored PAT is not for an admin."),w(`bundle apply failed: ${C instanceof Error?C.message:String(C)}`)}return}d||w("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:b,token:x}=await V(h.baseUrl),k=await u0(le(process.cwd(),d)),m=new F({baseUrl:b,token:x});try{let _=await J(`deploying ${Ob(d)}`,()=>m.deploy(k));Ee()?y(Mt("Deployed",[`${f.bold(_.id)} ${Er(_.status)} ${f.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 k=le(process.cwd(),h??".");await se.mkdir(k,{recursive:!0});let m=b.proposal??await T(k),{baseUrl:_,token:R}=await V(b.baseUrl),A=new F({baseUrl:_,token:R}),I=!1;try{I=(await A.appsList()).some(ce=>ce.slug===d||ce.id===d)}catch(ce){G(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 C;if(b.replace)if(typeof b.replace=="string")C=b.replace;else{let{previews:ce}=await ne(_,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}\`.`)}C=ce[0].previewId}let q;if(b.replaceLabel){let ce=b.replaceLabel,{previews:Te}=await ne(_,R,d),vt=Te.filter(Si=>Si.label===ce);vt.length>0?(C=vt[0].previewId,vt.length>1&&L(`${vt.length} open previews carry the label "${ce}"; replacing the newest (${C}). Close the others with \`turbobase apps preview discard\`.`)):y(`no open preview labelled "${ce}" \u2014 opening one.`),q=ce}let N=ce=>se.stat(Ye(k,ce)).then(()=>!0).catch(()=>!1),K=d,he=k,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(`${k} 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}`,()=>g(_,R,d));K=ce.slug??d,await $(k,ce.files,!0),y(`pulled generated source (rev ${ce.rev}).`)}let $r;if(me){let ce=gp();if($r={buildId:ce,assetBase:bp(ce)},b.install!==!1&&!await N("node_modules")){y("installing dependencies\u2026");try{await P(["install"],k)}catch(Te){w(`npm install failed: ${Te instanceof Error?Te.message:String(Te)}`)}}y("building\u2026");try{await P(["run","build"],k,{TURBOBASE_ASSET_BASE:$r.assetBase})}catch(Te){w(`build failed: ${Te instanceof Error?Te.message:String(Te)}`)}await N("dist")||w(`no dist/ after build in ${k} \u2014 check the app's build script.`),he=Ye(k,"dist")}x&&!$r&&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 Ue=await Y(_,R,K,he,b.entry,m,$r,x?{label:b.label??q,replacePreviewId:C}:void 0);if(x){let ce=Ue.previewUrl??"(no url returned)",Te=Ue.expiresAt?new Date(Ue.expiresAt).toLocaleDateString():`${yp} days`,vt=Ue.replacedVersion==null?null:`replaced v${Ue.replacedVersion} \u2014 same URL`;if(Ee())y(Mt(vt?"Preview replaced":"Preview deployed",[`${f.bold(K)} ${f.green(`v${Ue.version??"?"}`)} ${f.dim("not live")}`,`${f.bold(ce)}`,...vt?[f.dim(vt)]:[],f.dim(`expires ${Te}`)]));else{let Si=vt?`; ${vt}`:"";y(`preview ${K} v${Ue.version??"?"} \u2192 ${ce} (expires ${Te}; /a/${K} unchanged${Si}).`)}y(`next: turbobase apps promote ${K} ${Ue.previewId??"<preview-id>"} # make it live`),y(` turbobase apps preview discard ${Ue.previewId??"<preview-id>"}`);return}Ee()?y(Mt("Deployed",[`${f.bold(K)} ${f.green(`v${Ue.version??"?"}`)} ${f.dim(Ue.url??`/a/${K}`)}`])):y(`deployed ${K} \u2192 v${Ue.version??"?"} (${Ue.url??`/a/${K}`}).`),He(Ue),await je(Ue,k)}),l.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").action(async(d,h)=>{let b=await g0(d??".");b||w(`no public/turbobase.json under ${le(process.cwd(),d??".")}.`);let x=Array.isArray(b.manifest.tables)?b.manifest.tables:[],k=Array.isArray(b.manifest.writes)?b.manifest.writes:[],m=Array.isArray(b.manifest.roles)?b.manifest.roles:[];if(x.length===0&&k.length===0&&m.length===0)return y(`${b.manifestPath} declares no tables, writes or roles \u2014 nothing to plan.`);let{baseUrl:_,token:R}=await V(h.baseUrl),A=new F({baseUrl:_,token:R});if(x.length>0){let I;try{I=await J("planning tables",()=>A.tablesPlan({claimedBy:h.as,tables:x}))}catch(C){G(C,"extensions:deploy","plan tables"),ys(C)}y(`claiming as ${f.bold(I.claimedBy)}`);for(let C of I.tables)Sr(C,{showClaimants:!0})}if(k.length>0||m.length>0){let I;try{I=await J("checking declared writes and roles",()=>A.appsPlan({writes:k,roles:m}))}catch(C){G(C,"extensions:deploy","plan writes"),w(`plan writes failed: ${C instanceof Error?C.message:String(C)}`)}if(I.roles&&I.roles.verdicts.length>0){y(""),y(f.bold("roles"));let C=Math.max(...I.roles.verdicts.map(q=>q.name.length));for(let q of I.roles.verdicts){let N=q.name.padEnd(C);if(q.action==="error")L(` ${f.bold("ERROR")} ${N} \u2014 ${q.message??"cannot be created"}`);else if(q.action==="create"){let K=q.addCapabilities?.length??0;y(` create ${N} ${f.dim(`${K} capabilit${K===1?"y":"ies"}`)}`)}else if(q.action==="add_capabilities"){let K=(q.addCapabilities??[]).map(he=>`+${he}`).join(", ");y(` add ${N} ${f.dim(K)}`)}else y(` ${f.dim("ok")} ${N} ${f.dim("already up to date")}`)}I.roles.verdicts.some(q=>q.action!=="error")&&y(f.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}k.length>0&&y("");for(let C of I.verdicts){let q=`${C.source} ${C.recordType}.${C.op}`;C.allowed?C.heldForApproval?y(`${f.dim("HELD")} ${q} \u2014 allowed, but each write waits for operator approval.`):y(`${f.dim("ok")} ${q}`):L(`${f.bold("DENIED")} ${q}${C.rule?` \u2014 guardrail "${C.rule}"`:""} (${C.reason})`)}I.ok||(y(""),w(I.message??(I.roles&&!I.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}y(""),y(f.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,b)=>{let{baseUrl:x,token:k}=await V(b.baseUrl),m=await J(`promoting ${h}`,()=>D(x,k,d,"promote",{previewId:h}));Ee()?y(Mt("Promoted",[`${f.bold(d)} ${f.green(`v${m.version??"?"}`)} ${f.dim(m.url??`/a/${d}`)}`])):y(`promoted ${d} \u2192 v${m.version??"?"} is now live at ${m.url??`/a/${d}`}.`),await je(m)});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 V(h.baseUrl),k=await ne(b,x,d);if(h.json)return y(JSON.stringify(k.previews,null,2));if(k.previews.length===0){y(`no open previews for ${d}.`);return}for(let m of k.previews){let _=m.label?` ${m.label}`:"",R=m.expiresAt?new Date(m.expiresAt).toLocaleDateString():"?";y(`v${m.version} ${m.previewId}${_} ${m.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:k}=await V(b.baseUrl);await J(`discarding ${h}`,()=>D(x,k,d,"discard",{previewId:h})),y(`discarded ${h}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:b,token:x}=await V(h.baseUrl),k=await J(`creating ${d}`,()=>p(b,x,{slug:d,name:h.name,description:h.description})),m=k.slug??d;Ee()?y(Mt("Created",[`${f.bold(m)} ${f.dim(k.url??`/a/${m}`)}`])):y(`created ${m} (${k.url??`/a/${m}`}).`),y(`next: turbobase apps push ${m} . # store the source`),y(` turbobase apps deploy ${m} # build + go live`)});async function p(d,h,b,x={}){let k=`${d.replace(/\/+$/,"")}/v1/apps`,m;try{m=await fetch(k,{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(m.status===401&&w("create unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&w("create forbidden (403) \u2014 the PAT is not for an admin."),m.status===409){if(x.tolerateExisting)return{slug:b.slug,existed:!0};w(`an app with slug "${b.slug}" already exists.`)}return m.ok||w(`create failed: HTTP ${m.status} ${(await m.text().catch(()=>"")).slice(0,200)}`),await m.json().catch(()=>({}))}async function g(d,h,b){let x=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/pull`,k;try{k=await fetch(x,{headers:{Authorization:`Bearer ${h}`}})}catch(m){w(`pull request failed: ${m instanceof Error?m.message:String(m)}`)}return k.status===401&&w("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),k.status===403&&w("pull forbidden (403) \u2014 the PAT is not for an admin."),k.status===404&&w(`no generated source for "${b}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),k.ok||w(`pull failed: HTTP ${k.status} ${(await k.text().catch(()=>"")).slice(0,200)}`),await k.json()}async function $(d,h,b){let x=le(d),k=0;for(let[m,_]of Object.entries(h)){let R=le(x,m);R!==x&&!R.startsWith(x+wd)&&w(`refusing to write outside ${x}: ${m}`),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(an(R),{recursive:!0}),await se.writeFile(R,_,"utf8"),k+=1}return k}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 S(d,h,b){let x=le(d),k=async(_,R)=>{let A=le(x,_);A!==x&&!A.startsWith(x+wd)&&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(an(A),{recursive:!0}),await se.writeFile(A,R)},m=`# ${h.title||"App change request"}
3537
+ `),"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 (${kr.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=>Ku(d)),o.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>Gu(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)=>Wu(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)=>Ju(d,h)),o.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>Yu(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)=>Zu(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)=>Xu(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=>Qu(d)),i.command("list").description("List the instance\u2019s agent skills and whether each is actually injected. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only skills in this state.").action(d=>up(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)=>pp(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)=>hp(d,h)),i.command("releases").description("List the skill releases, newest first \u2014 the rollback targets. Needs `skills:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>mp(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)=>fp(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)=>gp(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(k){w(k instanceof Error?k.message:String(k))}let b=le(process.cwd(),h.relativePath);await lr(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(k){w(k instanceof Error?k.message:String(k))}let b=le(process.cwd(),h.relativePath);await lr(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=yd(h.reporter),x=await br(le(process.cwd(),d)),k=le(process.cwd(),h.samples),m=await gr(k);m.length===0&&!b&&y(`no samples found under ${k} \u2014 add JSON fixtures to dry-run against.`);let _;try{_=await As(x,m.map(I=>I.fixture))}catch(I){w(`bundle failed: ${I instanceof Error?I.message:String(I)}`)}if(b){let I=f0(_);y(Cs(I,b)),wi(I.cases.some(C=>C.status==="failed")?1:0)}let R=0;for(let I of _){let C=I.pass?f.green("PASS"):f.red("FAIL");I.pass||(R+=1);let M=I.error?` (error: ${I.error})`:I.observed!==I.expected?` (expected ${I.expected}, observed ${I.observed})`:I.rejection?` (rejected: ${I.rejection.code??"rejected"})`:"";y(` ${C} ${I.name}${M}`)}let A=`${_.length-R}/${_.length} sample(s) passed.`;y(`
3538
+ ${R===0?f.green(A):f.yellow(A)}`),wi(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 wd(),{baseUrl:R,token:A}=await V(h.baseUrl),I=new F({baseUrl:R,token:A});try{let C=await J(`applying bundle to ${h.to}`,()=>I.configApply(_,{prune:h.prune}));y(`applied bundle to ${h.to}: +${C.applied.add} ~${C.applied.change} -${C.applied.destroy}`+(C.backfillsQueued.length?` (${C.backfillsQueued.length} backfill(s) queued)`:""));let M=C.skippedDestroys??[];if(M.length>0){L(`${M.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let N of M)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(C){C instanceof Q&&C.status===403&&w("apply forbidden (403) \u2014 the stored PAT is not for an admin."),w(`bundle apply failed: ${C instanceof Error?C.message:String(C)}`)}return}d||w("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:b,token:x}=await V(h.baseUrl),k=await h0(le(process.cwd(),d)),m=new F({baseUrl:b,token:x});try{let _=await J(`deploying ${Lb(d)}`,()=>m.deploy(k));Ee()?y(zt("Deployed",[`${f.bold(_.id)} ${Pn(_.status)} ${f.dim(_.outcome)}`])):y(`deployed ${_.id} \u2192 status=${_.status} (${_.outcome}).`)}catch(_){_ instanceof Q&&_.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 k=le(process.cwd(),h??".");await se.mkdir(k,{recursive:!0});let m=b.proposal??await T(k),{baseUrl:_,token:R}=await V(b.baseUrl),A=new F({baseUrl:_,token:R}),I=!1;try{I=(await A.appsList()).some(ce=>ce.slug===d||ce.id===d)}catch(ce){G(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 C;if(b.replace)if(typeof b.replace=="string")C=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}\`.`)}C=ce[0].previewId}let M;if(b.replaceLabel){let ce=b.replaceLabel,{previews:Te}=await re(_,R,d),vt=Te.filter(Si=>Si.label===ce);vt.length>0?(C=vt[0].previewId,vt.length>1&&L(`${vt.length} open previews carry the label "${ce}"; replacing the newest (${C}). Close the others with \`turbobase apps preview discard\`.`)):y(`no open preview labelled "${ce}" \u2014 opening one.`),M=ce}let N=ce=>se.stat(Ye(k,ce)).then(()=>!0).catch(()=>!1),K=d,he=k,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(`${k} 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}`,()=>g(_,R,d));K=ce.slug??d,await $(k,ce.files,!0),y(`pulled generated source (rev ${ce.rev}).`)}let xn;if(me){let ce=wp();if(xn={buildId:ce,assetBase:vp(ce)},b.install!==!1&&!await N("node_modules")){y("installing dependencies\u2026");try{await P(["install"],k)}catch(Te){w(`npm install failed: ${Te instanceof Error?Te.message:String(Te)}`)}}y("building\u2026");try{await P(["run","build"],k,{TURBOBASE_ASSET_BASE:xn.assetBase})}catch(Te){w(`build failed: ${Te instanceof Error?Te.message:String(Te)}`)}await N("dist")||w(`no dist/ after build in ${k} \u2014 check the app's build script.`),he=Ye(k,"dist")}x&&!xn&&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 De=await Y(_,R,K,he,b.entry,m,xn,x?{label:b.label??M,replacePreviewId:C}:void 0);if(x){let ce=De.previewUrl??"(no url returned)",Te=De.expiresAt?new Date(De.expiresAt).toLocaleDateString():`${kp} days`,vt=De.replacedVersion==null?null:`replaced v${De.replacedVersion} \u2014 same URL`;if(Ee())y(zt(vt?"Preview replaced":"Preview deployed",[`${f.bold(K)} ${f.green(`v${De.version??"?"}`)} ${f.dim("not live")}`,`${f.bold(ce)}`,...vt?[f.dim(vt)]:[],f.dim(`expires ${Te}`)]));else{let Si=vt?`; ${vt}`:"";y(`preview ${K} v${De.version??"?"} \u2192 ${ce} (expires ${Te}; /a/${K} unchanged${Si}).`)}y(`next: turbobase apps promote ${K} ${De.previewId??"<preview-id>"} # make it live`),y(` turbobase apps preview discard ${De.previewId??"<preview-id>"}`);return}Ee()?y(zt("Deployed",[`${f.bold(K)} ${f.green(`v${De.version??"?"}`)} ${f.dim(De.url??`/a/${K}`)}`])):y(`deployed ${K} \u2192 v${De.version??"?"} (${De.url??`/a/${K}`}).`),He(De),await je(De,k)}),l.command("plan").description("Preflight this app's manifest against the instance \u2014 table conflicts, guardrail-blocked writes, and declared roles. Writes nothing.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim tables as `cli` or `app:<slug>`.").action(async(d,h)=>{let b=await y0(d??".");b||w(`no public/turbobase.json under ${le(process.cwd(),d??".")}.`);let x=Array.isArray(b.manifest.tables)?b.manifest.tables:[],k=Array.isArray(b.manifest.writes)?b.manifest.writes:[],m=Array.isArray(b.manifest.roles)?b.manifest.roles:[];if(x.length===0&&k.length===0&&m.length===0)return y(`${b.manifestPath} declares no tables, writes or roles \u2014 nothing to plan.`);let{baseUrl:_,token:R}=await V(h.baseUrl),A=new F({baseUrl:_,token:R});if(x.length>0){let I;try{I=await J("planning tables",()=>A.tablesPlan({claimedBy:h.as,tables:x}))}catch(C){G(C,"extensions:deploy","plan tables"),ys(C)}y(`claiming as ${f.bold(I.claimedBy)}`);for(let C of I.tables)_n(C,{showClaimants:!0})}if(k.length>0||m.length>0){let I;try{I=await J("checking declared writes and roles",()=>A.appsPlan({writes:k,roles:m}))}catch(C){G(C,"extensions:deploy","plan writes"),w(`plan writes failed: ${C instanceof Error?C.message:String(C)}`)}if(I.roles&&I.roles.verdicts.length>0){y(""),y(f.bold("roles"));let C=Math.max(...I.roles.verdicts.map(M=>M.name.length));for(let M of I.roles.verdicts){let N=M.name.padEnd(C);if(M.action==="error")L(` ${f.bold("ERROR")} ${N} \u2014 ${M.message??"cannot be created"}`);else if(M.action==="create"){let K=M.addCapabilities?.length??0;y(` create ${N} ${f.dim(`${K} capabilit${K===1?"y":"ies"}`)}`)}else if(M.action==="add_capabilities"){let K=(M.addCapabilities??[]).map(he=>`+${he}`).join(", ");y(` add ${N} ${f.dim(K)}`)}else y(` ${f.dim("ok")} ${N} ${f.dim("already up to date")}`)}I.roles.verdicts.some(M=>M.action!=="error")&&y(f.dim(" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users."))}k.length>0&&y("");for(let C of I.verdicts){let M=`${C.source} ${C.recordType}.${C.op}`;C.allowed?C.heldForApproval?y(`${f.dim("HELD")} ${M} \u2014 allowed, but each write waits for operator approval.`):y(`${f.dim("ok")} ${M}`):L(`${f.bold("DENIED")} ${M}${C.rule?` \u2014 guardrail "${C.rule}"`:""} (${C.reason})`)}I.ok||(y(""),w(I.message??(I.roles&&!I.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}y(""),y(f.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,b)=>{let{baseUrl:x,token:k}=await V(b.baseUrl),m=await J(`promoting ${h}`,()=>U(x,k,d,"promote",{previewId:h}));Ee()?y(zt("Promoted",[`${f.bold(d)} ${f.green(`v${m.version??"?"}`)} ${f.dim(m.url??`/a/${d}`)}`])):y(`promoted ${d} \u2192 v${m.version??"?"} is now live at ${m.url??`/a/${d}`}.`),await je(m)});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 V(h.baseUrl),k=await re(b,x,d);if(h.json)return y(JSON.stringify(k.previews,null,2));if(k.previews.length===0){y(`no open previews for ${d}.`);return}for(let m of k.previews){let _=m.label?` ${m.label}`:"",R=m.expiresAt?new Date(m.expiresAt).toLocaleDateString():"?";y(`v${m.version} ${m.previewId}${_} ${m.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:k}=await V(b.baseUrl);await J(`discarding ${h}`,()=>U(x,k,d,"discard",{previewId:h})),y(`discarded ${h}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:b,token:x}=await V(h.baseUrl),k=await J(`creating ${d}`,()=>p(b,x,{slug:d,name:h.name,description:h.description})),m=k.slug??d;Ee()?y(zt("Created",[`${f.bold(m)} ${f.dim(k.url??`/a/${m}`)}`])):y(`created ${m} (${k.url??`/a/${m}`}).`),y(`next: turbobase apps push ${m} . # store the source`),y(` turbobase apps deploy ${m} # build + go live`)});async function p(d,h,b,x={}){let k=`${d.replace(/\/+$/,"")}/v1/apps`,m;try{m=await fetch(k,{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(m.status===401&&w("create unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&w("create forbidden (403) \u2014 the PAT is not for an admin."),m.status===409){if(x.tolerateExisting)return{slug:b.slug,existed:!0};w(`an app with slug "${b.slug}" already exists.`)}return m.ok||w(`create failed: HTTP ${m.status} ${(await m.text().catch(()=>"")).slice(0,200)}`),await m.json().catch(()=>({}))}async function g(d,h,b){let x=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/pull`,k;try{k=await fetch(x,{headers:{Authorization:`Bearer ${h}`}})}catch(m){w(`pull request failed: ${m instanceof Error?m.message:String(m)}`)}return k.status===401&&w("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),k.status===403&&w("pull forbidden (403) \u2014 the PAT is not for an admin."),k.status===404&&w(`no generated source for "${b}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),k.ok||w(`pull failed: HTTP ${k.status} ${(await k.text().catch(()=>"")).slice(0,200)}`),await k.json()}async function $(d,h,b){let x=le(d),k=0;for(let[m,_]of Object.entries(h)){let R=le(x,m);R!==x&&!R.startsWith(x+Sd)&&w(`refusing to write outside ${x}: ${m}`),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(ar(R),{recursive:!0}),await se.writeFile(R,_,"utf8"),k+=1}return k}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 S(d,h,b){let x=le(d),k=async(_,R)=>{let A=le(x,_);A!==x&&!A.startsWith(x+Sd)&&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(ar(A),{recursive:!0}),await se.writeFile(A,R)},m=`# ${h.title||"App change request"}
3539
3539
 
3540
3540
  > Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
3541
3541
  > \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
@@ -3546,34 +3546,34 @@ ${h.bodyMarkdown||"_No description provided._"}
3546
3546
 
3547
3547
  `+(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.
3548
3548
  `);if(await k("PROPOSAL.md",m),h.screenshot){let _=v(h.screenshot);_&&await k("proposal-screenshot.png",_)}await k(Ye(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
3549
- `)}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,k,m){let _=new F({baseUrl:d,token:h});try{return await _.appsPush(b,x,{note:k,proposalId:m})}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&&G(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}`:"",C=A?.reason?` (${A.reason})`:"";w(`push rejected: ${A?.error??"bad request"}${C}${I}.`)}}w(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function P(d,h,b){return new Promise((x,k)=>{let m=vd("npm",d,{cwd:h,stdio:"inherit",...b?{env:{...process.env,...b}}:{}});m.on("error",k),m.on("exit",_=>_===0?x():k(new Error(`npm ${d.join(" ")} exited ${_??"?"}`)))})}async function O(d,h,b,x){let k=`${d.replace(/\/+$/,"")}${b}`,m;try{m=await fetch(k,{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(m.status===401&&w("unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&w("forbidden (403) \u2014 the PAT is not for an admin."),!m.ok){let _=await m.text().catch(()=>""),R=_.slice(0,300);try{let A=JSON.parse(_);R=A.message??A.error??R}catch{}w(`failed: HTTP ${m.status} ${R}`)}return await m.json().catch(()=>({}))}async function D(d,h,b,x,k){return await O(d,h,`/v1/apps/${encodeURIComponent(b)}/preview/${x}`,{method:"POST",body:k})}async function ne(d,h,b){return{previews:(await O(d,h,`/v1/apps/${encodeURIComponent(b)}/previews`,{method:"GET"})).previews??[]}}async function Y(d,h,b,x,k,m,_,R){let A;try{A=await J(`zipping ${x}`,()=>iu(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"};k&&(I["x-app-entry"]=k),m&&(I["x-proposal-id"]=m),_&&(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 C=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/deploy`,q;try{q=await J(`deploying ${b} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(C,{method:"POST",headers:I,body:new Uint8Array(A.buffer)}))}catch(N){w(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(q.status===401&&w("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),q.status===403&&w("deploy forbidden (403) \u2014 the PAT is not for an admin."),q.status===404){let N=await q.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(!q.ok){let N=await q.text().catch(()=>""),K=N.slice(0,300);try{let he=JSON.parse(N);K=he.message??he.error??K}catch{}w(`deploy failed: HTTP ${q.status} ${K}`)}return await q.json().catch(()=>({}))}function He(d){let h=d.roles;if(!h||h.verdicts.length===0)return;let b=h.verdicts.filter(k=>k.action!=="noop");if(b.length===0)return;y(""),y(f.bold(h.applied?"roles":"roles (preview \u2014 not applied)"));let x=Math.max(...b.map(k=>k.name.length));for(let k of b){let m=k.name.padEnd(x);if(k.action==="create"){let _=k.addCapabilities?.length??0;y(` created ${m} ${f.dim(`${_} capabilit${_===1?"y":"ies"}`)}`)}else if(k.action==="add_capabilities"){let _=(k.addCapabilities??[]).map(A=>`+${A}`).join(", "),R=k.holdersRestamped?f.dim(` (${k.holdersRestamped} holder${k.holdersRestamped===1?"":"s"} re-stamped)`):"";y(` updated ${m} ${f.dim(_)}${R}`)}}y(f.dim(h.applied?" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.":" nothing was created \u2014 promoting this preview applies them."))}async function je(d,h){let b=wu(d,{localDocsModifiedAt:await cn(h)});b&&y(b.level==="warn"?f.yellow(b.message):f.dim(b.message))}async function cn(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:k}=await V(b.baseUrl);if(b.proposal){let A=new F({baseUrl:x,token:k}),I;try{I=await J(`fetching proposal ${b.proposal}`,()=>A.appPullContext(b.proposal))}catch(he){G(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 C=await J(`pulling ${I.appSlug}`,()=>g(x,k,I.appSlug)),q=h??d,N=le(process.cwd(),q??I.appSlug);await se.mkdir(N,{recursive:!0});let K=await $(N,C.files,!!b.force);await S(N,I,!!b.force),y(`pulled ${K} file${K===1?"":"s"} \u2192 ${N} (rev ${C.rev}), linked to proposal ${I.proposalId}.`),y(`next: cd ${vi(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 m=await J(`pulling ${d}`,()=>g(x,k,d)),_=le(process.cwd(),h??m.slug??d);await se.mkdir(_,{recursive:!0});let R=await $(_,m.files,!!b.force);y(`pulled ${R} file${R===1?"":"s"} \u2192 ${_} (rev ${m.rev}).`),y(`next: cd ${vi(process.cwd(),_)||"."} && turbobase apps deploy ${m.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),k=await ut(b.baseUrl).catch(()=>null),{scaffoldAppFiles:m,starterApp:_}=await Promise.resolve().then(()=>(Xp(),Qp)),R=b.title??d,A=m({slug:d,title:R,appTsx:_(R),instanceOrigin:k?.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 q=Xi({baseUrl:k?.baseUrl,token:k?.token,appSlug:d}),N=0;for(let K of q){let he=await Cb(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/).`),k||L("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let C=vi(process.cwd(),x)||".";y(`next: cd ${C} && 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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.appsList()}catch(m){G(m,"extensions:deploy","list apps"),w(`list apps failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");y(pt(k.map(m=>[m.slug,m.name,m.deployed?"yes":"no",m.sourceRev===null?"\u2014":`rev ${m.sourceRev}`,m.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:m,token:_}=await V(b.baseUrl),R=b.proposal??await T(x),{files:A,skipped:I,secrets:C,unstorable:q}=await mp(x),N=Object.keys(A).length;if(N===0&&w(`no source files found under ${x} (build output and node_modules are skipped).`),q.length>0){for(let me of q)L(`${me} contains a NUL byte (U+0000), which cannot be stored.`);w(`push aborted: ${q.length} ${q.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(f.dim(`skipped binary file ${me}`));for(let me of C)L(f.dim(`skipped ${me} (holds credentials \u2014 never pushed)`));let K=await J(`pushing ${N} file${N===1?"":"s"}`,()=>E(m,_,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 Sn(new F({baseUrl:m,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 gd(),{baseUrl:b,token:x}=await V(d.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await J(`planning against ${d.to??b}`,()=>k.configPlan(h))}catch(_){w(`plan failed: ${_ instanceof Error?_.message:String(_)}`)}y0(m,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 gd(),{baseUrl:b,token:x}=await V(d.baseUrl),k=h.tenant??w0(b),m=Pu(d.confirm,k);m.ok||w(`promote refused (fail-closed): ${m.reason}`);let _=new F({baseUrl:b,token:x});try{let R=await J(`promoting ${d.from} \u2192 ${d.to} (${k})`,()=>_.configApply(h,{prune:d.prune}));if(Ee()){let I=[`${f.bold(`${d.from} \u2192 ${d.to}`)} ${f.dim(k??"")}`,`${qt.add(String(R.applied.add))} ${qt.change(String(R.applied.change))} ${qt.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&I.push(f.dim(`${R.backfillsQueued.length} backfill(s) queued`)),y(Mt("Promoted",I))}else y(`promoted ${d.from} \u2192 ${d.to} (${k}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let 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=md(h.reporter),x=le(process.cwd(),d),k=await bn(x),m=lu(k);b?y(Cs(h0(d,m),b)):y(cu(d,m,{warn:f.yellow,ok:f.green,dim:f.dim})),h.ci&&m.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=md(h.reporter),x=await eu(le(process.cwd(),d));if(h.against){h.against!=="sandbox"&&w(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Qd(Vi(x))}catch(_){w(_ instanceof Error?_.message:String(_))}return}h.fixture||w("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await Xd(le(process.cwd(),h.fixture))}catch(_){w(`could not read fixture ${h.fixture}: ${_ instanceof Error?_.message:String(_)}`)}let m=await Zd(x,k,h.fixture);if(b){let _=f0(m);y(Cs(_,b)),wi(_.cases.some(R=>R.status==="failed")?1:0)}y(tu(m,!!h.trace)),wi(m.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 V(d.baseUrl),x=new F({baseUrl:h,token:b});try{await gu(x,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:y})}catch(k){k instanceof X&&k.status===403&&w("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof X&&k.status===409&&w("binding is not retryable (only divergent/blocked bindings can be retried)."),w(`ext binding failed: ${k instanceof Error?k.message:String(k)}`)}});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 sp(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 op(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 ip(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,k=b>0?d.slice(b+1):void 0,m=Mi();m||w(`marketplace not configured \u2014 set ${xr} and ${Es}.
3550
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let _=zi(m.registryUrl);_&&w(_);let{baseUrl:R,token:A}=await V(h.baseUrl),I=new fn(m),C;try{C=await J(`fetching ${d}`,()=>I.fetchBundle(x,k))}catch(me){w(`marketplace fetch failed for ${d}: ${me instanceof Error?me.message:String(me)}`)}let q=ks(C.manifest),N=null;if(q.length>0){if(!h.connection){let me=q.map($r=>$r.source_system).join(", ");w(`${C.name}@${C.version} declares a connection input (source: ${me}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=h.connection}let K=m0(C.bundle,C.name,C.kind),he=new F({baseUrl:R,token:A});try{let me=await J(`installing ${C.name}@${C.version}`,()=>he.deploy({...K,provenance:"marketplace",...N?{connectionId:N}:{}}));y(`installed ${C.name}@${C.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=Mi();b||w(`marketplace not configured \u2014 set ${xr} and ${Es}.
3551
- 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 k=le(process.cwd(),d),m=await bn(k),_=/\bdefineConduit\s*[<(]/.test(m)?"conduit":"hook",R={};if(h.manifest){let C=le(process.cwd(),h.manifest),q;try{q=await se.readFile(C,"utf8")}catch{w(`manifest not found at ${h.manifest}.`)}let N;try{N=JSON.parse(q)}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{xi(R,m)}catch(C){C instanceof Dt&&w(C.message),w(`manifest validation failed: ${C instanceof Error?C.message:String(C)}`)}let A=new fn(b);try{await J(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:_,bundle:m,manifest:R}))}catch(C){C instanceof X&&C.status===403&&w("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),C instanceof X&&C.status===409&&w(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),w(`publish failed: ${C instanceof Error?C.message:String(C)}`)}let I=ks(R);y(`published ${h.name}@${h.pkgVersion} (kind=${_}) to the marketplace.`),I.length>0&&y(` declares ${I.length} connection input(s): ${I.map(C=>C.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let h=await ut(d.baseUrl).catch(()=>null),b=Xi({baseUrl:h?.baseUrl,token:h?.token}),x=0,k=0,m=0;for(let _ of b){let R=le(process.cwd(),_.path),A=await Cb(R,_);A==="wrote"?(x+=1,y(` wrote ${_.path}`)):A==="merged"?(m+=1,y(` merged ${_.path} (added the .mcp.json rule)`)):(k+=1,y(` skipped ${_.path} (exists)`))}y(`
3552
- project init: ${x} written, ${m} merged, ${k} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Qi} (non-destructive).`).action(async()=>{let d=vu(),h=0,b=0;for(let x of d){let k=le(process.cwd(),x.path);await ln(k,x.content,x.executable)==="wrote"?(h+=1,y(` wrote ${x.path}`)):(b+=1,y(` skipped ${x.path} (exists)`))}y(`
3549
+ `)}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,k,m){let _=new F({baseUrl:d,token:h});try{return await _.appsPush(b,x,{note:k,proposalId:m})}catch(R){if(R instanceof Q){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&&G(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}`:"",C=A?.reason?` (${A.reason})`:"";w(`push rejected: ${A?.error??"bad request"}${C}${I}.`)}}w(`push failed: ${R instanceof Error?R.message:String(R)}`)}}function P(d,h,b){return new Promise((x,k)=>{let m=_d("npm",d,{cwd:h,stdio:"inherit",...b?{env:{...process.env,...b}}:{}});m.on("error",k),m.on("exit",_=>_===0?x():k(new Error(`npm ${d.join(" ")} exited ${_??"?"}`)))})}async function O(d,h,b,x){let k=`${d.replace(/\/+$/,"")}${b}`,m;try{m=await fetch(k,{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(m.status===401&&w("unauthorized (401) \u2014 re-run `turbobase auth login`."),m.status===403&&w("forbidden (403) \u2014 the PAT is not for an admin."),!m.ok){let _=await m.text().catch(()=>""),R=_.slice(0,300);try{let A=JSON.parse(_);R=A.message??A.error??R}catch{}w(`failed: HTTP ${m.status} ${R}`)}return await m.json().catch(()=>({}))}async function U(d,h,b,x,k){return await O(d,h,`/v1/apps/${encodeURIComponent(b)}/preview/${x}`,{method:"POST",body:k})}async function re(d,h,b){return{previews:(await O(d,h,`/v1/apps/${encodeURIComponent(b)}/previews`,{method:"GET"})).previews??[]}}async function Y(d,h,b,x,k,m,_,R){let A;try{A=await J(`zipping ${x}`,()=>cu(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.`),A.buffer.byteLength>ua&&w(`${x} zips to ${Nb(A.buffer.byteLength)} \u2014 over the ${Nb(ua)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let I={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};k&&(I["x-app-entry"]=k),m&&(I["x-proposal-id"]=m),_&&(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 C=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(b)}/deploy`,M;try{M=await J(`deploying ${b} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>fetch(C,{method:"POST",headers:I,body:new Uint8Array(A.buffer)}))}catch(N){w(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(M.status===401&&w("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),M.status===403&&w("deploy forbidden (403) \u2014 the PAT is not for an admin."),M.status===404){let N=await M.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(!M.ok){let N=await M.text().catch(()=>""),K=N.slice(0,300);try{let he=JSON.parse(N);K=he.message??he.error??K}catch{}w(`deploy failed: HTTP ${M.status} ${K}`)}return await M.json().catch(()=>({}))}function He(d){let h=d.roles;if(!h||h.verdicts.length===0)return;let b=h.verdicts.filter(k=>k.action!=="noop");if(b.length===0)return;y(""),y(f.bold(h.applied?"roles":"roles (preview \u2014 not applied)"));let x=Math.max(...b.map(k=>k.name.length));for(let k of b){let m=k.name.padEnd(x);if(k.action==="create"){let _=k.addCapabilities?.length??0;y(` created ${m} ${f.dim(`${_} capabilit${_===1?"y":"ies"}`)}`)}else if(k.action==="add_capabilities"){let _=(k.addCapabilities??[]).map(A=>`+${A}`).join(", "),R=k.holdersRestamped?f.dim(` (${k.holdersRestamped} holder${k.holdersRestamped===1?"":"s"} re-stamped)`):"";y(` updated ${m} ${f.dim(_)}${R}`)}}y(f.dim(h.applied?" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.":" nothing was created \u2014 promoting this preview applies them."))}async function je(d,h){let b=Su(d,{localDocsModifiedAt:await cr(h)});b&&y(b.level==="warn"?f.yellow(b.message):f.dim(b.message))}async function cr(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:k}=await V(b.baseUrl);if(b.proposal){let A=new F({baseUrl:x,token:k}),I;try{I=await J(`fetching proposal ${b.proposal}`,()=>A.appPullContext(b.proposal))}catch(he){G(he,"extensions:deploy","pull proposal"),he instanceof Q&&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 C=await J(`pulling ${I.appSlug}`,()=>g(x,k,I.appSlug)),M=h??d,N=le(process.cwd(),M??I.appSlug);await se.mkdir(N,{recursive:!0});let K=await $(N,C.files,!!b.force);await S(N,I,!!b.force),y(`pulled ${K} file${K===1?"":"s"} \u2192 ${N} (rev ${C.rev}), linked to proposal ${I.proposalId}.`),y(`next: cd ${vi(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 m=await J(`pulling ${d}`,()=>g(x,k,d)),_=le(process.cwd(),h??m.slug??d);await se.mkdir(_,{recursive:!0});let R=await $(_,m.files,!!b.force);y(`pulled ${R} file${R===1?"":"s"} \u2192 ${_} (rev ${m.rev}).`),y(`next: cd ${vi(process.cwd(),_)||"."} && turbobase apps deploy ${m.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),k=await ut(b.baseUrl).catch(()=>null),{scaffoldAppFiles:m,starterApp:_}=await Promise.resolve().then(()=>(eh(),Qp)),R=b.title??d,A=m({slug:d,title:R,appTsx:_(R),instanceOrigin:k?.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 M=Qi({baseUrl:k?.baseUrl,token:k?.token,appSlug:d}),N=0;for(let K of M){let he=await Ob(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/).`),k||L("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let C=vi(process.cwd(),x)||".";y(`next: cd ${C} && 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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.appsList()}catch(m){G(m,"extensions:deploy","list apps"),w(`list apps failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");y(pt(k.map(m=>[m.slug,m.name,m.deployed?"yes":"no",m.sourceRev===null?"\u2014":`rev ${m.sourceRev}`,m.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:m,token:_}=await V(b.baseUrl),R=b.proposal??await T(x),{files:A,skipped:I,secrets:C,unstorable:M}=await yp(x),N=Object.keys(A).length;if(N===0&&w(`no source files found under ${x} (build output and node_modules are skipped).`),M.length>0){for(let me of M)L(`${me} contains a NUL byte (U+0000), which cannot be stored.`);w(`push aborted: ${M.length} ${M.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(f.dim(`skipped binary file ${me}`));for(let me of C)L(f.dim(`skipped ${me} (holds credentials \u2014 never pushed)`));let K=await J(`pushing ${N} file${N===1?"":"s"}`,()=>E(m,_,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 Sr(new F({baseUrl:m,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 wd(),{baseUrl:b,token:x}=await V(d.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await J(`planning against ${d.to??b}`,()=>k.configPlan(h))}catch(_){w(`plan failed: ${_ instanceof Error?_.message:String(_)}`)}v0(m,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 wd(),{baseUrl:b,token:x}=await V(d.baseUrl),k=h.tenant??k0(b),m=Cu(d.confirm,k);m.ok||w(`promote refused (fail-closed): ${m.reason}`);let _=new F({baseUrl:b,token:x});try{let R=await J(`promoting ${d.from} \u2192 ${d.to} (${k})`,()=>_.configApply(h,{prune:d.prune}));if(Ee()){let I=[`${f.bold(`${d.from} \u2192 ${d.to}`)} ${f.dim(k??"")}`,`${Mt.add(String(R.applied.add))} ${Mt.change(String(R.applied.change))} ${Mt.destroy(String(R.applied.destroy))}`];R.backfillsQueued.length&&I.push(f.dim(`${R.backfillsQueued.length} backfill(s) queued`)),y(zt("Promoted",I))}else y(`promoted ${d.from} \u2192 ${d.to} (${k}): +${R.applied.add} ~${R.applied.change} -${R.applied.destroy}`+(R.backfillsQueued.length?` (${R.backfillsQueued.length} backfill(s) queued)`:""));let 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 Q&&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=yd(h.reporter),x=le(process.cwd(),d),k=await br(x),m=uu(k);b?y(Cs(m0(d,m),b)):y(pu(d,m,{warn:f.yellow,ok:f.green,dim:f.dim})),h.ci&&m.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=yd(h.reporter),x=await ru(le(process.cwd(),d));if(h.against){h.against!=="sandbox"&&w(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await tu(Vi(x))}catch(_){w(_ instanceof Error?_.message:String(_))}return}h.fixture||w("replay needs a --fixture <file> (offline) or --against sandbox (online).");let k;try{k=await nu(le(process.cwd(),h.fixture))}catch(_){w(`could not read fixture ${h.fixture}: ${_ instanceof Error?_.message:String(_)}`)}let m=await eu(x,k,h.fixture);if(b){let _=g0(m);y(Cs(_,b)),wi(_.cases.some(R=>R.status==="failed")?1:0)}y(su(m,!!h.trace)),wi(m.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 V(d.baseUrl),x=new F({baseUrl:h,token:b});try{await wu(x,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:y})}catch(k){k instanceof Q&&k.status===403&&w("forbidden (403) \u2014 binding --retry requires an admin PAT."),k instanceof Q&&k.status===409&&w("binding is not retryable (only divergent/blocked bindings can be retried)."),w(`ext binding failed: ${k instanceof Error?k.message:String(k)}`)}});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 ip(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 ap(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 lp(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 cp(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,k=b>0?d.slice(b+1):void 0,m=zi();m||w(`marketplace not configured \u2014 set ${Tn} and ${Es}.
3550
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let _=qi(m.registryUrl);_&&w(_);let{baseUrl:R,token:A}=await V(h.baseUrl),I=new fr(m),C;try{C=await J(`fetching ${d}`,()=>I.fetchBundle(x,k))}catch(me){w(`marketplace fetch failed for ${d}: ${me instanceof Error?me.message:String(me)}`)}let M=ks(C.manifest),N=null;if(M.length>0){if(!h.connection){let me=M.map(xn=>xn.source_system).join(", ");w(`${C.name}@${C.version} declares a connection input (source: ${me}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=h.connection}let K=b0(C.bundle,C.name,C.kind),he=new F({baseUrl:R,token:A});try{let me=await J(`installing ${C.name}@${C.version}`,()=>he.deploy({...K,provenance:"marketplace",...N?{connectionId:N}:{}}));y(`installed ${C.name}@${C.version} \u2192 ${me.id} (status=${me.status}, ${me.outcome})`+(N?` bound to connection ${N}.`:"."))}catch(me){me instanceof Q&&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=zi();b||w(`marketplace not configured \u2014 set ${Tn} and ${Es}.
3551
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let x=qi(b.registryUrl);x&&w(x);let k=le(process.cwd(),d),m=await br(k),_=/\bdefineConduit\s*[<(]/.test(m)?"conduit":"hook",R={};if(h.manifest){let C=le(process.cwd(),h.manifest),M;try{M=await se.readFile(C,"utf8")}catch{w(`manifest not found at ${h.manifest}.`)}let N;try{N=JSON.parse(M)}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{xi(R,m)}catch(C){C instanceof Ut&&w(C.message),w(`manifest validation failed: ${C instanceof Error?C.message:String(C)}`)}let A=new fr(b);try{await J(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:_,bundle:m,manifest:R}))}catch(C){C instanceof Q&&C.status===403&&w("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),C instanceof Q&&C.status===409&&w(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),w(`publish failed: ${C instanceof Error?C.message:String(C)}`)}let I=ks(R);y(`published ${h.name}@${h.pkgVersion} (kind=${_}) to the marketplace.`),I.length>0&&y(` declares ${I.length} connection input(s): ${I.map(C=>C.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,k=0,m=0;for(let _ of b){let R=le(process.cwd(),_.path),A=await Ob(R,_);A==="wrote"?(x+=1,y(` wrote ${_.path}`)):A==="merged"?(m+=1,y(` merged ${_.path} (added the .mcp.json rule)`)):(k+=1,y(` skipped ${_.path} (exists)`))}y(`
3552
+ project init: ${x} written, ${m} merged, ${k} skipped.`)}),r.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Xi} (non-destructive).`).action(async()=>{let d=_u(),h=0,b=0;for(let x of d){let k=le(process.cwd(),x.path);await lr(k,x.content,x.executable)==="wrote"?(h+=1,y(` wrote ${x.path}`)):(b+=1,y(` skipped ${x.path} (exists)`))}y(`
3553
3553
  project ci: ${h} written, ${b} skipped.`),h>0&&(y(`
3554
- 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."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async d=>{let{baseUrl:h,token:b}=await V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=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(k.length===0){y("no records in the instance catalog \u2014 nothing to generate.");return}let m=le(process.cwd(),d.out),_=nu(k,{event:d.event}),R=0,A=0;for(let{recordType:I,fixture:C}of _){let q=Ye(m,`${I}.json`),N=`${JSON.stringify(C,null,2)}
3555
- `;d.force?(await se.mkdir(an(q),{recursive:!0}),await se.writeFile(q,N,{mode:420}),R+=1,y(` wrote ${d.out}/${I}.json`)):await ln(q,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(`
3556
- samples init: ${R} written, ${A} skipped.`)});let Ze=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),dn=d=>[d.name??f.dim(d.id.slice(0,8)),d.status==="active"?f.green("active"):d.status==="proposed"?f.yellow("proposed"):f.dim("inactive"),d.decision==="deny"?f.red(d.decision):d.decision==="require_confirm"?f.yellow(d.decision):f.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??f.dim("any"),d.when||f.dim("(always)"),d.reason??""],bs=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Ze.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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.guardrailsList()}catch(m){G(m,"extensions:deploy","list guardrails"),w(`list guardrails failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3557
- `+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(pt(k.map(dn),{head:bs})),y(f.dim(" first match wins; lower PRIO is evaluated first."))}),Ze.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(_){G(_,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} created${m.status==="active"?"":f.dim(` (${m.status} \u2014 activate it to take effect)`)}`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.actor?` actor=${m.actor}`:""}${m.when?` where ${m.when}`:""} @prio ${m.priority}`)),y(f.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),Ze.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(_){G(_,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} updated`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.when?` where ${m.when}`:""} @prio ${m.priority}`))});for(let[d,h,b]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Ze.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,k)=>{let{baseUrl:m,token:_}=await V(k.baseUrl),R=new F({baseUrl:m,token:_});try{await R.guardrailUpdate(x,{status:h})}catch(A){G(A,"extensions:deploy",`${d} a guardrail`),w(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(x)} ${b}`),h==="inactive"&&y(f.dim(" writes it was gating now fall through to the other rules."))});Ze.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 V(h.baseUrl),k=new F({baseUrl:b,token:x});try{await k.guardrailDelete(d)}catch(m){G(m,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),Ze.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await k.guardrailPostureGet()}catch(I){G(I,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}y(`guardrail posture: ${f.bold(m(A.mode))}`),y(f.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let _=d.trim().toLowerCase();_!=="allow"&&_!=="deny"&&w("posture must be 'allow' or 'deny'.");let R;try{R=await k.guardrailPostureSet(_)}catch(A){G(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail posture set to ${f.bold(m(R.mode))}`),R.mode==="deny"&&y(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Ze.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 V(d.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){G(R,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return y(JSON.stringify(m,null,2));let _=`${d.source}/${m.op??d.record}`;m.degraded?(y(`${f.red("\u2717")} ${_} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(f.dim(` ${m.reason}`))):m.allowed?y(`${f.green("\u2713")} ${_} \u2014 ${m.decision}`+(m.blockedBy?f.dim(` (rule ${m.blockedBy})`):f.dim(" (no rule matched)"))):(y(`${f.red("\u2717")} ${_} \u2014 ${m.decision} by ${f.bold(m.blockedBy??"?")} at the ${m.phase} gate`),m.message&&y(f.dim(` ${m.message}`))),m.decision==="require_confirm"&&y(f.yellow(" this write is HELD for operator approval, not refused.")),m.allowed||(process.exitCode=1)});let Ut=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Sr=(d,h={})=>{let b=`${f.bold(d.table)} ${f.dim(d.displayName)}`;y(d.exists===!1?`${b} ${f.dim("(new)")}`:b);for(let x of d.fields){let k=[x.required?"required":null].filter(Boolean).join(", "),m=h.showClaimants&&x.claimedBy?.length?` ${f.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";y(` ${x.column.padEnd(28)} ${x.type}${k?` (${k})`:""}${m}`)}h.showClaimants&&d.claimants.length>1&&y(f.dim(` claimed by ${d.claimants.join(", ")}`))};function ys(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 Sd=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(m){w(`${h} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let k=x.tables;return k===void 0?{tables:[],manifestPath:h}:(Array.isArray(k)||w(`${h}: "tables" must be an array.`),{tables:k,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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.tablesList()}catch(m){G(m,"extensions:deploy","list tables"),w(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(pt(k.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.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 Sd(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:k}=await V(h.baseUrl),m=new F({baseUrl:x,token:k}),_;try{_=await J("planning tables",()=>m.tablesPlan({claimedBy:h.as,tables:b.tables}))}catch(R){G(R,"extensions:deploy","plan tables"),ys(R)}y(`claiming as ${f.bold(_.claimedBy)}`);for(let R of _.tables)Sr(R,{showClaimants:!0});y(""),y(f.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 Sd(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:k}=await V(h.baseUrl),m=new F({baseUrl:x,token:k}),_;try{_=await J("applying tables",()=>m.tablesApply({claimedBy:h.as,tables:b.tables}))}catch(R){G(R,"extensions:deploy","apply tables"),ys(R)}for(let R of _.tables)Sr(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,C]=R.split(":");return(!A||!I)&&w(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),C!==void 0&&C!=="required"&&w(`--field "${R}": the third part may only be "required".`),{name:A,type:I,...C==="required"?{required:!0}:{}}}),{baseUrl:x,token:k}=await V(h.baseUrl),m=new F({baseUrl:x,token:k}),_;try{_=await J(`creating cr_${d}`,()=>m.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:b,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){G(R,"extensions:deploy","create a table"),ys(R)}for(let R of _.tables)Sr(R);y(""),y(f.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await J(`dropping cr_${d}`,()=>k.tablesDrop(d,h.confirm))}catch(_){G(_,"extensions:deploy","drop a table"),w(`drop failed: ${_ instanceof Error?_.message:String(_)}`)}if(!m.removed)return y(`no table named "${d}" on this instance \u2014 nothing dropped.`);y(`dropped ${m.table} and every row in it.`)});let ki=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ki.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=bd(),b;try{b=await Tp(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(x){x instanceof $n&&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}`)}),ki.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=bd();await ya(h).catch(()=>[]);let b;try{b=await Rp(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}).`)}),ki.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=bd(),h=await ya(d).catch(()=>[]),b=await Ws(),{active:x}=ba(b);if(x.length===0)y("no active sandboxes.");else{for(let k of x)y(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);y(`
3558
- ${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.",Us).action(async d=>{let{baseUrl:h,token:b}=await V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=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 m=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
3559
- `,_=le(process.cwd(),d.out,wn);await se.mkdir(an(_),{recursive:!0}),await se.writeFile(_,m,"utf8"),y(`wrote ${d.out}/${wn} (${m.split(`
3560
- `).length} lines).`)});let _d=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Nb=[{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(o0(),".turbobase"),Lb=()=>"1.6.5",ws=async()=>Promise.all(Nb.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));_d.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await ws();for(let h of d)y(`${h.present?ve.success("installed"):ve.warn("missing")} ${f.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3561
- run \`${vn} ext extras install\` to fetch them into ${$d()}.`)}),_d.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await ws();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=ua(process.platform,process.arch),k=async(A,I)=>{let{code:C,stderr:q}=await gs("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);C!==0&&w(`extras install failed while installing ${I} (npm exited ${C}).
3562
- ${q.trim()}
3563
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=b.filter(A=>A!=="isolated-vm");if(m.length>0){let A=m.map(I=>`${I}@${ca[I]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await k(A,m.join(", "))}if(b.includes("isolated-vm")){let A=`isolated-vm@${ca["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await k(["--ignore-scripts",A],"isolated-vm"),wp.includes(x)){let C=`${da}@${Lb()}`;y(`fetching ${C} (no upstream binary for ${x}) \u2026`);let{code:q}=await gs("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",C]);q!==0&&y(ve.warn(`could not fetch ${C} \u2014 falling back to a source build.`))}let I=await vp({home:h});I.length>0&&y(` ${ve.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let _=await ws(),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} (${pa()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await gs("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(_=await ws(),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} (${pa()}), 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 _r=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return _r.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 v0(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 m=(d.ref?await yd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await yd(["rev-parse","HEAD"]),_=d.gitRepo??process.env.GITHUB_REPOSITORY??await yd(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:I,token:C}=await V(d.baseUrl),q=new F({baseUrl:I,token:C}),N;try{N=await q.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:x>0?b:null,gitRepo:_,gitRef:R,gitSha:m,prUrl:A})}catch(K){G(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 sa(()=>q.releaseStatus(N.releaseId),`release ${N.releaseId}`,d.intervalMs)}),_r.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.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.`),G(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",m.owned],["context",m.context]])for(let[C,q]of Object.entries(I)){let N=Ye(_,A,C);await se.mkdir(an(N),{recursive:!0}),await se.writeFile(N,q,"utf8"),R++}await se.writeFile(Ye(_,".turbobase-release.json"),JSON.stringify({releaseId:m.releaseId,version:m.version,contentDigest:m.contentDigest},null,2),"utf8"),y(`pulled release ${m.releaseId} (${m.status}) \u2192 ${_}
3554
+ 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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.catalogRecords()}catch(I){I instanceof Q&&(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(k.length===0){y("no records in the instance catalog \u2014 nothing to generate.");return}let m=le(process.cwd(),d.out),_=iu(k,{event:d.event}),R=0,A=0;for(let{recordType:I,fixture:C}of _){let M=Ye(m,`${I}.json`),N=`${JSON.stringify(C,null,2)}
3555
+ `;d.force?(await se.mkdir(ar(M),{recursive:!0}),await se.writeFile(M,N,{mode:420}),R+=1,y(` wrote ${d.out}/${I}.json`)):await lr(M,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(`
3556
+ samples init: ${R} written, ${A} skipped.`)});let Ze=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),dr=d=>[d.name??f.dim(d.id.slice(0,8)),d.status==="active"?f.green("active"):d.status==="proposed"?f.yellow("proposed"):f.dim("inactive"),d.decision==="deny"?f.red(d.decision):d.decision==="require_confirm"?f.yellow(d.decision):f.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??f.dim("any"),d.when||f.dim("(always)"),d.reason??""],bs=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Ze.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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.guardrailsList()}catch(m){G(m,"extensions:deploy","list guardrails"),w(`list guardrails failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y(`no write guardrails \u2014 every record the admin entitlement allows is writable.
3557
+ `+f.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(pt(k.map(dr),{head:bs})),y(f.dim(" first match wins; lower PRIO is evaluated first."))}),Ze.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(_){G(_,"extensions:deploy","create a guardrail"),w(`create guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} created${m.status==="active"?"":f.dim(` (${m.status} \u2014 activate it to take effect)`)}`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.actor?` actor=${m.actor}`:""}${m.when?` where ${m.when}`:""} @prio ${m.priority}`)),y(f.dim(` verify with: turbobase guardrails test --source ${m.source==="*"?"<source>":m.source} --record <record>`))}),Ze.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(_){G(_,"extensions:deploy","edit a guardrail"),w(`edit guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(m.name??m.id)} updated`),y(f.dim(` ${m.decision} ${m.source}/${m.record??m.op}${m.when?` where ${m.when}`:""} @prio ${m.priority}`))});for(let[d,h,b]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Ze.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,k)=>{let{baseUrl:m,token:_}=await V(k.baseUrl),R=new F({baseUrl:m,token:_});try{await R.guardrailUpdate(x,{status:h})}catch(A){G(A,"extensions:deploy",`${d} a guardrail`),w(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(x)} ${b}`),h==="inactive"&&y(f.dim(" writes it was gating now fall through to the other rules."))});Ze.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 V(h.baseUrl),k=new F({baseUrl:b,token:x});try{await k.guardrailDelete(d)}catch(m){G(m,"extensions:deploy","delete a guardrail"),w(`delete guardrail failed: ${m instanceof Error?m.message:String(m)}`)}y(`${f.green("\u2713")} guardrail ${f.bold(d)} deleted`)}),Ze.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await k.guardrailPostureGet()}catch(I){G(I,"extensions:deploy","read the guardrail posture"),w(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}y(`guardrail posture: ${f.bold(m(A.mode))}`),y(f.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let _=d.trim().toLowerCase();_!=="allow"&&_!=="deny"&&w("posture must be 'allow' or 'deny'.");let R;try{R=await k.guardrailPostureSet(_)}catch(A){G(A,"extensions:deploy","set the guardrail posture"),w(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${f.green("\u2713")} guardrail posture set to ${f.bold(m(R.mode))}`),R.mode==="deny"&&y(f.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Ze.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 V(d.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.guardrailTest({source:d.source,record:d.record,...d.actor?{actor:d.actor}:{},...d.externalId?{externalId:d.externalId}:{},...h?{fields:h}:{},...d.op?{op:d.op}:{},...d.phase?{phase:d.phase}:{}})}catch(R){G(R,"extensions:deploy","test guardrails"),w(`guardrails test failed: ${R instanceof Error?R.message:String(R)}`)}if(d.json)return y(JSON.stringify(m,null,2));let _=`${d.source}/${m.op??d.record}`;m.degraded?(y(`${f.red("\u2717")} ${_} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(f.dim(` ${m.reason}`))):m.allowed?y(`${f.green("\u2713")} ${_} \u2014 ${m.decision}`+(m.blockedBy?f.dim(` (rule ${m.blockedBy})`):f.dim(" (no rule matched)"))):(y(`${f.red("\u2717")} ${_} \u2014 ${m.decision} by ${f.bold(m.blockedBy??"?")} at the ${m.phase} gate`),m.message&&y(f.dim(` ${m.message}`))),m.decision==="require_confirm"&&y(f.yellow(" this write is HELD for operator approval, not refused.")),m.allowed||(process.exitCode=1)});let Dt=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),_n=(d,h={})=>{let b=`${f.bold(d.table)} ${f.dim(d.displayName)}`;y(d.exists===!1?`${b} ${f.dim("(new)")}`:b);for(let x of d.fields){let k=[x.required?"required":null].filter(Boolean).join(", "),m=h.showClaimants&&x.claimedBy?.length?` ${f.dim(`\u2190 ${x.claimedBy.join(", ")}`)}`:"";y(` ${x.column.padEnd(28)} ${x.type}${k?` (${k})`:""}${m}`)}h.showClaimants&&d.claimants.length>1&&y(f.dim(` claimed by ${d.claimants.join(", ")}`))};function ys(d){if(d instanceof Q&&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 xd=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(m){w(`${h} is not valid JSON: ${m instanceof Error?m.message:String(m)}`)}let k=x.tables;return k===void 0?{tables:[],manifestPath:h}:(Array.isArray(k)||w(`${h}: "tables" must be an array.`),{tables:k,manifestPath:h})};Dt.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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.tablesList()}catch(m){G(m,"extensions:deploy","list tables"),w(`list tables failed: ${m instanceof Error?m.message:String(m)}`)}if(d.json)return y(JSON.stringify(k,null,2));if(k.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(pt(k.map(m=>[m.table,m.displayName,String(m.fields.length),m.status,m.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),Dt.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 xd(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:k}=await V(h.baseUrl),m=new F({baseUrl:x,token:k}),_;try{_=await J("planning tables",()=>m.tablesPlan({claimedBy:h.as,tables:b.tables}))}catch(R){G(R,"extensions:deploy","plan tables"),ys(R)}y(`claiming as ${f.bold(_.claimedBy)}`);for(let R of _.tables)_n(R,{showClaimants:!0});y(""),y(f.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),Dt.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 xd(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:k}=await V(h.baseUrl),m=new F({baseUrl:x,token:k}),_;try{_=await J("applying tables",()=>m.tablesApply({claimedBy:h.as,tables:b.tables}))}catch(R){G(R,"extensions:deploy","apply tables"),ys(R)}for(let R of _.tables)_n(R,{showClaimants:!0});y(`applied ${_.tables.length} table${_.tables.length===1?"":"s"} as ${_.claimedBy}.`)}),Dt.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,C]=R.split(":");return(!A||!I)&&w(`--field "${R}" must be name:type[:required] (e.g. title:text:required).`),C!==void 0&&C!=="required"&&w(`--field "${R}": the third part may only be "required".`),{name:A,type:I,...C==="required"?{required:!0}:{}}}),{baseUrl:x,token:k}=await V(h.baseUrl),m=new F({baseUrl:x,token:k}),_;try{_=await J(`creating cr_${d}`,()=>m.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:b,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(R){G(R,"extensions:deploy","create a table"),ys(R)}for(let R of _.tables)_n(R);y(""),y(f.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),Dt.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await J(`dropping cr_${d}`,()=>k.tablesDrop(d,h.confirm))}catch(_){G(_,"extensions:deploy","drop a table"),w(`drop failed: ${_ instanceof Error?_.message:String(_)}`)}if(!m.removed)return y(`no table named "${d}" on this instance \u2014 nothing dropped.`);y(`dropped ${m.table} and every row in it.`)});let ki=e.command("sandbox").description("Ephemeral local authoring sandboxes.");ki.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=vd(),b;try{b=await Pp(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(x){x instanceof $r&&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}`)}),ki.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=vd();await ka(h).catch(()=>[]);let b;try{b=await Ap(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}).`)}),ki.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=vd(),h=await ka(d).catch(()=>[]),b=await Ws(),{active:x}=va(b);if(x.length===0)y("no active sandboxes.");else{for(let k of x)y(` ${k.name} from=${k.fromTenant} expires=${k.expiresAt} ${k.url}`);y(`
3558
+ ${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.",Ds).action(async d=>{let{baseUrl:h,token:b}=await V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await J("exporting instance config",()=>x.configExport())}catch(R){R instanceof Q&&(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 m=typeof k.serialized=="string"?k.serialized:`${JSON.stringify(k.manifest??k,null,2)}
3559
+ `,_=le(process.cwd(),d.out,wr);await se.mkdir(ar(_),{recursive:!0}),await se.writeFile(_,m,"utf8"),y(`wrote ${d.out}/${wr} (${m.split(`
3560
+ `).length} lines).`)});let Td=s.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),jb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Rd=()=>process.env.TURBOBASE_HOME?.trim()||Ye(a0(),".turbobase"),Db=()=>"1.6.6",ws=async()=>Promise.all(jb.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Td.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await ws();for(let h of d)y(`${h.present?ve.success("installed"):ve.warn("missing")} ${f.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
3561
+ run \`${vr} ext extras install\` to fetch them into ${Rd()}.`)}),Td.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await ws();if(d.every(A=>A.present)){y(ve.success("extras already installed \u2014 nothing to do."));return}let h=Rd();await se.mkdir(h,{recursive:!0});let b=d.filter(A=>!A.present).map(A=>A.name),x=fa(process.platform,process.arch),k=async(A,I)=>{let{code:C,stderr:M}=await gs("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);C!==0&&w(`extras install failed while installing ${I} (npm exited ${C}).
3562
+ ${M.trim()}
3563
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},m=b.filter(A=>A!=="isolated-vm");if(m.length>0){let A=m.map(I=>`${I}@${pa[I]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await k(A,m.join(", "))}if(b.includes("isolated-vm")){let A=`isolated-vm@${pa["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await k(["--ignore-scripts",A],"isolated-vm"),Sp.includes(x)){let C=`${ha}@${Db()}`;y(`fetching ${C} (no upstream binary for ${x}) \u2026`);let{code:M}=await gs("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",C]);M!==0&&y(ve.warn(`could not fetch ${C} \u2014 falling back to a source build.`))}let I=await _p({home:h});I.length>0&&y(` ${ve.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${x}`)}let _=await ws(),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} (${ma()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await gs("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(_=await ws(),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} (${ma()}), 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 $n=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");return $n.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 S0(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 m=(d.ref?await kd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await kd(["rev-parse","HEAD"]),_=d.gitRepo??process.env.GITHUB_REPOSITORY??await kd(["remote","get-url","origin"]),R=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:I,token:C}=await V(d.baseUrl),M=new F({baseUrl:I,token:C}),N;try{N=await M.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:x>0?b:null,gitRepo:_,gitRef:R,gitSha:m,prUrl:A})}catch(K){G(K,"releases:write","release deploy"),K instanceof Q&&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 sa(()=>M.releaseStatus(N.releaseId),`release ${N.releaseId}`,d.intervalMs)}),$n.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.releaseFiles(d)}catch(A){A instanceof Q&&A.status===404&&w(`release ${d} not found.`),A instanceof Q&&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.`),G(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",m.owned],["context",m.context]])for(let[C,M]of Object.entries(I)){let N=Ye(_,A,C);await se.mkdir(ar(N),{recursive:!0}),await se.writeFile(N,M,"utf8"),R++}await se.writeFile(Ye(_,".turbobase-release.json"),JSON.stringify({releaseId:m.releaseId,version:m.version,contentDigest:m.contentDigest},null,2),"utf8"),y(`pulled release ${m.releaseId} (${m.status}) \u2192 ${_}
3564
3564
  ${Object.keys(m.owned).length} owned file(s), ${Object.keys(m.context).length} context file(s), ${R} total
3565
3565
  `+(m.logTail?`
3566
3566
  the failure these bytes produced:
3567
3567
  ${m.logTail.trim()}
3568
3568
  `:"")+`
3569
3569
  edit the files under owned/, then:
3570
- turbobase release push ${m.releaseId} --dir ${h.dir}`)}),_r.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m=le(process.cwd(),h.dir),_;try{_=await k.releaseFiles(d)}catch(N){N instanceof X&&N.status===404&&w(`release ${d} not found.`),G(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(m,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:
3570
+ turbobase release push ${m.releaseId} --dir ${h.dir}`)}),$n.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m=le(process.cwd(),h.dir),_;try{_=await k.releaseFiles(d)}catch(N){N instanceof Q&&N.status===404&&w(`release ${d} not found.`),G(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(m,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:
3571
3571
  `+A.map(N=>` context/${N}`).join(`
3572
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let I={..._.context},C=0;for(let[N,K]of Object.entries(_.owned)){let he=await R("owned",N);I[N]=he??K,he!==null&&he!==K&&C++}C===0&&y("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let q=h.target==="approved"?"approved":"auto";try{let N=await k.releasePush(d,{files:I,target:q,...h.approvedBy?{approvedBy:h.approvedBy}:{}});y(`pushed ${Object.keys(I).length} file(s) (${C} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
3572
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let I={..._.context},C=0;for(let[N,K]of Object.entries(_.owned)){let he=await R("owned",N);I[N]=he??K,he!==null&&he!==K&&C++}C===0&&y("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let M=h.target==="approved"?"approved":"auto";try{let N=await k.releasePush(d,{files:I,target:M,...h.approvedBy?{approvedBy:h.approvedBy}:{}});y(`pushed ${Object.keys(I).length} file(s) (${C} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
3573
3573
  follow it with:
3574
- 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."),G(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),_r.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 V(h.baseUrl),k=new F({baseUrl:b,token:x});if(h.follow){await sa(()=>k.releaseStatus(d),`release ${d}`,h.intervalMs);return}let m;try{m=await k.releaseStatus(d)}catch(_){G(_,"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=${m.releaseStatus??"?"} stage=${m.stage} ${m.percent}%`+(m.runStatus?` (${m.runStatus})`:"")),m.outputTail&&y(m.outputTail.replace(/\n+$/,""))}),_r.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.releaseRollback(d)}catch(_){G(_,"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 ${m.releaseId} rolled back \u2192 status=${m.release?.status??"rolled_back"}.`)}),_r.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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.releaseList()}catch(m){G(m,"releases:write","release list"),w(`release list failed: ${m instanceof Error?m.message:String(m)}`)}if(k.length===0){y("no releases.");return}if(Ee())y(pt(k.map(m=>[m.id,Er(m.status),m.target,m.backend,m.solutionTitles?.length?m.solutionTitles.map(_=>`"${_}"`).join(", "):f.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let m of k){let _=m.solutionTitles?.length?` "${m.solutionTitles.join('", "')}"`:"";y(` ${m.id} ${m.status.padEnd(11)} target=${m.target} backend=${m.backend}${_}`)}y(`
3575
- ${k.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:h,token:b}=await V(d.baseUrl),x=new F({baseUrl:h,token:b}),k=d.limit?Number(d.limit):void 0,m=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await mu(x,d.conduit,{...d.follow?{follow:!0}:{},...k!==void 0?{limit:k}:{},...m!==void 0?{intervalMs:m}:{},sink:y})}catch(_){w(`logs --conduit failed: ${_ instanceof Error?_.message:String(_)}`)}return}if(d.extension){try{let _=await x.logs(d.extension,k);_.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 bu(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}:{},...k!==void 0?{limit:k}:{},...m!==void 0?{intervalMs:m}:{},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(()=>(Ib(),Ab));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(`
3576
- `)),t&&void 0,e}function m0(t,e,r){let n=s=>{let o=new RegExp(`${s}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return o?o[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function g0(t){let e=Ye(le(process.cwd(),t),"public","turbobase.json"),r=await se.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(s){w(`${e} is not valid JSON: ${s instanceof Error?s.message:String(s)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&w(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function b0(){let t=le(process.cwd(),Us,wn),e;try{e=await se.readFile(t,"utf8")}catch{w(`no config found \u2014 this project authors none (no ${Ms}/, ${zs}/, ${Ft} or ${Ht}) and there is no ${Us}/${wn}.
3577
- Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Eu(e)}catch(r){w(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function gd(){let t=process.cwd();if(!await Iu(t))return b0();let e;try{e=await Cu(t)}catch(r){w(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)L(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&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 y0(t,e){y(`plan against ${e}:`);for(let r of t.add)y(` ${qt.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)y(` ${qt.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)y(` ${qt.destroy(`${r.kind} ${r.id}`)}`);y(`
3578
- ${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 w0(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function gs(t,e,r){return new Promise(n=>{let s=vd(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),o="";s.stderr?.on("data",i=>{let a=i.toString();o+=a,process.stderr.write(a)}),s.on("error",i=>n({code:-1,stderr:i.message})),s.on("exit",i=>n({code:i??-1,stderr:o}))})}function bd(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let s=n?t.replace(/\/[^/]*$/,`/${n}`):t,o=await gs("psql",[s,"-v","ON_ERROR_STOP=1","-c",r]);if(o.code!==0)throw new Error(`psql failed (exit ${o.code}): ${o.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),s=await gs("supabase",["migration","up","--db-url",n]);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 r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,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.${n} (${o.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function v0(t){let e=le(t,"src"),r={},n=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 n(a);else if(i.isFile()){let l=vi(e,a).split(wd).join("/");r[l]=await se.readFile(a,"utf8")}}};return await n(e),r}function yd(t){return new Promise(e=>{let r=vd("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",s=>{n+=s.toString()}),r.on("error",()=>e(null)),r.on("exit",s=>e(s===0&&n.trim()?n.trim():null))})}var k0=!1;k0&&kd().parseAsync(process.argv).catch(t=>w(t instanceof Error?t.message:String(t)));kd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3574
+ turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof Q&&N.status===403&&w("an approved target needs --approved-by (the deploy gate fails closed)."),N instanceof Q&&N.status===409&&w("that solution already has an active release \u2014 roll it back or wait for it."),G(N,"releases:write","push a release"),w(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),$n.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 V(h.baseUrl),k=new F({baseUrl:b,token:x});if(h.follow){await sa(()=>k.releaseStatus(d),`release ${d}`,h.intervalMs);return}let m;try{m=await k.releaseStatus(d)}catch(_){G(_,"releases:write","release status"),_ instanceof Q&&_.status===404&&w(`release ${d} not found.`),w(`release status failed: ${_ instanceof Error?_.message:String(_)}`)}y(`release ${d}: status=${m.releaseStatus??"?"} stage=${m.stage} ${m.percent}%`+(m.runStatus?` (${m.runStatus})`:"")),m.outputTail&&y(m.outputTail.replace(/\n+$/,""))}),$n.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 V(h.baseUrl),k=new F({baseUrl:b,token:x}),m;try{m=await k.releaseRollback(d)}catch(_){G(_,"releases:write","release rollback"),_ instanceof Q&&_.status===404&&w(`release ${d} not found.`),_ instanceof Q&&_.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 ${m.releaseId} rolled back \u2192 status=${m.release?.status??"rolled_back"}.`)}),$n.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 V(d.baseUrl),x=new F({baseUrl:h,token:b}),k;try{k=await x.releaseList()}catch(m){G(m,"releases:write","release list"),w(`release list failed: ${m instanceof Error?m.message:String(m)}`)}if(k.length===0){y("no releases.");return}if(Ee())y(pt(k.map(m=>[m.id,Pn(m.status),m.target,m.backend,m.solutionTitles?.length?m.solutionTitles.map(_=>`"${_}"`).join(", "):f.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let m of k){let _=m.solutionTitles?.length?` "${m.solutionTitles.join('", "')}"`:"";y(` ${m.id} ${m.status.padEnd(11)} target=${m.target} backend=${m.backend}${_}`)}y(`
3575
+ ${k.length} release(s).`)}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:h,token:b}=await V(d.baseUrl),x=new F({baseUrl:h,token:b}),k=d.limit?Number(d.limit):void 0,m=d.intervalMs?Number(d.intervalMs):void 0;if(d.conduit){try{await yu(x,d.conduit,{...d.follow?{follow:!0}:{},...k!==void 0?{limit:k}:{},...m!==void 0?{intervalMs:m}:{},sink:y})}catch(_){w(`logs --conduit failed: ${_ instanceof Error?_.message:String(_)}`)}return}if(d.extension){try{let _=await x.logs(d.extension,k);_.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 vu(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}:{},...k!==void 0?{limit:k}:{},...m!==void 0?{intervalMs:m}:{},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(()=>(Cb(),Ib));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(`
3576
+ `)),t&&void 0,e}function b0(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 y0(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 w0(){let t=le(process.cwd(),Ds,wr),e;try{e=await se.readFile(t,"utf8")}catch{w(`no config found \u2014 this project authors none (no ${zs}/, ${qs}/, ${Ft} or ${Ht}) and there is no ${Ds}/${wr}.
3577
+ Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Iu(e)}catch(n){w(`bundle is invalid: ${n instanceof Error?n.message:String(n)}`)}}async function wd(){let t=process.cwd();if(!await Nu(t))return w0();let e;try{e=await Lu(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 v0(t,e){y(`plan against ${e}:`);for(let n of t.add)y(` ${Mt.add(`${n.kind} ${n.id}`)}`);for(let n of t.change)y(` ${Mt.change(`${n.kind} ${n.id}`)}`);for(let n of t.destroy)y(` ${Mt.destroy(`${n.kind} ${n.id}`)}`);y(`
3578
+ ${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 k0(t){try{let n=new URL(t).hostname.split(".")[0];return n&&n!=="localhost"?n:void 0}catch{return}}function gs(t,e,n){return new Promise(r=>{let s=_d(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 vd(){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 gs("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 gs("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 S0(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=vi(e,a).split(Sd).join("/");n[l]=await se.readFile(a,"utf8")}}};return await r(e),n}function kd(t){return new Promise(e=>{let n=_d("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 _0=!1;_0&&$d().parseAsync(process.argv).catch(t=>w(t instanceof Error?t.message:String(t)));$d().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
3579
3579
  `),process.exit(1)});