@turbobase/cli 1.40.1 → 1.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/turbobase.js CHANGED
@@ -1,29 +1,29 @@
1
1
  #!/usr/bin/env node
2
2
  import { createRequire as __tbCreateRequire } from 'node:module';
3
3
  const require = __tbCreateRequire(import.meta.url);
4
- var tw=Object.create;var zi=Object.defineProperty;var rw=Object.getOwnPropertyDescriptor;var nw=Object.getOwnPropertyNames;var ow=Object.getPrototypeOf,sw=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),eu=(t,e)=>{for(var r in e)zi(t,r,{get:e[r],enumerable:!0})},iw=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nw(e))!sw.call(t,o)&&o!==r&&zi(t,o,{get:()=>e[o],enumerable:!(n=rw(e,o))||n.enumerable});return t};var tu=(t,e,r)=>(r=t!=null?tw(ow(t)):{},iw(e||!t||!t.__esModule?zi(r,"default",{value:t,enumerable:!0}):r,t));function pr(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var bn=j(()=>{});import{z as hr}from"zod";function Ao(t){let e=Bi.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Fi(t,e){let r=Bi.safeParse(t);if(!r.success)throw new Kt(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(ru.test(e))throw new Kt('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(ru.test(n))throw new Kt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var nu,ou,Bi,Kt,ru,su=j(()=>{nu=hr.object({type:hr.literal("connection"),source_system:hr.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:hr.string().min(1).max(200).optional()}),ou=hr.discriminatedUnion("type",[nu]),Bi=hr.object({inputs:hr.array(ou).optional()}).passthrough(),Kt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};ru=/\bconnection[_-]?id\b["']?\s*[:=]/i});var Co,Hi=j(()=>{Co=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Fe}from"zod";var Ki,iu,au=j(()=>{bn();Hi();Ki=Fe.object({id:Fe.string().min(1,"hook id must be non-empty"),recordType:Fe.union([Fe.string().min(1),Fe.array(Fe.string().min(1)).min(1),Fe.literal("*")]),event:Fe.enum(Co),source:Fe.string().min(1).optional(),when:Fe.unknown().optional(),run:Fe.unknown(),failClosed:Fe.boolean().optional(),timeoutMs:Fe.number().int().positive().optional(),description:Fe.string().optional(),systemReserved:Fe.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"})}),iu=pr({kind:"hook",schema:Ki,factoryName:"defineHook"})});var lu=j(()=>{au();Hi()});var Io,Vi=j(()=>{Io=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as ge}from"zod";var cu,cw,du,Gi,uu,pu=j(()=>{bn();Vi();cu=ge.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),cw=ge.object({recordType:ge.string().min(1,"reads[].recordType must be non-empty"),source:ge.string().min(1).optional(),columns:ge.array(cu).min(1,"reads[].columns must name at least one column"),by:ge.array(cu).optional(),maxRows:ge.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),du=ge.object({source:ge.string().min(1,"to.source must be non-empty"),recordType:ge.string().min(1,"to.recordType must be non-empty")}),Gi=ge.object({id:ge.string().min(1,"conduit id must be non-empty"),on:ge.enum(Io),from:ge.object({source:ge.string().min(1,"from.source must be non-empty"),recordType:ge.string().min(1,"from.recordType must be non-empty"),when:ge.unknown().optional()}),to:du.optional(),mode:ge.enum(["dual-bind","one-shot"]).optional(),transform:ge.unknown().optional(),sequence:ge.array(ge.object({to:du,transform:ge.unknown(),awaitSource:ge.boolean().optional()})).optional(),reads:ge.array(cw).optional(),maxQueriesPerRun:ge.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:ge.unknown().optional(),cycleBudget:ge.number().int().positive().optional(),conflictStrategy:ge.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:ge.number().int().positive().optional(),description:ge.string().optional(),systemReserved:ge.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((u,p)=>{typeof u.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),r.from?.source&&u.to?.source&&r.from.source===u.to.source&&e.addIssue({code:"custom",path:["sequence",p,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,l=r.to;a?.source&&l?.source&&a.source===l.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),uu=pr({kind:"conduit",schema:Gi,factoryName:"defineConduit"})});var hu=j(()=>{pu();Vi()});import{z as ye}from"zod";function fu(t,e,r){let n=e;(typeof n.recordType!="string"||n.recordType.length===0)&&t.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),typeof n.build!="function"&&t.addIssue({code:"custom",path:[...r,"build"],message:"build must be a function"}),n.when!==void 0&&typeof n.when!="function"&&t.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"});let o=n.update;if(o){for(let s of["pgRowId","externalId","expectedSyncVersion"]){let i=o[s];i!==void 0&&typeof i!="function"&&t.addIssue({code:"custom",path:[...r,"update",s],message:`update.${s} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}o.step===void 0&&o.pgRowId===void 0&&o.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function yw(t,e,r){e.forEach===void 0&&t.addIssue({code:"custom",path:["steps",r,"forEach"],message:"a step-list entry carrying nested steps must declare forEach.input, naming the input property to repeat over"});let n=e.steps;if(!Array.isArray(n)||n.length===0){t.addIssue({code:"custom",path:["steps",r,"steps"],message:"a repeated group needs at least one step in it, or it writes nothing at all"});return}let o=new Map;n.forEach((s,i)=>{fu(t,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let l=o.get(a);l!==void 0?t.addIssue({code:"custom",path:["steps",r,"steps"],message:`duplicate step id '${a}' (steps ${l} and ${i}) \u2014 step ids must be unique within a repeated group`}):o.set(a,i)})}var mu,fw,gw,Wi,gu,yu=j(()=>{bn();mu={id:ye.string().min(1,"step id must be non-empty"),recordType:ye.string().min(1,"step.recordType must be non-empty").optional(),awaitSource:ye.boolean().optional(),update:ye.object({step:ye.string().min(1,"update.step must name an earlier step").optional(),pgRowId:ye.unknown().optional(),externalId:ye.unknown().optional(),expectedSyncVersion:ye.unknown().optional()}).optional(),when:ye.unknown().optional(),rollback:ye.enum(["undo","keep"]).optional(),build:ye.unknown(),description:ye.string().optional()},fw=ye.object(mu),gw=ye.object({...mu,forEach:ye.object({input:ye.string().min(1,"forEach.input must name a property of the process input holding the array to repeat over")}).optional(),steps:ye.array(fw).optional()}),Wi=ye.object({id:ye.string().min(1,"process id must be non-empty"),input:ye.object({type:ye.literal("object"),properties:ye.record(ye.unknown()).optional(),required:ye.array(ye.string()).optional()}).passthrough(),steps:ye.array(gw).min(1,"a process needs at least one step"),eachRow:ye.object({outstanding:ye.unknown(),key:ye.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:ye.enum(["stop","rollback"]).optional(),description:ye.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(a.forEach!==void 0||a.steps!==void 0?yw(e,a,i):fu(e,s,["steps",i]),typeof a.id=="string"){let l=o.get(a.id);l!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${l} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})});gu=pr({kind:"process",schema:Wi,factoryName:"defineProcess"})});var bu=j(()=>{});var wu=j(()=>{yu();bu()});async function Sw(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 Lo(t,e={}){return(e.transform??Sw)(t)}var Ji=j(()=>{});function Yi(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 vu(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Xi(t){return`${vu(t.source)}${vu(t.recordType)}`}function kw(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Tw(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 Zi(t){let e=Xi(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]} */`:`/**
4
+ var lw=Object.create;var Fi=Object.defineProperty;var cw=Object.getOwnPropertyDescriptor;var dw=Object.getOwnPropertyNames;var uw=Object.getPrototypeOf,pw=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(t&&(e=t(t=0)),e);var q=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),su=(t,e)=>{for(var r in e)Fi(t,r,{get:e[r],enumerable:!0})},hw=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of dw(e))!pw.call(t,o)&&o!==r&&Fi(t,o,{get:()=>e[o],enumerable:!(n=cw(e,o))||n.enumerable});return t};var iu=(t,e,r)=>(r=t!=null?lw(uw(t)):{},hw(e||!t||!t.__esModule?Fi(r,"default",{value:t,enumerable:!0}):r,t));function hr(t){return Object.freeze({kind:t.kind,define:e=>e,schema:t.schema,factoryName:t.factoryName})}var wn=j(()=>{});import{z as mr}from"zod";function Oo(t){let e=Hi.safeParse(t);return e.success?(e.data.inputs??[]).filter(r=>r.type==="connection"):[]}function Ki(t,e){let r=Hi.safeParse(t);if(!r.success)throw new Gt(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(au.test(e))throw new Gt('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(au.test(n))throw new Gt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var lu,cu,Hi,Gt,au,du=j(()=>{lu=mr.object({type:mr.literal("connection"),source_system:mr.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:mr.string().min(1).max(200).optional()}),cu=mr.discriminatedUnion("type",[lu]),Hi=mr.object({inputs:mr.array(cu).optional()}).passthrough(),Gt=class extends Error{constructor(e){super(e),this.name="ManifestValidationError"}};au=/\bconnection[_-]?id\b["']?\s*[:=]/i});var No,Vi=j(()=>{No=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as He}from"zod";var Gi,uu,pu=j(()=>{wn();Vi();Gi=He.object({id:He.string().min(1,"hook id must be non-empty"),recordType:He.union([He.string().min(1),He.array(He.string().min(1)).min(1),He.literal("*")]),event:He.enum(No),source:He.string().min(1).optional(),when:He.unknown().optional(),run:He.unknown(),failClosed:He.boolean().optional(),timeoutMs:He.number().int().positive().optional(),description:He.string().optional(),systemReserved:He.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"})}),uu=hr({kind:"hook",schema:Gi,factoryName:"defineHook"})});var hu=j(()=>{pu();Vi()});var Lo,Wi=j(()=>{Lo=["after_canonicalize_inbound","after_sync_success_outbound"]});import{z as ge}from"zod";var mu,gw,fu,Ji,gu,yu=j(()=>{wn();Wi();mu=ge.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),gw=ge.object({recordType:ge.string().min(1,"reads[].recordType must be non-empty"),source:ge.string().min(1).optional(),columns:ge.array(mu).min(1,"reads[].columns must name at least one column"),by:ge.array(mu).optional(),maxRows:ge.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),fu=ge.object({source:ge.string().min(1,"to.source must be non-empty"),recordType:ge.string().min(1,"to.recordType must be non-empty")}),Ji=ge.object({id:ge.string().min(1,"conduit id must be non-empty"),on:ge.enum(Lo),from:ge.object({source:ge.string().min(1,"from.source must be non-empty"),recordType:ge.string().min(1,"from.recordType must be non-empty"),when:ge.unknown().optional()}),to:fu.optional(),mode:ge.enum(["dual-bind","one-shot"]).optional(),transform:ge.unknown().optional(),sequence:ge.array(ge.object({to:fu,transform:ge.unknown(),awaitSource:ge.boolean().optional()})).optional(),reads:ge.array(gw).optional(),maxQueriesPerRun:ge.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:ge.unknown().optional(),cycleBudget:ge.number().int().positive().optional(),conflictStrategy:ge.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:ge.number().int().positive().optional(),description:ge.string().optional(),systemReserved:ge.boolean().optional()}).superRefine((t,e)=>{let r=t,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?e.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?e.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&e.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((u,p)=>{typeof u.transform!="function"&&e.addIssue({code:"custom",path:["sequence",p,"transform"],message:"transform must be a function"}),r.from?.source&&u.to?.source&&r.from.source===u.to.source&&e.addIssue({code:"custom",path:["sequence",p,"to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})})):(r.to===void 0&&e.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&e.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=t.from?.when;s!==void 0&&typeof s!="function"&&e.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=t.idempotencyKey;i!==void 0&&typeof i!="function"&&e.addIssue({code:"custom",path:["idempotencyKey"],message:"idempotencyKey, when present, must be a function"});let a=r.from,l=r.to;a?.source&&l?.source&&a.source===l.source&&e.addIssue({code:"custom",path:["to","source"],message:"a conduit must bridge two DIFFERENT sources (from.source === to.source) \u2014 use a hook for an intra-source transform"})}),gu=hr({kind:"conduit",schema:Ji,factoryName:"defineConduit"})});var bu=j(()=>{yu();Wi()});import{z as ae}from"zod";function vu(t,e,r){let n=e;if((typeof n.recordType!="string"||n.recordType.length===0)&&t.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),n.when!==void 0&&typeof n.when!="function"&&t.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"}),n.delete!==void 0){Tw(t,n,r);return}n.onRefused!==void 0&&t.addIssue({code:"custom",path:[...r,"onRefused"],message:"onRefused is only honoured on a delete step \u2014 a refused write always ends the run. Remove it, or declare a `delete` block to make this a delete step"}),typeof n.build!="function"&&t.addIssue({code:"custom",path:[...r,"build"],message:"build must be a function"});let o=n.update;if(o){for(let s of["pgRowId","externalId","expectedSyncVersion"]){let i=o[s];i!==void 0&&typeof i!="function"&&t.addIssue({code:"custom",path:[...r,"update",s],message:`update.${s} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}o.step===void 0&&o.pgRowId===void 0&&o.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function Tw(t,e,r){e.build!==void 0&&t.addIssue({code:"custom",path:[...r,"build"],message:"a delete step has nothing to build \u2014 remove `build`, or remove `delete` to make this a write step"}),e.rollback==="undo"&&t.addIssue({code:"custom",path:[...r,"rollback"],message:"a delete cannot be undone, so a delete step is always rollback: 'keep'"});let n=e.delete??{};for(let o of["pgRowId","externalId"]){let s=n[o];s!==void 0&&typeof s!="function"&&t.addIssue({code:"custom",path:[...r,"delete",o],message:`delete.${o} must be a function of the step context \u2014 a declaration cannot know the value until the run`})}n.pgRowId===void 0&&n.externalId===void 0&&t.addIssue({code:"custom",path:[...r,"delete"],message:"delete must address a record: one of `pgRowId` or `externalId`"})}function Rw(t,e,r){e.forEach===void 0&&t.addIssue({code:"custom",path:["steps",r,"forEach"],message:"a step-list entry carrying nested steps must declare forEach.input, naming the input property to repeat over"});let n=e.steps;if(!Array.isArray(n)||n.length===0){t.addIssue({code:"custom",path:["steps",r,"steps"],message:"a repeated group needs at least one step in it, or it writes nothing at all"});return}let o=new Map;n.forEach((s,i)=>{vu(t,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let l=o.get(a);l!==void 0?t.addIssue({code:"custom",path:["steps",r,"steps"],message:`duplicate step id '${a}' (steps ${l} and ${i}) \u2014 step ids must be unique within a repeated group`}):o.set(a,i)})}var wu,Sw,kw,Yi,_u,Su=j(()=>{wn();wu={id:ae.string().min(1,"step id must be non-empty"),recordType:ae.string().min(1,"step.recordType must be non-empty").optional(),awaitSource:ae.boolean().optional(),update:ae.object({step:ae.string().min(1,"update.step must name an earlier step").optional(),pgRowId:ae.unknown().optional(),externalId:ae.unknown().optional(),expectedSyncVersion:ae.unknown().optional()}).optional(),when:ae.unknown().optional(),rollback:ae.enum(["undo","keep"]).optional(),onRefused:ae.enum(["continue","stop"]).optional(),delete:ae.object({pgRowId:ae.unknown().optional(),externalId:ae.unknown().optional(),sourceSystem:ae.string().min(1,"delete.sourceSystem must name a connected system").optional()}).optional(),build:ae.unknown(),description:ae.string().optional()},Sw=ae.object(wu),kw=ae.object({...wu,forEach:ae.object({input:ae.string().min(1,"forEach.input must name a property of the process input holding the array to repeat over")}).optional(),steps:ae.array(Sw).optional()}),Yi=ae.object({id:ae.string().min(1,"process id must be non-empty"),input:ae.object({type:ae.literal("object"),properties:ae.record(ae.unknown()).optional(),required:ae.array(ae.string()).optional()}).passthrough(),steps:ae.array(kw).min(1,"a process needs at least one step"),eachRow:ae.object({outstanding:ae.unknown(),key:ae.string().min(1,"eachRow.key must name the column that identifies an outstanding row")}).optional(),onFailure:ae.enum(["stop","rollback"]).optional(),description:ae.string().optional()}).superRefine((t,e)=>{let r=t.eachRow;r&&typeof r.outstanding!="function"&&e.addIssue({code:"custom",path:["eachRow","outstanding"],message:"eachRow.outstanding must be a function returning one PostgREST query for the rows still to migrate"});let n=t.steps;if(!Array.isArray(n))return;let o=new Map;n.forEach((s,i)=>{let a=s;if(a.forEach!==void 0||a.steps!==void 0?Rw(e,a,i):vu(e,s,["steps",i]),typeof a.id=="string"){let l=o.get(a.id);l!==void 0?e.addIssue({code:"custom",path:["steps"],message:`duplicate step id '${a.id}' (steps ${l} and ${i}) \u2014 step ids must be unique within a process`}):o.set(a.id,i)}})});_u=hr({kind:"process",schema:Yi,factoryName:"defineProcess"})});var ku=j(()=>{});var Tu=j(()=>{Su();ku()});async function Aw(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 Uo(t,e={}){return(e.transform??Aw)(t)}var Xi=j(()=>{});function Zi(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 Ru(t){return t.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function Qi(t){return`${Ru(t.source)}${Ru(t.recordType)}`}function Cw(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Iw(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 ea(t){let e=Qi(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
5
  * ${r.join(`
6
6
  * `)}
7
7
  */`;if(t.columns.length===0)return`${n}
8
8
  export interface ${e} {
9
9
  // no columns introspected
10
10
  [key: string]: unknown;
11
- }`;let o=t.columns.map(s=>{let i=Yi(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${Tw(s)} */
12
- ${kw(s.name)}${a}: ${i}${l};`});return`${n}
11
+ }`;let o=t.columns.map(s=>{let i=Zi(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${Iw(s)} */
12
+ ${Cw(s.name)}${a}: ${i}${l};`});return`${n}
13
13
  export interface ${e} {
14
14
  ${o.join(`
15
15
  `)}
16
- }`}function jo(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(Zi).join(`
16
+ }`}function Mo(t){return[...t.records].sort((n,o)=>`${n.source}:${n.recordType}`.localeCompare(`${o.source}:${o.recordType}`)).map(ea).join(`
17
17
 
18
- `)}function _u(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function xw(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function Qi(t){let e=_u(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${xw(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
19
- `)}var ea=j(()=>{});function Rw(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function Su(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 mr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=Rw(t.baseUrl),n=await Su(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=jo(n),s=[$w,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",Qi(n)];if(!t.recordsOnly){let i=await Su(r.openapi,t.token,e),a=await Lo(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
18
+ `)}function xu(t){let e=new Map,r=(o,s)=>{let i=e.get(o);i||e.set(o,i=new Map);for(let a of s)i.set(a.name,(i.get(a.name)??!0)&&a.nullable)};for(let o of t.records){o.table&&r(o.table,o.columns);for(let s of o.lines??[])r(s.table,s.columns)}let n={};for(let[o,s]of[...e].sort(([i],[a])=>i.localeCompare(a))){let i=["line_index","line_number"].find(a=>s.get(a)===!1);if(s.get("parent_pg_row_id")===!1&&i){n[o]=["parent_pg_row_id",i];continue}if(s.get("pg_row_id")===!1){n[o]="pg_row_id";continue}if(s.get("external_id")===!1){n[o]="external_id";continue}}return n}function Ow(t){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(t)?t:JSON.stringify(t)}function ta(t){let e=xu(t);return["/**"," * The seek key each table can be keyset-paged on \u2014 pass it to `selectPage`:"," *"," * selectPage(`vendor_credit?select=*`, { sortKey: SEEK_KEYS.vendor_credit })"," *"," * A seek key must be NOT NULL and UNIQUE. Hard-coding one instead goes stale"," * silently: a table that gains `pg_row_id` has its `external_id` made"," * nullable in the same change, and seeking on a nullable column drops rows",' * with no error \u2014 the column still exists, so an "is it there?" check on the'," * override stays green. Read it from here and regenerating types fixes it."," *"," * An entry may be a TUPLE, and it is passed exactly the same way. A line"," * table is keyed `(parent_pg_row_id, line_index)` and has no correct single"," * column \u2014 every line of one parent shares `parent_pg_row_id`, and"," * `line_index` is unique only within a parent \u2014 so `selectPage` seeks the"," * pair with a row-wise comparison."," *"," * A table with no entry has no keyset-safe key at all; page it by filtering"," * to a bounded subset rather than seeking across the whole table."," */","export const SEEK_KEYS = {",...Object.entries(e).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${Ow(n)}: ${s},`}),"} as const satisfies Record<string, string | readonly string[]>;","","/** Tables with a keyset-safe seek key. */","export type SeekableTable = keyof typeof SEEK_KEYS;"].join(`
19
+ `)}var ra=j(()=>{});function Nw(t){let e=t.replace(/\/+$/,"");return{records:`${e}/v1/catalog/records`,openapi:`${e}/v1/catalog/openapi.json`}}async function $u(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 fr(t){let e=t.fetchImpl??fetch;if(typeof e!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=Nw(t.baseUrl),n=await $u(r.records,t.token,e);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=Mo(n),s=[Lw,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",ta(n)];if(!t.recordsOnly){let i=await $u(r.openapi,t.token,e),a=await Uo(i,t.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
20
20
 
21
21
  `)+`
22
- `}var $w,ku=j(()=>{Ji();ea();ea();Ji();$w=["/**"," * 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 ta=j(()=>{bn();su();lu();hu();wu();ku()});import{homedir as Ew}from"node:os";import{join as Tu}from"node:path";import{promises as ra}from"node:fs";function rt(t){return t.trim().replace(/\/+$/,"")}function Do(){let t=process.env.TURBOBASE_HOME??Tu(Ew(),".turbobase");return{dir:t,file:Tu(t,"credentials")}}function xu(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function wn(){let{file:t}=Do(),e;try{let s=await ra.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,l]of Object.entries(r.tenants))xu(l)&&(s[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))xu(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:Pw(n),tenants:n}}function Pw(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function na(t){let{dir:e,file:r}=Do();await ra.mkdir(e,{recursive:!0,mode:448}),await ra.writeFile(r,JSON.stringify(t,null,2)+`
24
- `,{mode:384})}async function Ru(t){let e=rt(t.baseUrl),r=await wn(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await na(r),{baseUrl:e,token:t.token,updatedAt:n}}async function ht(t){let e=await wn();if(t){let s=rt(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function Uo(t){let e=rt(t),r=await wn(),n=r.tenants[e];return n?(r.active=e,await na(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function oa(t){let e=await wn(),r=t?rt(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 na(e),r}async function Lt(){let t=await wn();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var vn=j(()=>{});function ia(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function Aw(t){if(t)try{return JSON.parse(t)}catch{return t}}function Cw(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function Iw(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function Ow(t,e){let r=Cw(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=Aw(n),s=ia(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??Iw(n),error:i}}function Nw(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function $u(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function sa(t){return`${Math.round(t/1e3)}s`}function Lw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${sa(t.delayMs)} before retrying (${sa(t.remainingMs)} of the retry budget left).
25
- `)}function jw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${sa(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
26
- `)}function Mo(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(u=>new Promise(p=>setTimeout(p,u))),s=e.now??(()=>Date.now()),i=e.onWait??Lw,a=e.onGiveUp??jw;return async(u,p)=>{let g=s(),S=0;for(;;){let y=await t(u,p);if(y.status!==503||p&&!Nw(p.body))return y;let x=r-(s()-g),{maintenance:R,delayMs:E,error:P}=await Ow(y,s());if(!R)return y;if(x<=0)return S>0&&a({waitedMs:s()-g,attempts:S,host:$u(u),error:P}),y;let I=E??n;I=Math.min(Math.max(I,1e3),12e4),I=Math.min(I,x),S+=1,i({attempt:S,delayMs:I,remainingMs:x,host:$u(u),error:P}),await o(I)}}}var aa=j(()=>{});function Eu(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t;if(typeof e.message=="string"&&e.message.trim())return e.message.trim();let r=typeof e.error=="string"?e.error.trim():"",n=typeof e.reason=="string"?e.reason.trim():"";return n?r?`${r}: ${n}`:n:r}function Dw(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function Pu(t){let e=Eu(t);return typeof t=="string"&&Dw(e)?Uw:e.slice(0,200)}function Au(t,e){return ia(t,e)}function Cu(t){return t instanceof Y&&Au(t.status,t.body)}function qw(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Iu(t){return t.replace(/\/+$/,"")}function la(t=process.env){let e=(t[Or]??"").trim(),r=(t[qo]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ca(t){let e;try{e=new URL(t)}catch{return`${Or} 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:`${Or} 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 Y,Uw,Mw,q,Or,qo,_n,mt=j(()=>{aa();Y=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Uw="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";Mw="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";q=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Iu(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?r:Mo(r,e.retry??{})}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){if(qw()){let u=Eu(a);throw new Y(`${e} ${r} \u2192 ${s.status}${u?`: ${u}`:""}`,s.status,a)}if(Au(s.status,a))throw new Y(Mw,s.status,a);let l=Pu(a);throw new Y(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(e){return(await this.request("GET",`/v1/processes/${encodeURIComponent(e)}/runs`)).runs??[]}async processRun(e){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(e)}`)}async invokeProcess(e,r,n="async"){let o=n==="sync"?"?mode=sync":"";return this.request("POST",`/v1/processes/${encodeURIComponent(e)}${o}`,r)}async settleRow(e,r){return this.request("POST",`/v1/data/${encodeURIComponent(e)}/settle`,{pgRowId:r})}async cancelProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/cancel`)}async rollbackProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/rollback`)}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}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`)}},Or="TURBOBASE_REGISTRY_URL",qo="TURBOBASE_REGISTRY_TOKEN";_n=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Iu(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let l=Pu(a);throw new Y(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});import{existsSync as zw,statSync as Bw}from"node:fs";import{resolve as zo,sep as Ou}from"node:path";function Nu(t){if(Hw.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function Vw(t,e,r){let n=zo(e,r),o=zo(t);if(n!==o&&!n.startsWith(o+Ou))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+Ou)&&zw(i)&&Bw(i).isFile())return i;return null}function Lu(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Nu(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=Vw(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||Ww(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Kw,loader:"js"}))}}}function Ww(t){let e=t.startsWith("node:")?t.slice(5):t;return Gw.has(e.split("/")[0])}function ju(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 Du(){try{return(await import("esbuild")).build}catch(t){throw ju("esbuild",t)}}async function Jw(){try{return(await import("isolated-vm")).default}catch(t){throw ju("isolated-vm",t)}}async function Ho(t,e={}){let r=await Du(),n=e.resolveDir?zo(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[Lu(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new Bo(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function da(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Du(),n=zo(e),o=Lu(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:Nu(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let u=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new Bo(u||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function Sn(t,e,r={}){let n=r.timeoutMs??Fo,o=r.memoryLimitMb??Fw,s=r.member??"run",i={patches:[],logs:[]},a=await Jw(),l=new a.Isolate({memoryLimit:o});try{let u=await l.createContext(),p=u.global,g=new a.Callback(F=>{let K=JSON.parse(String(F));i.rejection||(i.rejection=K)}),S=new a.Callback(F=>{i.patches.push(JSON.parse(String(F)))}),y=new a.Callback(F=>{let K=JSON.parse(String(F));i.logs.push(K)}),x=new a.Callback(F=>{i.result=JSON.parse(String(F))}),R=r.query,E=new a.Reference(async F=>{if(!R)throw new Error("ctx.query is not available in this context");return JSON.stringify(await R(String(F)))});await p.set("__tb_reject",g),await p.set("__tb_patch",S),await p.set("__tb_log",y),await p.set("__tb_result",x),await p.set("__tb_query",E),await p.set("__tb_ctx_json",JSON.stringify(Yw(e)));let P=Zw(t,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),D=await(await l.compileScript(P)).run(u,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Yw(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null,materialized:t.materialized??null,process:t.process??null}}function Xw(t){return`
22
+ `}var Lw,Eu=j(()=>{Xi();ra();ra();Xi();Lw=["/**"," * 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 na=j(()=>{wn();du();hu();bu();Tu();Eu()});import{homedir as jw}from"node:os";import{join as Pu}from"node:path";import{promises as oa}from"node:fs";function nt(t){return t.trim().replace(/\/+$/,"")}function qo(){let t=process.env.TURBOBASE_HOME??Pu(jw(),".turbobase");return{dir:t,file:Pu(t,"credentials")}}function Au(t){return!!t&&typeof t=="object"&&typeof t.token=="string"}async function vn(){let{file:t}=qo(),e;try{let s=await oa.readFile(t,"utf8");e=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!e||typeof e!="object")return{tenants:{}};let r=e;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,l]of Object.entries(r.tenants))Au(l)&&(s[a]={token:l.token,updatedAt:l.updatedAt});return{active:typeof r.active=="string"&&s[r.active]?r.active:void 0,tenants:s}}let n={};for(let[s,i]of Object.entries(r))Au(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:Dw(n),tenants:n}}function Dw(t){let e,r="";for(let[n,o]of Object.entries(t))(!e||String(o.updatedAt)>r)&&(e=n,r=String(o.updatedAt));return e}async function sa(t){let{dir:e,file:r}=qo();await oa.mkdir(e,{recursive:!0,mode:448}),await oa.writeFile(r,JSON.stringify(t,null,2)+`
24
+ `,{mode:384})}async function Cu(t){let e=nt(t.baseUrl),r=await vn(),n=new Date().toISOString();return r.tenants[e]={token:t.token,updatedAt:n},r.active=e,await sa(r),{baseUrl:e,token:t.token,updatedAt:n}}async function ft(t){let e=await vn();if(t){let s=nt(t),i=e.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(e.tenants),n=e.active&&e.tenants[e.active]?e.active:r.length===1?r[0]:void 0;if(!n)return null;let o=e.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function zo(t){let e=nt(t),r=await vn(),n=r.tenants[e];return n?(r.active=e,await sa(r),{baseUrl:e,token:n.token,updatedAt:n.updatedAt}):null}async function ia(t){let e=await vn(),r=t?nt(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 sa(e),r}async function jt(){let t=await vn();return Object.entries(t.tenants).map(([e,r])=>({baseUrl:e,token:r.token,updatedAt:r.updatedAt}))}var _n=j(()=>{});function la(t,e){return t!==503?!1:typeof e=="string"?!0:e?.error==="instance_unavailable"}function Uw(t){if(t)try{return JSON.parse(t)}catch{return t}}function Mw(t,e){if(!t)return null;let r=t.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-e)}function qw(t){let e=/retry\s+after\s+(\d+)\s*s/i.exec(t);return e?Number(e[1])*1e3:null}async function zw(t,e){let r=Mw(t.headers?.get?.("retry-after"),e),n="";try{n=await t.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=Uw(n),s=la(t.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??qw(n),error:i}}function Bw(t){return!!(t==null||typeof t=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(t)||t instanceof ArrayBuffer||typeof URLSearchParams<"u"&&t instanceof URLSearchParams||typeof Blob<"u"&&t instanceof Blob)}function Iu(t){try{let e=typeof t=="string"?t:t instanceof URL?t.href:t?.url??"";return e?new URL(e).host:"the instance"}catch{return"the instance"}}function aa(t){return`${Math.round(t/1e3)}s`}function Fw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: ${t.host} is unavailable${e} \u2014 waiting ${aa(t.delayMs)} before retrying (${aa(t.remainingMs)} of the retry budget left).
25
+ `)}function Hw(t){let e=t.error?` (${t.error})`:"";process.stderr.write(`turbobase: gave up after ${aa(t.waitedMs)} waiting for ${t.host} to come back${e}; ${t.attempts} ${t.attempts===1?"retry":"retries"} made.
26
+ `)}function Bo(t,e={}){let r=e.budgetMs??6e5,n=e.defaultDelayMs??6e4,o=e.sleep??(u=>new Promise(p=>setTimeout(p,u))),s=e.now??(()=>Date.now()),i=e.onWait??Fw,a=e.onGiveUp??Hw;return async(u,p)=>{let g=s(),k=0;for(;;){let b=await t(u,p);if(b.status!==503||p&&!Bw(p.body))return b;let R=r-(s()-g),{maintenance:x,delayMs:E,error:P}=await zw(b,s());if(!x)return b;if(R<=0)return k>0&&a({waitedMs:s()-g,attempts:k,host:Iu(u),error:P}),b;let I=E??n;I=Math.min(Math.max(I,1e3),12e4),I=Math.min(I,R),k+=1,i({attempt:k,delayMs:I,remainingMs:R,host:Iu(u),error:P}),await o(I)}}}var ca=j(()=>{});function Ou(t){if(typeof t=="string")return t.trim();if(!t||typeof t!="object")return"";let e=t;if(typeof e.message=="string"&&e.message.trim())return e.message.trim();let r=typeof e.error=="string"?e.error.trim():"",n=typeof e.reason=="string"?e.reason.trim():"";return n?r?`${r}: ${n}`:n:r}function Kw(t){let e=t.trimStart().slice(0,200).toLowerCase();return e.startsWith("<!doctype")||e.startsWith("<html")||e.startsWith("<")}function Gw(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.error=="string"&&typeof e.reason=="string"&&e.reason.trim()!==""}function Nu(t){let e=Ou(t);return typeof t=="string"&&Kw(e)?Vw:Gw(t)?e.slice(0,Jw):e.slice(0,Ww)}function Lu(t,e){return la(t,e)}function ju(t){return t instanceof Y&&Lu(t.status,t.body)}function Xw(){let t=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return t!==""&&t!=="0"&&t!=="false"}function Du(t){return t.replace(/\/+$/,"")}function da(t=process.env){let e=(t[Nr]??"").trim(),r=(t[Fo]??"").trim();return!e||!r?null:{registryUrl:e,token:r}}function ua(t){let e;try{e=new URL(t)}catch{return`${Nr} 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:`${Nr} 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 Y,Vw,Ww,Jw,Yw,z,Nr,Fo,Sn,gt=j(()=>{ca();Y=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Vw="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";Ww=200,Jw=2e3;Yw="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";z=class{baseUrl;token;fetchImpl;constructor(e){this.baseUrl=Du(e.baseUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=e.retry===!1?r:Bo(r,e.retry??{})}async request(e,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:e,headers:{Authorization:`Bearer ${this.token}`,Accept:"application/json",...n!==void 0?{"Content-Type":"application/json"}:{},...o??{}},...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){if(Xw()){let u=Ou(a);throw new Y(`${e} ${r} \u2192 ${s.status}${u?`: ${u}`:""}`,s.status,a)}if(Lu(s.status,a))throw new Y(Yw,s.status,a);let l=Nu(a);throw new Y(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}deploy(e){return this.request("POST","/v1/extensions",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli",...e.connectionId?{connectionId:e.connectionId}:{}})}async list(e){let r=e?`?kind=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(e){return this.request("POST","/v1/extensions/test",{id:e.id,recordType:e.recordType,event:e.event,source:e.source,sourceCode:e.sourceCode,extensionKind:e.extensionKind??"hook",provenance:e.provenance??"cli"})}authorConduit(e){return this.request("POST","/v1/extensions/author-conduit",{intent:e.intent,from:e.from,to:e.to,...e.intentId?{intentId:e.intentId}:{},...e.columns?.length?{columns:e.columns}:{}})}async proposals(e={}){let r=new URLSearchParams;e.status?.length&&r.set("status",e.status.join(",")),e.provenance?.length&&r.set("provenance",e.provenance.join(",")),e.recordType&&r.set("recordType",e.recordType),e.source&&r.set("source",e.source),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/promote`,{})}proposalRetract(e){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/retract`,{})}proposalReject(e,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(e)}/reject`,r?{reason:r}:{})}extensionDisable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/disable`,{})}extensionEnable(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/enable`,{})}extensionRemove(e){return this.request("POST",`/v1/extensions/${encodeURIComponent(e)}/remove`,{})}async logs(e,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(e)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(e,r={}){let n=new URLSearchParams;r.since&&n.set("since",r.since),r.limit&&r.limit>0&&n.set("limit",String(Math.floor(r.limit)));let o=n.toString()?`?${n.toString()}`:"";return(await this.request("GET",`/v1/conduits/${encodeURIComponent(e)}/events${o}`)).events??[]}async processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(e){return(await this.request("GET",`/v1/processes/${encodeURIComponent(e)}/runs`)).runs??[]}async processRun(e){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(e)}`)}async invokeProcess(e,r,n="async"){let o=n==="sync"?"?mode=sync":"";return this.request("POST",`/v1/processes/${encodeURIComponent(e)}${o}`,r)}async settleRow(e,r){return this.request("POST",`/v1/data/${encodeURIComponent(e)}/settle`,{pgRowId:r})}async cancelProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/cancel`)}async rollbackProcessRun(e){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(e)}/rollback`)}async platformEvents(e={}){let r=new URLSearchParams;e.subsystem&&r.set("subsystem",e.subsystem),e.severity&&r.set("severity",e.severity),e.code&&r.set("code",e.code),e.since&&r.set("since",e.since),e.after&&r.set("after",e.after),e.correlationId&&r.set("correlationId",e.correlationId),e.extension&&r.set("extension",e.extension),e.conduit&&r.set("conduit",e.conduit),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status),e.limit&&e.limit>0&&r.set("limit",String(Math.floor(e.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/bindings${n}`)).bindings??[]}async appsList(){return(await this.request("GET","/v1/apps")).apps??[]}appsCreate(e){return this.request("POST","/v1/apps",{slug:e.slug,name:e.name??e.slug,description:e.description})}appsPull(e){return this.request("GET",`/v1/apps/${encodeURIComponent(e)}/pull`)}appPullContext(e){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(e)}/pull-context`)}appsPush(e,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.section&&r.set("section",e.section),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(e){return this.request("POST","/v1/learnings/ingest",{...e?{app:e}:{}})}rulesPending(e={}){let r=new URLSearchParams;e.app&&r.set("app",e.app),e.limit!==void 0&&r.set("limit",String(e.limit)),e.group===!1&&r.set("group","false"),e.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(e,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:e,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(e,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(e)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(e){return this.request("POST","/v1/skills/publish",{slugs:[...e]})}skillsUnpublish(e){return this.request("POST","/v1/skills/unpublish",{slugs:[...e]})}skillsRollback(e){return this.request("POST","/v1/skills/rollback",{versionNo:e})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(e){return this.request("DELETE",`/v1/skills/${encodeURIComponent(e)}`)}docsList(e={}){let r=new URLSearchParams;e.status&&r.set("status",e.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(e){return this.request("POST","/v1/docs/publish",{slugs:[...e]})}docsUnpublish(e){return this.request("POST","/v1/docs/unpublish",{slugs:[...e]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(e){return this.request("POST","/v1/docs/rollback",{versionNo:e})}docsDelete(e){return this.request("DELETE",`/v1/docs/${encodeURIComponent(e)}`)}learningsPushKb(e,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:e,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(e){return this.request("POST",`/v1/bindings/${encodeURIComponent(e)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(e){return this.request("POST","/v1/config/plan",{bundle:e})}configApply(e,r={}){return this.request("POST","/v1/config/apply",{bundle:e,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(e){return this.request("POST","/v1/tables/plan",e)}appsPlan(e){return this.request("POST","/v1/apps/plan",{writes:e.writes??[],...e.roles!==void 0?{roles:e.roles}:{},labels:e.labels??[],...e.app?{app:e.app}:{}})}tablesApply(e){return this.request("POST","/v1/tables/apply",e)}tablesDrop(e,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(e)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(e){return(await this.request("POST","/v1/guardrails",e)).guardrail}async guardrailUpdate(e,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(e)}`,r)).guardrail}guardrailDelete(e){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(e)}`)}guardrailTest(e){return this.request("POST","/v1/guardrails/test",e)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(e){return this.request("PUT","/v1/guardrails/posture",{mode:e})}async relationshipsList(e){let r=e?`?source=${encodeURIComponent(e)}`:"";return(await this.request("GET",`/v1/relationships${r}`)).relations??[]}relationshipRefresh(e,r){return this.request("PATCH",`/v1/relationships/${encodeURIComponent(e)}`,r)}releaseDeploy(e){return this.request("POST","/v1/releases/deploy",{...e.solutionId?{solutionId:e.solutionId}:{},target:e.target,...e.approvedBy?{approvedBy:e.approvedBy}:{},...e.files?{files:e.files}:{},...e.gitRepo?{gitRepo:e.gitRepo}:{},...e.gitRef?{gitRef:e.gitRef}:{},...e.gitSha?{gitSha:e.gitSha}:{},...e.prUrl?{prUrl:e.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}`)}releaseFiles(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/files`)}releasePush(e,r){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(e){return this.request("GET",`/v1/releases/${encodeURIComponent(e)}/status`)}releaseRollback(e){return this.request("POST",`/v1/releases/${encodeURIComponent(e)}/rollback`)}},Nr="TURBOBASE_REGISTRY_URL",Fo="TURBOBASE_REGISTRY_TOKEN";Sn=class{registryUrl;token;fetchImpl;constructor(e){this.registryUrl=Du(e.registryUrl),this.token=e.token;let r=e.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(e,r,n){let o={Authorization:`Bearer ${this.token}`,Accept:"application/json"};n!==void 0&&(o["Content-Type"]="application/json");let s=await this.fetchImpl(`${this.registryUrl}${r}`,{method:e,headers:o,...n!==void 0?{body:JSON.stringify(n)}:{}}),i=await s.text(),a;try{a=i?JSON.parse(i):void 0}catch{a=i}if(!s.ok){let l=Nu(a);throw new Y(`${e} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(e,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(e)}${n}`)}publish(e){return this.request("POST","/extensions",{name:e.name,version:e.version,kind:e.kind,bundle:e.bundle,...e.manifest?{manifest:e.manifest}:{}})}}});import{existsSync as Zw,statSync as Qw}from"node:fs";import{resolve as Ho,sep as Uu}from"node:path";function Mu(t){if(tv.has(t))return!0;let e=t.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(e)}function nv(t,e,r){let n=Ho(e,r),o=Ho(t);if(n!==o&&!n.startsWith(o+Uu))return null;let s=[n];/\.(js|mjs|cjs)$/.test(n)&&s.push(n.replace(/\.js$/,".ts"),n.replace(/\.mjs$/,".mts"),n.replace(/\.cjs$/,".cts")),/\.[cm]?[jt]sx?$/.test(n)||s.push(`${n}.ts`,`${n}.tsx`,`${n}.js`,`${n}/index.ts`,`${n}/index.js`);for(let i of s)if(i.startsWith(o+Uu)&&Zw(i)&&Qw(i).isFile())return i;return null}function qu(t){return{name:"extension-self-contained-fence",setup(e){e.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(Mu(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&t){let s=nv(t,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${t?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||sv(r.path)?`imports a Node builtin ('${r.path}')`:`imports an external module ('${r.path}')`} \u2014 sandboxed extensions must be self-contained. The ONLY allowed imports are the SDK factory ('@/sync/hooks' or '@turbobase/extensions') and a relative sibling inside the extension's own directory; inline everything else into the extension file.`}]}}),e.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:rv,loader:"js"}))}}}function sv(t){let e=t.startsWith("node:")?t.slice(5):t;return ov.has(e.split("/")[0])}function zu(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 Bu(){try{return(await import("esbuild")).build}catch(t){throw zu("esbuild",t)}}async function iv(){try{return(await import("isolated-vm")).default}catch(t){throw zu("isolated-vm",t)}}async function Go(t,e={}){let r=await Bu(),n=e.resolveDir?Ho(e.resolveDir):void 0,o;try{o=await r({stdin:{contents:t,loader:"ts",resolveDir:n??process.cwd(),sourcefile:"extension.ts"},bundle:!0,write:!1,format:"iife",globalName:"__tb_extension_module",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[qu(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new Ko(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function pa(t,e){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(t)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(t))return t;let r=await Bu(),n=Ho(e),o=qu(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:Mu(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:t,loader:"ts",resolveDir:n,sourcefile:"extension.ts"},bundle:!0,write:!1,format:"esm",platform:"neutral",target:"es2022",logLevel:"silent",plugins:[s,o]})}catch(a){let u=a.errors?.map(p=>p.text).filter(Boolean).join("; ");throw new Ko(u||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??t}async function kn(t,e,r={}){let n=r.timeoutMs??Vo,o=r.memoryLimitMb??ev,s=r.member??"run",i={patches:[],logs:[]},a=await iv(),l=new a.Isolate({memoryLimit:o});try{let u=await l.createContext(),p=u.global,g=new a.Callback(H=>{let G=JSON.parse(String(H));i.rejection||(i.rejection=G)}),k=new a.Callback(H=>{i.patches.push(JSON.parse(String(H)))}),b=new a.Callback(H=>{let G=JSON.parse(String(H));i.logs.push(G)}),R=new a.Callback(H=>{i.result=JSON.parse(String(H))}),x=r.query,E=new a.Reference(async H=>{if(!x)throw new Error("ctx.query is not available in this context");return JSON.stringify(await x(String(H)))});await p.set("__tb_reject",g),await p.set("__tb_patch",k),await p.set("__tb_log",b),await p.set("__tb_result",R),await p.set("__tb_query",E),await p.set("__tb_ctx_json",JSON.stringify(av(e)));let P=cv(t,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),D=await(await l.compileScript(P)).run(u,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!D}:{effects:i}}finally{l.isDisposed||l.dispose()}}function av(t){return{recordType:t.recordType,event:t.event,direction:t.direction,origin:t.origin,source:t.source,payload:t.payload??null,prior:t.prior??null,user:t.user??null,tenantConfig:t.tenantConfig??{},metadata:t.metadata??null,bindings:t.bindings??null,atlasLinks:t.atlasLinks??null,materialized:t.materialized??null,process:t.process??null}}function lv(t){return`
27
27
  "use strict";
28
28
  (async () => {
29
29
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -46,7 +46,7 @@ ${o.join(`
46
46
  __tb_result(JSON.stringify(out == null ? null : String(out)));
47
47
  return undefined;
48
48
  })()
49
- `}function Zw(t,e,r,n,o=!1){return e==="build"?ev(t,n):e==="prompt"?Qw(t,n):e==="outstanding"?Xw(t):`
49
+ `}function cv(t,e,r,n,o=!1){return e==="build"?uv(t,n):e==="delete"?pv(t,n):e==="prompt"?dv(t,n):e==="outstanding"?lv(t):`
50
50
  "use strict";
51
51
  (async () => {
52
52
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -127,7 +127,7 @@ ${o.join(`
127
127
  ${e==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":e==="idempotencyKey"?"__tb_result(JSON.stringify(out == null ? null : String(out)));":""}
128
128
  return ${e==="when"?"out":"undefined"};
129
129
  })()
130
- `}function Qw(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
130
+ `}function dv(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
131
131
  "use strict";
132
132
  (async () => {
133
133
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -172,7 +172,7 @@ ${o.join(`
172
172
  __tb_result(String(out == null ? '' : out));
173
173
  return undefined;
174
174
  })()
175
- `}function ev(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
175
+ `}function uv(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
176
176
  "use strict";
177
177
  (async () => {
178
178
  const __tb_ctx = JSON.parse(__tb_ctx_json);
@@ -243,37 +243,96 @@ ${o.join(`
243
243
  __tb_result(JSON.stringify({ declined: out == null, address: address, write: out == null ? null : out }));
244
244
  return undefined;
245
245
  })()
246
- `}var Fo,Fw,Hw,Kw,Bo,Gw,Ko=j(()=>{Fo=200,Fw=16,Hw=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@/sync/processes","@/sync/processes/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit","@turbobase/extensions/process"]);Kw=`
246
+ `}function pv(t,e){let r=JSON.stringify(e.map(n=>Number(n)));return`
247
+ "use strict";
248
+ (async () => {
249
+ const __tb_ctx = JSON.parse(__tb_ctx_json);
250
+ const __tb_process = __tb_ctx.process || {};
251
+ const ctx = {
252
+ input: __tb_process.input,
253
+ runId: __tb_process.runId,
254
+ steps: __tb_process.steps || {},
255
+ row: __tb_process.row == null ? undefined : __tb_process.row,
256
+ item: __tb_process.item == null ? undefined : __tb_process.item,
257
+ index: __tb_process.index == null ? undefined : __tb_process.index,
258
+ async query(q) {
259
+ const json = await __tb_query.apply(undefined, [String(q)], {
260
+ arguments: { copy: true },
261
+ result: { promise: true, copy: true },
262
+ });
263
+ return JSON.parse(json);
264
+ },
265
+ log(level, message, meta) {
266
+ __tb_log(JSON.stringify({ level, message, meta }));
267
+ },
268
+ };
269
+
270
+ // ---- bundled extension module (IIFE assigns __tb_extension_module) ----
271
+ ${t}
272
+
273
+ const def = (typeof __tb_extension_module !== 'undefined' && __tb_extension_module)
274
+ ? __tb_extension_module.default
275
+ : undefined;
276
+ if (!def || typeof def !== 'object') {
277
+ throw new Error('extension bundle has no default export (use export default defineProcess({...}))');
278
+ }
279
+ const __tb_path = ${r};
280
+ let step = Array.isArray(def.steps) ? def.steps[__tb_path[0]] : undefined;
281
+ if (step && __tb_path.length > 1) {
282
+ step = Array.isArray(step.steps) ? step.steps[__tb_path[1]] : undefined;
283
+ }
284
+ if (!step || !step.delete || typeof step.delete !== 'object') {
285
+ throw new Error('process step ' + __tb_path.join('.') + ' has no delete block');
286
+ }
287
+
288
+ // A \`when\` that returns false declines the step and no address is
289
+ // resolved. A \`when\` that THROWS propagates \u2014 same rule as a write
290
+ // step's, and the stakes are higher: reading a broken condition as
291
+ // "no" would silently drop a delete from a cleanup that was told to
292
+ // make it.
293
+ if (typeof step.when === 'function' && !(await step.when(ctx))) {
294
+ __tb_result(JSON.stringify({ declined: true }));
295
+ return undefined;
296
+ }
297
+
298
+ const address = {};
299
+ for (const key of ['pgRowId', 'externalId']) {
300
+ if (typeof step.delete[key] === 'function') address[key] = await step.delete[key](ctx);
301
+ }
302
+ __tb_result(JSON.stringify({ declined: false, address: address }));
303
+ return undefined;
304
+ })()
305
+ `}var Vo,ev,tv,rv,Ko,ov,Wo=j(()=>{Vo=200,ev=16,tv=new Set(["@/sync/hooks","@/sync/hooks/index.js","@/sync/conduits","@/sync/conduits/index.js","@/sync/processes","@/sync/processes/index.js","@turbobase/extensions","@turbobase/extensions/hook","@turbobase/extensions/conduit","@turbobase/extensions/process"]);rv=`
247
306
  export const defineHook = (def) => def;
248
307
  export const defineConduit = (def) => def;
249
308
  export const defineProcess = (def) => def;
250
309
  export default defineHook;
251
- `;Bo=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};Gw=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 ua}from"node:fs";import{join as tv}from"node:path";function rv(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 nv(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await Sn(t,rv(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function Vo(t,e,r={}){let n=await Ho(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await nv(n,e[s],`sample[${s}]`));return o}async function kn(t){let e;try{e=await ua.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await ua.readFile(tv(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let l=i[a];r.push({file:n,fixture:{...l,name:l.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function Tn(t){return ua.readFile(t,"utf8")}var pa=j(()=>{Ko()});function We(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function Xv(t){let e=t.recordType;if(!e)throw new Je("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
310
+ `;Ko=class extends Error{constructor(e){super(e),this.name="SandboxBundleError"}};ov=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 ha}from"node:fs";import{join as hv}from"node:path";function mv(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 fv(t,e,r){let n=e.name??r,o=e.expect??"pass";try{let{effects:s}=await kn(t,mv(e.context)),i=s.rejection?"reject":"pass";return{name:n,expected:o,observed:i,pass:i===o,rejection:s.rejection,patchCount:s.patches.length}}catch(s){return{name:n,expected:o,observed:"pass",pass:!1,patchCount:0,error:s instanceof Error?s.message:String(s)}}}async function Jo(t,e,r={}){let n=await Go(t,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<e.length;s+=1)o.push(await fv(n,e[s],`sample[${s}]`));return o}async function Tn(t){let e;try{e=await ha.readdir(t)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of e.sort()){if(!n.endsWith(".json"))continue;let o=await ha.readFile(hv(t,n),"utf8"),s=JSON.parse(o),i=Array.isArray(s)?s:[s];for(let a=0;a<i.length;a+=1){let l=i[a];r.push({file:n,fixture:{...l,name:l.name??`${n}${i.length>1?`#${a}`:""}`}})}}return r}function Rn(t){return ha.readFile(t,"utf8")}var ma=j(()=>{Wo()});function Je(t){return t.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function c_(t){let e=t.recordType;if(!e)throw new Ye("record type is required (e.g. --record=salesOrder)");let r=t.event??"before_save",n=t.template??"require-field",o=t.source,s=o?`
252
311
  source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
253
312
  run: (ctx) => {
254
313
  // Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
255
314
  // with ctx.patch({...}); observe with ctx.log('info', '...').
256
- },`,a="custom";else if(n==="require-field"){let S=t.field;if(!S)throw new Je("require-field template needs --field=<name>");i=`
315
+ },`,a="custom";else if(n==="require-field"){let k=t.field;if(!k)throw new Ye("require-field template needs --field=<name>");i=`
257
316
  run: (ctx) => {
258
- const v = ctx.payload[${JSON.stringify(S)}];
317
+ const v = ctx.payload[${JSON.stringify(k)}];
259
318
  if (v === undefined || v === null || v === '') {
260
319
  ctx.reject({
261
320
  code: 'MANDATORY_FIELD_MISSING',
262
- field: ${JSON.stringify(S)},
263
- message: ${JSON.stringify(`${S} is required`)},
321
+ field: ${JSON.stringify(k)},
322
+ message: ${JSON.stringify(`${k} is required`)},
264
323
  });
265
324
  }
266
- },`,a=`require-field-${S}`}else if(n==="enforce-format"){let S=t.field;if(!S)throw new Je("enforce-format template needs --field=<name>");if(!t.regex)throw new Je("enforce-format template needs --regex=<pattern>");i=`
325
+ },`,a=`require-field-${k}`}else if(n==="enforce-format"){let k=t.field;if(!k)throw new Ye("enforce-format template needs --field=<name>");if(!t.regex)throw new Ye("enforce-format template needs --regex=<pattern>");i=`
267
326
  run: (ctx) => {
268
- const v = ctx.payload[${JSON.stringify(S)}];
327
+ const v = ctx.payload[${JSON.stringify(k)}];
269
328
  if (typeof v === 'string' && v && !/${t.regex}/.test(v)) {
270
329
  ctx.reject({
271
330
  code: 'INVALID_FORMAT',
272
- field: ${JSON.stringify(S)},
273
- message: ${JSON.stringify(`${S} does not match expected format`)},
331
+ field: ${JSON.stringify(k)},
332
+ message: ${JSON.stringify(`${k} does not match expected format`)},
274
333
  });
275
334
  }
276
- },`,a=`enforce-format-${S}`}else throw new Je(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${We(t.regex).slice(0,24)}`:""}`,p=`/**
335
+ },`,a=`enforce-format-${k}`}else throw new Ye(`unsupported template: ${n}. Supported: require-field | enforce-format | blank.`);let l=t.id??`custom:${e}:${a}${t.regex?`-${Je(t.regex).slice(0,24)}`:""}`,p=`/**
277
336
  * ${t.description??`${a} on ${e}.${r}`}
278
337
  *
279
338
  * Scaffolded by \`turbobase ext new hook\`. Edit freely, then \`turbobase ext test\` and
@@ -286,7 +345,7 @@ export default defineHook<Record<string, unknown>>({
286
345
  recordType: ${JSON.stringify(e)},
287
346
  event: ${JSON.stringify(r)},${s}${i}
288
347
  });
289
- `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:p}}function Zv(t){let e=t.recordType;if(!e)throw new Je("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Je("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Je("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Je(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${We(r)}2${We(n)}:${We(e)}`,l=`/**
348
+ `;return{relativePath:`hooks/${e}/${r}.${a}.ts`,content:p}}function d_(t){let e=t.recordType;if(!e)throw new Ye("record type is required (e.g. --record=order)");let r=t.source;if(!r)throw new Ye("--source is required (the origin source, e.g. --source=shopify)");let n=t.to;if(!n)throw new Ye("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Ye(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=t.toRecordType??e,s=t.event??"after_canonicalize_inbound",i=t.id??`${Je(r)}2${Je(n)}:${Je(e)}`,l=`/**
290
349
  * ${t.description??`Bridge ${r} ${e} \u2192 ${n} ${o} (${s}).`}
291
350
  *
292
351
  * Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
@@ -329,14 +388,14 @@ export default defineConduit<Record<string, unknown>>({
329
388
  },
330
389
  idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
331
390
  });
332
- `;return{relativePath:`conduits/${We(r)}-${We(e)}-to-${We(n)}-${We(o)}.ts`,content:l}}function Qv(t){let e=t.recordType;if(!e)throw new Je("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Je(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${We(e)}-then-${We(r)}`:We(e),s=t.id??`custom:process:${o}`,i=t.description??(r?`Raise a ${e}, wait for the source, then raise a ${r}.`:`Raise a ${e}.`),a=r?`
391
+ `;return{relativePath:`conduits/${Je(r)}-${Je(e)}-to-${Je(n)}-${Je(o)}.ts`,content:l}}function u_(t){let e=t.recordType;if(!e)throw new Ye("record type is required (e.g. --record=purchaseOrder)");let r=t.then,n=t.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Ye(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${Je(e)}-then-${Je(r)}`:Je(e),s=t.id??`custom:process:${o}`,i=t.description??(r?`Raise a ${e}, wait for the source, then raise a ${r}.`:`Raise a ${e}.`),a=r?`
333
392
  {
334
- id: ${JSON.stringify(We(r))},
393
+ id: ${JSON.stringify(Je(r))},
335
394
  recordType: ${JSON.stringify(r)},
336
395
  build: (ctx) => ({
337
396
  parent: {
338
397
  // The first step declared awaitSource, so its source-minted id is here.
339
- created_from_id: ctx.steps[${JSON.stringify(We(e))}]?.externalId ?? null,
398
+ created_from_id: ctx.steps[${JSON.stringify(Je(e))}]?.externalId ?? null,
340
399
  // ...mapped fields from ctx.input...
341
400
  },
342
401
  }),
@@ -366,7 +425,7 @@ export default defineProcess({
366
425
  },
367
426
  steps: [
368
427
  {
369
- id: ${JSON.stringify(We(e))},
428
+ id: ${JSON.stringify(Je(e))},
370
429
  recordType: ${JSON.stringify(e)},${r?`
371
430
  awaitSource: true,`:""}
372
431
  build: (ctx) => ({
@@ -378,7 +437,7 @@ export default defineProcess({
378
437
  ],
379
438
  onFailure: ${JSON.stringify(n)},
380
439
  });
381
- `;return{relativePath:`processes/${o}.ts`,content:l}}function $t(t,e){let r=e_[t];if(!r)throw new Je(`unknown extension kind '${t}'. Scaffoldable kinds: ${wp.join(", ")}.`);return r(e)}var wp,Je,e_,Zo=j(()=>{wp=["hook","conduit","process"];Je=class extends Error{};e_={hook:Xv,conduit:Zv,process:Qv}});var La,ja=j(()=>{La=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function vk(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 _k(t){return Yh[vk(t)%Yh.length]}function Sk(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 Xh(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Zh(t,e){let[r,n]=_k(t),o=Xh(Sk(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Xh(e)}">
440
+ `;return{relativePath:`processes/${o}.ts`,content:l}}function Et(t,e){let r=p_[t];if(!r)throw new Ye(`unknown extension kind '${t}'. Scaffoldable kinds: ${Tp.join(", ")}.`);return r(e)}var Tp,Ye,p_,ts=j(()=>{Tp=["hook","conduit","process"];Ye=class extends Error{};p_={hook:c_,conduit:d_,process:u_}});var Ua,Ma=j(()=>{Ua=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function Ik(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 Ok(t){return em[Ik(t)%em.length]}function Nk(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 tm(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function rm(t,e){let[r,n]=Ok(t),o=tm(Nk(e));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${tm(e)}">
382
441
  <defs>
383
442
  <linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
384
443
  <stop offset="0" stop-color="${r}"/>
@@ -388,9 +447,9 @@ export default defineProcess({
388
447
  <rect width="64" height="64" rx="14" fill="url(#tile)"/>
389
448
  <text x="32" y="34" text-anchor="middle" dominant-baseline="central" font-family="system-ui, -apple-system, Segoe UI, sans-serif" font-size="26" font-weight="600" fill="#ffffff">${o}</text>
390
449
  </svg>
391
- `}var Yh,Qh=j(()=>{Yh=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var fm={};eu(fm,{CN_UTIL:()=>sm,COMPONENTS_JSON:()=>om,MAIN_TSX:()=>am,STYLES_CSS:()=>lm,TSCONFIG:()=>nm,TURBOBASE_CLIENT:()=>em,UI_BADGE:()=>um,UI_BUTTON:()=>cm,UI_CARD:()=>dm,UI_INPUT:()=>hm,UI_LABEL:()=>mm,UI_TABLE:()=>pm,indexHtml:()=>im,instanceOriginFromEnv:()=>Ck,packageJson:()=>tm,scaffoldAppFiles:()=>Ok,starterApp:()=>Nk,viteConfig:()=>rm});function xk(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function Rk(t){let e={name:xk(t.title,Tk)},r=(t.description??"").trim().slice(0,kk);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...La},JSON.stringify(e,null,2)+`
392
- `}function tm(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:$k},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^19.2.0","@types/react-dom":"^19.2.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
393
- `}function Ak(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 Ck(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function rm(t,e={}){let r=Ak(e.instanceOrigin);return`import { defineConfig } from 'vite';
450
+ `}var em,nm=j(()=>{em=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var wm={};su(wm,{CN_UTIL:()=>cm,COMPONENTS_JSON:()=>lm,MAIN_TSX:()=>um,STYLES_CSS:()=>pm,TSCONFIG:()=>am,TURBOBASE_CLIENT:()=>om,UI_BADGE:()=>fm,UI_BUTTON:()=>hm,UI_CARD:()=>mm,UI_INPUT:()=>ym,UI_LABEL:()=>bm,UI_TABLE:()=>gm,indexHtml:()=>dm,instanceOriginFromEnv:()=>Fk,packageJson:()=>sm,scaffoldAppFiles:()=>Kk,starterApp:()=>Vk,viteConfig:()=>im});function Dk(t,e){let r=t.trim();if(r.length<=e)return r;let n=r.slice(0,e);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function Uk(t){let e={name:Dk(t.title,jk)},r=(t.description??"").trim().slice(0,Lk);return r&&(e.description=r),e.icon="favicon.svg",e.learnings={...Ua},JSON.stringify(e,null,2)+`
451
+ `}function sm(t){return`${JSON.stringify({name:t,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:Mk},dependencies:{react:"^19.2.0","react-dom":"^19.2.0","class-variance-authority":"^0.7.1",clsx:"^2.1.1","tailwind-merge":"^3.0.0","lucide-react":"^0.469.0","@fontsource/inter":"^5.1.0"},devDependencies:{"@types/react":"^19.2.0","@types/react-dom":"^19.2.0","@vitejs/plugin-react":"^4.3.1",tailwindcss:"^4.0.0","@tailwindcss/vite":"^4.0.0","tw-animate-css":"^1.2.5",typescript:"^5.5.3",vite:"^5.4.0"}},null,2)}
452
+ `}function Bk(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 Fk(t=process.env){let e=(t.TENANT_SLUG??"").trim(),r=(t.TENANT_DOMAIN_ROOT??"").trim();if(!(!e||!r))return`https://${e}.${r}`}function im(t,e={}){let r=Bk(e.instanceOrigin);return`import { defineConfig } from 'vite';
394
453
  import { fileURLToPath, URL } from 'node:url';
395
454
  import react from '@vitejs/plugin-react';
396
455
  // Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
@@ -409,8 +468,8 @@ import tailwindcss from '@tailwindcss/vite';
409
468
  // you sign in, and the cookies land on localhost:3000. Override the targets
410
469
  // with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
411
470
  // them at boot; restart the dev server after changing one).
412
- const TENANT = process.env.SUPABASE_URL || '${r??Ek}'; // /rest + the Realtime WS
413
- const API = process.env.TURBOBASE_API_URL || '${r??Pk}'; // /v1, /auth, /login, /_app
471
+ const TENANT = process.env.SUPABASE_URL || '${r??qk}'; // /rest + the Realtime WS
472
+ const API = process.env.TURBOBASE_API_URL || '${r??zk}'; // /v1, /auth, /login, /_app
414
473
 
415
474
  // Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
416
475
  // this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
@@ -448,7 +507,7 @@ export default defineConfig({
448
507
  },
449
508
  build: { outDir: 'dist' },
450
509
  });
451
- `}function im(t){return`<!doctype html>
510
+ `}function dm(t){return`<!doctype html>
452
511
  <html lang="en">
453
512
  <head>
454
513
  <meta charset="UTF-8" />
@@ -461,7 +520,7 @@ export default defineConfig({
461
520
  <script type="module" src="/src/main.tsx"></script>
462
521
  </body>
463
522
  </html>
464
- `}function Ok(t){return{"package.json":tm(t.slug),"vite.config.ts":rm(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":Ik,"tsconfig.json":nm,"index.html":im(t.title),"public/turbobase.json":Rk(t),"public/favicon.svg":Zh(t.slug,t.title),"src/main.tsx":am,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":em,"src/styles.css":lm,"components.json":om,"src/lib/utils.ts":sm,"src/components/ui/button.tsx":cm,"src/components/ui/card.tsx":dm,"src/components/ui/badge.tsx":um,"src/components/ui/table.tsx":pm,"src/components/ui/input.tsx":hm,"src/components/ui/label.tsx":mm,"README.md":`# ${t.title}
523
+ `}function Kk(t){return{"package.json":sm(t.slug),"vite.config.ts":im(t.slug,{instanceOrigin:t.instanceOrigin}),".gitignore":Hk,"tsconfig.json":am,"index.html":dm(t.title),"public/turbobase.json":Uk(t),"public/favicon.svg":rm(t.slug,t.title),"src/main.tsx":um,"src/App.tsx":t.appTsx,"src/lib/turbobase.ts":om,"src/styles.css":pm,"components.json":lm,"src/lib/utils.ts":cm,"src/components/ui/button.tsx":hm,"src/components/ui/card.tsx":mm,"src/components/ui/badge.tsx":fm,"src/components/ui/table.tsx":gm,"src/components/ui/input.tsx":ym,"src/components/ui/label.tsx":bm,"README.md":`# ${t.title}
465
524
 
466
525
  \`\`\`sh
467
526
  npm install
@@ -482,7 +541,7 @@ every read comes back "permission denied", which looks like an RLS problem.
482
541
 
483
542
  \`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
484
543
  live access token and is gitignored \u2014 keep it that way.
485
- `}}function Nk(t){return`import React from 'react';
544
+ `}}function Vk(t){return`import React from 'react';
486
545
  import { Loader2, Trash2 } from 'lucide-react';
487
546
 
488
547
  import { select, write, del } from '@/lib/turbobase';
@@ -707,7 +766,7 @@ export default function App() {
707
766
  </main>
708
767
  );
709
768
  }
710
- `}var kk,Tk,em,Ln,$k,Ek,Pk,Ik,nm,om,sm,am,lm,cm,dm,um,pm,hm,mm,gm=j(()=>{Qh();ja();kk=200,Tk=60;em=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
769
+ `}var Lk,jk,om,jn,Mk,qk,zk,Hk,am,lm,cm,um,pm,hm,mm,fm,gm,ym,bm,vm=j(()=>{nm();Ma();Lk=200,jk=60;om=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
711
770
  // Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
712
771
  // A cold first paint that fans out many reads should use batch() \u2014 ONE request
713
772
  // that multiplexes them, sidestepping the per-request rate limiter.
@@ -1960,7 +2019,7 @@ export async function cancelProcessRun(runId: string): Promise<{ cancelled: bool
1960
2019
  if (!res.ok) throw await writeError(res, 'process run');
1961
2020
  return (await res.json()) as { cancelled: boolean };
1962
2021
  }
1963
- `,Ln="src/types.ts",$k=`turbobase project types -o ${Ln} || node -e "if(require('node:fs').existsSync('${Ln}')){console.error('turbobase: could not refresh ${Ln} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Ln} 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 ${Ln}');process.exit(1)}"`;Ek="http://localhost:54331",Pk="http://localhost:4100";Ik=`node_modules/
2022
+ `,jn="src/types.ts",Mk=`turbobase project types -o ${jn} || node -e "if(require('node:fs').existsSync('${jn}')){console.error('turbobase: could not refresh ${jn} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${jn} 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 ${jn}');process.exit(1)}"`;qk="http://localhost:54331",zk="http://localhost:4100";Hk=`node_modules/
1964
2023
  dist/
1965
2024
  build/
1966
2025
 
@@ -1972,9 +2031,9 @@ build/
1972
2031
  !.env.example
1973
2032
 
1974
2033
  .DS_Store
1975
- `,nm=`${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)}
1976
- `,om=`${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)}
1977
- `,sm=`import { clsx, type ClassValue } from 'clsx';
2034
+ `,am=`${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)}
2035
+ `,lm=`${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)}
2036
+ `,cm=`import { clsx, type ClassValue } from 'clsx';
1978
2037
  import { twMerge } from 'tailwind-merge';
1979
2038
 
1980
2039
  /**
@@ -1988,7 +2047,7 @@ import { twMerge } from 'tailwind-merge';
1988
2047
  export function cn(...inputs: ClassValue[]) {
1989
2048
  return twMerge(clsx(inputs));
1990
2049
  }
1991
- `;am=`import React from 'react';
2050
+ `;um=`import React from 'react';
1992
2051
  import { createRoot } from 'react-dom/client';
1993
2052
  import App from './App';
1994
2053
  import './styles.css';
@@ -1998,7 +2057,7 @@ createRoot(document.getElementById('root')!).render(
1998
2057
  <App />
1999
2058
  </React.StrictMode>,
2000
2059
  );
2001
- `,lm=`@import 'tailwindcss';
2060
+ `,pm=`@import 'tailwindcss';
2002
2061
  @import 'tw-animate-css';
2003
2062
 
2004
2063
  /* Inter, self-hosted \u2014 the design system's font.
@@ -2086,7 +2145,7 @@ createRoot(document.getElementById('root')!).render(
2086
2145
  transition-duration: 0.01ms !important;
2087
2146
  }
2088
2147
  }
2089
- `,cm=`import * as React from 'react';
2148
+ `,hm=`import * as React from 'react';
2090
2149
  import { cva, type VariantProps } from 'class-variance-authority';
2091
2150
 
2092
2151
  import { cn } from '@/lib/utils';
@@ -2126,7 +2185,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
2126
2185
  Button.displayName = 'Button';
2127
2186
 
2128
2187
  export { Button, buttonVariants };
2129
- `,dm=`import * as React from 'react';
2188
+ `,mm=`import * as React from 'react';
2130
2189
 
2131
2190
  import { cn } from '@/lib/utils';
2132
2191
 
@@ -2164,7 +2223,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
2164
2223
  CardContent.displayName = 'CardContent';
2165
2224
 
2166
2225
  export { Card, CardHeader, CardTitle, CardDescription, CardContent };
2167
- `,um=`import * as React from 'react';
2226
+ `,fm=`import * as React from 'react';
2168
2227
  import { cva, type VariantProps } from 'class-variance-authority';
2169
2228
 
2170
2229
  import { cn } from '@/lib/utils';
@@ -2199,7 +2258,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
2199
2258
  }
2200
2259
 
2201
2260
  export { Badge, badgeVariants };
2202
- `,pm=`import * as React from 'react';
2261
+ `,gm=`import * as React from 'react';
2203
2262
 
2204
2263
  import { cn } from '@/lib/utils';
2205
2264
 
@@ -2258,7 +2317,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
2258
2317
  TableCell.displayName = 'TableCell';
2259
2318
 
2260
2319
  export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
2261
- `,hm=`import * as React from 'react';
2320
+ `,ym=`import * as React from 'react';
2262
2321
 
2263
2322
  import { cn } from '@/lib/utils';
2264
2323
 
@@ -2278,7 +2337,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
2278
2337
  Input.displayName = 'Input';
2279
2338
 
2280
2339
  export { Input };
2281
- `,mm=`import * as React from 'react';
2340
+ `,bm=`import * as React from 'react';
2282
2341
 
2283
2342
  import { cn } from '@/lib/utils';
2284
2343
 
@@ -2295,55 +2354,55 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
2295
2354
  Label.displayName = 'Label';
2296
2355
 
2297
2356
  export { Label };
2298
- `});import*as ym from"zod/v3";import*as yr from"zod/v4-mini";function Et(t){return!!t._zod}function br(t){let e=Object.values(t);if(e.length===0)return yr.object({});let r=e.every(Et),n=e.every(o=>!Et(o));if(r)return yr.object(t);if(n)return ym.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Yt(t,e){return Et(t)?yr.safeParse(t,e):t.safeParse(e)}async function ps(t,e){return Et(t)?await yr.safeParseAsync(t,e):await t.safeParseAsync(e)}function Xt(t){if(!t)return;let e;if(Et(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Kr(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return br(t)}}if(Et(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 Lk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function hs(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 ${Lk(e.path)}`:e.message).join(`
2299
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function bm(t){return t.description}function wm(t){if(Et(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Vr(t){if(Et(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var jn=j(()=>{});import*as c from"zod/v4";function jm(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Dm(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ja,vm,Zt,fs,Ae,_m,Sm,JN,jk,Dk,Ya,tt,Dn,km,je,it,at,De,gs,Tm,Xa,xm,Rm,Za,Un,G,Qa,$m,Em,YN,ys,Uk,bs,Mk,Mn,Gr,Pm,qk,zk,Bk,Fk,Hk,Kk,el,Vk,Gk,tl,ws,Wk,Jk,vs,Yk,qn,zn,Xk,Bn,Wr,Zk,Fn,_s,Ss,ks,XN,Ts,xs,Rs,Am,Cm,Im,rl,Om,Hn,Jr,Nm,Qk,$s,eT,Es,tT,nl,rT,Ps,nT,oT,sT,iT,aT,lT,cT,dT,uT,pT,As,hT,mT,Cs,ol,sl,il,fT,gT,yT,al,bT,wT,vT,_T,ST,Lm,Is,kT,Os,ZN,TT,Yr,xT,QN,Kn,RT,ll,$T,ET,PT,AT,CT,IT,OT,ms,NT,LT,jT,Vn,cl,DT,UT,MT,qT,zT,BT,FT,HT,KT,VT,GT,WT,JT,YT,XT,ZT,QT,ex,Xr,tx,rx,nx,Ns,ox,sx,ix,dl,ax,eL,tL,rL,nL,oL,sL,B,Wa,Zr=j(()=>{Ja="2025-11-25",vm=[Ja,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Zt="io.modelcontextprotocol/related-task",fs="2.0",Ae=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_m=c.union([c.string(),c.number().int()]),Sm=c.string(),JN=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),jk=c.object({ttl:c.number().optional()}),Dk=c.object({taskId:c.string()}),Ya=c.looseObject({progressToken:_m.optional(),[Zt]:Dk.optional()}),tt=c.object({_meta:Ya.optional()}),Dn=tt.extend({task:jk.optional()}),km=t=>Dn.safeParse(t).success,je=c.object({method:c.string(),params:tt.loose().optional()}),it=c.object({_meta:Ya.optional()}),at=c.object({method:c.string(),params:it.loose().optional()}),De=c.looseObject({_meta:Ya.optional()}),gs=c.union([c.string(),c.number().int()]),Tm=c.object({jsonrpc:c.literal(fs),id:gs,...je.shape}).strict(),Xa=t=>Tm.safeParse(t).success,xm=c.object({jsonrpc:c.literal(fs),...at.shape}).strict(),Rm=t=>xm.safeParse(t).success,Za=c.object({jsonrpc:c.literal(fs),id:gs,result:De}).strict(),Un=t=>Za.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"})(G||(G={}));Qa=c.object({jsonrpc:c.literal(fs),id:gs.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),$m=t=>Qa.safeParse(t).success,Em=c.union([Tm,xm,Za,Qa]),YN=c.union([Za,Qa]),ys=De.strict(),Uk=it.extend({requestId:gs.optional(),reason:c.string().optional()}),bs=at.extend({method:c.literal("notifications/cancelled"),params:Uk}),Mk=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Mn=c.object({icons:c.array(Mk).optional()}),Gr=c.object({name:c.string(),title:c.string().optional()}),Pm=Gr.extend({...Gr.shape,...Mn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),qk=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),zk=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:qk.optional(),url:Ae.optional()}),c.record(c.string(),c.unknown()).optional())),Bk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Ae.optional()}).optional(),elicitation:c.looseObject({create:Ae.optional()}).optional()}).optional()}),Fk=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({tools:c.looseObject({call:Ae.optional()}).optional()}).optional()}),Hk=c.object({experimental:c.record(c.string(),Ae).optional(),sampling:c.object({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:zk.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Bk.optional(),extensions:c.record(c.string(),Ae).optional()}),Kk=tt.extend({protocolVersion:c.string(),capabilities:Hk,clientInfo:Pm}),el=je.extend({method:c.literal("initialize"),params:Kk}),Vk=c.object({experimental:c.record(c.string(),Ae).optional(),logging:Ae.optional(),completions:Ae.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:Fk.optional(),extensions:c.record(c.string(),Ae).optional()}),Gk=De.extend({protocolVersion:c.string(),capabilities:Vk,serverInfo:Pm,instructions:c.string().optional()}),tl=at.extend({method:c.literal("notifications/initialized"),params:it.optional()}),ws=je.extend({method:c.literal("ping"),params:tt.optional()}),Wk=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),Jk=c.object({...it.shape,...Wk.shape,progressToken:_m}),vs=at.extend({method:c.literal("notifications/progress"),params:Jk}),Yk=tt.extend({cursor:Sm.optional()}),qn=je.extend({params:Yk.optional()}),zn=De.extend({nextCursor:Sm.optional()}),Xk=c.enum(["working","input_required","completed","failed","cancelled"]),Bn=c.object({taskId:c.string(),status:Xk,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Wr=De.extend({task:Bn}),Zk=it.merge(Bn),Fn=at.extend({method:c.literal("notifications/tasks/status"),params:Zk}),_s=je.extend({method:c.literal("tasks/get"),params:tt.extend({taskId:c.string()})}),Ss=De.merge(Bn),ks=je.extend({method:c.literal("tasks/result"),params:tt.extend({taskId:c.string()})}),XN=De.loose(),Ts=qn.extend({method:c.literal("tasks/list")}),xs=zn.extend({tasks:c.array(Bn)}),Rs=je.extend({method:c.literal("tasks/cancel"),params:tt.extend({taskId:c.string()})}),Am=De.merge(Bn),Cm=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),Im=Cm.extend({text:c.string()}),rl=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Om=Cm.extend({blob:rl}),Hn=c.enum(["user","assistant"]),Jr=c.object({audience:c.array(Hn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),Nm=c.object({...Gr.shape,...Mn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Jr.optional(),_meta:c.optional(c.looseObject({}))}),Qk=c.object({...Gr.shape,...Mn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Jr.optional(),_meta:c.optional(c.looseObject({}))}),$s=qn.extend({method:c.literal("resources/list")}),eT=zn.extend({resources:c.array(Nm)}),Es=qn.extend({method:c.literal("resources/templates/list")}),tT=zn.extend({resourceTemplates:c.array(Qk)}),nl=tt.extend({uri:c.string()}),rT=nl,Ps=je.extend({method:c.literal("resources/read"),params:rT}),nT=De.extend({contents:c.array(c.union([Im,Om]))}),oT=at.extend({method:c.literal("notifications/resources/list_changed"),params:it.optional()}),sT=nl,iT=je.extend({method:c.literal("resources/subscribe"),params:sT}),aT=nl,lT=je.extend({method:c.literal("resources/unsubscribe"),params:aT}),cT=it.extend({uri:c.string()}),dT=at.extend({method:c.literal("notifications/resources/updated"),params:cT}),uT=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),pT=c.object({...Gr.shape,...Mn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(uT)),_meta:c.optional(c.looseObject({}))}),As=qn.extend({method:c.literal("prompts/list")}),hT=zn.extend({prompts:c.array(pT)}),mT=tt.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Cs=je.extend({method:c.literal("prompts/get"),params:mT}),ol=c.object({type:c.literal("text"),text:c.string(),annotations:Jr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),sl=c.object({type:c.literal("image"),data:rl,mimeType:c.string(),annotations:Jr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),il=c.object({type:c.literal("audio"),data:rl,mimeType:c.string(),annotations:Jr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),fT=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()}),gT=c.object({type:c.literal("resource"),resource:c.union([Im,Om]),annotations:Jr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),yT=Nm.extend({type:c.literal("resource_link")}),al=c.union([ol,sl,il,yT,gT]),bT=c.object({role:Hn,content:al}),wT=De.extend({description:c.string().optional(),messages:c.array(bT)}),vT=at.extend({method:c.literal("notifications/prompts/list_changed"),params:it.optional()}),_T=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),ST=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),Lm=c.object({...Gr.shape,...Mn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:_T.optional(),execution:ST.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Is=qn.extend({method:c.literal("tools/list")}),kT=zn.extend({tools:c.array(Lm)}),Os=De.extend({content:c.array(al).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),ZN=Os.or(De.extend({toolResult:c.unknown()})),TT=Dn.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Yr=je.extend({method:c.literal("tools/call"),params:TT}),xT=at.extend({method:c.literal("notifications/tools/list_changed"),params:it.optional()}),QN=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Kn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),RT=tt.extend({level:Kn}),ll=je.extend({method:c.literal("logging/setLevel"),params:RT}),$T=it.extend({level:Kn,logger:c.string().optional(),data:c.unknown()}),ET=at.extend({method:c.literal("notifications/message"),params:$T}),PT=c.object({name:c.string().optional()}),AT=c.object({hints:c.array(PT).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()}),CT=c.object({mode:c.enum(["auto","required","none"]).optional()}),IT=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(al).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),OT=c.discriminatedUnion("type",[ol,sl,il]),ms=c.discriminatedUnion("type",[ol,sl,il,fT,IT]),NT=c.object({role:Hn,content:c.union([ms,c.array(ms)]),_meta:c.record(c.string(),c.unknown()).optional()}),LT=Dn.extend({messages:c.array(NT),modelPreferences:AT.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:Ae.optional(),tools:c.array(Lm).optional(),toolChoice:CT.optional()}),jT=je.extend({method:c.literal("sampling/createMessage"),params:LT}),Vn=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Hn,content:OT}),cl=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Hn,content:c.union([ms,c.array(ms)])}),DT=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),UT=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()}),MT=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()}),qT=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),zT=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()}),BT=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()}),FT=c.union([qT,zT]),HT=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()}),KT=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()}),VT=c.union([HT,KT]),GT=c.union([BT,FT,VT]),WT=c.union([GT,DT,UT,MT]),JT=Dn.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),WT),required:c.array(c.string()).optional()})}),YT=Dn.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),XT=c.union([JT,YT]),ZT=je.extend({method:c.literal("elicitation/create"),params:XT}),QT=it.extend({elicitationId:c.string()}),ex=at.extend({method:c.literal("notifications/elicitation/complete"),params:QT}),Xr=De.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())}),tx=c.object({type:c.literal("ref/resource"),uri:c.string()}),rx=c.object({type:c.literal("ref/prompt"),name:c.string()}),nx=tt.extend({ref:c.union([rx,tx]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Ns=je.extend({method:c.literal("completion/complete"),params:nx});ox=De.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),sx=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ix=je.extend({method:c.literal("roots/list"),params:tt.optional()}),dl=De.extend({roots:c.array(sx)}),ax=at.extend({method:c.literal("notifications/roots/list_changed"),params:it.optional()}),eL=c.union([ws,el,Ns,ll,Cs,As,$s,Es,Ps,iT,lT,Yr,Is,_s,ks,Ts,Rs]),tL=c.union([bs,vs,tl,ax,Fn]),rL=c.union([ys,Vn,cl,Xr,dl,Ss,xs,Wr]),nL=c.union([ws,jT,ZT,ix,_s,ks,Ts,Rs]),oL=c.union([bs,vs,ET,dT,oT,xT,vT,Fn,ex]),sL=c.union([ys,Gk,ox,wT,hT,eT,tT,nT,Os,kT,Ss,xs,Wr]),B=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===G.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Wa(o.elicitations,r)}return new t(e,r,n)}},Wa=class extends B{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(G.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Qt(t){return t==="completed"||t==="failed"||t==="cancelled"}var Um=j(()=>{});var qm,Mm,zm,Ls=j(()=>{qm=Symbol("Let zodToJsonSchema decide on which parser to use"),Mm={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"},zm=t=>typeof t=="string"?{...Mm,name:t}:{...Mm,...t}});var Bm,ul=j(()=>{Ls();Bm=t=>{let e=zm(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function pl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ce(t,e,r,n,o){t[e]=r,pl(t,e,n,o)}var er=j(()=>{});var js,Ds=j(()=>{js=(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 Te(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?js(e,t.currentPath):e.join("/")}}var lt=j(()=>{Ds()});import{ZodFirstPartyTypeKind as lx}from"zod/v3";function Fm(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==lx.ZodAny&&(r.items=Z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var hl=j(()=>{er();Pe()});function Hm(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?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var ml=j(()=>{er()});function Km(){return{type:"boolean"}}var fl=j(()=>{});function Us(t,e){return Z(t.type._def,e)}var Ms=j(()=>{Pe()});var Vm,gl=j(()=>{Pe();Vm=(t,e)=>Z(t.innerType._def,e)});function yl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>yl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return cx(t,e)}}var cx,bl=j(()=>{er();cx=(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":ce(r,"minimum",n.value,n.message,e);break;case"max":ce(r,"maximum",n.value,n.message,e);break}return r}});function Gm(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}var wl=j(()=>{Pe()});function Wm(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):Te(e)}var vl=j(()=>{Pe();lt()});function Jm(t){return{type:"string",enum:Array.from(t.values)}}var _l=j(()=>{});function Ym(t,e){let r=[Z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(dx(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...l}=s;i=l}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var dx,Sl=j(()=>{Pe();dx=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function Xm(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 kl=j(()=>{});function qs(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ce(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":bt(r,"email",n.message,e);break;case"format:idn-email":bt(r,"idn-email",n.message,e);break;case"pattern:zod":He(r,yt.email,n.message,e);break}break;case"url":bt(r,"uri",n.message,e);break;case"uuid":bt(r,"uuid",n.message,e);break;case"regex":He(r,n.regex,n.message,e);break;case"cuid":He(r,yt.cuid,n.message,e);break;case"cuid2":He(r,yt.cuid2,n.message,e);break;case"startsWith":He(r,RegExp(`^${xl(n.value,e)}`),n.message,e);break;case"endsWith":He(r,RegExp(`${xl(n.value,e)}$`),n.message,e);break;case"datetime":bt(r,"date-time",n.message,e);break;case"date":bt(r,"date",n.message,e);break;case"time":bt(r,"time",n.message,e);break;case"duration":bt(r,"duration",n.message,e);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{He(r,RegExp(xl(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&bt(r,"ipv4",n.message,e),n.version!=="v4"&&bt(r,"ipv6",n.message,e);break}case"base64url":He(r,yt.base64url,n.message,e);break;case"jwt":He(r,yt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&He(r,yt.ipv4Cidr,n.message,e),n.version!=="v4"&&He(r,yt.ipv6Cidr,n.message,e);break}case"emoji":He(r,yt.emoji(),n.message,e);break;case"ulid":{He(r,yt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{bt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{He(r,yt.base64,n.message,e);break}}break}case"nanoid":He(r,yt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function xl(t,e){return e.patternStrategy==="escape"?px(t):t}function px(t){let e="";for(let r=0;r<t.length;r++)ux.has(t[r])||(e+="\\"),e+=t[r];return e}function bt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ce(t,"format",e,r,n)}function He(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Zm(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(t,"pattern",Zm(e,n),r,n)}function Zm(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],a=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
2357
+ `});import*as _m from"zod/v3";import*as br from"zod/v4-mini";function Pt(t){return!!t._zod}function wr(t){let e=Object.values(t);if(e.length===0)return br.object({});let r=e.every(Pt),n=e.every(o=>!Pt(o));if(r)return br.object(t);if(n)return _m.object(t);throw new Error("Mixed Zod versions detected in object shape.")}function Zt(t,e){return Pt(t)?br.safeParse(t,e):t.safeParse(e)}async function fs(t,e){return Pt(t)?await br.safeParseAsync(t,e):await t.safeParseAsync(e)}function Qt(t){if(!t)return;let e;if(Pt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Vr(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return wr(t)}}if(Pt(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 Gk(t){return t.length===0?"object root":t.reduce((e,r,n)=>n===0?String(r):typeof r=="number"?`${e}[${r}]`:`${e}.${r}`,"")}function gs(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 ${Gk(e.path)}`:e.message).join(`
2358
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Sm(t){return t.description}function km(t){if(Pt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Gr(t){if(Pt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Dn=j(()=>{});import*as c from"zod/v4";function qm(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function zm(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Za,Tm,er,bs,Ae,Rm,xm,aL,Wk,Jk,Qa,rt,Un,$m,je,lt,ct,De,ws,Em,el,Pm,Am,tl,Mn,W,rl,Cm,Im,lL,vs,Yk,_s,Xk,qn,Wr,Om,Zk,Qk,eT,tT,rT,nT,nl,oT,sT,ol,Ss,iT,aT,ks,lT,zn,Bn,cT,Fn,Jr,dT,Hn,Ts,Rs,xs,cL,$s,Es,Ps,Nm,Lm,jm,sl,Dm,Kn,Yr,Um,uT,As,pT,Cs,hT,il,mT,Is,fT,gT,yT,bT,wT,vT,_T,ST,kT,TT,Os,RT,xT,Ns,al,ll,cl,$T,ET,PT,dl,AT,CT,IT,OT,NT,Mm,Ls,LT,js,dL,jT,Xr,DT,uL,Vn,UT,ul,MT,qT,zT,BT,FT,HT,KT,ys,VT,GT,WT,Gn,pl,JT,YT,XT,ZT,QT,eR,tR,rR,nR,oR,sR,iR,aR,lR,cR,dR,uR,pR,Zr,hR,mR,fR,Ds,gR,yR,bR,hl,wR,pL,hL,mL,fL,gL,yL,F,Xa,Qr=j(()=>{Za="2025-11-25",Tm=[Za,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],er="io.modelcontextprotocol/related-task",bs="2.0",Ae=c.custom(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Rm=c.union([c.string(),c.number().int()]),xm=c.string(),aL=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),Wk=c.object({ttl:c.number().optional()}),Jk=c.object({taskId:c.string()}),Qa=c.looseObject({progressToken:Rm.optional(),[er]:Jk.optional()}),rt=c.object({_meta:Qa.optional()}),Un=rt.extend({task:Wk.optional()}),$m=t=>Un.safeParse(t).success,je=c.object({method:c.string(),params:rt.loose().optional()}),lt=c.object({_meta:Qa.optional()}),ct=c.object({method:c.string(),params:lt.loose().optional()}),De=c.looseObject({_meta:Qa.optional()}),ws=c.union([c.string(),c.number().int()]),Em=c.object({jsonrpc:c.literal(bs),id:ws,...je.shape}).strict(),el=t=>Em.safeParse(t).success,Pm=c.object({jsonrpc:c.literal(bs),...ct.shape}).strict(),Am=t=>Pm.safeParse(t).success,tl=c.object({jsonrpc:c.literal(bs),id:ws,result:De}).strict(),Mn=t=>tl.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(W||(W={}));rl=c.object({jsonrpc:c.literal(bs),id:ws.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),Cm=t=>rl.safeParse(t).success,Im=c.union([Em,Pm,tl,rl]),lL=c.union([tl,rl]),vs=De.strict(),Yk=lt.extend({requestId:ws.optional(),reason:c.string().optional()}),_s=ct.extend({method:c.literal("notifications/cancelled"),params:Yk}),Xk=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),qn=c.object({icons:c.array(Xk).optional()}),Wr=c.object({name:c.string(),title:c.string().optional()}),Om=Wr.extend({...Wr.shape,...qn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),Zk=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Qk=c.preprocess(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,c.intersection(c.object({form:Zk.optional(),url:Ae.optional()}),c.record(c.string(),c.unknown()).optional())),eT=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({sampling:c.looseObject({createMessage:Ae.optional()}).optional(),elicitation:c.looseObject({create:Ae.optional()}).optional()}).optional()}),tT=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({tools:c.looseObject({call:Ae.optional()}).optional()}).optional()}),rT=c.object({experimental:c.record(c.string(),Ae).optional(),sampling:c.object({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:Qk.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:eT.optional(),extensions:c.record(c.string(),Ae).optional()}),nT=rt.extend({protocolVersion:c.string(),capabilities:rT,clientInfo:Om}),nl=je.extend({method:c.literal("initialize"),params:nT}),oT=c.object({experimental:c.record(c.string(),Ae).optional(),logging:Ae.optional(),completions:Ae.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:tT.optional(),extensions:c.record(c.string(),Ae).optional()}),sT=De.extend({protocolVersion:c.string(),capabilities:oT,serverInfo:Om,instructions:c.string().optional()}),ol=ct.extend({method:c.literal("notifications/initialized"),params:lt.optional()}),Ss=je.extend({method:c.literal("ping"),params:rt.optional()}),iT=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),aT=c.object({...lt.shape,...iT.shape,progressToken:Rm}),ks=ct.extend({method:c.literal("notifications/progress"),params:aT}),lT=rt.extend({cursor:xm.optional()}),zn=je.extend({params:lT.optional()}),Bn=De.extend({nextCursor:xm.optional()}),cT=c.enum(["working","input_required","completed","failed","cancelled"]),Fn=c.object({taskId:c.string(),status:cT,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),Jr=De.extend({task:Fn}),dT=lt.merge(Fn),Hn=ct.extend({method:c.literal("notifications/tasks/status"),params:dT}),Ts=je.extend({method:c.literal("tasks/get"),params:rt.extend({taskId:c.string()})}),Rs=De.merge(Fn),xs=je.extend({method:c.literal("tasks/result"),params:rt.extend({taskId:c.string()})}),cL=De.loose(),$s=zn.extend({method:c.literal("tasks/list")}),Es=Bn.extend({tasks:c.array(Fn)}),Ps=je.extend({method:c.literal("tasks/cancel"),params:rt.extend({taskId:c.string()})}),Nm=De.merge(Fn),Lm=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),jm=Lm.extend({text:c.string()}),sl=c.string().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Dm=Lm.extend({blob:sl}),Kn=c.enum(["user","assistant"]),Yr=c.object({audience:c.array(Kn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),Um=c.object({...Wr.shape,...qn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:Yr.optional(),_meta:c.optional(c.looseObject({}))}),uT=c.object({...Wr.shape,...qn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:Yr.optional(),_meta:c.optional(c.looseObject({}))}),As=zn.extend({method:c.literal("resources/list")}),pT=Bn.extend({resources:c.array(Um)}),Cs=zn.extend({method:c.literal("resources/templates/list")}),hT=Bn.extend({resourceTemplates:c.array(uT)}),il=rt.extend({uri:c.string()}),mT=il,Is=je.extend({method:c.literal("resources/read"),params:mT}),fT=De.extend({contents:c.array(c.union([jm,Dm]))}),gT=ct.extend({method:c.literal("notifications/resources/list_changed"),params:lt.optional()}),yT=il,bT=je.extend({method:c.literal("resources/subscribe"),params:yT}),wT=il,vT=je.extend({method:c.literal("resources/unsubscribe"),params:wT}),_T=lt.extend({uri:c.string()}),ST=ct.extend({method:c.literal("notifications/resources/updated"),params:_T}),kT=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),TT=c.object({...Wr.shape,...qn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(kT)),_meta:c.optional(c.looseObject({}))}),Os=zn.extend({method:c.literal("prompts/list")}),RT=Bn.extend({prompts:c.array(TT)}),xT=rt.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Ns=je.extend({method:c.literal("prompts/get"),params:xT}),al=c.object({type:c.literal("text"),text:c.string(),annotations:Yr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ll=c.object({type:c.literal("image"),data:sl,mimeType:c.string(),annotations:Yr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),cl=c.object({type:c.literal("audio"),data:sl,mimeType:c.string(),annotations:Yr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),$T=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()}),ET=c.object({type:c.literal("resource"),resource:c.union([jm,Dm]),annotations:Yr.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),PT=Um.extend({type:c.literal("resource_link")}),dl=c.union([al,ll,cl,PT,ET]),AT=c.object({role:Kn,content:dl}),CT=De.extend({description:c.string().optional(),messages:c.array(AT)}),IT=ct.extend({method:c.literal("notifications/prompts/list_changed"),params:lt.optional()}),OT=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),NT=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),Mm=c.object({...Wr.shape,...qn.shape,description:c.string().optional(),inputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()),outputSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Ae).optional(),required:c.array(c.string()).optional()}).catchall(c.unknown()).optional(),annotations:OT.optional(),execution:NT.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Ls=zn.extend({method:c.literal("tools/list")}),LT=Bn.extend({tools:c.array(Mm)}),js=De.extend({content:c.array(dl).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),dL=js.or(De.extend({toolResult:c.unknown()})),jT=Un.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),Xr=je.extend({method:c.literal("tools/call"),params:jT}),DT=ct.extend({method:c.literal("notifications/tools/list_changed"),params:lt.optional()}),uL=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Vn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),UT=rt.extend({level:Vn}),ul=je.extend({method:c.literal("logging/setLevel"),params:UT}),MT=lt.extend({level:Vn,logger:c.string().optional(),data:c.unknown()}),qT=ct.extend({method:c.literal("notifications/message"),params:MT}),zT=c.object({name:c.string().optional()}),BT=c.object({hints:c.array(zT).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()}),FT=c.object({mode:c.enum(["auto","required","none"]).optional()}),HT=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(dl).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),KT=c.discriminatedUnion("type",[al,ll,cl]),ys=c.discriminatedUnion("type",[al,ll,cl,$T,HT]),VT=c.object({role:Kn,content:c.union([ys,c.array(ys)]),_meta:c.record(c.string(),c.unknown()).optional()}),GT=Un.extend({messages:c.array(VT),modelPreferences:BT.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:Ae.optional(),tools:c.array(Mm).optional(),toolChoice:FT.optional()}),WT=je.extend({method:c.literal("sampling/createMessage"),params:GT}),Gn=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Kn,content:KT}),pl=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Kn,content:c.union([ys,c.array(ys)])}),JT=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),YT=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()}),XT=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()}),ZT=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),QT=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()}),eR=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()}),tR=c.union([ZT,QT]),rR=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()}),nR=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()}),oR=c.union([rR,nR]),sR=c.union([eR,tR,oR]),iR=c.union([sR,JT,YT,XT]),aR=Un.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),iR),required:c.array(c.string()).optional()})}),lR=Un.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),cR=c.union([aR,lR]),dR=je.extend({method:c.literal("elicitation/create"),params:cR}),uR=lt.extend({elicitationId:c.string()}),pR=ct.extend({method:c.literal("notifications/elicitation/complete"),params:uR}),Zr=De.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())}),hR=c.object({type:c.literal("ref/resource"),uri:c.string()}),mR=c.object({type:c.literal("ref/prompt"),name:c.string()}),fR=rt.extend({ref:c.union([mR,hR]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Ds=je.extend({method:c.literal("completion/complete"),params:fR});gR=De.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),yR=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),bR=je.extend({method:c.literal("roots/list"),params:rt.optional()}),hl=De.extend({roots:c.array(yR)}),wR=ct.extend({method:c.literal("notifications/roots/list_changed"),params:lt.optional()}),pL=c.union([Ss,nl,Ds,ul,Ns,Os,As,Cs,Is,bT,vT,Xr,Ls,Ts,xs,$s,Ps]),hL=c.union([_s,ks,ol,wR,Hn]),mL=c.union([vs,Gn,pl,Zr,hl,Rs,Es,Jr]),fL=c.union([Ss,WT,dR,bR,Ts,xs,$s,Ps]),gL=c.union([_s,ks,qT,ST,gT,DT,IT,Hn,pR]),yL=c.union([vs,sT,gR,CT,RT,pT,hT,fT,js,LT,Rs,Es,Jr]),F=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===W.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Xa(o.elicitations,r)}return new t(e,r,n)}},Xa=class extends F{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(W.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function tr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Bm=j(()=>{});var Hm,Fm,Km,Us=j(()=>{Hm=Symbol("Let zodToJsonSchema decide on which parser to use"),Fm={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"},Km=t=>typeof t=="string"?{...Fm,name:t}:{...Fm,...t}});var Vm,ml=j(()=>{Us();Vm=t=>{let e=Km(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function fl(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ce(t,e,r,n,o){t[e]=r,fl(t,e,n,o)}var rr=j(()=>{});var Ms,qs=j(()=>{Ms=(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 Te(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Ms(e,t.currentPath):e.join("/")}}var dt=j(()=>{qs()});import{ZodFirstPartyTypeKind as vR}from"zod/v3";function Gm(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==vR.ZodAny&&(r.items=Z(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(r,"minItems",t.exactLength.value,t.exactLength.message,e),ce(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var gl=j(()=>{rr();Pe()});function Wm(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?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var yl=j(()=>{rr()});function Jm(){return{type:"boolean"}}var bl=j(()=>{});function zs(t,e){return Z(t.type._def,e)}var Bs=j(()=>{Pe()});var Ym,wl=j(()=>{Pe();Ym=(t,e)=>Z(t.innerType._def,e)});function vl(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>vl(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return _R(t,e)}}var _R,_l=j(()=>{rr();_R=(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":ce(r,"minimum",n.value,n.message,e);break;case"max":ce(r,"maximum",n.value,n.message,e);break}return r}});function Xm(t,e){return{...Z(t.innerType._def,e),default:t.defaultValue()}}var Sl=j(()=>{Pe()});function Zm(t,e){return e.effectStrategy==="input"?Z(t.schema._def,e):Te(e)}var kl=j(()=>{Pe();dt()});function Qm(t){return{type:"string",enum:Array.from(t.values)}}var Tl=j(()=>{});function ef(t,e){let r=[Z(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Z(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(SR(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...l}=s;i=l}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var SR,Rl=j(()=>{Pe();SR=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function tf(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 xl=j(()=>{});function Fs(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ce(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":wt(r,"email",n.message,e);break;case"format:idn-email":wt(r,"idn-email",n.message,e);break;case"pattern:zod":Ke(r,bt.email,n.message,e);break}break;case"url":wt(r,"uri",n.message,e);break;case"uuid":wt(r,"uuid",n.message,e);break;case"regex":Ke(r,n.regex,n.message,e);break;case"cuid":Ke(r,bt.cuid,n.message,e);break;case"cuid2":Ke(r,bt.cuid2,n.message,e);break;case"startsWith":Ke(r,RegExp(`^${El(n.value,e)}`),n.message,e);break;case"endsWith":Ke(r,RegExp(`${El(n.value,e)}$`),n.message,e);break;case"datetime":wt(r,"date-time",n.message,e);break;case"date":wt(r,"date",n.message,e);break;case"time":wt(r,"time",n.message,e);break;case"duration":wt(r,"duration",n.message,e);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Ke(r,RegExp(El(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&wt(r,"ipv4",n.message,e),n.version!=="v4"&&wt(r,"ipv6",n.message,e);break}case"base64url":Ke(r,bt.base64url,n.message,e);break;case"jwt":Ke(r,bt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Ke(r,bt.ipv4Cidr,n.message,e),n.version!=="v4"&&Ke(r,bt.ipv6Cidr,n.message,e);break}case"emoji":Ke(r,bt.emoji(),n.message,e);break;case"ulid":{Ke(r,bt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{wt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Ke(r,bt.base64,n.message,e);break}}break}case"nanoid":Ke(r,bt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function El(t,e){return e.patternStrategy==="escape"?TR(t):t}function TR(t){let e="";for(let r=0;r<t.length;r++)kR.has(t[r])||(e+="\\"),e+=t[r];return e}function wt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ce(t,"format",e,r,n)}function Ke(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:rf(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(t,"pattern",rf(e,n),r,n)}function rf(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let l=0;l<n.length;l++){if(s){o+=n[l],s=!1;continue}if(r.i){if(i){if(n[l].match(/[a-z]/)){a?(o+=n[l],o+=`${n[l-2]}-${n[l]}`.toUpperCase(),a=!1):n[l+1]==="-"&&n[l+2]?.match(/[a-z]/)?(o+=n[l],a=!0):o+=`${n[l]}${n[l].toUpperCase()}`;continue}}else if(n[l].match(/[a-z]/)){o+=`[${n[l]}${n[l].toUpperCase()}]`;continue}}if(r.m){if(n[l]==="^"){o+=`(^|(?<=[\r
2300
2359
  ]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
2301
2360
  ]))`;continue}}if(r.s&&n[l]==="."){o+=i?`${n[l]}\r
2302
2361
  `:`[${n[l]}\r
2303
- ]`;continue}o+=n[l],n[l]==="\\"?s=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Tl,yt,ux,zs=j(()=>{er();yt={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:()=>(Tl===void 0&&(Tl=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Tl),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-_]*$/};ux=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Gn}from"zod/v3";function Bs(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===Gn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Te(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Gn.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=qs(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Gn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Gn.ZodBranded&&t.keyType._def.type._def.typeName===Gn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Us(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Fs=j(()=>{Pe();zs();Ms();lt()});function Qm(t,e){if(e.mapStrategy==="record")return Bs(t,e);let r=Z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Te(e),n=Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Te(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Rl=j(()=>{Pe();Fs();lt()});function ef(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var $l=j(()=>{});function tf(t){return t.target==="openAi"?void 0:{not:Te({...t,currentPath:[...t.currentPath,"not"]})}}var El=j(()=>{lt()});function rf(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Pl=j(()=>{});function of(t,e){if(e.target==="openApi3")return nf(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Wn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Wn[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return nf(t,e)}var Wn,nf,Hs=j(()=>{Pe();Wn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};nf=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Z(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function sf(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:Wn[t.innerType._def.typeName],nullable:!0}:{type:[Wn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Al=j(()=>{Pe();Hs()});function af(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",pl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var Cl=j(()=>{er()});function lf(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let l=s[a];if(l===void 0||l._def===void 0)continue;let u=mx(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=Z(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,u||o.push(a))}o.length&&(n.required=o);let i=hx(t,e);return i!==void 0&&(n.additionalProperties=i),n}function hx(t,e){if(t.catchall._def.typeName!=="ZodNever")return Z(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 mx(t){try{return t.isOptional()}catch{return!0}}var Il=j(()=>{Pe()});var cf,Ol=j(()=>{Pe();lt();cf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Z(t.innerType._def,e);let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Te(e)},r]}:Te(e)}});var df,Nl=j(()=>{Pe();df=(t,e)=>{if(e.pipeStrategy==="input")return Z(t.in._def,e);if(e.pipeStrategy==="output")return Z(t.out._def,e);let r=Z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function uf(t,e){return Z(t.type._def,e)}var Ll=j(()=>{Pe()});function pf(t,e){let n={type:"array",uniqueItems:!0,items:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var jl=j(()=>{er();Pe()});function hf(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Dl=j(()=>{Pe()});function mf(t){return{not:Te(t)}}var Ul=j(()=>{lt()});function ff(t){return Te(t)}var Ml=j(()=>{lt()});var gf,ql=j(()=>{Pe();gf=(t,e)=>Z(t.innerType._def,e)});import{ZodFirstPartyTypeKind as le}from"zod/v3";var yf,zl=j(()=>{lt();hl();ml();fl();Ms();gl();bl();wl();vl();_l();Sl();kl();Rl();$l();El();Pl();Al();Cl();Il();Ol();Nl();Ll();Fs();jl();zs();Dl();Ul();Hs();Ml();ql();yf=(t,e,r)=>{switch(e){case le.ZodString:return qs(t,r);case le.ZodNumber:return af(t,r);case le.ZodObject:return lf(t,r);case le.ZodBigInt:return Hm(t,r);case le.ZodBoolean:return Km();case le.ZodDate:return yl(t,r);case le.ZodUndefined:return mf(r);case le.ZodNull:return rf(r);case le.ZodArray:return Fm(t,r);case le.ZodUnion:case le.ZodDiscriminatedUnion:return of(t,r);case le.ZodIntersection:return Ym(t,r);case le.ZodTuple:return hf(t,r);case le.ZodRecord:return Bs(t,r);case le.ZodLiteral:return Xm(t,r);case le.ZodEnum:return Jm(t);case le.ZodNativeEnum:return ef(t);case le.ZodNullable:return sf(t,r);case le.ZodOptional:return cf(t,r);case le.ZodMap:return Qm(t,r);case le.ZodSet:return pf(t,r);case le.ZodLazy:return()=>t.getter()._def;case le.ZodPromise:return uf(t,r);case le.ZodNaN:case le.ZodNever:return tf(r);case le.ZodEffects:return Wm(t,r);case le.ZodAny:return Te(r);case le.ZodUnknown:return ff(r);case le.ZodDefault:return Gm(t,r);case le.ZodBranded:return Us(t,r);case le.ZodReadonly:return gf(t,r);case le.ZodCatch:return Vm(t,r);case le.ZodPipeline:return df(t,r);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(e)}}});function Z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==qm)return a}if(n&&!r){let a=fx(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=yf(t,t.typeName,e),i=typeof s=="function"?Z(s(),e):s;if(i&&gx(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var fx,gx,Pe=j(()=>{Ls();zl();Ds();lt();fx=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:js(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`),Te(e)):e.$refStrategy==="seen"?Te(e):void 0}},gx=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var bf=j(()=>{});var Bl,Fl=j(()=>{Pe();ul();lt();Bl=(t,e)=>{let r=Bm(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:Z(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Te(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Z(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Te(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var wf=j(()=>{Ls();ul();er();Ds();Pe();bf();lt();hl();ml();fl();Ms();gl();bl();wl();vl();_l();Sl();kl();Rl();$l();El();Pl();Al();Cl();Il();Ol();Nl();Ll();ql();Fs();jl();zs();Dl();Ul();Hs();Ml();zl();Fl();Fl()});import*as vf from"zod/v4-mini";function yx(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Hl(t,e){return Et(t)?vf.toJSONSchema(t,{target:yx(e?.target),io:e?.pipeStrategy??"input"}):Bl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Kl(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Vr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Vl(t,e){let r=Yt(t,e);if(!r.success)throw r.error;return r.data}var Gl=j(()=>{jn();wf()});function _f(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Sf(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];_f(i)&&_f(s)?r[o]={...i,...s}:r[o]=s}return r}var bx,Ks,kf=j(()=>{jn();Zr();Um();Gl();bx=6e4,Ks=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(bs,r=>{this._oncancel(r)}),this.setNotificationHandler(vs,r=>{this._onprogress(r)}),this.setRequestHandler(ws,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(_s,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(ks,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(l);else{let g=l,S=new B(g.error.code,g.error.message,g.error.data);p(S)}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(s,n.sessionId);if(!i)throw new B(G.InvalidParams,`Task not found: ${s}`);if(!Qt(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qt(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Zt]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ts,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new B(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Rs,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qt(o.status))throw new B(G.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new B(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof B?o:new B(G.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),B.fromError(G.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Un(s)||$m(s)?this._onresponse(s):Xa(s)?this._onrequest(s,i):Rm(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=B.fromError(G.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Zt]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:G.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.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=km(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(p,g)},sendRequest:async(p,g,S)=>{if(i.signal.aborted)throw new B(G.ConnectionClosed,"Request was cancelled");let y={...S,relatedRequestId:e.id};s&&!y.relatedTask&&(y.relatedTask={taskId:s});let x=y.relatedTask?.taskId??s;return x&&l&&await l.updateTaskStatus(x,"input_required"),await this.request(p,g,y)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async p=>{if(i.signal.aborted)return;let g={result:p,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.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:G.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.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,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Un(e))n(e);else{let i=new B(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Un(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Un(e))o(e);else{let i=B.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof B?i:new B(G.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Wr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new B(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Qt(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new B(G.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(G.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof B?i:new B(G.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((u,p)=>{let g=I=>{p(I)};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(I){g(I);return}n?.signal?.throwIfAborted();let S=this._requestMessageId++,y={...e,jsonrpc:"2.0",id:S};n?.onprogress&&(this._progressHandlers.set(S,n.onprogress),y.params={...e.params,_meta:{...e.params?._meta||{},progressToken:S}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[Zt]:l}});let x=I=>{this._responseHandlers.delete(S),this._progressHandlers.delete(S),this._cleanupTimeout(S),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:S,reason:String(I)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(F=>this._onerror(new Error(`Failed to send cancellation: ${F}`)));let D=I instanceof B?I:new B(G.RequestTimeout,String(I));p(D)};this._responseHandlers.set(S,I=>{if(!n?.signal?.aborted){if(I instanceof Error)return p(I);try{let D=Yt(r,I.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{x(n?.signal?.reason)});let R=n?.timeout??bx,E=()=>x(B.fromError(G.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(S,R,n?.maxTotalTimeout,E,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let I=D=>{let F=this._responseHandlers.get(S);F?F(D):this._onerror(new Error(`Response handler missing for side-channeled request ${S}`))};this._requestResolvers.set(S,I),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(S),p(D)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(S),p(I)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ss,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},xs,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Am,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||{},[Zt]: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||{},[Zt]: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||{},[Zt]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Kl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Vl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Kl(e);this._notificationHandlers.set(n,o=>{let s=Vl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Xa(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new B(G.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new B(G.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new B(G.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new B(G.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let l=Fn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),Qt(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new B(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qt(a.status))throw new B(G.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let l=await n.getTask(o,r);if(l){let u=Fn.parse({method:"notifications/tasks/status",params:l});await this.notification(u),Qt(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Xn=U(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var Jn=class{};he._CodeOrName=Jn;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var wr=class extends Jn{constructor(e){if(super(),!he.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};he.Name=wr;var ct=class extends Jn{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 wr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=ct;he.nil=new ct("");function Tf(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Jl(r,e[n]),r.push(t[++n]);return new ct(r)}he._=Tf;var Wl=new ct("+");function xf(t,...e){let r=[Yn(t[0])],n=0;for(;n<e.length;)r.push(Wl),Jl(r,e[n]),r.push(Wl,Yn(t[++n]));return wx(r),new ct(r)}he.str=xf;function Jl(t,e){e instanceof ct?t.push(...e._items):e instanceof wr?t.push(e):t.push(Sx(e))}he.addCodeArg=Jl;function wx(t){let e=1;for(;e<t.length-1;){if(t[e]===Wl){let r=vx(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function vx(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof wr||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 wr))return`"${t}${e.slice(1)}`}function _x(t,e){return e.emptyStr()?t:t.emptyStr()?e:xf`${t}${e}`}he.strConcat=_x;function Sx(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Yn(Array.isArray(t)?t.join(","):t)}function kx(t){return new ct(Yn(t))}he.stringify=kx;function Yn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Yn;function Tx(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new ct(`.${t}`):Tf`[${t}]`}he.getProperty=Tx;function xx(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new ct(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=xx;function Rx(t){return new ct(t.toString())}he.regexpCode=Rx});var Zl=U(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Ye=Xn(),Yl=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Vs;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Vs||(Xe.UsedValueState=Vs={}));Xe.varKinds={const:new Ye.Name("const"),let:new Ye.Name("let"),var:new Ye.Name("var")};var Gs=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Ye.Name?e:this.name(e)}name(e){return new Ye.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}}};Xe.Scope=Gs;var Ws=class extends Ye.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Ye._)`.${new Ye.Name(r)}[${n}]`}};Xe.ValueScopeName=Ws;var $x=(0,Ye._)`\n`,Xl=class extends Gs{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?$x:Ye.nil}}get(){return this._scope}name(e){return new Ws(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let p=a.get(i);if(p)return p}else a=this._values[s]=new Map;a.set(i,o);let l=this._scope[s]||(this._scope[s]=[]),u=l.length;return l[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ye._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Ye.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,Vs.Started);let p=r(u);if(p){let g=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;s=(0,Ye._)`${s}${g} ${u} = ${p};${this.opts._n}`}else if(p=o?.(u))s=(0,Ye._)`${s}${p}${this.opts._n}`;else throw new Yl(u);l.set(u,Vs.Completed)})}return s}};Xe.ValueScope=Xl});var re=U(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var de=Xn(),wt=Zl(),tr=Xn();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return tr._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return tr.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return tr.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return tr.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return tr.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return tr.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return tr.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return tr.Name}});var Zs=Zl();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return Zs.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return Zs.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return Zs.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return Zs.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var Mt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ql=class extends Mt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?wt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=en(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},Js=class extends Mt{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 de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=en(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return Xs(e,this.rhs)}},ec=class extends Js{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},tc=class extends Mt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},rc=class extends Mt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},nc=class extends Mt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},oc=class extends Mt{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=en(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},Zn=class extends Mt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(Ex(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Sr(e,r.names),{})}},qt=class extends Zn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},sc=class extends Zn{},Qr=class extends qt{};Qr.kind="else";var vr=class t extends qt{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 Qr(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Rf(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=en(this.condition,e,r),this}get names(){let e=super.names;return Xs(e,this.condition),this.else&&Sr(e,this.else.names),e}};vr.kind="if";var _r=class extends qt{};_r.kind="for";var ic=class extends _r{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=en(this.iteration,e,r),this}get names(){return Sr(super.names,this.iteration.names)}},ac=class extends _r{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?wt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Xs(super.names,this.from);return Xs(e,this.to)}},Ys=class extends _r{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=en(this.iterable,e,r),this}get names(){return Sr(super.names,this.iterable.names)}},Qn=class extends qt{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)}};Qn.kind="func";var eo=class extends Zn{render(e){return"return "+super.render(e)}};eo.kind="return";var lc=class extends qt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Sr(e,this.catch.names),this.finally&&Sr(e,this.finally.names),e}},to=class extends qt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};to.kind="catch";var ro=class extends qt{render(e){return"finally"+super.render(e)}};ro.kind="finally";var cc=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2304
- `:""},this._extScope=e,this._scope=new wt.Scope({parent:e}),this._nodes=[new sc]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Ql(e,s,n)),s}const(e,r,n){return this._def(wt.varKinds.const,e,r,n)}let(e,r,n){return this._def(wt.varKinds.let,e,r,n)}var(e,r,n){return this._def(wt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Js(e,r,n))}add(e,r){return this._leafNode(new ec(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new oc(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,de.addCodeArg)(r,o));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new vr(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 vr(e))}else(){return this._elseNode(new Qr)}endIf(){return this._endBlockNode(vr,Qr)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new ic(e),r)}forRange(e,r,n,o,s=this.opts.es5?wt.varKinds.var:wt.varKinds.let){let i=this._scope.toName(e);return this._for(new ac(s,i,r,n),()=>o(i))}forOf(e,r,n,o=wt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(s,(0,de._)`${i}[${a}]`),n(s)})}return this._for(new Ys("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?wt.varKinds.var:wt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Ys("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(_r)}label(e){return this._leafNode(new tc(e))}break(e){return this._leafNode(new rc(e))}return(e){let r=new eo;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(eo)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new lc;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new to(s),r(s)}return n&&(this._currNode=o.finally=new ro,this.code(n)),this._endBlockNode(to,ro)}throw(e){return this._leafNode(new nc(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=de.nil,n,o){return this._blockNode(new Qn(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Qn)}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 vr))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}};ne.CodeGen=cc;function Sr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Xs(t,e){return e instanceof de._CodeOrName?Sr(t,e.names):t}function en(t,e,r){if(t instanceof de.Name)return n(t);if(!o(t))return t;return new de._Code(t._items.reduce((s,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof de._Code&&s._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function Ex(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Rf(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,de._)`!${dc(t)}`}ne.not=Rf;var Px=$f(ne.operators.AND);function Ax(...t){return t.reduce(Px)}ne.and=Ax;var Cx=$f(ne.operators.OR);function Ix(...t){return t.reduce(Cx)}ne.or=Ix;function $f(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${dc(e)} ${t} ${dc(r)}`}function dc(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var ue=U(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;var ve=re(),Ox=Xn();function Nx(t){let e={};for(let r of t)e[r]=!0;return e}se.toHash=Nx;function Lx(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Af(t,e),!Cf(e,t.self.RULES.all))}se.alwaysValidSchema=Lx;function Af(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Nf(t,`unknown keyword: "${s}"`)}se.checkUnknownRules=Af;function Cf(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}se.schemaHasRules=Cf;function jx(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}se.schemaHasRulesButRef=jx;function Dx({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ve._)`${r}`}return(0,ve._)`${t}${e}${(0,ve.getProperty)(n)}`}se.schemaRefOrVal=Dx;function Ux(t){return If(decodeURIComponent(t))}se.unescapeFragment=Ux;function Mx(t){return encodeURIComponent(pc(t))}se.escapeFragment=Mx;function pc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=pc;function If(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=If;function qx(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}se.eachItem=qx;function Ef({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof ve.Name?(s instanceof ve.Name?t(o,s,i):e(o,s,i),i):s instanceof ve.Name?(e(o,i,s),s):r(s,i);return a===ve.Name&&!(l instanceof ve.Name)?n(o,l):l}}se.mergeEvaluated={props:Ef({mergeNames:(t,e,r)=>t.if((0,ve._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ve._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ve._)`${r} || {}`).code((0,ve._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ve._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ve._)`${r} || {}`),hc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Of}),items:Ef({mergeNames:(t,e,r)=>t.if((0,ve._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ve._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ve._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ve._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Of(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ve._)`{}`);return e!==void 0&&hc(t,r,e),r}se.evaluatedPropsToName=Of;function hc(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ve._)`${e}${(0,ve.getProperty)(n)}`,!0))}se.setEvaluated=hc;var Pf={};function zx(t,e){return t.scopeValue("func",{ref:e,code:Pf[e.code]||(Pf[e.code]=new Ox._Code(e.code))})}se.useFunc=zx;var uc;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(uc||(se.Type=uc={}));function Bx(t,e,r){if(t instanceof ve.Name){let n=e===uc.Num;return r?n?(0,ve._)`"[" + ${t} + "]"`:(0,ve._)`"['" + ${t} + "']"`:n?(0,ve._)`"/" + ${t}`:(0,ve._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ve.getProperty)(t).toString():"/"+pc(t)}se.getErrorPath=Bx;function Nf(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}se.checkStrictMode=Nf});var zt=U(mc=>{"use strict";Object.defineProperty(mc,"__esModule",{value:!0});var qe=re(),Fx={data:new qe.Name("data"),valCxt:new qe.Name("valCxt"),instancePath:new qe.Name("instancePath"),parentData:new qe.Name("parentData"),parentDataProperty:new qe.Name("parentDataProperty"),rootData:new qe.Name("rootData"),dynamicAnchors:new qe.Name("dynamicAnchors"),vErrors:new qe.Name("vErrors"),errors:new qe.Name("errors"),this:new qe.Name("this"),self:new qe.Name("self"),scope:new qe.Name("scope"),json:new qe.Name("json"),jsonPos:new qe.Name("jsonPos"),jsonLen:new qe.Name("jsonLen"),jsonPart:new qe.Name("jsonPart")};mc.default=Fx});var no=U(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.extendErrors=ze.resetErrorsCount=ze.reportExtraError=ze.reportError=ze.keyword$DataError=ze.keywordError=void 0;var pe=re(),Qs=ue(),Ke=zt();ze.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};ze.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function Hx(t,e=ze.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,l=Df(t,e,r);n??(i||a)?Lf(s,l):jf(o,(0,pe._)`[${l}]`)}ze.reportError=Hx;function Kx(t,e=ze.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Df(t,e,r);Lf(o,a),s||i||jf(n,Ke.default.vErrors)}ze.reportExtraError=Kx;function Vx(t,e){t.assign(Ke.default.errors,e),t.if((0,pe._)`${Ke.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${Ke.default.vErrors}.length`,e),()=>t.assign(Ke.default.vErrors,null)))}ze.resetErrorsCount=Vx;function Gx({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Ke.default.errors,a=>{t.const(i,(0,pe._)`${Ke.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(Ke.default.instancePath,s.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,r),t.assign((0,pe._)`${i}.data`,n))})}ze.extendErrors=Gx;function Lf(t,e){let r=t.const("err",e);t.if((0,pe._)`${Ke.default.vErrors} === null`,()=>t.assign(Ke.default.vErrors,(0,pe._)`[${r}]`),(0,pe._)`${Ke.default.vErrors}.push(${r})`),t.code((0,pe._)`${Ke.default.errors}++`)}function jf(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,pe._)`new ${t.ValidationError}(${e})`):(r.assign((0,pe._)`${n}.errors`,e),r.return(!1))}var kr={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function Df(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,pe._)`{}`:Wx(t,e,r)}function Wx(t,e,r={}){let{gen:n,it:o}=t,s=[Jx(o,r),Yx(t,r)];return Xx(t,e,s),n.object(...s)}function Jx({errorPath:t},{instancePath:e}){let r=e?(0,pe.str)`${t}${(0,Qs.getErrorPath)(e,Qs.Type.Str)}`:t;return[Ke.default.instancePath,(0,pe.strConcat)(Ke.default.instancePath,r)]}function Yx({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,pe.str)`${e}/${t}`;return r&&(o=(0,pe.str)`${o}${(0,Qs.getErrorPath)(r,Qs.Type.Str)}`),[kr.schemaPath,o]}function Xx(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:g}=a;n.push([kr.keyword,o],[kr.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),l.messages&&n.push([kr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([kr.schema,i],[kr.parentSchema,(0,pe._)`${p}${g}`],[Ke.default.data,s]),u&&n.push([kr.propertyName,u])}});var Mf=U(tn=>{"use strict";Object.defineProperty(tn,"__esModule",{value:!0});tn.boolOrEmptySchema=tn.topBoolOrEmptySchema=void 0;var Zx=no(),Qx=re(),eR=zt(),tR={message:"boolean schema is false"};function rR(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Uf(t,!1):typeof r=="object"&&r.$async===!0?e.return(eR.default.data):(e.assign((0,Qx._)`${n}.errors`,null),e.return(!0))}tn.topBoolOrEmptySchema=rR;function nR(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Uf(t)):r.var(e,!0)}tn.boolOrEmptySchema=nR;function Uf(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Zx.reportError)(o,tR,void 0,e)}});var fc=U(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.getRules=rn.isJSONType=void 0;var oR=["string","number","integer","boolean","null","object","array"],sR=new Set(oR);function iR(t){return typeof t=="string"&&sR.has(t)}rn.isJSONType=iR;function aR(){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:{}}}rn.getRules=aR});var gc=U(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.shouldUseRule=rr.shouldUseGroup=rr.schemaHasRulesForType=void 0;function lR({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&qf(t,n)}rr.schemaHasRulesForType=lR;function qf(t,e){return e.rules.some(r=>zf(t,r))}rr.shouldUseGroup=qf;function zf(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))}rr.shouldUseRule=zf});var oo=U(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.reportTypeError=Be.checkDataTypes=Be.checkDataType=Be.coerceAndCheckDataType=Be.getJSONTypes=Be.getSchemaTypes=Be.DataType=void 0;var cR=fc(),dR=gc(),uR=no(),te=re(),Bf=ue(),nn;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(nn||(Be.DataType=nn={}));function pR(t){let e=Ff(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}Be.getSchemaTypes=pR;function Ff(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(cR.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Be.getJSONTypes=Ff;function hR(t,e){let{gen:r,data:n,opts:o}=t,s=mR(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,dR.schemaHasRulesForType)(t,e[0]));if(i){let a=bc(e,n,o.strictNumbers,nn.Wrong);r.if(a,()=>{s.length?fR(t,e,s):wc(t)})}return i}Be.coerceAndCheckDataType=hR;var Hf=new Set(["string","number","integer","boolean","null"]);function mR(t,e){return e?t.filter(r=>Hf.has(r)||e==="array"&&r==="array"):[]}function fR(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,te._)`typeof ${o}`),a=n.let("coerced",(0,te._)`undefined`);s.coerceTypes==="array"&&n.if((0,te._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,te._)`${o}[0]`).assign(i,(0,te._)`typeof ${o}`).if(bc(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,te._)`${a} !== undefined`);for(let u of r)(Hf.has(u)||u==="array"&&s.coerceTypes==="array")&&l(u);n.else(),wc(t),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(o,a),gR(t,a)});function l(u){switch(u){case"string":n.elseIf((0,te._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,te._)`"" + ${o}`).elseIf((0,te._)`${o} === null`).assign(a,(0,te._)`""`);return;case"number":n.elseIf((0,te._)`${i} == "boolean" || ${o} === null
2362
+ ]`;continue}o+=n[l],n[l]==="\\"?s=!0:i&&n[l]==="]"?i=!1:!i&&n[l]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var $l,bt,kR,Hs=j(()=>{rr();bt={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:()=>($l===void 0&&($l=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),$l),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-_]*$/};kR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as Wn}from"zod/v3";function Ks(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===Wn.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Te(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===Wn.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Fs(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===Wn.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===Wn.ZodBranded&&t.keyType._def.type._def.typeName===Wn.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=zs(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Vs=j(()=>{Pe();Hs();Bs();dt()});function nf(t,e){if(e.mapStrategy==="record")return Ks(t,e);let r=Z(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Te(e),n=Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Te(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Pl=j(()=>{Pe();Vs();dt()});function of(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Al=j(()=>{});function sf(t){return t.target==="openAi"?void 0:{not:Te({...t,currentPath:[...t.currentPath,"not"]})}}var Cl=j(()=>{dt()});function af(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Il=j(()=>{});function cf(t,e){if(e.target==="openApi3")return lf(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Jn&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Jn[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return lf(t,e)}var Jn,lf,Gs=j(()=>{Pe();Jn={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};lf=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Z(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function df(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:Jn[t.innerType._def.typeName],nullable:!0}:{type:[Jn[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Z(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Ol=j(()=>{Pe();Gs()});function uf(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",fl(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,e):ce(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,e):ce(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,e));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,e);break}return r}var Nl=j(()=>{rr()});function pf(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let l=s[a];if(l===void 0||l._def===void 0)continue;let u=xR(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=Z(l._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,u||o.push(a))}o.length&&(n.required=o);let i=RR(t,e);return i!==void 0&&(n.additionalProperties=i),n}function RR(t,e){if(t.catchall._def.typeName!=="ZodNever")return Z(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 xR(t){try{return t.isOptional()}catch{return!0}}var Ll=j(()=>{Pe()});var hf,jl=j(()=>{Pe();dt();hf=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Z(t.innerType._def,e);let r=Z(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Te(e)},r]}:Te(e)}});var mf,Dl=j(()=>{Pe();mf=(t,e)=>{if(e.pipeStrategy==="input")return Z(t.in._def,e);if(e.pipeStrategy==="output")return Z(t.out._def,e);let r=Z(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Z(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function ff(t,e){return Z(t.type._def,e)}var Ul=j(()=>{Pe()});function gf(t,e){let n={type:"array",uniqueItems:!0,items:Z(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Ml=j(()=>{rr();Pe()});function yf(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Z(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var ql=j(()=>{Pe()});function bf(t){return{not:Te(t)}}var zl=j(()=>{dt()});function wf(t){return Te(t)}var Bl=j(()=>{dt()});var vf,Fl=j(()=>{Pe();vf=(t,e)=>Z(t.innerType._def,e)});import{ZodFirstPartyTypeKind as le}from"zod/v3";var _f,Hl=j(()=>{dt();gl();yl();bl();Bs();wl();_l();Sl();kl();Tl();Rl();xl();Pl();Al();Cl();Il();Ol();Nl();Ll();jl();Dl();Ul();Vs();Ml();Hs();ql();zl();Gs();Bl();Fl();_f=(t,e,r)=>{switch(e){case le.ZodString:return Fs(t,r);case le.ZodNumber:return uf(t,r);case le.ZodObject:return pf(t,r);case le.ZodBigInt:return Wm(t,r);case le.ZodBoolean:return Jm();case le.ZodDate:return vl(t,r);case le.ZodUndefined:return bf(r);case le.ZodNull:return af(r);case le.ZodArray:return Gm(t,r);case le.ZodUnion:case le.ZodDiscriminatedUnion:return cf(t,r);case le.ZodIntersection:return ef(t,r);case le.ZodTuple:return yf(t,r);case le.ZodRecord:return Ks(t,r);case le.ZodLiteral:return tf(t,r);case le.ZodEnum:return Qm(t);case le.ZodNativeEnum:return of(t);case le.ZodNullable:return df(t,r);case le.ZodOptional:return hf(t,r);case le.ZodMap:return nf(t,r);case le.ZodSet:return gf(t,r);case le.ZodLazy:return()=>t.getter()._def;case le.ZodPromise:return ff(t,r);case le.ZodNaN:case le.ZodNever:return sf(r);case le.ZodEffects:return Zm(t,r);case le.ZodAny:return Te(r);case le.ZodUnknown:return wf(r);case le.ZodDefault:return Xm(t,r);case le.ZodBranded:return zs(t,r);case le.ZodReadonly:return vf(t,r);case le.ZodCatch:return Ym(t,r);case le.ZodPipeline:return mf(t,r);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(e)}}});function Z(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==Hm)return a}if(n&&!r){let a=$R(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=_f(t,t.typeName,e),i=typeof s=="function"?Z(s(),e):s;if(i&&ER(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var $R,ER,Pe=j(()=>{Us();Hl();qs();dt();$R=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ms(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`),Te(e)):e.$refStrategy==="seen"?Te(e):void 0}},ER=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var Sf=j(()=>{});var Kl,Vl=j(()=>{Pe();ml();dt();Kl=(t,e)=>{let r=Vm(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,p])=>({...l,[u]:Z(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Te(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Z(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Te(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var kf=j(()=>{Us();ml();rr();qs();Pe();Sf();dt();gl();yl();bl();Bs();wl();_l();Sl();kl();Tl();Rl();xl();Pl();Al();Cl();Il();Ol();Nl();Ll();jl();Dl();Ul();Fl();Vs();Ml();Hs();ql();zl();Gs();Bl();Hl();Vl();Vl()});import*as Tf from"zod/v4-mini";function PR(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Gl(t,e){return Pt(t)?Tf.toJSONSchema(t,{target:PR(e?.target),io:e?.pipeStrategy??"input"}):Kl(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Wl(t){let r=Qt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Gr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Jl(t,e){let r=Zt(t,e);if(!r.success)throw r.error;return r.data}var Yl=j(()=>{Dn();kf()});function Rf(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function xf(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];Rf(i)&&Rf(s)?r[o]={...i,...s}:r[o]=s}return r}var AR,Ws,$f=j(()=>{Dn();Qr();Bm();Yl();AR=6e4,Ws=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(_s,r=>{this._oncancel(r)}),this.setNotificationHandler(ks,r=>{this._onprogress(r)}),this.setRequestHandler(Ss,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ts,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new F(W.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(xs,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let l=a.message,u=l.id,p=this._requestResolvers.get(u);if(p)if(this._requestResolvers.delete(u),a.type==="response")p(l);else{let g=l,k=new F(g.error.code,g.error.message,g.error.data);p(k)}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(s,n.sessionId);if(!i)throw new F(W.InvalidParams,`Task not found: ${s}`);if(!tr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(tr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[er]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler($s,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new F(W.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ps,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new F(W.InvalidParams,`Task not found: ${r.params.taskId}`);if(tr(o.status))throw new F(W.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new F(W.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof F?o:new F(W.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),F.fromError(W.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Mn(s)||Cm(s)?this._onresponse(s):el(s)?this._onrequest(s,i):Am(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=F.fromError(W.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[er]?.taskId;if(n===void 0){let p={jsonrpc:"2.0",id:e.id,error:{code:W.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId).catch(g=>this._onerror(new Error(`Failed to enqueue error response: ${g}`))):o?.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=$m(e.params)?e.params.task:void 0,l=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async p=>{if(i.signal.aborted)return;let g={relatedRequestId:e.id};s&&(g.relatedTask={taskId:s}),await this.notification(p,g)},sendRequest:async(p,g,k)=>{if(i.signal.aborted)throw new F(W.ConnectionClosed,"Request was cancelled");let b={...k,relatedRequestId:e.id};s&&!b.relatedTask&&(b.relatedTask={taskId:s});let R=b.relatedTask?.taskId??s;return R&&l&&await l.updateTaskStatus(R,"input_required"),await this.request(p,g,b)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:l,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async p=>{if(i.signal.aborted)return;let g={result:p,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:g,timestamp:Date.now()},o?.sessionId):await o?.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:W.InternalError,message:p.message??"Internal error",...p.data!==void 0&&{data:p.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:g,timestamp:Date.now()},o?.sessionId):await o?.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,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(l){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(l);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Mn(e))n(e);else{let i=new F(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Mn(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Mn(e))o(e);else{let i=F.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof F?i:new F(W.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Jr,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new F(W.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},tr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new F(W.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new F(W.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let l=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,l)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof F?i:new F(W.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((u,p)=>{let g=I=>{p(I)};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(I){g(I);return}n?.signal?.throwIfAborted();let k=this._requestMessageId++,b={...e,jsonrpc:"2.0",id:k};n?.onprogress&&(this._progressHandlers.set(k,n.onprogress),b.params={...e.params,_meta:{...e.params?._meta||{},progressToken:k}}),a&&(b.params={...b.params,task:a}),l&&(b.params={...b.params,_meta:{...b.params?._meta||{},[er]:l}});let R=I=>{this._responseHandlers.delete(k),this._progressHandlers.delete(k),this._cleanupTimeout(k),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:k,reason:String(I)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let D=I instanceof F?I:new F(W.RequestTimeout,String(I));p(D)};this._responseHandlers.set(k,I=>{if(!n?.signal?.aborted){if(I instanceof Error)return p(I);try{let D=Zt(r,I.result);D.success?u(D.data):p(D.error)}catch(D){p(D)}}}),n?.signal?.addEventListener("abort",()=>{R(n?.signal?.reason)});let x=n?.timeout??AR,E=()=>R(F.fromError(W.RequestTimeout,"Request timed out",{timeout:x}));this._setupTimeout(k,x,n?.maxTotalTimeout,E,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let I=D=>{let H=this._responseHandlers.get(k);H?H(D):this._onerror(new Error(`Response handler missing for side-channeled request ${k}`))};this._requestResolvers.set(k,I),this._enqueueTaskMessage(P,{type:"request",message:b,timestamp:Date.now()}).catch(D=>{this._cleanupTimeout(k),p(D)})}else this._transport.send(b,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(I=>{this._cleanupTimeout(k),p(I)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Rs,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},Es,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Nm,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||{},[er]: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||{},[er]: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||{},[er]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Wl(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Jl(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Wl(e);this._notificationHandlers.set(n,o=>{let s=Jl(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&el(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new F(W.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new F(W.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new F(W.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new F(W.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let l=Hn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),tr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new F(W.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(tr(a.status))throw new F(W.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let l=await n.getTask(o,r);if(l){let u=Hn.parse({method:"notifications/tasks/status",params:l});await this.notification(u),tr(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var Zn=q(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.regexpCode=me.getEsmExportName=me.getProperty=me.safeStringify=me.stringify=me.strConcat=me.addCodeArg=me.str=me._=me.nil=me._Code=me.Name=me.IDENTIFIER=me._CodeOrName=void 0;var Yn=class{};me._CodeOrName=Yn;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var vr=class extends Yn{constructor(e){if(super(),!me.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};me.Name=vr;var ut=class extends Yn{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 vr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=ut;me.nil=new ut("");function Ef(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Zl(r,e[n]),r.push(t[++n]);return new ut(r)}me._=Ef;var Xl=new ut("+");function Pf(t,...e){let r=[Xn(t[0])],n=0;for(;n<e.length;)r.push(Xl),Zl(r,e[n]),r.push(Xl,Xn(t[++n]));return CR(r),new ut(r)}me.str=Pf;function Zl(t,e){e instanceof ut?t.push(...e._items):e instanceof vr?t.push(e):t.push(NR(e))}me.addCodeArg=Zl;function CR(t){let e=1;for(;e<t.length-1;){if(t[e]===Xl){let r=IR(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function IR(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof vr||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 vr))return`"${t}${e.slice(1)}`}function OR(t,e){return e.emptyStr()?t:t.emptyStr()?e:Pf`${t}${e}`}me.strConcat=OR;function NR(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Xn(Array.isArray(t)?t.join(","):t)}function LR(t){return new ut(Xn(t))}me.stringify=LR;function Xn(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=Xn;function jR(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new ut(`.${t}`):Ef`[${t}]`}me.getProperty=jR;function DR(t){if(typeof t=="string"&&me.IDENTIFIER.test(t))return new ut(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}me.getEsmExportName=DR;function UR(t){return new ut(t.toString())}me.regexpCode=UR});var tc=q(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.ValueScope=Ze.ValueScopeName=Ze.Scope=Ze.varKinds=Ze.UsedValueState=void 0;var Xe=Zn(),Ql=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Js;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Js||(Ze.UsedValueState=Js={}));Ze.varKinds={const:new Xe.Name("const"),let:new Xe.Name("let"),var:new Xe.Name("var")};var Ys=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Xe.Name?e:this.name(e)}name(e){return new Xe.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}}};Ze.Scope=Ys;var Xs=class extends Xe.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Xe._)`.${new Xe.Name(r)}[${n}]`}};Ze.ValueScopeName=Xs;var MR=(0,Xe._)`\n`,ec=class extends Ys{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?MR:Xe.nil}}get(){return this._scope}name(e){return new Xs(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let p=a.get(i);if(p)return p}else a=this._values[s]=new Map;a.set(i,o);let l=this._scope[s]||(this._scope[s]=[]),u=l.length;return l[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Xe._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Xe.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,Js.Started);let p=r(u);if(p){let g=this.opts.es5?Ze.varKinds.var:Ze.varKinds.const;s=(0,Xe._)`${s}${g} ${u} = ${p};${this.opts._n}`}else if(p=o?.(u))s=(0,Xe._)`${s}${p}${this.opts._n}`;else throw new Ql(u);l.set(u,Js.Completed)})}return s}};Ze.ValueScope=ec});var re=q(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var de=Zn(),vt=tc(),nr=Zn();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return nr._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return nr.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return nr.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return nr.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return nr.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return nr.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return nr.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return nr.Name}});var ti=tc();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return ti.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return ti.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return ti.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return ti.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var qt=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},rc=class extends qt{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?vt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=tn(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},Zs=class extends qt{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 de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=tn(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return ei(e,this.rhs)}},nc=class extends Zs{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},oc=class extends qt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},sc=class extends qt{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ic=class extends qt{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ac=class extends qt{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=tn(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},Qn=class extends qt{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(qR(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>kr(e,r.names),{})}},zt=class extends Qn{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},lc=class extends Qn{},en=class extends zt{};en.kind="else";var _r=class t extends zt{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 en(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Af(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=tn(this.condition,e,r),this}get names(){let e=super.names;return ei(e,this.condition),this.else&&kr(e,this.else.names),e}};_r.kind="if";var Sr=class extends zt{};Sr.kind="for";var cc=class extends Sr{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=tn(this.iteration,e,r),this}get names(){return kr(super.names,this.iteration.names)}},dc=class extends Sr{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?vt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ei(super.names,this.from);return ei(e,this.to)}},Qs=class extends Sr{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=tn(this.iterable,e,r),this}get names(){return kr(super.names,this.iterable.names)}},eo=class extends zt{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)}};eo.kind="func";var to=class extends Qn{render(e){return"return "+super.render(e)}};to.kind="return";var uc=class extends zt{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&kr(e,this.catch.names),this.finally&&kr(e,this.finally.names),e}},ro=class extends zt{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ro.kind="catch";var no=class extends zt{render(e){return"finally"+super.render(e)}};no.kind="finally";var pc=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
2363
+ `:""},this._extScope=e,this._scope=new vt.Scope({parent:e}),this._nodes=[new lc]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new rc(e,s,n)),s}const(e,r,n){return this._def(vt.varKinds.const,e,r,n)}let(e,r,n){return this._def(vt.varKinds.let,e,r,n)}var(e,r,n){return this._def(vt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Zs(e,r,n))}add(e,r){return this._leafNode(new nc(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new ac(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,de.addCodeArg)(r,o));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new _r(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 _r(e))}else(){return this._elseNode(new en)}endIf(){return this._endBlockNode(_r,en)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new cc(e),r)}forRange(e,r,n,o,s=this.opts.es5?vt.varKinds.var:vt.varKinds.let){let i=this._scope.toName(e);return this._for(new dc(s,i,r,n),()=>o(i))}forOf(e,r,n,o=vt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(s,(0,de._)`${i}[${a}]`),n(s)})}return this._for(new Qs("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?vt.varKinds.var:vt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Qs("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Sr)}label(e){return this._leafNode(new oc(e))}break(e){return this._leafNode(new sc(e))}return(e){let r=new to;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(to)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new uc;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ro(s),r(s)}return n&&(this._currNode=o.finally=new no,this.code(n)),this._endBlockNode(ro,no)}throw(e){return this._leafNode(new ic(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=de.nil,n,o){return this._blockNode(new eo(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(eo)}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 _r))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}};ne.CodeGen=pc;function kr(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ei(t,e){return e instanceof de._CodeOrName?kr(t,e.names):t}function tn(t,e,r){if(t instanceof de.Name)return n(t);if(!o(t))return t;return new de._Code(t._items.reduce((s,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof de._Code&&s._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function qR(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Af(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,de._)`!${hc(t)}`}ne.not=Af;var zR=Cf(ne.operators.AND);function BR(...t){return t.reduce(zR)}ne.and=BR;var FR=Cf(ne.operators.OR);function HR(...t){return t.reduce(FR)}ne.or=HR;function Cf(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${hc(e)} ${t} ${hc(r)}`}function hc(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var pe=q(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;var we=re(),KR=Zn();function VR(t){let e={};for(let r of t)e[r]=!0;return e}se.toHash=VR;function GR(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Nf(t,e),!Lf(e,t.self.RULES.all))}se.alwaysValidSchema=GR;function Nf(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||Uf(t,`unknown keyword: "${s}"`)}se.checkUnknownRules=Nf;function Lf(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}se.schemaHasRules=Lf;function WR(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}se.schemaHasRulesButRef=WR;function JR({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,we._)`${r}`}return(0,we._)`${t}${e}${(0,we.getProperty)(n)}`}se.schemaRefOrVal=JR;function YR(t){return jf(decodeURIComponent(t))}se.unescapeFragment=YR;function XR(t){return encodeURIComponent(fc(t))}se.escapeFragment=XR;function fc(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=fc;function jf(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=jf;function ZR(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}se.eachItem=ZR;function If({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?t(o,s,i):e(o,s,i),i):s instanceof we.Name?(e(o,i,s),s):r(s,i);return a===we.Name&&!(l instanceof we.Name)?n(o,l):l}}se.mergeEvaluated={props:If({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,we._)`${r} || {}`),gc(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Df}),items:If({mergeNames:(t,e,r)=>t.if((0,we._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,we._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,we._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,we._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Df(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,we._)`{}`);return e!==void 0&&gc(t,r,e),r}se.evaluatedPropsToName=Df;function gc(t,e,r){Object.keys(r).forEach(n=>t.assign((0,we._)`${e}${(0,we.getProperty)(n)}`,!0))}se.setEvaluated=gc;var Of={};function QR(t,e){return t.scopeValue("func",{ref:e,code:Of[e.code]||(Of[e.code]=new KR._Code(e.code))})}se.useFunc=QR;var mc;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(mc||(se.Type=mc={}));function ex(t,e,r){if(t instanceof we.Name){let n=e===mc.Num;return r?n?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:n?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(t).toString():"/"+fc(t)}se.getErrorPath=ex;function Uf(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}se.checkStrictMode=Uf});var Bt=q(yc=>{"use strict";Object.defineProperty(yc,"__esModule",{value:!0});var ze=re(),tx={data:new ze.Name("data"),valCxt:new ze.Name("valCxt"),instancePath:new ze.Name("instancePath"),parentData:new ze.Name("parentData"),parentDataProperty:new ze.Name("parentDataProperty"),rootData:new ze.Name("rootData"),dynamicAnchors:new ze.Name("dynamicAnchors"),vErrors:new ze.Name("vErrors"),errors:new ze.Name("errors"),this:new ze.Name("this"),self:new ze.Name("self"),scope:new ze.Name("scope"),json:new ze.Name("json"),jsonPos:new ze.Name("jsonPos"),jsonLen:new ze.Name("jsonLen"),jsonPart:new ze.Name("jsonPart")};yc.default=tx});var oo=q(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.extendErrors=Be.resetErrorsCount=Be.reportExtraError=Be.reportError=Be.keyword$DataError=Be.keywordError=void 0;var he=re(),ri=pe(),Ve=Bt();Be.keywordError={message:({keyword:t})=>(0,he.str)`must pass "${t}" keyword validation`};Be.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,he.str)`"${t}" keyword must be ${e} ($data)`:(0,he.str)`"${t}" keyword is invalid ($data)`};function rx(t,e=Be.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,l=zf(t,e,r);n??(i||a)?Mf(s,l):qf(o,(0,he._)`[${l}]`)}Be.reportError=rx;function nx(t,e=Be.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=zf(t,e,r);Mf(o,a),s||i||qf(n,Ve.default.vErrors)}Be.reportExtraError=nx;function ox(t,e){t.assign(Ve.default.errors,e),t.if((0,he._)`${Ve.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,he._)`${Ve.default.vErrors}.length`,e),()=>t.assign(Ve.default.vErrors,null)))}Be.resetErrorsCount=ox;function sx({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Ve.default.errors,a=>{t.const(i,(0,he._)`${Ve.default.vErrors}[${a}]`),t.if((0,he._)`${i}.instancePath === undefined`,()=>t.assign((0,he._)`${i}.instancePath`,(0,he.strConcat)(Ve.default.instancePath,s.errorPath))),t.assign((0,he._)`${i}.schemaPath`,(0,he.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,he._)`${i}.schema`,r),t.assign((0,he._)`${i}.data`,n))})}Be.extendErrors=sx;function Mf(t,e){let r=t.const("err",e);t.if((0,he._)`${Ve.default.vErrors} === null`,()=>t.assign(Ve.default.vErrors,(0,he._)`[${r}]`),(0,he._)`${Ve.default.vErrors}.push(${r})`),t.code((0,he._)`${Ve.default.errors}++`)}function qf(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,he._)`new ${t.ValidationError}(${e})`):(r.assign((0,he._)`${n}.errors`,e),r.return(!1))}var Tr={keyword:new he.Name("keyword"),schemaPath:new he.Name("schemaPath"),params:new he.Name("params"),propertyName:new he.Name("propertyName"),message:new he.Name("message"),schema:new he.Name("schema"),parentSchema:new he.Name("parentSchema")};function zf(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,he._)`{}`:ix(t,e,r)}function ix(t,e,r={}){let{gen:n,it:o}=t,s=[ax(o,r),lx(t,r)];return cx(t,e,s),n.object(...s)}function ax({errorPath:t},{instancePath:e}){let r=e?(0,he.str)`${t}${(0,ri.getErrorPath)(e,ri.Type.Str)}`:t;return[Ve.default.instancePath,(0,he.strConcat)(Ve.default.instancePath,r)]}function lx({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,he.str)`${e}/${t}`;return r&&(o=(0,he.str)`${o}${(0,ri.getErrorPath)(r,ri.Type.Str)}`),[Tr.schemaPath,o]}function cx(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:g}=a;n.push([Tr.keyword,o],[Tr.params,typeof e=="function"?e(t):e||(0,he._)`{}`]),l.messages&&n.push([Tr.message,typeof r=="function"?r(t):r]),l.verbose&&n.push([Tr.schema,i],[Tr.parentSchema,(0,he._)`${p}${g}`],[Ve.default.data,s]),u&&n.push([Tr.propertyName,u])}});var Ff=q(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.boolOrEmptySchema=rn.topBoolOrEmptySchema=void 0;var dx=oo(),ux=re(),px=Bt(),hx={message:"boolean schema is false"};function mx(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Bf(t,!1):typeof r=="object"&&r.$async===!0?e.return(px.default.data):(e.assign((0,ux._)`${n}.errors`,null),e.return(!0))}rn.topBoolOrEmptySchema=mx;function fx(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Bf(t)):r.var(e,!0)}rn.boolOrEmptySchema=fx;function Bf(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,dx.reportError)(o,hx,void 0,e)}});var bc=q(nn=>{"use strict";Object.defineProperty(nn,"__esModule",{value:!0});nn.getRules=nn.isJSONType=void 0;var gx=["string","number","integer","boolean","null","object","array"],yx=new Set(gx);function bx(t){return typeof t=="string"&&yx.has(t)}nn.isJSONType=bx;function wx(){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:{}}}nn.getRules=wx});var wc=q(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.shouldUseRule=or.shouldUseGroup=or.schemaHasRulesForType=void 0;function vx({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Hf(t,n)}or.schemaHasRulesForType=vx;function Hf(t,e){return e.rules.some(r=>Kf(t,r))}or.shouldUseGroup=Hf;function Kf(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))}or.shouldUseRule=Kf});var so=q(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.reportTypeError=Fe.checkDataTypes=Fe.checkDataType=Fe.coerceAndCheckDataType=Fe.getJSONTypes=Fe.getSchemaTypes=Fe.DataType=void 0;var _x=bc(),Sx=wc(),kx=oo(),te=re(),Vf=pe(),on;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(on||(Fe.DataType=on={}));function Tx(t){let e=Gf(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}Fe.getSchemaTypes=Tx;function Gf(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(_x.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Fe.getJSONTypes=Gf;function Rx(t,e){let{gen:r,data:n,opts:o}=t,s=xx(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Sx.schemaHasRulesForType)(t,e[0]));if(i){let a=_c(e,n,o.strictNumbers,on.Wrong);r.if(a,()=>{s.length?$x(t,e,s):Sc(t)})}return i}Fe.coerceAndCheckDataType=Rx;var Wf=new Set(["string","number","integer","boolean","null"]);function xx(t,e){return e?t.filter(r=>Wf.has(r)||e==="array"&&r==="array"):[]}function $x(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,te._)`typeof ${o}`),a=n.let("coerced",(0,te._)`undefined`);s.coerceTypes==="array"&&n.if((0,te._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,te._)`${o}[0]`).assign(i,(0,te._)`typeof ${o}`).if(_c(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,te._)`${a} !== undefined`);for(let u of r)(Wf.has(u)||u==="array"&&s.coerceTypes==="array")&&l(u);n.else(),Sc(t),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(o,a),Ex(t,a)});function l(u){switch(u){case"string":n.elseIf((0,te._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,te._)`"" + ${o}`).elseIf((0,te._)`${o} === null`).assign(a,(0,te._)`""`);return;case"number":n.elseIf((0,te._)`${i} == "boolean" || ${o} === null
2305
2364
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,te._)`+${o}`);return;case"integer":n.elseIf((0,te._)`${i} === "boolean" || ${o} === null
2306
2365
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,te._)`+${o}`);return;case"boolean":n.elseIf((0,te._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,te._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,te._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,te._)`${i} === "string" || ${i} === "number"
2307
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function gR({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,te._)`${e} !== undefined`,()=>t.assign((0,te._)`${e}[${r}]`,n))}function yc(t,e,r,n=nn.Correct){let o=n===nn.Correct?te.operators.EQ:te.operators.NEQ,s;switch(t){case"null":return(0,te._)`${e} ${o} null`;case"array":s=(0,te._)`Array.isArray(${e})`;break;case"object":s=(0,te._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,te._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${e} ${o} ${t}`}return n===nn.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${e} == "number"`,a,r?(0,te._)`isFinite(${e})`:te.nil)}}Be.checkDataType=yc;function bc(t,e,r,n){if(t.length===1)return yc(t[0],e,r,n);let o,s=(0,Bf.toHash)(t);if(s.array&&s.object){let i=(0,te._)`typeof ${e} != "object"`;o=s.null?i:(0,te._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=te.nil;s.number&&delete s.integer;for(let i in s)o=(0,te.and)(o,yc(i,e,r,n));return o}Be.checkDataTypes=bc;var yR={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,te._)`{type: ${t}}`:(0,te._)`{type: ${e}}`};function wc(t){let e=bR(t);(0,uR.reportError)(e,yR)}Be.reportTypeError=wc;function bR(t){let{gen:e,data:r,schema:n}=t,o=(0,Bf.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Vf=U(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.assignDefaults=void 0;var on=re(),wR=ue();function vR(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Kf(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Kf(t,s,o.default))}ei.assignDefaults=vR;function Kf(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,on._)`${s}${(0,on.getProperty)(e)}`;if(o){(0,wR.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,on._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,on._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,on._)`${a} = ${(0,on.stringify)(r)}`)}});var dt=U(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.validateUnion=we.validateArray=we.usePattern=we.callValidateCode=we.schemaProperties=we.allSchemaProperties=we.noPropertyInData=we.propertyInData=we.isOwnProperty=we.hasPropFunc=we.reportMissingProp=we.checkMissingProp=we.checkReportMissingProp=void 0;var Se=re(),vc=ue(),nr=zt(),_R=ue();function SR(t,e){let{gen:r,data:n,it:o}=t;r.if(Sc(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Se._)`${e}`},!0),t.error()})}we.checkReportMissingProp=SR;function kR({gen:t,data:e,it:{opts:r}},n,o){return(0,Se.or)(...n.map(s=>(0,Se.and)(Sc(t,e,s,r.ownProperties),(0,Se._)`${o} = ${s}`)))}we.checkMissingProp=kR;function TR(t,e){t.setParams({missingProperty:e},!0),t.error()}we.reportMissingProp=TR;function Gf(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Se._)`Object.prototype.hasOwnProperty`})}we.hasPropFunc=Gf;function _c(t,e,r){return(0,Se._)`${Gf(t)}.call(${e}, ${r})`}we.isOwnProperty=_c;function xR(t,e,r,n){let o=(0,Se._)`${e}${(0,Se.getProperty)(r)} !== undefined`;return n?(0,Se._)`${o} && ${_c(t,e,r)}`:o}we.propertyInData=xR;function Sc(t,e,r,n){let o=(0,Se._)`${e}${(0,Se.getProperty)(r)} === undefined`;return n?(0,Se.or)(o,(0,Se.not)(_c(t,e,r))):o}we.noPropertyInData=Sc;function Wf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}we.allSchemaProperties=Wf;function RR(t,e){return Wf(e).filter(r=>!(0,vc.alwaysValidSchema)(t,e[r]))}we.schemaProperties=RR;function $R({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,u){let p=u?(0,Se._)`${t}, ${e}, ${n}${o}`:e,g=[[nr.default.instancePath,(0,Se.strConcat)(nr.default.instancePath,s)],[nr.default.parentData,i.parentData],[nr.default.parentDataProperty,i.parentDataProperty],[nr.default.rootData,nr.default.rootData]];i.opts.dynamicRef&&g.push([nr.default.dynamicAnchors,nr.default.dynamicAnchors]);let S=(0,Se._)`${p}, ${r.object(...g)}`;return l!==Se.nil?(0,Se._)`${a}.call(${l}, ${S})`:(0,Se._)`${a}(${S})`}we.callValidateCode=$R;var ER=(0,Se._)`new RegExp`;function PR({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Se._)`${o.code==="new RegExp"?ER:(0,_R.useFunc)(t,o)}(${r}, ${n})`})}we.usePattern=PR;function AR(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let l=e.const("len",(0,Se._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:vc.Type.Num},s),e.if((0,Se.not)(s),a)})}}we.validateArray=AR;function CR(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,vc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,u)=>{let p=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Se._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,Se.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}we.validateUnion=CR});var Xf=U(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.validateKeywordUsage=Pt.validSchemaType=Pt.funcKeywordCode=Pt.macroKeywordCode=void 0;var Ve=re(),Tr=zt(),IR=dt(),OR=no();function NR(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),l=Yf(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ve.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Pt.macroKeywordCode=NR;function LR(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=t;DR(l,e);let u=!a&&e.compile?e.compile.call(l.self,s,i,l):e.validate,p=Yf(n,o,u),g=n.let("valid");t.block$data(g,S),t.ok((r=e.valid)!==null&&r!==void 0?r:g);function S(){if(e.errors===!1)R(),e.modifying&&Jf(t),E(()=>t.error());else{let P=e.async?y():x();e.modifying&&Jf(t),E(()=>jR(t,P))}}function y(){let P=n.let("ruleErrs",null);return n.try(()=>R((0,Ve._)`await `),I=>n.assign(g,!1).if((0,Ve._)`${I} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ve._)`${I}.errors`),()=>n.throw(I))),P}function x(){let P=(0,Ve._)`${p}.errors`;return n.assign(P,null),R(Ve.nil),P}function R(P=e.async?(0,Ve._)`await `:Ve.nil){let I=l.opts.passContext?Tr.default.this:Tr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(g,(0,Ve._)`${P}${(0,IR.callValidateCode)(t,p,I,D)}`,e.modifying)}function E(P){var I;n.if((0,Ve.not)((I=e.valid)!==null&&I!==void 0?I:g),P)}}Pt.funcKeywordCode=LR;function Jf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ve._)`${n.parentData}[${n.parentDataProperty}]`))}function jR(t,e){let{gen:r}=t;r.if((0,Ve._)`Array.isArray(${e})`,()=>{r.assign(Tr.default.vErrors,(0,Ve._)`${Tr.default.vErrors} === null ? ${e} : ${Tr.default.vErrors}.concat(${e})`).assign(Tr.default.errors,(0,Ve._)`${Tr.default.vErrors}.length`),(0,OR.extendErrors)(t)},()=>t.error())}function DR({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Yf(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,Ve.stringify)(r)})}function UR(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")}Pt.validSchemaType=UR;function MR({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Pt.validateKeywordUsage=MR});var Qf=U(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.extendSubschemaMode=or.extendSubschemaData=or.getSubschema=void 0;var At=re(),Zf=ue();function qR(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,At._)`${t.schemaPath}${(0,At.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,At._)`${t.schemaPath}${(0,At.getProperty)(e)}${(0,At.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Zf.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}or.getSubschema=qR;function zR(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:p,opts:g}=e,S=a.let("data",(0,At._)`${e.data}${(0,At.getProperty)(r)}`,!0);l(S),t.errorPath=(0,At.str)`${u}${(0,Zf.getErrorPath)(r,n,g.jsPropertySyntax)}`,t.parentDataProperty=(0,At._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(o!==void 0){let u=o instanceof At.Name?o:a.let("data",o,!0);l(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}or.extendSubschemaData=zR;function BR(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}or.extendSubschemaMode=BR});var kc=U((_1,eg)=>{"use strict";eg.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var rg=U((S1,tg)=>{"use strict";var sr=tg.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};ti(e,n,o,t,"",t)};sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sr.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 ti(t,e,r,n,o,s,i,a,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,l,u);for(var p in n){var g=n[p];if(Array.isArray(g)){if(p in sr.arrayKeywords)for(var S=0;S<g.length;S++)ti(t,e,r,g[S],o+"/"+p+"/"+S,s,o,p,n,S)}else if(p in sr.propsKeywords){if(g&&typeof g=="object")for(var y in g)ti(t,e,r,g[y],o+"/"+p+"/"+FR(y),s,o,p,n,y)}else(p in sr.keywords||t.allKeys&&!(p in sr.skipKeywords))&&ti(t,e,r,g,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,u)}}function FR(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var so=U(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.getSchemaRefs=Ze.resolveUrl=Ze.normalizeId=Ze._getFullPath=Ze.getFullPath=Ze.inlineRef=void 0;var HR=ue(),KR=kc(),VR=rg(),GR=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function WR(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Tc(t):e?ng(t)<=e:!1}Ze.inlineRef=WR;var JR=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Tc(t){for(let e in t){if(JR.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Tc)||typeof r=="object"&&Tc(r))return!0}return!1}function ng(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!GR.has(r)&&(typeof t[r]=="object"&&(0,HR.eachItem)(t[r],n=>e+=ng(n)),e===1/0))return 1/0}return e}function og(t,e="",r){r!==!1&&(e=sn(e));let n=t.parse(e);return sg(t,n)}Ze.getFullPath=og;function sg(t,e){return t.serialize(e).split("#")[0]+"#"}Ze._getFullPath=sg;var YR=/#\/?$/;function sn(t){return t?t.replace(YR,""):""}Ze.normalizeId=sn;function XR(t,e,r){return r=sn(r),t.resolve(e,r)}Ze.resolveUrl=XR;var ZR=/^[a-z_][-a-z0-9._]*$/i;function QR(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=sn(t[r]||e),s={"":o},i=og(n,o,!1),a={},l=new Set;return VR(t,{allKeys:!0},(g,S,y,x)=>{if(x===void 0)return;let R=i+S,E=s[x];typeof g[r]=="string"&&(E=P.call(this,g[r])),I.call(this,g.$anchor),I.call(this,g.$dynamicAnchor),s[S]=E;function P(D){let F=this.opts.uriResolver.resolve;if(D=sn(E?F(E,D):D),l.has(D))throw p(D);l.add(D);let K=this.refs[D];return typeof K=="string"&&(K=this.refs[K]),typeof K=="object"?u(g,K.schema,D):D!==sn(R)&&(D[0]==="#"?(u(g,a[D],D),a[D]=g):this.refs[D]=R),D}function I(D){if(typeof D=="string"){if(!ZR.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(g,S,y){if(S!==void 0&&!KR(g,S))throw p(y)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}Ze.getSchemaRefs=QR});var lo=U(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var dg=Mf(),ig=oo(),Rc=gc(),ri=oo(),e$=Vf(),ao=Xf(),xc=Qf(),H=re(),ee=zt(),t$=so(),Bt=ue(),io=no();function r$(t){if(hg(t)&&(mg(t),pg(t))){s$(t);return}ug(t,()=>(0,dg.topBoolOrEmptySchema)(t))}ir.validateFunctionCode=r$;function ug({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,H._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,H._)`"use strict"; ${ag(r,o)}`),o$(t,o),t.code(s)}):t.func(e,(0,H._)`${ee.default.data}, ${n$(o)}`,n.$async,()=>t.code(ag(r,o)).code(s))}function n$(t){return(0,H._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,H._)`, ${ee.default.dynamicAnchors}={}`:H.nil}}={}`}function o$(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,H._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,H._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,H._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,H._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,H._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,H._)`""`),t.var(ee.default.parentData,(0,H._)`undefined`),t.var(ee.default.parentDataProperty,(0,H._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,H._)`{}`)})}function s$(t){let{schema:e,opts:r,gen:n}=t;ug(t,()=>{r.$comment&&e.$comment&&gg(t),d$(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&i$(t),fg(t),h$(t)})}function i$(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,H._)`${r}.evaluated`),e.if((0,H._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,H._)`${t.evaluated}.props`,(0,H._)`undefined`)),e.if((0,H._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,H._)`${t.evaluated}.items`,(0,H._)`undefined`))}function ag(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,H._)`/*# sourceURL=${r} */`:H.nil}function a$(t,e){if(hg(t)&&(mg(t),pg(t))){l$(t,e);return}(0,dg.boolOrEmptySchema)(t,e)}function pg({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 hg(t){return typeof t.schema!="boolean"}function l$(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&gg(t),u$(t),p$(t);let s=n.const("_errs",ee.default.errors);fg(t,s),n.var(e,(0,H._)`${s} === ${ee.default.errors}`)}function mg(t){(0,Bt.checkUnknownRules)(t),c$(t)}function fg(t,e){if(t.opts.jtd)return lg(t,[],!1,e);let r=(0,ig.getSchemaTypes)(t.schema),n=(0,ig.coerceAndCheckDataType)(t,r);lg(t,r,!n,e)}function c$(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Bt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function d$(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Bt.checkStrictMode)(t,"default is ignored in the schema root")}function u$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,t$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function p$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function gg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,H._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,H.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,H._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function h$(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,H._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,H._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,H._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&m$(t),e.return((0,H._)`${ee.default.errors} === 0`))}function m$({gen:t,evaluated:e,props:r,items:n}){r instanceof H.Name&&t.assign((0,H._)`${e}.props`,r),n instanceof H.Name&&t.assign((0,H._)`${e}.items`,n)}function lg(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:u}=t,{RULES:p}=u;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,Bt.schemaHasRulesButRef)(s,p))){o.block(()=>bg(t,"$ref",p.all.$ref.definition));return}l.jtd||f$(t,e),o.block(()=>{for(let S of p.rules)g(S);g(p.post)});function g(S){(0,Rc.shouldUseGroup)(s,S)&&(S.type?(o.if((0,ri.checkDataType)(S.type,i,l.strictNumbers)),cg(t,S),e.length===1&&e[0]===S.type&&r&&(o.else(),(0,ri.reportTypeError)(t)),o.endIf()):cg(t,S),a||o.if((0,H._)`${ee.default.errors} === ${n||0}`))}}function cg(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,e$.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Rc.shouldUseRule)(n,s)&&bg(t,s.keyword,s.definition,e.type)})}function f$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(g$(t,e),t.opts.allowUnionTypes||y$(t,e),b$(t,t.dataTypes))}function g$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{yg(t.dataTypes,r)||$c(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),v$(t,e)}}function y$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&$c(t,"use allowUnionTypes to allow union type keyword")}function b$(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Rc.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>w$(e,i))&&$c(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function w$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function yg(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function v$(t,e){let r=[];for(let n of t.dataTypes)yg(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function $c(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Bt.checkStrictMode)(t,e,t.opts.strictTypes)}var ni=class{constructor(e,r,n){if((0,ao.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,Bt.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",wg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ao.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",ee.default.errors))}result(e,r,n){this.failResult((0,H.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,H.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,H._)`${r} !== undefined && (${(0,H.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?io.reportExtraError:io.reportError)(this,this.def.error,r)}$dataError(){(0,io.reportError)(this,this.def.$dataError||io.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,io.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=H.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=H.nil,r=H.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,H.or)((0,H._)`${o} === undefined`,r)),e!==H.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==H.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,H.or)(i(),a());function i(){if(n.length){if(!(r instanceof H.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,H._)`${(0,ri.checkDataTypes)(l,r,s.opts.strictNumbers,ri.DataType.Wrong)}`}return H.nil}function a(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,H._)`!${l}(${r})`}return H.nil}}subschema(e,r){let n=(0,xc.getSubschema)(this.it,e);(0,xc.extendSubschemaData)(n,this.it,e),(0,xc.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return a$(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Bt.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Bt.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,H.Name)),!0}};ir.KeywordCxt=ni;function bg(t,e,r,n){let o=new ni(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ao.funcKeywordCode)(o,r):"macro"in r?(0,ao.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ao.funcKeywordCode)(o,r)}var _$=/^\/(?:[^~]|~0|~1)*$/,S$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function wg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!_$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=S$.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+u[1];if(o=u[2],o==="#"){if(p>=e)throw new Error(l("property/index",p));return n[e-p]}if(p>e)throw new Error(l("data",p));if(s=r[e-p],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,H._)`${s}${(0,H.getProperty)((0,Bt.unescapeJsonPointer)(u))}`,i=(0,H._)`${i} && ${s}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}ir.getData=wg});var oi=U(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var Ec=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Pc.default=Ec});var co=U(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Ac=so(),Cc=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ac.resolveUrl)(e,r,n),this.missingSchema=(0,Ac.normalizeId)((0,Ac.getFullPath)(e,this.missingRef))}};Ic.default=Cc});var ii=U(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.resolveSchema=ut.getCompilingSchema=ut.resolveRef=ut.compileSchema=ut.SchemaEnv=void 0;var vt=re(),k$=oi(),xr=zt(),_t=so(),vg=ue(),T$=lo(),an=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,_t.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ut.SchemaEnv=an;function Nc(t){let e=_g.call(this,t);if(e)return e;let r=(0,_t.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:k$.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:xr.default.data,parentData:xr.default.parentData,parentDataProperty:xr.default.parentDataProperty,dataNames:[xr.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,T$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(xr.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let y=new Function(`${xr.default.self}`,`${xr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=t.schema,y.schemaEnv=t,t.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:g,scopeValues:i._values}),this.opts.unevaluated){let{props:x,items:R}=u;y.evaluated={props:x instanceof vt.Name?void 0:x,items:R instanceof vt.Name?void 0:R,dynamicProps:x instanceof vt.Name,dynamicItems:R instanceof vt.Name},y.source&&(y.source.evaluated=(0,vt.stringify)(y.evaluated))}return t.validate=y,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)}}ut.compileSchema=Nc;function x$(t,e,r){var n;r=(0,_t.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=E$.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new an({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=R$.call(this,s)}ut.resolveRef=x$;function R$(t){return(0,_t.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Nc.call(this,t)}function _g(t){for(let e of this._compilations)if($$(e,t))return e}ut.getCompilingSchema=_g;function $$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function E$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||si.call(this,t,e)}function si(t,e){let r=this.opts.uriResolver.parse(e),n=(0,_t._getFullPath)(this.opts.uriResolver,r),o=(0,_t.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Oc.call(this,r,t);let s=(0,_t.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=si.call(this,t,i);return typeof a?.schema!="object"?void 0:Oc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Nc.call(this,i),s===(0,_t.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(o=(0,_t.resolveUrl)(this.opts.uriResolver,o,u)),new an({schema:a,schemaId:l,root:t,baseId:o})}return Oc.call(this,r,i)}}ut.resolveSchema=si;var P$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Oc(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,vg.unescapeFragment)(a)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!P$.has(a)&&u&&(e=(0,_t.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,vg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,_t.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=si.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new an({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Sg=U((E1,A$)=>{A$.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 Dc=U((P1,Eg)=>{"use strict";var C$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Tg=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),Lc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),xg=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),I$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function jc(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 O$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function kg(t){return t.length=0,!0}function N$(t,e,r){if(t.length){let n=jc(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function L$(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=N$;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=kg}else{o.push(u);continue}}return o.length&&(a===kg?r.zone=o.join(""):i?n.push(o.join("")):n.push(jc(o))),r.address=n.join(""),r}function Rg(t){if(j$(t,":")<2)return{host:t,isIPV6:!1};let e=L$(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 j$(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function D$(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var U$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},M$=/[@/?#:]/g,q$=/[@/?#]/g;function $g(t,e){let r=e?q$:M$;return r.lastIndex=0,t.replace(r,n=>U$[n])}function z$(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Lc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&xg(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function B$(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(Lc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&xg(s)?e+=s:e+="%"+o,r+=2;continue}}I$(t[r])?e+=t[r]:e+=escape(t[r])}return e}function F$(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(Lc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function H$(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Tg(r)){let n=Rg(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=$g(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}Eg.exports={nonSimpleDomain:O$,recomposeAuthority:H$,reescapeHostDelimiters:$g,normalizePercentEncoding:z$,normalizePathEncoding:B$,escapePreservingEscapes:F$,removeDotSegments:D$,isIPv4:Tg,isUUID:C$,normalizeIPv6:Rg,stringArrayToHexStripped:jc}});var Og=U((A1,Ig)=>{"use strict";var{isUUID:K$}=Dc(),V$=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,G$=["http","https","ws","wss","urn","urn:uuid"];function W$(t){return G$.indexOf(t)!==-1}function Uc(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 Pg(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Ag(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 J$(t){return t.secure=Uc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function Y$(t){if((t.port===(Uc(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 X$(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(V$);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Mc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Z$(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Mc(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function Q$(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!K$(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function eE(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Cg={scheme:"http",domainHost:!0,parse:Pg,serialize:Ag},tE={scheme:"https",domainHost:Cg.domainHost,parse:Pg,serialize:Ag},ai={scheme:"ws",domainHost:!0,parse:J$,serialize:Y$},rE={scheme:"wss",domainHost:ai.domainHost,parse:ai.parse,serialize:ai.serialize},nE={scheme:"urn",parse:X$,serialize:Z$,skipNormalize:!0},oE={scheme:"urn:uuid",parse:Q$,serialize:eE,skipNormalize:!0},li={http:Cg,https:tE,ws:ai,wss:rE,urn:nE,"urn:uuid":oE};Object.setPrototypeOf(li,null);function Mc(t){return t&&(li[t]||li[t.toLowerCase()])||void 0}Ig.exports={wsIsSecure:Uc,SCHEMES:li,isValidSchemeName:W$,getSchemeHandler:Mc}});var Ug=U((C1,ui)=>{"use strict";var{normalizeIPv6:sE,removeDotSegments:uo,recomposeAuthority:iE,normalizePercentEncoding:aE,normalizePathEncoding:lE,escapePreservingEscapes:cE,reescapeHostDelimiters:dE,isIPv4:uE,nonSimpleDomain:pE}=Dc(),{SCHEMES:hE,getSchemeHandler:Lg}=Og();function mE(t,e){return typeof t=="string"?t=_E(t,e):typeof t=="object"&&(t=di(Rr(t,e),e)),t}function fE(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=ci(t,n),{parsed:i,malformedAuthorityOrPort:a}=ci(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let l=jg(o,i,n,!0);return n.skipEscape=!0,Rr(l,n)}function jg(t,e,r,n){let o={};return n||(t=di(Rr(t,r),r),e=di(Rr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=uo(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=uo(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=uo(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=uo(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function gE(t,e,r){let n=Ng(t,r),o=Ng(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function Rr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=Lg(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=aE(r.path):(r.path=cE(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=iE(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=uo(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var yE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,bE=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,wE=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function vE(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 ci(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(bE);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(wE);if(a!==null){let u=a[1],p=u.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):u.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let l=t.match(yE);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=vE(n,l);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(uE(n.host)===!1){let S=sE(n.host);n.host=S.host.toLowerCase(),s=S.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let p=Lg(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&pE(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=dE(unescape(n.host),s))),n.path&&(n.path=lE(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}p&&p.parse&&p.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function di(t,e){return ci(t,e).parsed}function _E(t,e){return Dg(t,e).normalized}function Dg(t,e){let{parsed:r,malformedAuthorityOrPort:n}=ci(t,e);return{normalized:n?t:Rr(r,e),malformedAuthorityOrPort:n}}function Ng(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=Dg(t,e);return n?void 0:r}if(typeof t=="object")return Rr(t,e)}var qc={SCHEMES:hE,normalize:mE,resolve:fE,resolveComponent:jg,equal:gE,serialize:Rr,parse:di};ui.exports=qc;ui.exports.default=qc;ui.exports.fastUri=qc});var qg=U(zc=>{"use strict";Object.defineProperty(zc,"__esModule",{value:!0});var Mg=Ug();Mg.code='require("ajv/dist/runtime/uri").default';zc.default=Mg});var Wg=U(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CodeGen=Ue.Name=Ue.nil=Ue.stringify=Ue.str=Ue._=Ue.KeywordCxt=void 0;var SE=lo();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:function(){return SE.KeywordCxt}});var ln=re();Object.defineProperty(Ue,"_",{enumerable:!0,get:function(){return ln._}});Object.defineProperty(Ue,"str",{enumerable:!0,get:function(){return ln.str}});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:function(){return ln.stringify}});Object.defineProperty(Ue,"nil",{enumerable:!0,get:function(){return ln.nil}});Object.defineProperty(Ue,"Name",{enumerable:!0,get:function(){return ln.Name}});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:function(){return ln.CodeGen}});var kE=oi(),Kg=co(),TE=fc(),po=ii(),xE=re(),ho=so(),pi=oo(),Fc=ue(),zg=Sg(),RE=qg(),Vg=(t,e)=>new RegExp(t,e);Vg.code="new RegExp";var $E=["removeAdditional","useDefaults","coerceTypes"],EE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),PE={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."},AE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Bg=200;function CE(t){var e,r,n,o,s,i,a,l,u,p,g,S,y,x,R,E,P,I,D,F,K,Ce,Ie,Nt,Ht;let Tt=t.strict,dr=(e=t.code)===null||e===void 0?void 0:e.optimize,ur=dr===!0||dr===void 0?1:dr||0,xt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Vg,Ui=(o=t.uriResolver)!==null&&o!==void 0?o:RE.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:Tt)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:Tt)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:Tt)!==null&&p!==void 0?p:"log",strictTuples:(S=(g=t.strictTuples)!==null&&g!==void 0?g:Tt)!==null&&S!==void 0?S:"log",strictRequired:(x=(y=t.strictRequired)!==null&&y!==void 0?y:Tt)!==null&&x!==void 0?x:!1,code:t.code?{...t.code,optimize:ur,regExp:xt}:{optimize:ur,regExp:xt},loopRequired:(R=t.loopRequired)!==null&&R!==void 0?R:Bg,loopEnum:(E=t.loopEnum)!==null&&E!==void 0?E:Bg,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(F=t.schemaId)!==null&&F!==void 0?F:"$id",addUsedSchema:(K=t.addUsedSchema)!==null&&K!==void 0?K:!0,validateSchema:(Ce=t.validateSchema)!==null&&Ce!==void 0?Ce:!0,validateFormats:(Ie=t.validateFormats)!==null&&Ie!==void 0?Ie:!0,unicodeRegExp:(Nt=t.unicodeRegExp)!==null&&Nt!==void 0?Nt:!0,int32range:(Ht=t.int32range)!==null&&Ht!==void 0?Ht:!0,uriResolver:Ui}}var mo=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,...CE(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new xE.ValueScope({scope:{},prefixes:EE,es5:r,lines:n}),this.logger=DE(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,TE.getRules)(),Fg.call(this,PE,e,"NOT SUPPORTED"),Fg.call(this,AE,e,"DEPRECATED","warn"),this._metaOpts=LE.call(this),e.formats&&OE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&NE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),IE.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=zg;n==="id"&&(o={...zg},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(p,g){await s.call(this,p.$schema);let S=this._addSchema(p,g);return S.validate||i.call(this,S)}async function s(p){p&&!this.getSchema(p)&&await o.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(g){if(!(g instanceof Kg.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 s.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,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,ho.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Hg.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new po.SchemaEnv({schema:{},schemaId:n});if(r=po.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Hg.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,ho.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(ME.call(this,n,r),!r)return(0,Fc.eachItem)(n,s=>Bc.call(this,s)),this;zE.call(this,r);let o={...r,type:(0,pi.getJSONTypes)(r.type),schemaType:(0,pi.getJSONTypes)(r.schemaType)};return(0,Fc.eachItem)(n,o.type.length===0?s=>Bc.call(this,s,o):s=>o.type.forEach(i=>Bc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:u}=l.definition,p=i[a];u&&p&&(i[a]=Gg(p))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,ho.normalizeId)(i||n);let u=ho.getSchemaRefs.call(this,e,n);return l=new po.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(l.schema,l),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):po.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{po.compileSchema.call(this,e)}finally{this.opts=r}}};mo.ValidationError=kE.default;mo.MissingRefError=Kg.default;Ue.default=mo;function Fg(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Hg(t){return t=(0,ho.normalizeId)(t),this.schemas[t]||this.refs[t]}function IE(){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 OE(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function NE(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 LE(){let t={...this.opts};for(let e of $E)delete t[e];return t}var jE={log(){},warn(){},error(){}};function DE(t){if(t===!1)return jE;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 UE=/^[a-z_$][a-z0-9_$:-]*$/i;function ME(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(!UE.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 Bc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,pi.getJSONTypes)(e.type),schemaType:(0,pi.getJSONTypes)(e.schemaType)}};e.before?qE.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function qE(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function zE(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Gg(e)),t.validateSchema=this.compile(e,!0))}var BE={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Gg(t){return{anyOf:[t,BE]}}});var Jg=U(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var FE={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Hc.default=FE});var Qg=U($r=>{"use strict";Object.defineProperty($r,"__esModule",{value:!0});$r.callRef=$r.getValidate=void 0;var HE=co(),Yg=dt(),Qe=re(),cn=zt(),Xg=ii(),hi=ue(),KE={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return g();let p=Xg.resolveRef.call(l,u,o,r);if(p===void 0)throw new HE.default(n.opts.uriResolver,o,r);if(p instanceof Xg.SchemaEnv)return S(p);return y(p);function g(){if(s===u)return mi(t,i,s,s.$async);let x=e.scopeValue("root",{ref:u});return mi(t,(0,Qe._)`${x}.validate`,u,u.$async)}function S(x){let R=Zg(t,x);mi(t,R,x,x.$async)}function y(x){let R=e.scopeValue("schema",a.code.source===!0?{ref:x,code:(0,Qe.stringify)(x)}:{ref:x}),E=e.name("valid"),P=t.subschema({schema:x,dataTypes:[],schemaPath:Qe.nil,topSchemaRef:R,errSchemaPath:r},E);t.mergeEvaluated(P),t.ok(E)}}};function Zg(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Qe._)`${r.scopeValue("wrapper",{ref:e})}.validate`}$r.getValidate=Zg;function mi(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:l}=s,u=l.passContext?cn.default.this:Qe.nil;n?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let x=o.let("valid");o.try(()=>{o.code((0,Qe._)`await ${(0,Yg.callValidateCode)(t,e,u)}`),y(e),i||o.assign(x,!0)},R=>{o.if((0,Qe._)`!(${R} instanceof ${s.ValidationError})`,()=>o.throw(R)),S(R),i||o.assign(x,!1)}),t.ok(x)}function g(){t.result((0,Yg.callValidateCode)(t,e,u),()=>y(e),()=>S(e))}function S(x){let R=(0,Qe._)`${x}.errors`;o.assign(cn.default.vErrors,(0,Qe._)`${cn.default.vErrors} === null ? ${R} : ${cn.default.vErrors}.concat(${R})`),o.assign(cn.default.errors,(0,Qe._)`${cn.default.vErrors}.length`)}function y(x){var R;if(!s.opts.unevaluated)return;let E=(R=r?.validate)===null||R===void 0?void 0:R.evaluated;if(s.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(s.props=hi.mergeEvaluated.props(o,E.props,s.props));else{let P=o.var("props",(0,Qe._)`${x}.evaluated.props`);s.props=hi.mergeEvaluated.props(o,P,s.props,Qe.Name)}if(s.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(s.items=hi.mergeEvaluated.items(o,E.items,s.items));else{let P=o.var("items",(0,Qe._)`${x}.evaluated.items`);s.items=hi.mergeEvaluated.items(o,P,s.items,Qe.Name)}}}$r.callRef=mi;$r.default=KE});var ey=U(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var VE=Jg(),GE=Qg(),WE=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",VE.default,GE.default];Kc.default=WE});var ty=U(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});var fi=re(),ar=fi.operators,gi={maximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},minimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},exclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},exclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},JE={message:({keyword:t,schemaCode:e})=>(0,fi.str)`must be ${gi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,fi._)`{comparison: ${gi[t].okStr}, limit: ${e}}`},YE={keyword:Object.keys(gi),type:"number",schemaType:"number",$data:!0,error:JE,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,fi._)`${r} ${gi[e].fail} ${n} || isNaN(${r})`)}};Vc.default=YE});var ry=U(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var fo=re(),XE={message:({schemaCode:t})=>(0,fo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,fo._)`{multipleOf: ${t}}`},ZE={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:XE,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,fo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,fo._)`${i} !== parseInt(${i})`;t.fail$data((0,fo._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Gc.default=ZE});var oy=U(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});function ny(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Wc.default=ny;ny.code='require("ajv/dist/runtime/ucs2length").default'});var sy=U(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var Er=re(),QE=ue(),eP=oy(),tP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Er.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Er._)`{limit: ${t}}`},rP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:tP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Er.operators.GT:Er.operators.LT,i=o.opts.unicode===!1?(0,Er._)`${r}.length`:(0,Er._)`${(0,QE.useFunc)(t.gen,eP.default)}(${r})`;t.fail$data((0,Er._)`${i} ${s} ${n}`)}};Jc.default=rP});var iy=U(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var nP=dt(),oP=ue(),dn=re(),sP={message:({schemaCode:t})=>(0,dn.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,dn._)`{pattern: ${t}}`},iP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:sP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,dn._)`new RegExp`:(0,oP.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,dn._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,dn._)`!${p}`)}else{let l=(0,nP.usePattern)(t,o);t.fail$data((0,dn._)`!${l}.test(${r})`)}}};Yc.default=iP});var ay=U(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});var go=re(),aP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,go.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,go._)`{limit: ${t}}`},lP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:aP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?go.operators.GT:go.operators.LT;t.fail$data((0,go._)`Object.keys(${r}).length ${o} ${n}`)}};Xc.default=lP});var ly=U(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var yo=dt(),bo=re(),cP=ue(),dP={message:({params:{missingProperty:t}})=>(0,bo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,bo._)`{missingProperty: ${t}}`},uP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:dP,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let y=t.parentSchema.properties,{definedProperties:x}=t.it;for(let R of r)if(y?.[R]===void 0&&!x.has(R)){let E=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${R}" is not defined at "${E}" (strictRequired)`;(0,cP.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||s)t.block$data(bo.nil,g);else for(let y of r)(0,yo.checkReportMissingProp)(t,y)}function p(){let y=e.let("missing");if(l||s){let x=e.let("valid",!0);t.block$data(x,()=>S(y,x)),t.ok(x)}else e.if((0,yo.checkMissingProp)(t,r,y)),(0,yo.reportMissingProp)(t,y),e.else()}function g(){e.forOf("prop",n,y=>{t.setParams({missingProperty:y}),e.if((0,yo.noPropertyInData)(e,o,y,a.ownProperties),()=>t.error())})}function S(y,x){t.setParams({missingProperty:y}),e.forOf(y,n,()=>{e.assign(x,(0,yo.propertyInData)(e,o,y,a.ownProperties)),e.if((0,bo.not)(x),()=>{t.error(),e.break()})},bo.nil)}}};Zc.default=uP});var cy=U(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var wo=re(),pP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,wo.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,wo._)`{limit: ${t}}`},hP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:pP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?wo.operators.GT:wo.operators.LT;t.fail$data((0,wo._)`${r}.length ${o} ${n}`)}};Qc.default=hP});var yi=U(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var dy=kc();dy.code='require("ajv/dist/runtime/equal").default';ed.default=dy});var uy=U(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var td=oo(),Me=re(),mP=ue(),fP=yi(),gP={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},yP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:gP,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let l=e.let("valid"),u=s.items?(0,td.getSchemaTypes)(s.items):[];t.block$data(l,p,(0,Me._)`${i} === false`),t.ok(l);function p(){let x=e.let("i",(0,Me._)`${r}.length`),R=e.let("j");t.setParams({i:x,j:R}),e.assign(l,!0),e.if((0,Me._)`${x} > 1`,()=>(g()?S:y)(x,R))}function g(){return u.length>0&&!u.some(x=>x==="object"||x==="array")}function S(x,R){let E=e.name("item"),P=(0,td.checkDataTypes)(u,E,a.opts.strictNumbers,td.DataType.Wrong),I=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${x}--;`,()=>{e.let(E,(0,Me._)`${r}[${x}]`),e.if(P,(0,Me._)`continue`),u.length>1&&e.if((0,Me._)`typeof ${E} == "string"`,(0,Me._)`${E} += "_"`),e.if((0,Me._)`typeof ${I}[${E}] == "number"`,()=>{e.assign(R,(0,Me._)`${I}[${E}]`),t.error(),e.assign(l,!1).break()}).code((0,Me._)`${I}[${E}] = ${x}`)})}function y(x,R){let E=(0,mP.useFunc)(e,fP.default),P=e.name("outer");e.label(P).for((0,Me._)`;${x}--;`,()=>e.for((0,Me._)`${R} = ${x}; ${R}--;`,()=>e.if((0,Me._)`${E}(${r}[${x}], ${r}[${R}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};rd.default=yP});var py=U(od=>{"use strict";Object.defineProperty(od,"__esModule",{value:!0});var nd=re(),bP=ue(),wP=yi(),vP={message:"must be equal to constant",params:({schemaCode:t})=>(0,nd._)`{allowedValue: ${t}}`},_P={keyword:"const",$data:!0,error:vP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,nd._)`!${(0,bP.useFunc)(e,wP.default)}(${r}, ${o})`):t.fail((0,nd._)`${s} !== ${r}`)}};od.default=_P});var hy=U(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var vo=re(),SP=ue(),kP=yi(),TP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,vo._)`{allowedValues: ${t}}`},xP={keyword:"enum",schemaType:"array",$data:!0,error:TP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,l,u=()=>l??(l=(0,SP.useFunc)(e,kP.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,g);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=e.const("vSchema",s);p=(0,vo.or)(...o.map((x,R)=>S(y,R)))}t.pass(p);function g(){e.assign(p,!1),e.forOf("v",s,y=>e.if((0,vo._)`${u()}(${r}, ${y})`,()=>e.assign(p,!0).break()))}function S(y,x){let R=o[x];return typeof R=="object"&&R!==null?(0,vo._)`${u()}(${r}, ${y}[${x}])`:(0,vo._)`${r} === ${R}`}}};sd.default=xP});var my=U(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var RP=ty(),$P=ry(),EP=sy(),PP=iy(),AP=ay(),CP=ly(),IP=cy(),OP=uy(),NP=py(),LP=hy(),jP=[RP.default,$P.default,EP.default,PP.default,AP.default,CP.default,IP.default,OP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},NP.default,LP.default];id.default=jP});var ld=U(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.validateAdditionalItems=void 0;var Pr=re(),ad=ue(),DP={message:({params:{len:t}})=>(0,Pr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Pr._)`{limit: ${t}}`},UP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:DP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,ad.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}fy(t,n)}};function fy(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Pr._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Pr._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ad.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Pr._)`${a} <= ${e.length}`);r.if((0,Pr.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,a,p=>{t.subschema({keyword:s,dataProp:p,dataPropType:ad.Type.Num},u),i.allErrors||r.if((0,Pr.not)(u),()=>r.break())})}}_o.validateAdditionalItems=fy;_o.default=UP});var cd=U(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.validateTuple=void 0;var gy=re(),bi=ue(),MP=dt(),qP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return yy(t,"additionalItems",e);r.items=!0,!(0,bi.alwaysValidSchema)(r,e)&&t.ok((0,MP.validateArray)(t))}};function yy(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=bi.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),u=n.const("len",(0,gy._)`${s}.length`);r.forEach((g,S)=>{(0,bi.alwaysValidSchema)(a,g)||(n.if((0,gy._)`${u} > ${S}`,()=>t.subschema({keyword:i,schemaProp:S,dataProp:S},l)),t.ok(l))});function p(g){let{opts:S,errSchemaPath:y}=a,x=r.length,R=x===g.minItems&&(x===g.maxItems||g[e]===!1);if(S.strictTuples&&!R){let E=`"${i}" is ${x}-tuple, but minItems or maxItems/${e} are not specified or different at path "${y}"`;(0,bi.checkStrictMode)(a,E,S.strictTuples)}}}So.validateTuple=yy;So.default=qP});var by=U(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var zP=cd(),BP={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,zP.validateTuple)(t,"items")};dd.default=BP});var vy=U(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var wy=re(),FP=ue(),HP=dt(),KP=ld(),VP={message:({params:{len:t}})=>(0,wy.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,wy._)`{limit: ${t}}`},GP={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:VP,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,FP.alwaysValidSchema)(n,e)&&(o?(0,KP.validateAdditionalItems)(t,o):t.ok((0,HP.validateArray)(t)))}};ud.default=GP});var _y=U(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var pt=re(),wi=ue(),WP={message:({params:{min:t,max:e}})=>e===void 0?(0,pt.str)`must contain at least ${t} valid item(s)`:(0,pt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,pt._)`{minContains: ${t}}`:(0,pt._)`{minContains: ${t}, maxContains: ${e}}`},JP={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:WP,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:l,maxContains:u}=n;s.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=e.const("len",(0,pt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,wi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,wi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,wi.alwaysValidSchema)(s,r)){let R=(0,pt._)`${p} >= ${i}`;a!==void 0&&(R=(0,pt._)`${R} && ${p} <= ${a}`),t.pass(R);return}s.items=!0;let g=e.name("valid");a===void 0&&i===1?y(g,()=>e.if(g,()=>e.break())):i===0?(e.let(g,!0),a!==void 0&&e.if((0,pt._)`${o}.length > 0`,S)):(e.let(g,!1),S()),t.result(g,()=>t.reset());function S(){let R=e.name("_valid"),E=e.let("count",0);y(R,()=>e.if(R,()=>x(E)))}function y(R,E){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:wi.Type.Num,compositeRule:!0},R),E()})}function x(R){e.code((0,pt._)`${R}++`),a===void 0?e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(g,!0).break()):(e.if((0,pt._)`${R} > ${a}`,()=>e.assign(g,!1).break()),i===1?e.assign(g,!0):e.if((0,pt._)`${R} >= ${i}`,()=>e.assign(g,!0)))}}};pd.default=JP});var Ty=U(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateSchemaDeps=Ct.validatePropertyDeps=Ct.error=void 0;var hd=re(),YP=ue(),ko=dt();Ct.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,hd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,hd._)`{property: ${t},
2366
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function Ex({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,te._)`${e} !== undefined`,()=>t.assign((0,te._)`${e}[${r}]`,n))}function vc(t,e,r,n=on.Correct){let o=n===on.Correct?te.operators.EQ:te.operators.NEQ,s;switch(t){case"null":return(0,te._)`${e} ${o} null`;case"array":s=(0,te._)`Array.isArray(${e})`;break;case"object":s=(0,te._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,te._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${e} ${o} ${t}`}return n===on.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${e} == "number"`,a,r?(0,te._)`isFinite(${e})`:te.nil)}}Fe.checkDataType=vc;function _c(t,e,r,n){if(t.length===1)return vc(t[0],e,r,n);let o,s=(0,Vf.toHash)(t);if(s.array&&s.object){let i=(0,te._)`typeof ${e} != "object"`;o=s.null?i:(0,te._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=te.nil;s.number&&delete s.integer;for(let i in s)o=(0,te.and)(o,vc(i,e,r,n));return o}Fe.checkDataTypes=_c;var Px={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,te._)`{type: ${t}}`:(0,te._)`{type: ${e}}`};function Sc(t){let e=Ax(t);(0,kx.reportError)(e,Px)}Fe.reportTypeError=Sc;function Ax(t){let{gen:e,data:r,schema:n}=t,o=(0,Vf.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Yf=q(ni=>{"use strict";Object.defineProperty(ni,"__esModule",{value:!0});ni.assignDefaults=void 0;var sn=re(),Cx=pe();function Ix(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Jf(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Jf(t,s,o.default))}ni.assignDefaults=Ix;function Jf(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,sn._)`${s}${(0,sn.getProperty)(e)}`;if(o){(0,Cx.checkStrictMode)(t,`default is ignored for: ${a}`);return}let l=(0,sn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,sn._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,sn._)`${a} = ${(0,sn.stringify)(r)}`)}});var pt=q(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.validateUnion=ye.validateArray=ye.usePattern=ye.callValidateCode=ye.schemaProperties=ye.allSchemaProperties=ye.noPropertyInData=ye.propertyInData=ye.isOwnProperty=ye.hasPropFunc=ye.reportMissingProp=ye.checkMissingProp=ye.checkReportMissingProp=void 0;var _e=re(),kc=pe(),sr=Bt(),Ox=pe();function Nx(t,e){let{gen:r,data:n,it:o}=t;r.if(Rc(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,_e._)`${e}`},!0),t.error()})}ye.checkReportMissingProp=Nx;function Lx({gen:t,data:e,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(Rc(t,e,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}ye.checkMissingProp=Lx;function jx(t,e){t.setParams({missingProperty:e},!0),t.error()}ye.reportMissingProp=jx;function Xf(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}ye.hasPropFunc=Xf;function Tc(t,e,r){return(0,_e._)`${Xf(t)}.call(${e}, ${r})`}ye.isOwnProperty=Tc;function Dx(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${Tc(t,e,r)}`:o}ye.propertyInData=Dx;function Rc(t,e,r,n){let o=(0,_e._)`${e}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(Tc(t,e,r))):o}ye.noPropertyInData=Rc;function Zf(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ye.allSchemaProperties=Zf;function Ux(t,e){return Zf(e).filter(r=>!(0,kc.alwaysValidSchema)(t,e[r]))}ye.schemaProperties=Ux;function Mx({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,u){let p=u?(0,_e._)`${t}, ${e}, ${n}${o}`:e,g=[[sr.default.instancePath,(0,_e.strConcat)(sr.default.instancePath,s)],[sr.default.parentData,i.parentData],[sr.default.parentDataProperty,i.parentDataProperty],[sr.default.rootData,sr.default.rootData]];i.opts.dynamicRef&&g.push([sr.default.dynamicAnchors,sr.default.dynamicAnchors]);let k=(0,_e._)`${p}, ${r.object(...g)}`;return l!==_e.nil?(0,_e._)`${a}.call(${l}, ${k})`:(0,_e._)`${a}(${k})`}ye.callValidateCode=Mx;var qx=(0,_e._)`new RegExp`;function zx({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,_e._)`${o.code==="new RegExp"?qx:(0,Ox.useFunc)(t,o)}(${r}, ${n})`})}ye.usePattern=zx;function Bx(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let l=e.const("len",(0,_e._)`${r}.length`);e.forRange("i",0,l,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:kc.Type.Num},s),e.if((0,_e.not)(s),a)})}}ye.validateArray=Bx;function Fx(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,kc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((l,u)=>{let p=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,_e._)`${i} || ${a}`),t.mergeValidEvaluated(p,a)||e.if((0,_e.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ye.validateUnion=Fx});var tg=q(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.validateKeywordUsage=At.validSchemaType=At.funcKeywordCode=At.macroKeywordCode=void 0;var Ge=re(),Rr=Bt(),Hx=pt(),Kx=oo();function Vx(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),l=eg(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:Ge.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}At.macroKeywordCode=Vx;function Gx(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=t;Jx(l,e);let u=!a&&e.compile?e.compile.call(l.self,s,i,l):e.validate,p=eg(n,o,u),g=n.let("valid");t.block$data(g,k),t.ok((r=e.valid)!==null&&r!==void 0?r:g);function k(){if(e.errors===!1)x(),e.modifying&&Qf(t),E(()=>t.error());else{let P=e.async?b():R();e.modifying&&Qf(t),E(()=>Wx(t,P))}}function b(){let P=n.let("ruleErrs",null);return n.try(()=>x((0,Ge._)`await `),I=>n.assign(g,!1).if((0,Ge._)`${I} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ge._)`${I}.errors`),()=>n.throw(I))),P}function R(){let P=(0,Ge._)`${p}.errors`;return n.assign(P,null),x(Ge.nil),P}function x(P=e.async?(0,Ge._)`await `:Ge.nil){let I=l.opts.passContext?Rr.default.this:Rr.default.self,D=!("compile"in e&&!a||e.schema===!1);n.assign(g,(0,Ge._)`${P}${(0,Hx.callValidateCode)(t,p,I,D)}`,e.modifying)}function E(P){var I;n.if((0,Ge.not)((I=e.valid)!==null&&I!==void 0?I:g),P)}}At.funcKeywordCode=Gx;function Qf(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ge._)`${n.parentData}[${n.parentDataProperty}]`))}function Wx(t,e){let{gen:r}=t;r.if((0,Ge._)`Array.isArray(${e})`,()=>{r.assign(Rr.default.vErrors,(0,Ge._)`${Rr.default.vErrors} === null ? ${e} : ${Rr.default.vErrors}.concat(${e})`).assign(Rr.default.errors,(0,Ge._)`${Rr.default.vErrors}.length`),(0,Kx.extendErrors)(t)},()=>t.error())}function Jx({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function eg(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,Ge.stringify)(r)})}function Yx(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")}At.validSchemaType=Yx;function Xx({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}At.validateKeywordUsage=Xx});var ng=q(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.extendSubschemaMode=ir.extendSubschemaData=ir.getSubschema=void 0;var Ct=re(),rg=pe();function Zx(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ct._)`${t.schemaPath}${(0,Ct.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ct._)`${t.schemaPath}${(0,Ct.getProperty)(e)}${(0,Ct.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,rg.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}ir.getSubschema=Zx;function Qx(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:p,opts:g}=e,k=a.let("data",(0,Ct._)`${e.data}${(0,Ct.getProperty)(r)}`,!0);l(k),t.errorPath=(0,Ct.str)`${u}${(0,rg.getErrorPath)(r,n,g.jsPropertySyntax)}`,t.parentDataProperty=(0,Ct._)`${r}`,t.dataPathArr=[...p,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Ct.Name?o:a.let("data",o,!0);l(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function l(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}ir.extendSubschemaData=Qx;function e$(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}ir.extendSubschemaMode=e$});var xc=q((O1,og)=>{"use strict";og.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var ig=q((N1,sg)=>{"use strict";var ar=sg.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};oi(e,n,o,t,"",t)};ar.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ar.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ar.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ar.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 oi(t,e,r,n,o,s,i,a,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,l,u);for(var p in n){var g=n[p];if(Array.isArray(g)){if(p in ar.arrayKeywords)for(var k=0;k<g.length;k++)oi(t,e,r,g[k],o+"/"+p+"/"+k,s,o,p,n,k)}else if(p in ar.propsKeywords){if(g&&typeof g=="object")for(var b in g)oi(t,e,r,g[b],o+"/"+p+"/"+t$(b),s,o,p,n,b)}else(p in ar.keywords||t.allKeys&&!(p in ar.skipKeywords))&&oi(t,e,r,g,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,u)}}function t$(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var io=q(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.getSchemaRefs=Qe.resolveUrl=Qe.normalizeId=Qe._getFullPath=Qe.getFullPath=Qe.inlineRef=void 0;var r$=pe(),n$=xc(),o$=ig(),s$=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function i$(t,e=!0){return typeof t=="boolean"?!0:e===!0?!$c(t):e?ag(t)<=e:!1}Qe.inlineRef=i$;var a$=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function $c(t){for(let e in t){if(a$.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some($c)||typeof r=="object"&&$c(r))return!0}return!1}function ag(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!s$.has(r)&&(typeof t[r]=="object"&&(0,r$.eachItem)(t[r],n=>e+=ag(n)),e===1/0))return 1/0}return e}function lg(t,e="",r){r!==!1&&(e=an(e));let n=t.parse(e);return cg(t,n)}Qe.getFullPath=lg;function cg(t,e){return t.serialize(e).split("#")[0]+"#"}Qe._getFullPath=cg;var l$=/#\/?$/;function an(t){return t?t.replace(l$,""):""}Qe.normalizeId=an;function c$(t,e,r){return r=an(r),t.resolve(e,r)}Qe.resolveUrl=c$;var d$=/^[a-z_][-a-z0-9._]*$/i;function u$(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=an(t[r]||e),s={"":o},i=lg(n,o,!1),a={},l=new Set;return o$(t,{allKeys:!0},(g,k,b,R)=>{if(R===void 0)return;let x=i+k,E=s[R];typeof g[r]=="string"&&(E=P.call(this,g[r])),I.call(this,g.$anchor),I.call(this,g.$dynamicAnchor),s[k]=E;function P(D){let H=this.opts.uriResolver.resolve;if(D=an(E?H(E,D):D),l.has(D))throw p(D);l.add(D);let G=this.refs[D];return typeof G=="string"&&(G=this.refs[G]),typeof G=="object"?u(g,G.schema,D):D!==an(x)&&(D[0]==="#"?(u(g,a[D],D),a[D]=g):this.refs[D]=x),D}function I(D){if(typeof D=="string"){if(!d$.test(D))throw new Error(`invalid anchor "${D}"`);P.call(this,`#${D}`)}}}),a;function u(g,k,b){if(k!==void 0&&!n$(g,k))throw p(b)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}Qe.getSchemaRefs=u$});var co=q(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.getData=lr.KeywordCxt=lr.validateFunctionCode=void 0;var mg=Ff(),dg=so(),Pc=wc(),si=so(),p$=Yf(),lo=tg(),Ec=ng(),K=re(),ee=Bt(),h$=io(),Ft=pe(),ao=oo();function m$(t){if(yg(t)&&(bg(t),gg(t))){y$(t);return}fg(t,()=>(0,mg.topBoolOrEmptySchema)(t))}lr.validateFunctionCode=m$;function fg({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,K._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{t.code((0,K._)`"use strict"; ${ug(r,o)}`),g$(t,o),t.code(s)}):t.func(e,(0,K._)`${ee.default.data}, ${f$(o)}`,n.$async,()=>t.code(ug(r,o)).code(s))}function f$(t){return(0,K._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${t.dynamicRef?(0,K._)`, ${ee.default.dynamicAnchors}={}`:K.nil}}={}`}function g$(t,e){t.if(ee.default.valCxt,()=>{t.var(ee.default.instancePath,(0,K._)`${ee.default.valCxt}.${ee.default.instancePath}`),t.var(ee.default.parentData,(0,K._)`${ee.default.valCxt}.${ee.default.parentData}`),t.var(ee.default.parentDataProperty,(0,K._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),t.var(ee.default.rootData,(0,K._)`${ee.default.valCxt}.${ee.default.rootData}`),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,K._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{t.var(ee.default.instancePath,(0,K._)`""`),t.var(ee.default.parentData,(0,K._)`undefined`),t.var(ee.default.parentDataProperty,(0,K._)`undefined`),t.var(ee.default.rootData,ee.default.data),e.dynamicRef&&t.var(ee.default.dynamicAnchors,(0,K._)`{}`)})}function y$(t){let{schema:e,opts:r,gen:n}=t;fg(t,()=>{r.$comment&&e.$comment&&vg(t),S$(t),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&b$(t),wg(t),R$(t)})}function b$(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,K._)`${r}.evaluated`),e.if((0,K._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,K._)`${t.evaluated}.props`,(0,K._)`undefined`)),e.if((0,K._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,K._)`${t.evaluated}.items`,(0,K._)`undefined`))}function ug(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,K._)`/*# sourceURL=${r} */`:K.nil}function w$(t,e){if(yg(t)&&(bg(t),gg(t))){v$(t,e);return}(0,mg.boolOrEmptySchema)(t,e)}function gg({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 yg(t){return typeof t.schema!="boolean"}function v$(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&vg(t),k$(t),T$(t);let s=n.const("_errs",ee.default.errors);wg(t,s),n.var(e,(0,K._)`${s} === ${ee.default.errors}`)}function bg(t){(0,Ft.checkUnknownRules)(t),_$(t)}function wg(t,e){if(t.opts.jtd)return pg(t,[],!1,e);let r=(0,dg.getSchemaTypes)(t.schema),n=(0,dg.coerceAndCheckDataType)(t,r);pg(t,r,!n,e)}function _$(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Ft.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function S$(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ft.checkStrictMode)(t,"default is ignored in the schema root")}function k$(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,h$.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function T$(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function vg({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,K._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,K.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,K._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function R$(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,K._)`${ee.default.errors} === 0`,()=>e.return(ee.default.data),()=>e.throw((0,K._)`new ${o}(${ee.default.vErrors})`)):(e.assign((0,K._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&x$(t),e.return((0,K._)`${ee.default.errors} === 0`))}function x$({gen:t,evaluated:e,props:r,items:n}){r instanceof K.Name&&t.assign((0,K._)`${e}.props`,r),n instanceof K.Name&&t.assign((0,K._)`${e}.items`,n)}function pg(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:u}=t,{RULES:p}=u;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,Ft.schemaHasRulesButRef)(s,p))){o.block(()=>Sg(t,"$ref",p.all.$ref.definition));return}l.jtd||$$(t,e),o.block(()=>{for(let k of p.rules)g(k);g(p.post)});function g(k){(0,Pc.shouldUseGroup)(s,k)&&(k.type?(o.if((0,si.checkDataType)(k.type,i,l.strictNumbers)),hg(t,k),e.length===1&&e[0]===k.type&&r&&(o.else(),(0,si.reportTypeError)(t)),o.endIf()):hg(t,k),a||o.if((0,K._)`${ee.default.errors} === ${n||0}`))}}function hg(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,p$.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Pc.shouldUseRule)(n,s)&&Sg(t,s.keyword,s.definition,e.type)})}function $$(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(E$(t,e),t.opts.allowUnionTypes||P$(t,e),A$(t,t.dataTypes))}function E$(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{_g(t.dataTypes,r)||Ac(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),I$(t,e)}}function P$(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Ac(t,"use allowUnionTypes to allow union type keyword")}function A$(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Pc.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>C$(e,i))&&Ac(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function C$(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function _g(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function I$(t,e){let r=[];for(let n of t.dataTypes)_g(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Ac(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Ft.checkStrictMode)(t,e,t.opts.strictTypes)}var ii=class{constructor(e,r,n){if((0,lo.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,Ft.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",kg(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,lo.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",ee.default.errors))}result(e,r,n){this.failResult((0,K.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,K.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,K._)`${r} !== undefined && (${(0,K.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?ao.reportExtraError:ao.reportError)(this,this.def.error,r)}$dataError(){(0,ao.reportError)(this,this.def.$dataError||ao.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ao.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=K.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=K.nil,r=K.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,K.or)((0,K._)`${o} === undefined`,r)),e!==K.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==K.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,K.or)(i(),a());function i(){if(n.length){if(!(r instanceof K.Name))throw new Error("ajv implementation error");let l=Array.isArray(n)?n:[n];return(0,K._)`${(0,si.checkDataTypes)(l,r,s.opts.strictNumbers,si.DataType.Wrong)}`}return K.nil}function a(){if(o.validateSchema){let l=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,K._)`!${l}(${r})`}return K.nil}}subschema(e,r){let n=(0,Ec.getSubschema)(this.it,e);(0,Ec.extendSubschemaData)(n,this.it,e),(0,Ec.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return w$(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Ft.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Ft.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,K.Name)),!0}};lr.KeywordCxt=ii;function Sg(t,e,r,n){let o=new ii(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,lo.funcKeywordCode)(o,r):"macro"in r?(0,lo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,lo.funcKeywordCode)(o,r)}var O$=/^\/(?:[^~]|~0|~1)*$/,N$=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function kg(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return ee.default.rootData;if(t[0]==="/"){if(!O$.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=ee.default.rootData}else{let u=N$.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let p=+u[1];if(o=u[2],o==="#"){if(p>=e)throw new Error(l("property/index",p));return n[e-p]}if(p>e)throw new Error(l("data",p));if(s=r[e-p],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,K._)`${s}${(0,K.getProperty)((0,Ft.unescapeJsonPointer)(u))}`,i=(0,K._)`${i} && ${s}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${e}`}}lr.getData=kg});var ai=q(Ic=>{"use strict";Object.defineProperty(Ic,"__esModule",{value:!0});var Cc=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ic.default=Cc});var uo=q(Lc=>{"use strict";Object.defineProperty(Lc,"__esModule",{value:!0});var Oc=io(),Nc=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Oc.resolveUrl)(e,r,n),this.missingSchema=(0,Oc.normalizeId)((0,Oc.getFullPath)(e,this.missingRef))}};Lc.default=Nc});var ci=q(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.resolveSchema=ht.getCompilingSchema=ht.resolveRef=ht.compileSchema=ht.SchemaEnv=void 0;var _t=re(),L$=ai(),xr=Bt(),St=io(),Tg=pe(),j$=co(),ln=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,St.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};ht.SchemaEnv=ln;function Dc(t){let e=Rg.call(this,t);if(e)return e;let r=(0,St.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new _t.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:L$.default,code:(0,_t._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");t.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:xr.default.data,parentData:xr.default.parentData,parentDataProperty:xr.default.parentDataProperty,dataNames:[xr.default.data],dataPathArr:[_t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,_t.stringify)(t.schema)}:{ref:t.schema}),validateName:l,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:_t.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,_t._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(t),(0,j$.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(xr.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,t));let b=new Function(`${xr.default.self}`,`${xr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:b}),b.errors=null,b.schema=t.schema,b.schemaEnv=t,t.$async&&(b.$async=!0),this.opts.code.source===!0&&(b.source={validateName:l,validateCode:g,scopeValues:i._values}),this.opts.unevaluated){let{props:R,items:x}=u;b.evaluated={props:R instanceof _t.Name?void 0:R,items:x instanceof _t.Name?void 0:x,dynamicProps:R instanceof _t.Name,dynamicItems:x instanceof _t.Name},b.source&&(b.source.evaluated=(0,_t.stringify)(b.evaluated))}return t.validate=b,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)}}ht.compileSchema=Dc;function D$(t,e,r){var n;r=(0,St.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=q$.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new ln({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=U$.call(this,s)}ht.resolveRef=D$;function U$(t){return(0,St.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Dc.call(this,t)}function Rg(t){for(let e of this._compilations)if(M$(e,t))return e}ht.getCompilingSchema=Rg;function M$(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function q$(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||li.call(this,t,e)}function li(t,e){let r=this.opts.uriResolver.parse(e),n=(0,St._getFullPath)(this.opts.uriResolver,r),o=(0,St.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return jc.call(this,r,t);let s=(0,St.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=li.call(this,t,i);return typeof a?.schema!="object"?void 0:jc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Dc.call(this,i),s===(0,St.normalizeId)(e)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(o=(0,St.resolveUrl)(this.opts.uriResolver,o,u)),new ln({schema:a,schemaId:l,root:t,baseId:o})}return jc.call(this,r,i)}}ht.resolveSchema=li;var z$=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function jc(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,Tg.unescapeFragment)(a)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!z$.has(a)&&u&&(e=(0,St.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Tg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,St.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=li.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new ln({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var xg=q((q1,B$)=>{B$.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 qc=q((z1,Ig)=>{"use strict";var F$=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Eg=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),Uc=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Pg=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),H$=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Mc(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 K$=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function $g(t){return t.length=0,!0}function V$(t,e,r){if(t.length){let n=Mc(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function G$(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=V$;for(let l=0;l<t.length;l++){let u=t[l];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}l>0&&t[l-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=$g}else{o.push(u);continue}}return o.length&&(a===$g?r.zone=o.join(""):i?n.push(o.join("")):n.push(Mc(o))),r.address=n.join(""),r}function Ag(t){if(W$(t,":")<2)return{host:t,isIPV6:!1};let e=G$(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function W$(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function J$(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}var Y$={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},X$=/[@/?#:]/g,Z$=/[@/?#]/g;function Cg(t,e){let r=e?Z$:X$;return r.lastIndex=0,t.replace(r,n=>Y$[n])}function Q$(t,e=!1){if(t.indexOf("%")===-1)return t;let r="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(Uc(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Pg(i)?r+=i:r+="%"+s,n+=2;continue}}r+=t[n]}return r}function eE(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(Uc(n)){let o=n.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Pg(s)?e+=s:e+="%"+o,r+=2;continue}}H$(t[r])?e+=t[r]:e+=escape(t[r])}return e}function tE(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(Uc(n)){e+="%"+n.toUpperCase(),r+=2;continue}}e+=escape(t[r])}return e}function rE(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Eg(r)){let n=Ag(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=Cg(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}Ig.exports={nonSimpleDomain:K$,recomposeAuthority:rE,reescapeHostDelimiters:Cg,normalizePercentEncoding:Q$,normalizePathEncoding:eE,escapePreservingEscapes:tE,removeDotSegments:J$,isIPv4:Eg,isUUID:F$,normalizeIPv6:Ag,stringArrayToHexStripped:Mc}});var Dg=q((B1,jg)=>{"use strict";var{isUUID:nE}=qc(),oE=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,sE=["http","https","ws","wss","urn","urn:uuid"];function iE(t){return sE.indexOf(t)!==-1}function zc(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 Og(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Ng(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 aE(t){return t.secure=zc(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function lE(t){if((t.port===(zc(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 cE(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(oE);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Bc(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function dE(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Bc(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function uE(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!nE(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function pE(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Lg={scheme:"http",domainHost:!0,parse:Og,serialize:Ng},hE={scheme:"https",domainHost:Lg.domainHost,parse:Og,serialize:Ng},di={scheme:"ws",domainHost:!0,parse:aE,serialize:lE},mE={scheme:"wss",domainHost:di.domainHost,parse:di.parse,serialize:di.serialize},fE={scheme:"urn",parse:cE,serialize:dE,skipNormalize:!0},gE={scheme:"urn:uuid",parse:uE,serialize:pE,skipNormalize:!0},ui={http:Lg,https:hE,ws:di,wss:mE,urn:fE,"urn:uuid":gE};Object.setPrototypeOf(ui,null);function Bc(t){return t&&(ui[t]||ui[t.toLowerCase()])||void 0}jg.exports={wsIsSecure:zc,SCHEMES:ui,isValidSchemeName:iE,getSchemeHandler:Bc}});var Bg=q((F1,mi)=>{"use strict";var{normalizeIPv6:yE,removeDotSegments:po,recomposeAuthority:bE,normalizePercentEncoding:wE,normalizePathEncoding:vE,escapePreservingEscapes:_E,reescapeHostDelimiters:SE,isIPv4:kE,nonSimpleDomain:TE}=qc(),{SCHEMES:RE,getSchemeHandler:Mg}=Dg();function xE(t,e){return typeof t=="string"?t=OE(t,e):typeof t=="object"&&(t=hi($r(t,e),e)),t}function $E(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s}=pi(t,n),{parsed:i,malformedAuthorityOrPort:a}=pi(e,n);if(s||a)throw new Error(o.error||i.error||"URI is malformed.");let l=qg(o,i,n,!0);return n.skipEscape=!0,$r(l,n)}function qg(t,e,r,n){let o={};return n||(t=hi($r(t,r),r),e=hi($r(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=po(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=po(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=po(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=po(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function EE(t,e,r){let n=Ug(t,r),o=Ug(e,r);return n!==void 0&&o!==void 0&&n.toLowerCase()===o.toLowerCase()}function $r(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=Mg(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=wE(r.path):(r.path=_E(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=bE(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=po(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var PE=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,AE=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,CE=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function IE(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 pi(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let i=t.match(AE);i!==null&&i[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let a=t.match(CE);if(a!==null){let u=a[1],p=u.replace(/[\t\n\r]/g,"");p.length>=2&&(p.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):u.length!==p.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let l=t.match(PE);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=IE(n,l);if(u!==void 0&&(n.error=n.error||u,o=!0),n.host)if(kE(n.host)===!1){let k=yE(n.host);n.host=k.host.toLowerCase(),s=k.isIPV6}else s=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let p=Mg(r.scheme||n.scheme);if(!r.unicodeSupport&&(!p||!p.unicodeSupport)&&n.host&&(r.domainHost||p&&p.domainHost)&&s===!1&&TE(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=SE(unescape(n.host),s))),n.path&&(n.path=vE(n.path)),n.fragment))try{n.fragment=encodeURI(decodeURIComponent(n.fragment))}catch{n.error=n.error||"URI malformed"}p&&p.parse&&p.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o}}function hi(t,e){return pi(t,e).parsed}function OE(t,e){return zg(t,e).normalized}function zg(t,e){let{parsed:r,malformedAuthorityOrPort:n}=pi(t,e);return{normalized:n?t:$r(r,e),malformedAuthorityOrPort:n}}function Ug(t,e){if(typeof t=="string"){let{normalized:r,malformedAuthorityOrPort:n}=zg(t,e);return n?void 0:r}if(typeof t=="object")return $r(t,e)}var Fc={SCHEMES:RE,normalize:xE,resolve:$E,resolveComponent:qg,equal:EE,serialize:$r,parse:hi};mi.exports=Fc;mi.exports.default=Fc;mi.exports.fastUri=Fc});var Hg=q(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var Fg=Bg();Fg.code='require("ajv/dist/runtime/uri").default';Hc.default=Fg});var Zg=q(Ue=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.CodeGen=Ue.Name=Ue.nil=Ue.stringify=Ue.str=Ue._=Ue.KeywordCxt=void 0;var NE=co();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:function(){return NE.KeywordCxt}});var cn=re();Object.defineProperty(Ue,"_",{enumerable:!0,get:function(){return cn._}});Object.defineProperty(Ue,"str",{enumerable:!0,get:function(){return cn.str}});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:function(){return cn.stringify}});Object.defineProperty(Ue,"nil",{enumerable:!0,get:function(){return cn.nil}});Object.defineProperty(Ue,"Name",{enumerable:!0,get:function(){return cn.Name}});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:function(){return cn.CodeGen}});var LE=ai(),Jg=uo(),jE=bc(),ho=ci(),DE=re(),mo=io(),fi=so(),Vc=pe(),Kg=xg(),UE=Hg(),Yg=(t,e)=>new RegExp(t,e);Yg.code="new RegExp";var ME=["removeAdditional","useDefaults","coerceTypes"],qE=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),zE={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."},BE={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Vg=200;function FE(t){var e,r,n,o,s,i,a,l,u,p,g,k,b,R,x,E,P,I,D,H,G,xe,qe,Rt,Kt;let xt=t.strict,Vt=(e=t.code)===null||e===void 0?void 0:e.optimize,Eo=Vt===!0||Vt===void 0?1:Vt||0,pr=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Yg,Lt=(o=t.uriResolver)!==null&&o!==void 0?o:UE.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:xt)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=t.strictNumbers)!==null&&a!==void 0?a:xt)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=t.strictTypes)!==null&&u!==void 0?u:xt)!==null&&p!==void 0?p:"log",strictTuples:(k=(g=t.strictTuples)!==null&&g!==void 0?g:xt)!==null&&k!==void 0?k:"log",strictRequired:(R=(b=t.strictRequired)!==null&&b!==void 0?b:xt)!==null&&R!==void 0?R:!1,code:t.code?{...t.code,optimize:Eo,regExp:pr}:{optimize:Eo,regExp:pr},loopRequired:(x=t.loopRequired)!==null&&x!==void 0?x:Vg,loopEnum:(E=t.loopEnum)!==null&&E!==void 0?E:Vg,meta:(P=t.meta)!==null&&P!==void 0?P:!0,messages:(I=t.messages)!==null&&I!==void 0?I:!0,inlineRefs:(D=t.inlineRefs)!==null&&D!==void 0?D:!0,schemaId:(H=t.schemaId)!==null&&H!==void 0?H:"$id",addUsedSchema:(G=t.addUsedSchema)!==null&&G!==void 0?G:!0,validateSchema:(xe=t.validateSchema)!==null&&xe!==void 0?xe:!0,validateFormats:(qe=t.validateFormats)!==null&&qe!==void 0?qe:!0,unicodeRegExp:(Rt=t.unicodeRegExp)!==null&&Rt!==void 0?Rt:!0,int32range:(Kt=t.int32range)!==null&&Kt!==void 0?Kt:!0,uriResolver:Lt}}var fo=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,...FE(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new DE.ValueScope({scope:{},prefixes:qE,es5:r,lines:n}),this.logger=JE(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,jE.getRules)(),Gg.call(this,zE,e,"NOT SUPPORTED"),Gg.call(this,BE,e,"DEPRECATED","warn"),this._metaOpts=GE.call(this),e.formats&&KE.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&VE.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),HE.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Kg;n==="id"&&(o={...Kg},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(p,g){await s.call(this,p.$schema);let k=this._addSchema(p,g);return k.validate||i.call(this,k)}async function s(p){p&&!this.getSchema(p)&&await o.call(this,{$ref:p},!0)}async function i(p){try{return this._compileSchemaEnv(p)}catch(g){if(!(g instanceof Jg.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 s.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,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,mo.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=Wg.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ho.SchemaEnv({schema:{},schemaId:n});if(r=ho.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Wg.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,mo.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(XE.call(this,n,r),!r)return(0,Vc.eachItem)(n,s=>Kc.call(this,s)),this;QE.call(this,r);let o={...r,type:(0,fi.getJSONTypes)(r.type),schemaType:(0,fi.getJSONTypes)(r.schemaType)};return(0,Vc.eachItem)(n,o.type.length===0?s=>Kc.call(this,s,o):s=>o.type.forEach(i=>Kc.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let l=n[a];if(typeof l!="object")continue;let{$data:u}=l.definition,p=i[a];u&&p&&(i[a]=Xg(p))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(e);if(l!==void 0)return l;n=(0,mo.normalizeId)(i||n);let u=mo.getSchemaRefs.call(this,e,n);return l=new ho.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(l.schema,l),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=l),o&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):ho.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{ho.compileSchema.call(this,e)}finally{this.opts=r}}};fo.ValidationError=LE.default;fo.MissingRefError=Jg.default;Ue.default=fo;function Gg(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function Wg(t){return t=(0,mo.normalizeId)(t),this.schemas[t]||this.refs[t]}function HE(){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 KE(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function VE(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 GE(){let t={...this.opts};for(let e of ME)delete t[e];return t}var WE={log(){},warn(){},error(){}};function JE(t){if(t===!1)return WE;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 YE=/^[a-z_$][a-z0-9_$:-]*$/i;function XE(t,e){let{RULES:r}=this;if((0,Vc.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!YE.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 Kc(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:l})=>l===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,fi.getJSONTypes)(e.type),schemaType:(0,fi.getJSONTypes)(e.schemaType)}};e.before?ZE.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function ZE(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function QE(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Xg(e)),t.validateSchema=this.compile(e,!0))}var eP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Xg(t){return{anyOf:[t,eP]}}});var Qg=q(Gc=>{"use strict";Object.defineProperty(Gc,"__esModule",{value:!0});var tP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Gc.default=tP});var ny=q(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.callRef=Er.getValidate=void 0;var rP=uo(),ey=pt(),et=re(),dn=Bt(),ty=ci(),gi=pe(),nP={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return g();let p=ty.resolveRef.call(l,u,o,r);if(p===void 0)throw new rP.default(n.opts.uriResolver,o,r);if(p instanceof ty.SchemaEnv)return k(p);return b(p);function g(){if(s===u)return yi(t,i,s,s.$async);let R=e.scopeValue("root",{ref:u});return yi(t,(0,et._)`${R}.validate`,u,u.$async)}function k(R){let x=ry(t,R);yi(t,x,R,R.$async)}function b(R){let x=e.scopeValue("schema",a.code.source===!0?{ref:R,code:(0,et.stringify)(R)}:{ref:R}),E=e.name("valid"),P=t.subschema({schema:R,dataTypes:[],schemaPath:et.nil,topSchemaRef:x,errSchemaPath:r},E);t.mergeEvaluated(P),t.ok(E)}}};function ry(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Er.getValidate=ry;function yi(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:l}=s,u=l.passContext?dn.default.this:et.nil;n?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let R=o.let("valid");o.try(()=>{o.code((0,et._)`await ${(0,ey.callValidateCode)(t,e,u)}`),b(e),i||o.assign(R,!0)},x=>{o.if((0,et._)`!(${x} instanceof ${s.ValidationError})`,()=>o.throw(x)),k(x),i||o.assign(R,!1)}),t.ok(R)}function g(){t.result((0,ey.callValidateCode)(t,e,u),()=>b(e),()=>k(e))}function k(R){let x=(0,et._)`${R}.errors`;o.assign(dn.default.vErrors,(0,et._)`${dn.default.vErrors} === null ? ${x} : ${dn.default.vErrors}.concat(${x})`),o.assign(dn.default.errors,(0,et._)`${dn.default.vErrors}.length`)}function b(R){var x;if(!s.opts.unevaluated)return;let E=(x=r?.validate)===null||x===void 0?void 0:x.evaluated;if(s.props!==!0)if(E&&!E.dynamicProps)E.props!==void 0&&(s.props=gi.mergeEvaluated.props(o,E.props,s.props));else{let P=o.var("props",(0,et._)`${R}.evaluated.props`);s.props=gi.mergeEvaluated.props(o,P,s.props,et.Name)}if(s.items!==!0)if(E&&!E.dynamicItems)E.items!==void 0&&(s.items=gi.mergeEvaluated.items(o,E.items,s.items));else{let P=o.var("items",(0,et._)`${R}.evaluated.items`);s.items=gi.mergeEvaluated.items(o,P,s.items,et.Name)}}}Er.callRef=yi;Er.default=nP});var oy=q(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var oP=Qg(),sP=ny(),iP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",oP.default,sP.default];Wc.default=iP});var sy=q(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});var bi=re(),cr=bi.operators,wi={maximum:{okStr:"<=",ok:cr.LTE,fail:cr.GT},minimum:{okStr:">=",ok:cr.GTE,fail:cr.LT},exclusiveMaximum:{okStr:"<",ok:cr.LT,fail:cr.GTE},exclusiveMinimum:{okStr:">",ok:cr.GT,fail:cr.LTE}},aP={message:({keyword:t,schemaCode:e})=>(0,bi.str)`must be ${wi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,bi._)`{comparison: ${wi[t].okStr}, limit: ${e}}`},lP={keyword:Object.keys(wi),type:"number",schemaType:"number",$data:!0,error:aP,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,bi._)`${r} ${wi[e].fail} ${n} || isNaN(${r})`)}};Jc.default=lP});var iy=q(Yc=>{"use strict";Object.defineProperty(Yc,"__esModule",{value:!0});var go=re(),cP={message:({schemaCode:t})=>(0,go.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,go._)`{multipleOf: ${t}}`},dP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:cP,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,go._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,go._)`${i} !== parseInt(${i})`;t.fail$data((0,go._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Yc.default=dP});var ly=q(Xc=>{"use strict";Object.defineProperty(Xc,"__esModule",{value:!0});function ay(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Xc.default=ay;ay.code='require("ajv/dist/runtime/ucs2length").default'});var cy=q(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});var Pr=re(),uP=pe(),pP=ly(),hP={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Pr.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Pr._)`{limit: ${t}}`},mP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:hP,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Pr.operators.GT:Pr.operators.LT,i=o.opts.unicode===!1?(0,Pr._)`${r}.length`:(0,Pr._)`${(0,uP.useFunc)(t.gen,pP.default)}(${r})`;t.fail$data((0,Pr._)`${i} ${s} ${n}`)}};Zc.default=mP});var dy=q(Qc=>{"use strict";Object.defineProperty(Qc,"__esModule",{value:!0});var fP=pt(),gP=pe(),un=re(),yP={message:({schemaCode:t})=>(0,un.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,un._)`{pattern: ${t}}`},bP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:yP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,un._)`new RegExp`:(0,gP.useFunc)(e,l),p=e.let("valid");e.try(()=>e.assign(p,(0,un._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(p,!1)),t.fail$data((0,un._)`!${p}`)}else{let l=(0,fP.usePattern)(t,o);t.fail$data((0,un._)`!${l}.test(${r})`)}}};Qc.default=bP});var uy=q(ed=>{"use strict";Object.defineProperty(ed,"__esModule",{value:!0});var yo=re(),wP={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,yo.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,yo._)`{limit: ${t}}`},vP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:wP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?yo.operators.GT:yo.operators.LT;t.fail$data((0,yo._)`Object.keys(${r}).length ${o} ${n}`)}};ed.default=vP});var py=q(td=>{"use strict";Object.defineProperty(td,"__esModule",{value:!0});var bo=pt(),wo=re(),_P=pe(),SP={message:({params:{missingProperty:t}})=>(0,wo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,wo._)`{missingProperty: ${t}}`},kP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:SP,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let b=t.parentSchema.properties,{definedProperties:R}=t.it;for(let x of r)if(b?.[x]===void 0&&!R.has(x)){let E=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${x}" is not defined at "${E}" (strictRequired)`;(0,_P.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||s)t.block$data(wo.nil,g);else for(let b of r)(0,bo.checkReportMissingProp)(t,b)}function p(){let b=e.let("missing");if(l||s){let R=e.let("valid",!0);t.block$data(R,()=>k(b,R)),t.ok(R)}else e.if((0,bo.checkMissingProp)(t,r,b)),(0,bo.reportMissingProp)(t,b),e.else()}function g(){e.forOf("prop",n,b=>{t.setParams({missingProperty:b}),e.if((0,bo.noPropertyInData)(e,o,b,a.ownProperties),()=>t.error())})}function k(b,R){t.setParams({missingProperty:b}),e.forOf(b,n,()=>{e.assign(R,(0,bo.propertyInData)(e,o,b,a.ownProperties)),e.if((0,wo.not)(R),()=>{t.error(),e.break()})},wo.nil)}}};td.default=kP});var hy=q(rd=>{"use strict";Object.defineProperty(rd,"__esModule",{value:!0});var vo=re(),TP={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,vo.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,vo._)`{limit: ${t}}`},RP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:TP,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?vo.operators.GT:vo.operators.LT;t.fail$data((0,vo._)`${r}.length ${o} ${n}`)}};rd.default=RP});var vi=q(nd=>{"use strict";Object.defineProperty(nd,"__esModule",{value:!0});var my=xc();my.code='require("ajv/dist/runtime/equal").default';nd.default=my});var fy=q(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});var od=so(),Me=re(),xP=pe(),$P=vi(),EP={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},PP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:EP,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let l=e.let("valid"),u=s.items?(0,od.getSchemaTypes)(s.items):[];t.block$data(l,p,(0,Me._)`${i} === false`),t.ok(l);function p(){let R=e.let("i",(0,Me._)`${r}.length`),x=e.let("j");t.setParams({i:R,j:x}),e.assign(l,!0),e.if((0,Me._)`${R} > 1`,()=>(g()?k:b)(R,x))}function g(){return u.length>0&&!u.some(R=>R==="object"||R==="array")}function k(R,x){let E=e.name("item"),P=(0,od.checkDataTypes)(u,E,a.opts.strictNumbers,od.DataType.Wrong),I=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${R}--;`,()=>{e.let(E,(0,Me._)`${r}[${R}]`),e.if(P,(0,Me._)`continue`),u.length>1&&e.if((0,Me._)`typeof ${E} == "string"`,(0,Me._)`${E} += "_"`),e.if((0,Me._)`typeof ${I}[${E}] == "number"`,()=>{e.assign(x,(0,Me._)`${I}[${E}]`),t.error(),e.assign(l,!1).break()}).code((0,Me._)`${I}[${E}] = ${R}`)})}function b(R,x){let E=(0,xP.useFunc)(e,$P.default),P=e.name("outer");e.label(P).for((0,Me._)`;${R}--;`,()=>e.for((0,Me._)`${x} = ${R}; ${x}--;`,()=>e.if((0,Me._)`${E}(${r}[${R}], ${r}[${x}])`,()=>{t.error(),e.assign(l,!1).break(P)})))}}};sd.default=PP});var gy=q(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var id=re(),AP=pe(),CP=vi(),IP={message:"must be equal to constant",params:({schemaCode:t})=>(0,id._)`{allowedValue: ${t}}`},OP={keyword:"const",$data:!0,error:IP,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,id._)`!${(0,AP.useFunc)(e,CP.default)}(${r}, ${o})`):t.fail((0,id._)`${s} !== ${r}`)}};ad.default=OP});var yy=q(ld=>{"use strict";Object.defineProperty(ld,"__esModule",{value:!0});var _o=re(),NP=pe(),LP=vi(),jP={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,_o._)`{allowedValues: ${t}}`},DP={keyword:"enum",schemaType:"array",$data:!0,error:jP,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,l,u=()=>l??(l=(0,NP.useFunc)(e,LP.default)),p;if(a||n)p=e.let("valid"),t.block$data(p,g);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let b=e.const("vSchema",s);p=(0,_o.or)(...o.map((R,x)=>k(b,x)))}t.pass(p);function g(){e.assign(p,!1),e.forOf("v",s,b=>e.if((0,_o._)`${u()}(${r}, ${b})`,()=>e.assign(p,!0).break()))}function k(b,R){let x=o[R];return typeof x=="object"&&x!==null?(0,_o._)`${u()}(${r}, ${b}[${R}])`:(0,_o._)`${r} === ${x}`}}};ld.default=DP});var by=q(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var UP=sy(),MP=iy(),qP=cy(),zP=dy(),BP=uy(),FP=py(),HP=hy(),KP=fy(),VP=gy(),GP=yy(),WP=[UP.default,MP.default,qP.default,zP.default,BP.default,FP.default,HP.default,KP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},VP.default,GP.default];cd.default=WP});var ud=q(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.validateAdditionalItems=void 0;var Ar=re(),dd=pe(),JP={message:({params:{len:t}})=>(0,Ar.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ar._)`{limit: ${t}}`},YP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:JP,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,dd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}wy(t,n)}};function wy(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Ar._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ar._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,dd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Ar._)`${a} <= ${e.length}`);r.if((0,Ar.not)(u),()=>l(u)),t.ok(u)}function l(u){r.forRange("i",e.length,a,p=>{t.subschema({keyword:s,dataProp:p,dataPropType:dd.Type.Num},u),i.allErrors||r.if((0,Ar.not)(u),()=>r.break())})}}So.validateAdditionalItems=wy;So.default=YP});var pd=q(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.validateTuple=void 0;var vy=re(),_i=pe(),XP=pt(),ZP={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return _y(t,"additionalItems",e);r.items=!0,!(0,_i.alwaysValidSchema)(r,e)&&t.ok((0,XP.validateArray)(t))}};function _y(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=_i.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),u=n.const("len",(0,vy._)`${s}.length`);r.forEach((g,k)=>{(0,_i.alwaysValidSchema)(a,g)||(n.if((0,vy._)`${u} > ${k}`,()=>t.subschema({keyword:i,schemaProp:k,dataProp:k},l)),t.ok(l))});function p(g){let{opts:k,errSchemaPath:b}=a,R=r.length,x=R===g.minItems&&(R===g.maxItems||g[e]===!1);if(k.strictTuples&&!x){let E=`"${i}" is ${R}-tuple, but minItems or maxItems/${e} are not specified or different at path "${b}"`;(0,_i.checkStrictMode)(a,E,k.strictTuples)}}}ko.validateTuple=_y;ko.default=ZP});var Sy=q(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var QP=pd(),e0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,QP.validateTuple)(t,"items")};hd.default=e0});var Ty=q(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var ky=re(),t0=pe(),r0=pt(),n0=ud(),o0={message:({params:{len:t}})=>(0,ky.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ky._)`{limit: ${t}}`},s0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:o0,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,t0.alwaysValidSchema)(n,e)&&(o?(0,n0.validateAdditionalItems)(t,o):t.ok((0,r0.validateArray)(t)))}};md.default=s0});var Ry=q(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var mt=re(),Si=pe(),i0={message:({params:{min:t,max:e}})=>e===void 0?(0,mt.str)`must contain at least ${t} valid item(s)`:(0,mt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,mt._)`{minContains: ${t}}`:(0,mt._)`{minContains: ${t}, maxContains: ${e}}`},a0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:i0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:l,maxContains:u}=n;s.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=e.const("len",(0,mt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Si.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Si.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Si.alwaysValidSchema)(s,r)){let x=(0,mt._)`${p} >= ${i}`;a!==void 0&&(x=(0,mt._)`${x} && ${p} <= ${a}`),t.pass(x);return}s.items=!0;let g=e.name("valid");a===void 0&&i===1?b(g,()=>e.if(g,()=>e.break())):i===0?(e.let(g,!0),a!==void 0&&e.if((0,mt._)`${o}.length > 0`,k)):(e.let(g,!1),k()),t.result(g,()=>t.reset());function k(){let x=e.name("_valid"),E=e.let("count",0);b(x,()=>e.if(x,()=>R(E)))}function b(x,E){e.forRange("i",0,p,P=>{t.subschema({keyword:"contains",dataProp:P,dataPropType:Si.Type.Num,compositeRule:!0},x),E()})}function R(x){e.code((0,mt._)`${x}++`),a===void 0?e.if((0,mt._)`${x} >= ${i}`,()=>e.assign(g,!0).break()):(e.if((0,mt._)`${x} > ${a}`,()=>e.assign(g,!1).break()),i===1?e.assign(g,!0):e.if((0,mt._)`${x} >= ${i}`,()=>e.assign(g,!0)))}}};fd.default=a0});var Ey=q(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.validateSchemaDeps=It.validatePropertyDeps=It.error=void 0;var gd=re(),l0=pe(),To=pt();It.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,gd.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,gd._)`{property: ${t},
2308
2367
  missingProperty: ${n},
2309
2368
  depsCount: ${e},
2310
- deps: ${r}}`};var XP={keyword:"dependencies",type:"object",schemaType:"object",error:Ct.error,code(t){let[e,r]=ZP(t);Sy(t,e),ky(t,r)}};function ZP({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function Sy(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,ko.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let u of a)(0,ko.checkReportMissingProp)(t,u)}):(r.if((0,hd._)`${l} && (${(0,ko.checkMissingProp)(t,a,s)})`),(0,ko.reportMissingProp)(t,s),r.else())}}Ct.validatePropertyDeps=Sy;function ky(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,YP.alwaysValidSchema)(s,e[a])||(r.if((0,ko.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}Ct.validateSchemaDeps=ky;Ct.default=XP});var Ry=U(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var xy=re(),QP=ue(),e0={message:"property name must be valid",params:({params:t})=>(0,xy._)`{propertyName: ${t.propertyName}}`},t0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:e0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,QP.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,xy.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};md.default=t0});var gd=U(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var vi=dt(),St=re(),r0=zt(),_i=ue(),n0={message:"must NOT have additional properties",params:({params:t})=>(0,St._)`{additionalProperty: ${t.additionalProperty}}`},o0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:n0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,_i.alwaysValidSchema)(i,r))return;let u=(0,vi.allSchemaProperties)(n.properties),p=(0,vi.allSchemaProperties)(n.patternProperties);g(),t.ok((0,St._)`${s} === ${r0.default.errors}`);function g(){e.forIn("key",o,E=>{!u.length&&!p.length?x(E):e.if(S(E),()=>x(E))})}function S(E){let P;if(u.length>8){let I=(0,_i.schemaRefOrVal)(i,n.properties,"properties");P=(0,vi.isOwnProperty)(e,I,E)}else u.length?P=(0,St.or)(...u.map(I=>(0,St._)`${E} === ${I}`)):P=St.nil;return p.length&&(P=(0,St.or)(P,...p.map(I=>(0,St._)`${(0,vi.usePattern)(t,I)}.test(${E})`))),(0,St.not)(P)}function y(E){e.code((0,St._)`delete ${o}[${E}]`)}function x(E){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){y(E);return}if(r===!1){t.setParams({additionalProperty:E}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,_i.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?(R(E,P,!1),e.if((0,St.not)(P),()=>{t.reset(),y(E)})):(R(E,P),a||e.if((0,St.not)(P),()=>e.break()))}}function R(E,P,I){let D={keyword:"additionalProperties",dataProp:E,dataPropType:_i.Type.Str};I===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};fd.default=o0});var Py=U(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var s0=lo(),$y=dt(),yd=ue(),Ey=gd(),i0={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Ey.default.code(new s0.KeywordCxt(s,Ey.default,"additionalProperties"));let i=(0,$y.allSchemaProperties)(r);for(let g of i)s.definedProperties.add(g);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=yd.mergeEvaluated.props(e,(0,yd.toHash)(i),s.props));let a=i.filter(g=>!(0,yd.alwaysValidSchema)(s,r[g]));if(a.length===0)return;let l=e.name("valid");for(let g of a)u(g)?p(g):(e.if((0,$y.propertyInData)(e,o,g,s.opts.ownProperties)),p(g),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(g),t.ok(l);function u(g){return s.opts.useDefaults&&!s.compositeRule&&r[g].default!==void 0}function p(g){t.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};bd.default=i0});var Oy=U(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var Ay=dt(),Si=re(),Cy=ue(),Iy=ue(),a0={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Ay.allSchemaProperties)(r),l=a.filter(R=>(0,Cy.alwaysValidSchema)(s,r[R]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,p=e.name("valid");s.props!==!0&&!(s.props instanceof Si.Name)&&(s.props=(0,Iy.evaluatedPropsToName)(e,s.props));let{props:g}=s;S();function S(){for(let R of a)u&&y(R),s.allErrors?x(R):(e.var(p,!0),x(R),e.if(p))}function y(R){for(let E in u)new RegExp(R).test(E)&&(0,Cy.checkStrictMode)(s,`property ${E} matches pattern ${R} (use allowMatchingProperties)`)}function x(R){e.forIn("key",n,E=>{e.if((0,Si._)`${(0,Ay.usePattern)(t,R)}.test(${E})`,()=>{let P=l.includes(R);P||t.subschema({keyword:"patternProperties",schemaProp:R,dataProp:E,dataPropType:Iy.Type.Str},p),s.opts.unevaluated&&g!==!0?e.assign((0,Si._)`${g}[${E}]`,!0):!P&&!s.allErrors&&e.if((0,Si.not)(p),()=>e.break())})})}}};wd.default=a0});var Ny=U(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var l0=ue(),c0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,l0.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};vd.default=c0});var Ly=U(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var d0=dt(),u0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:d0.validateUnion,error:{message:"must match a schema in anyOf"}};_d.default=u0});var jy=U(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var ki=re(),p0=ue(),h0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,ki._)`{passingSchemas: ${t.passing}}`},m0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:h0,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((p,g)=>{let S;(0,p0.alwaysValidSchema)(o,p)?e.var(l,!0):S=t.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&e.if((0,ki._)`${l} && ${i}`).assign(i,!1).assign(a,(0,ki._)`[${a}, ${g}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,g),S&&t.mergeEvaluated(S,ki.Name)})})}}};Sd.default=m0});var Dy=U(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var f0=ue(),g0={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,f0.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};kd.default=g0});var qy=U(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Ti=re(),My=ue(),y0={message:({params:t})=>(0,Ti.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ti._)`{failingKeyword: ${t.ifClause}}`},b0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:y0,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,My.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Uy(n,"then"),s=Uy(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),o&&s){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,u("then",p),u("else",p))}else o?e.if(a,u("then")):e.if((0,Ti.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 S=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(S,i),g?e.assign(g,(0,Ti._)`${p}`):t.setParams({ifClause:p})}}}};function Uy(t,e){let r=t.schema[e];return r!==void 0&&!(0,My.alwaysValidSchema)(t,r)}Td.default=b0});var zy=U(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var w0=ue(),v0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,w0.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};xd.default=v0});var By=U(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var _0=ld(),S0=by(),k0=cd(),T0=vy(),x0=_y(),R0=Ty(),$0=Ry(),E0=gd(),P0=Py(),A0=Oy(),C0=Ny(),I0=Ly(),O0=jy(),N0=Dy(),L0=qy(),j0=zy();function D0(t=!1){let e=[C0.default,I0.default,O0.default,N0.default,L0.default,j0.default,$0.default,E0.default,R0.default,P0.default,A0.default];return t?e.push(S0.default,T0.default):e.push(_0.default,k0.default),e.push(x0.default),e}Rd.default=D0});var Fy=U($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var Re=re(),U0={message:({schemaCode:t})=>(0,Re.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Re._)`{format: ${t}}`},M0={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:U0,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;o?S():y();function S(){let x=r.scopeValue("formats",{ref:g.formats,code:l.code.formats}),R=r.const("fDef",(0,Re._)`${x}[${i}]`),E=r.let("fType"),P=r.let("format");r.if((0,Re._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>r.assign(E,(0,Re._)`${R}.type || "string"`).assign(P,(0,Re._)`${R}.validate`),()=>r.assign(E,(0,Re._)`"string"`).assign(P,R)),t.fail$data((0,Re.or)(I(),D()));function I(){return l.strictSchema===!1?Re.nil:(0,Re._)`${i} && !${P}`}function D(){let F=p.$async?(0,Re._)`(${R}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,Re._)`${P}(${n})`,K=(0,Re._)`(typeof ${P} == "function" ? ${F} : ${P}.test(${n}))`;return(0,Re._)`${P} && ${P} !== true && ${E} === ${e} && !${K}`}}function y(){let x=g.formats[s];if(!x){I();return}if(x===!0)return;let[R,E,P]=D(x);R===e&&t.pass(F());function I(){if(l.strictSchema===!1){g.logger.warn(K());return}throw new Error(K());function K(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function D(K){let Ce=K instanceof RegExp?(0,Re.regexpCode)(K):l.code.formats?(0,Re._)`${l.code.formats}${(0,Re.getProperty)(s)}`:void 0,Ie=r.scopeValue("formats",{key:s,ref:K,code:Ce});return typeof K=="object"&&!(K instanceof RegExp)?[K.type||"string",K.validate,(0,Re._)`${Ie}.validate`]:["string",K,Ie]}function F(){if(typeof x=="object"&&!(x instanceof RegExp)&&x.async){if(!p.$async)throw new Error("async format in sync schema");return(0,Re._)`await ${P}(${n})`}return typeof E=="function"?(0,Re._)`${P}(${n})`:(0,Re._)`${P}.test(${n})`}}}};$d.default=M0});var Hy=U(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var q0=Fy(),z0=[q0.default];Ed.default=z0});var Ky=U(un=>{"use strict";Object.defineProperty(un,"__esModule",{value:!0});un.contentVocabulary=un.metadataVocabulary=void 0;un.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];un.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Gy=U(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var B0=ey(),F0=my(),H0=By(),K0=Hy(),Vy=Ky(),V0=[B0.default,F0.default,(0,H0.default)(),K0.default,Vy.metadataVocabulary,Vy.contentVocabulary];Pd.default=V0});var Jy=U(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.DiscrError=void 0;var Wy;(function(t){t.Tag="tag",t.Mapping="mapping"})(Wy||(xi.DiscrError=Wy={}))});var Xy=U(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var pn=re(),Ad=Jy(),Yy=ii(),G0=co(),W0=ue(),J0={message:({params:{discrError:t,tagName:e}})=>t===Ad.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,pn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},Y0={keyword:"discriminator",type:"object",schemaType:"object",error:J0,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),u=e.const("tag",(0,pn._)`${r}${(0,pn.getProperty)(a)}`);e.if((0,pn._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:Ad.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let y=S();e.if(!1);for(let x in y)e.elseIf((0,pn._)`${u} === ${x}`),e.assign(l,g(y[x]));e.else(),t.error(!1,{discrError:Ad.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function g(y){let x=e.name("valid"),R=t.subschema({keyword:"oneOf",schemaProp:y},x);return t.mergeEvaluated(R,pn.Name),x}function S(){var y;let x={},R=P(o),E=!0;for(let F=0;F<i.length;F++){let K=i[F];if(K?.$ref&&!(0,W0.schemaHasRulesButRef)(K,s.self.RULES)){let Ie=K.$ref;if(K=Yy.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Ie),K instanceof Yy.SchemaEnv&&(K=K.schema),K===void 0)throw new G0.default(s.opts.uriResolver,s.baseId,Ie)}let Ce=(y=K?.properties)===null||y===void 0?void 0:y[a];if(typeof Ce!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);E=E&&(R||P(K)),I(Ce,F)}if(!E)throw new Error(`discriminator: "${a}" must be required`);return x;function P({required:F}){return Array.isArray(F)&&F.includes(a)}function I(F,K){if(F.const)D(F.const,K);else if(F.enum)for(let Ce of F.enum)D(Ce,K);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(F,K){if(typeof F!="string"||F in x)throw new Error(`discriminator: "${a}" values must be unique strings`);x[F]=K}}}};Cd.default=Y0});var Zy=U((wU,X0)=>{X0.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 Od=U((ke,Id)=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.MissingRefError=ke.ValidationError=ke.CodeGen=ke.Name=ke.nil=ke.stringify=ke.str=ke._=ke.KeywordCxt=ke.Ajv=void 0;var Z0=Wg(),Q0=Gy(),eA=Xy(),Qy=Zy(),tA=["/properties"],Ri="http://json-schema.org/draft-07/schema",hn=class extends Z0.default{_addVocabularies(){super._addVocabularies(),Q0.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(eA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Qy,tA):Qy;this.addMetaSchema(e,Ri,!1),this.refs["http://json-schema.org/schema"]=Ri}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Ri)?Ri:void 0)}};ke.Ajv=hn;Id.exports=ke=hn;Id.exports.Ajv=hn;Object.defineProperty(ke,"__esModule",{value:!0});ke.default=hn;var rA=lo();Object.defineProperty(ke,"KeywordCxt",{enumerable:!0,get:function(){return rA.KeywordCxt}});var mn=re();Object.defineProperty(ke,"_",{enumerable:!0,get:function(){return mn._}});Object.defineProperty(ke,"str",{enumerable:!0,get:function(){return mn.str}});Object.defineProperty(ke,"stringify",{enumerable:!0,get:function(){return mn.stringify}});Object.defineProperty(ke,"nil",{enumerable:!0,get:function(){return mn.nil}});Object.defineProperty(ke,"Name",{enumerable:!0,get:function(){return mn.Name}});Object.defineProperty(ke,"CodeGen",{enumerable:!0,get:function(){return mn.CodeGen}});var nA=oi();Object.defineProperty(ke,"ValidationError",{enumerable:!0,get:function(){return nA.default}});var oA=co();Object.defineProperty(ke,"MissingRefError",{enumerable:!0,get:function(){return oA.default}})});var ab=U(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.formatNames=Ot.fastFormats=Ot.fullFormats=void 0;function It(t,e){return{validate:t,compare:e}}Ot.fullFormats={date:It(nb,Dd),time:It(Ld(!0),Ud),"date-time":It(eb(!0),sb),"iso-time":It(Ld(),ob),"iso-date-time":It(eb(),ib),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:dA,"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:yA,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:uA,int32:{type:"number",validate:mA},int64:{type:"number",validate:fA},float:{type:"number",validate:rb},double:{type:"number",validate:rb},password:!0,binary:!0};Ot.fastFormats={...Ot.fullFormats,date:It(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Dd),time:It(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ud),"date-time":It(/^\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,sb),"iso-time":It(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,ob),"iso-date-time":It(/^\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,ib),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};Ot.formatNames=Object.keys(Ot.fullFormats);function sA(t){return t%4===0&&(t%100!==0||t%400===0)}var iA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,aA=[0,31,28,31,30,31,30,31,31,30,31,30,31];function nb(t){let e=iA.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&sA(r)?29:aA[n])}function Dd(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Nd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Ld(t){return function(r){let n=Nd.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,u=+(n[6]||0),p=+(n[7]||0);if(u>23||p>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let g=s-p*l,S=o-u*l-(g<0?1:0);return(S===23||S===-1)&&(g===59||g===-1)&&i<61}}function Ud(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 ob(t,e){if(!(t&&e))return;let r=Nd.exec(t),n=Nd.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 jd=/t|\s/i;function eb(t){let e=Ld(t);return function(n){let o=n.split(jd);return o.length===2&&nb(o[0])&&e(o[1])}}function sb(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function ib(t,e){if(!(t&&e))return;let[r,n]=t.split(jd),[o,s]=e.split(jd),i=Dd(r,o);if(i!==void 0)return i||Ud(n,s)}var lA=/\/|:/,cA=/^(?:[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 dA(t){return lA.test(t)&&cA.test(t)}var tb=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function uA(t){return tb.lastIndex=0,tb.test(t)}var pA=-(2**31),hA=2**31-1;function mA(t){return Number.isInteger(t)&&t<=hA&&t>=pA}function fA(t){return Number.isInteger(t)}function rb(){return!0}var gA=/[^\\]\\Z/;function yA(t){if(gA.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var lb=U(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.formatLimitDefinition=void 0;var bA=Od(),kt=re(),lr=kt.operators,$i={formatMaximum:{okStr:"<=",ok:lr.LTE,fail:lr.GT},formatMinimum:{okStr:">=",ok:lr.GTE,fail:lr.LT},formatExclusiveMaximum:{okStr:"<",ok:lr.LT,fail:lr.GTE},formatExclusiveMinimum:{okStr:">",ok:lr.GT,fail:lr.LTE}},wA={message:({keyword:t,schemaCode:e})=>(0,kt.str)`should be ${$i[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,kt._)`{comparison: ${$i[t].okStr}, limit: ${e}}`};fn.formatLimitDefinition={keyword:Object.keys($i),type:"string",schemaType:"string",$data:!0,error:wA,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let l=new bA.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let S=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=e.const("fmt",(0,kt._)`${S}[${l.schemaCode}]`);t.fail$data((0,kt.or)((0,kt._)`typeof ${y} != "object"`,(0,kt._)`${y} instanceof RegExp`,(0,kt._)`typeof ${y}.compare != "function"`,g(y)))}function p(){let S=l.schema,y=a.formats[S];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${S}" does not define "compare" function`);let x=e.scopeValue("formats",{key:S,ref:y,code:i.code.formats?(0,kt._)`${i.code.formats}${(0,kt.getProperty)(S)}`:void 0});t.fail$data(g(x))}function g(S){return(0,kt._)`${S}.compare(${r}, ${n}) ${$i[o].fail} 0`}},dependencies:["format"]};var vA=t=>(t.addKeyword(fn.formatLimitDefinition),t);fn.default=vA});var pb=U((To,ub)=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});var gn=ab(),_A=lb(),Md=re(),cb=new Md.Name("fullFormats"),SA=new Md.Name("fastFormats"),qd=(t,e={keywords:!0})=>{if(Array.isArray(e))return db(t,e,gn.fullFormats,cb),t;let[r,n]=e.mode==="fast"?[gn.fastFormats,SA]:[gn.fullFormats,cb],o=e.formats||gn.formatNames;return db(t,o,r,n),e.keywords&&(0,_A.default)(t),t};qd.get=(t,e="full")=>{let n=(e==="fast"?gn.fastFormats:gn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function db(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Md._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}ub.exports=To=qd;Object.defineProperty(To,"__esModule",{value:!0});To.default=qd});function kA(){let t=new hb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,mb.default)(t),t}var hb,mb,Ei,fb=j(()=>{hb=tu(Od(),1),mb=tu(pb(),1);Ei=class{constructor(e){this._ajv=e??kA()}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 Pi,gb=j(()=>{Zr();Pi=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],u=l.some(p=>p.type==="tool_use");if(i){if(s.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let p=new Set(l.filter(S=>S.type==="tool_use").map(S=>S.id)),g=new Set(s.filter(S=>S.type==="tool_result").map(S=>S.toolUseId));if(p.size!==g.size||![...p].every(S=>g.has(S)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Vn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Xr,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 yb(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 bb(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 wb=j(()=>{});var Ai,vb=j(()=>{kf();Zr();fb();jn();gb();wb();Ai=class extends Ks{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Kn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ei,this.setRequestHandler(el,n=>this._oninitialize(n)),this.setNotificationHandler(tl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ll,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Kn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Pi(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Sf(this._capabilities,e)}setRequestHandler(e,r){let o=Xt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Vr(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(l,u)=>{let p=Yt(Yr,l);if(!p.success){let x=p.error instanceof Error?p.error.message:String(p.error);throw new B(G.InvalidParams,`Invalid tools/call request: ${x}`)}let{params:g}=p.data,S=await Promise.resolve(r(l,u));if(g.task){let x=Yt(Wr,S);if(!x.success){let R=x.error instanceof Error?x.error.message:String(x.error);throw new B(G.InvalidParams,`Invalid task creation result: ${R}`)}return x.data}let y=Yt(Os,S);if(!y.success){let x=y.error instanceof Error?y.error.message:String(y.error);throw new B(G.InvalidParams,`Invalid tools/call result: ${x}`)}return y.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){bb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&yb(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:vm.includes(r)?r:Ja,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"},ys)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(a.filter(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(o.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},cl,r):this.request({method:"sampling/createMessage",params:e},Vn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Xr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Xr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new B(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof B?i:new B(G.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},dl,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 zd(t){return!!t&&typeof t=="object"&&Sb in t}function kb(t){return t[Sb]?.complete}var Sb,_b,Tb=j(()=>{Sb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(_b||(_b={}))});var xb=j(()=>{});function xA(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"),!TA.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function RA(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 Bd(t){let e=xA(t);return RA(t,e.warnings),e.isValid}var TA,Rb=j(()=>{TA=/^[A-Za-z0-9._-]{1,128}$/});var Ci,$b=j(()=>{Ci=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});import{ZodOptional as $A}from"zod";function Ab(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Cb(t){return"_def"in t||"_zod"in t||Ab(t)}function Fd(t){return typeof t!="object"||t===null||Cb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ab)}function Eb(t){if(t){if(Fd(t))return br(t);if(!Cb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function PA(t){let e=Xt(t);return e?Object.entries(e).map(([r,n])=>{let o=bm(n),s=wm(n);return{name:r,description:o,required:!s}}):[]}function cr(t){let r=Xt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Vr(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 Ii,EA,xo,Ib=j(()=>{vb();jn();Gl();Zr();Tb();xb();Rb();$b();Ii=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 Ai(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ci(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(Is)),this.server.assertCanSetRequestHandler(cr(Yr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Is,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Kr(r.inputSchema);return o?Hl(o,{strictUnions:!0,pipeStrategy:"input"}):EA})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Kr(r.outputSchema);o&&(n.outputSchema=Hl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Yr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new B(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new B(G.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new B(G.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof B&&n.code===G.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Kr(e.inputSchema)??e.inputSchema,i=await ps(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=hs(a);throw new B(G.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Kr(e.outputSchema),s=await ps(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=hs(i);throw new B(G.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),l=a.task.taskId,u=a.task,p=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(S=>setTimeout(S,p));let g=await n.taskStore.getTask(l);if(!g)throw new B(G.InternalError,`Task ${l} not found during polling`);u=g}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(cr(Ns)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ns,async e=>{switch(e.params.ref.type){case"ref/prompt":return jm(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Dm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new B(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return xo;let s=Xt(n.argsSchema)?.[e.params.argument.name];if(!zd(s))return xo;let i=kb(s);if(!i)return xo;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 xo;throw new B(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return xo;let s=await o(e.params.argument.value,e.params.context);return Pb(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(cr($s)),this.server.assertCanSetRequestHandler(cr(Es)),this.server.assertCanSetRequestHandler(cr(Ps)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler($s,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Es,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Ps,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new B(G.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new B(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(cr(As)),this.server.assertCanSetRequestHandler(cr(Cs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(As,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?PA(r.argsSchema):void 0}))})),this.server.setRequestHandler(Cs,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new B(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new B(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Kr(n.argsSchema),s=await ps(o,e.params.arguments);if(!s.success){let l="error"in s?s.error:"Unknown error",u=hs(l);throw new B(G.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:br(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=br(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(l=>{let u=l instanceof $A?l._def?.innerType:l;return zd(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,l,u){Bd(e);let p={title:r,description:n,inputSchema:Eb(o),outputSchema:Eb(s),annotations:i,execution:a,_meta:l,handler:u,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:g=>{typeof g.name<"u"&&g.name!==e&&(typeof g.name=="string"&&Bd(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=br(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=br(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,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(Fd(l))o=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,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:l,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,l,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},EA={type:"object",properties:{}};xo={completion:{values:[],hasMore:!1}}});function CA(t){return Em.parse(JSON.parse(t))}function Ob(t){return JSON.stringify(t)+`
2311
- `}var AA,Oi,Nb=j(()=>{Zr();AA=10*1024*1024,Oi=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??AA}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(`
2312
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),CA(r)}clear(){this._buffer=void 0}}});import Lb from"node:process";var Ni,jb=j(()=>{Nb();Ni=class{constructor(e=Lb.stdin,r=Lb.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Oi({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=Ob(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Db,Ub=j(()=>{Db=[]});var Gb={};eu(Gb,{AUTHORING_MCP_SERVER_NAME:()=>Bb,AUTHORING_MCP_SERVER_VERSION:()=>Fb,AUTHORING_RESOURCES:()=>UA,AUTHORING_TOOLS:()=>DA,AUTHORING_TOOLS_PUBLIC:()=>Vb,buildAuthoringMcpServer:()=>Kb,resolveSamplesDir:()=>Hb,runAuthoringMcpServer:()=>MA});import{promises as IA}from"node:fs";import{isAbsolute as OA,resolve as Li,sep as NA}from"node:path";import{z as M}from"zod";function zb(){return qb??=import("../mcp/grounding.js").then(e=>e,()=>null),qb}function Hb(t,e){if(e===void 0)return Li(process.cwd(),t??"samples");let r=Li(e);if(t===void 0)return r;if(OA(t))return null;let n=Li(r,t);return n===r||n.startsWith(r+NA)?n:null}function xe(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function jA(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function Kb(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let y=await ht(t.baseUrl);if(!y)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:y.baseUrl,token:y.token}}let r=t.grounding??{},n=await zb(),o=null;if(n)try{let y=await e();o={surface:"mcp-authoring",baseUrl:y.baseUrl,token:y.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],l=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{l=(await n.listRecipesForSurface(o,i)).map(y=>({id:y.id,record_type:y.record_type,intent:y.intent}))}catch{l=[]}}let u=o?await jA(o,r):null,p=new Ii({name:Bb,version:Fb},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:l,promptNames:a.map(y=>y.id),deployedExtensions:u,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let y=o;for(let x of a)p.registerPrompt(x.id,{title:x.name,description:x.description},async()=>{let R=await n.getMcpPromptSkill(y,x.id,r);if(!R)throw new Error(`unknown prompt: ${x.id}`);return{description:R.description,messages:[{role:"user",content:{type:"text",text:(R.prompts??[]).join(`
2369
+ deps: ${r}}`};var c0={keyword:"dependencies",type:"object",schemaType:"object",error:It.error,code(t){let[e,r]=d0(t);xy(t,e),$y(t,r)}};function d0({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function xy(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let l=(0,To.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let u of a)(0,To.checkReportMissingProp)(t,u)}):(r.if((0,gd._)`${l} && (${(0,To.checkMissingProp)(t,a,s)})`),(0,To.reportMissingProp)(t,s),r.else())}}It.validatePropertyDeps=xy;function $y(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,l0.alwaysValidSchema)(s,e[a])||(r.if((0,To.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),t.ok(i))}It.validateSchemaDeps=$y;It.default=c0});var Ay=q(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var Py=re(),u0=pe(),p0={message:"property name must be valid",params:({params:t})=>(0,Py._)`{propertyName: ${t.propertyName}}`},h0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:p0,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,u0.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Py.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};yd.default=h0});var wd=q(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var ki=pt(),kt=re(),m0=Bt(),Ti=pe(),f0={message:"must NOT have additional properties",params:({params:t})=>(0,kt._)`{additionalProperty: ${t.additionalProperty}}`},g0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:f0,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Ti.alwaysValidSchema)(i,r))return;let u=(0,ki.allSchemaProperties)(n.properties),p=(0,ki.allSchemaProperties)(n.patternProperties);g(),t.ok((0,kt._)`${s} === ${m0.default.errors}`);function g(){e.forIn("key",o,E=>{!u.length&&!p.length?R(E):e.if(k(E),()=>R(E))})}function k(E){let P;if(u.length>8){let I=(0,Ti.schemaRefOrVal)(i,n.properties,"properties");P=(0,ki.isOwnProperty)(e,I,E)}else u.length?P=(0,kt.or)(...u.map(I=>(0,kt._)`${E} === ${I}`)):P=kt.nil;return p.length&&(P=(0,kt.or)(P,...p.map(I=>(0,kt._)`${(0,ki.usePattern)(t,I)}.test(${E})`))),(0,kt.not)(P)}function b(E){e.code((0,kt._)`delete ${o}[${E}]`)}function R(E){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){b(E);return}if(r===!1){t.setParams({additionalProperty:E}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Ti.alwaysValidSchema)(i,r)){let P=e.name("valid");l.removeAdditional==="failing"?(x(E,P,!1),e.if((0,kt.not)(P),()=>{t.reset(),b(E)})):(x(E,P),a||e.if((0,kt.not)(P),()=>e.break()))}}function x(E,P,I){let D={keyword:"additionalProperties",dataProp:E,dataPropType:Ti.Type.Str};I===!1&&Object.assign(D,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(D,P)}}};bd.default=g0});var Oy=q(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var y0=co(),Cy=pt(),vd=pe(),Iy=wd(),b0={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&Iy.default.code(new y0.KeywordCxt(s,Iy.default,"additionalProperties"));let i=(0,Cy.allSchemaProperties)(r);for(let g of i)s.definedProperties.add(g);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=vd.mergeEvaluated.props(e,(0,vd.toHash)(i),s.props));let a=i.filter(g=>!(0,vd.alwaysValidSchema)(s,r[g]));if(a.length===0)return;let l=e.name("valid");for(let g of a)u(g)?p(g):(e.if((0,Cy.propertyInData)(e,o,g,s.opts.ownProperties)),p(g),s.allErrors||e.else().var(l,!0),e.endIf()),t.it.definedProperties.add(g),t.ok(l);function u(g){return s.opts.useDefaults&&!s.compositeRule&&r[g].default!==void 0}function p(g){t.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};_d.default=b0});var Dy=q(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var Ny=pt(),Ri=re(),Ly=pe(),jy=pe(),w0={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Ny.allSchemaProperties)(r),l=a.filter(x=>(0,Ly.alwaysValidSchema)(s,r[x]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,p=e.name("valid");s.props!==!0&&!(s.props instanceof Ri.Name)&&(s.props=(0,jy.evaluatedPropsToName)(e,s.props));let{props:g}=s;k();function k(){for(let x of a)u&&b(x),s.allErrors?R(x):(e.var(p,!0),R(x),e.if(p))}function b(x){for(let E in u)new RegExp(x).test(E)&&(0,Ly.checkStrictMode)(s,`property ${E} matches pattern ${x} (use allowMatchingProperties)`)}function R(x){e.forIn("key",n,E=>{e.if((0,Ri._)`${(0,Ny.usePattern)(t,x)}.test(${E})`,()=>{let P=l.includes(x);P||t.subschema({keyword:"patternProperties",schemaProp:x,dataProp:E,dataPropType:jy.Type.Str},p),s.opts.unevaluated&&g!==!0?e.assign((0,Ri._)`${g}[${E}]`,!0):!P&&!s.allErrors&&e.if((0,Ri.not)(p),()=>e.break())})})}}};Sd.default=w0});var Uy=q(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var v0=pe(),_0={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,v0.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};kd.default=_0});var My=q(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var S0=pt(),k0={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:S0.validateUnion,error:{message:"must match a schema in anyOf"}};Td.default=k0});var qy=q(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var xi=re(),T0=pe(),R0={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,xi._)`{passingSchemas: ${t.passing}}`},x0={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:R0,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),l=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((p,g)=>{let k;(0,T0.alwaysValidSchema)(o,p)?e.var(l,!0):k=t.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&e.if((0,xi._)`${l} && ${i}`).assign(i,!1).assign(a,(0,xi._)`[${a}, ${g}]`).else(),e.if(l,()=>{e.assign(i,!0),e.assign(a,g),k&&t.mergeEvaluated(k,xi.Name)})})}}};Rd.default=x0});var zy=q(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var $0=pe(),E0={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,$0.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};xd.default=E0});var Hy=q($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});var $i=re(),Fy=pe(),P0={message:({params:t})=>(0,$i.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,$i._)`{failingKeyword: ${t.ifClause}}`},A0={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:P0,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Fy.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=By(n,"then"),s=By(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(l(),t.reset(),o&&s){let p=e.let("ifClause");t.setParams({ifClause:p}),e.if(a,u("then",p),u("else",p))}else o?e.if(a,u("then")):e.if((0,$i.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 k=t.subschema({keyword:p},a);e.assign(i,a),t.mergeValidEvaluated(k,i),g?e.assign(g,(0,$i._)`${p}`):t.setParams({ifClause:p})}}}};function By(t,e){let r=t.schema[e];return r!==void 0&&!(0,Fy.alwaysValidSchema)(t,r)}$d.default=A0});var Ky=q(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var C0=pe(),I0={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,C0.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Ed.default=I0});var Vy=q(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var O0=ud(),N0=Sy(),L0=pd(),j0=Ty(),D0=Ry(),U0=Ey(),M0=Ay(),q0=wd(),z0=Oy(),B0=Dy(),F0=Uy(),H0=My(),K0=qy(),V0=zy(),G0=Hy(),W0=Ky();function J0(t=!1){let e=[F0.default,H0.default,K0.default,V0.default,G0.default,W0.default,M0.default,q0.default,U0.default,z0.default,B0.default];return t?e.push(N0.default,j0.default):e.push(O0.default,L0.default),e.push(D0.default),e}Pd.default=J0});var Gy=q(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var Re=re(),Y0={message:({schemaCode:t})=>(0,Re.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Re._)`{format: ${t}}`},X0={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Y0,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:l,errSchemaPath:u,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;o?k():b();function k(){let R=r.scopeValue("formats",{ref:g.formats,code:l.code.formats}),x=r.const("fDef",(0,Re._)`${R}[${i}]`),E=r.let("fType"),P=r.let("format");r.if((0,Re._)`typeof ${x} == "object" && !(${x} instanceof RegExp)`,()=>r.assign(E,(0,Re._)`${x}.type || "string"`).assign(P,(0,Re._)`${x}.validate`),()=>r.assign(E,(0,Re._)`"string"`).assign(P,x)),t.fail$data((0,Re.or)(I(),D()));function I(){return l.strictSchema===!1?Re.nil:(0,Re._)`${i} && !${P}`}function D(){let H=p.$async?(0,Re._)`(${x}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,Re._)`${P}(${n})`,G=(0,Re._)`(typeof ${P} == "function" ? ${H} : ${P}.test(${n}))`;return(0,Re._)`${P} && ${P} !== true && ${E} === ${e} && !${G}`}}function b(){let R=g.formats[s];if(!R){I();return}if(R===!0)return;let[x,E,P]=D(R);x===e&&t.pass(H());function I(){if(l.strictSchema===!1){g.logger.warn(G());return}throw new Error(G());function G(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function D(G){let xe=G instanceof RegExp?(0,Re.regexpCode)(G):l.code.formats?(0,Re._)`${l.code.formats}${(0,Re.getProperty)(s)}`:void 0,qe=r.scopeValue("formats",{key:s,ref:G,code:xe});return typeof G=="object"&&!(G instanceof RegExp)?[G.type||"string",G.validate,(0,Re._)`${qe}.validate`]:["string",G,qe]}function H(){if(typeof R=="object"&&!(R instanceof RegExp)&&R.async){if(!p.$async)throw new Error("async format in sync schema");return(0,Re._)`await ${P}(${n})`}return typeof E=="function"?(0,Re._)`${P}(${n})`:(0,Re._)`${P}.test(${n})`}}}};Ad.default=X0});var Wy=q(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var Z0=Gy(),Q0=[Z0.default];Cd.default=Q0});var Jy=q(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.contentVocabulary=pn.metadataVocabulary=void 0;pn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];pn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Xy=q(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var eA=oy(),tA=by(),rA=Vy(),nA=Wy(),Yy=Jy(),oA=[eA.default,tA.default,(0,rA.default)(),nA.default,Yy.metadataVocabulary,Yy.contentVocabulary];Id.default=oA});var Qy=q(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.DiscrError=void 0;var Zy;(function(t){t.Tag="tag",t.Mapping="mapping"})(Zy||(Ei.DiscrError=Zy={}))});var tb=q(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var hn=re(),Od=Qy(),eb=ci(),sA=uo(),iA=pe(),aA={message:({params:{discrError:t,tagName:e}})=>t===Od.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,hn._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},lA={keyword:"discriminator",type:"object",schemaType:"object",error:aA,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let l=e.let("valid",!1),u=e.const("tag",(0,hn._)`${r}${(0,hn.getProperty)(a)}`);e.if((0,hn._)`typeof ${u} == "string"`,()=>p(),()=>t.error(!1,{discrError:Od.DiscrError.Tag,tag:u,tagName:a})),t.ok(l);function p(){let b=k();e.if(!1);for(let R in b)e.elseIf((0,hn._)`${u} === ${R}`),e.assign(l,g(b[R]));e.else(),t.error(!1,{discrError:Od.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function g(b){let R=e.name("valid"),x=t.subschema({keyword:"oneOf",schemaProp:b},R);return t.mergeEvaluated(x,hn.Name),R}function k(){var b;let R={},x=P(o),E=!0;for(let H=0;H<i.length;H++){let G=i[H];if(G?.$ref&&!(0,iA.schemaHasRulesButRef)(G,s.self.RULES)){let qe=G.$ref;if(G=eb.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,qe),G instanceof eb.SchemaEnv&&(G=G.schema),G===void 0)throw new sA.default(s.opts.uriResolver,s.baseId,qe)}let xe=(b=G?.properties)===null||b===void 0?void 0:b[a];if(typeof xe!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);E=E&&(x||P(G)),I(xe,H)}if(!E)throw new Error(`discriminator: "${a}" must be required`);return R;function P({required:H}){return Array.isArray(H)&&H.includes(a)}function I(H,G){if(H.const)D(H.const,G);else if(H.enum)for(let xe of H.enum)D(xe,G);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function D(H,G){if(typeof H!="string"||H in R)throw new Error(`discriminator: "${a}" values must be unique strings`);R[H]=G}}}};Nd.default=lA});var rb=q((CU,cA)=>{cA.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 jd=q((Se,Ld)=>{"use strict";Object.defineProperty(Se,"__esModule",{value:!0});Se.MissingRefError=Se.ValidationError=Se.CodeGen=Se.Name=Se.nil=Se.stringify=Se.str=Se._=Se.KeywordCxt=Se.Ajv=void 0;var dA=Zg(),uA=Xy(),pA=tb(),nb=rb(),hA=["/properties"],Pi="http://json-schema.org/draft-07/schema",mn=class extends dA.default{_addVocabularies(){super._addVocabularies(),uA.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(pA.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(nb,hA):nb;this.addMetaSchema(e,Pi,!1),this.refs["http://json-schema.org/schema"]=Pi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Pi)?Pi:void 0)}};Se.Ajv=mn;Ld.exports=Se=mn;Ld.exports.Ajv=mn;Object.defineProperty(Se,"__esModule",{value:!0});Se.default=mn;var mA=co();Object.defineProperty(Se,"KeywordCxt",{enumerable:!0,get:function(){return mA.KeywordCxt}});var fn=re();Object.defineProperty(Se,"_",{enumerable:!0,get:function(){return fn._}});Object.defineProperty(Se,"str",{enumerable:!0,get:function(){return fn.str}});Object.defineProperty(Se,"stringify",{enumerable:!0,get:function(){return fn.stringify}});Object.defineProperty(Se,"nil",{enumerable:!0,get:function(){return fn.nil}});Object.defineProperty(Se,"Name",{enumerable:!0,get:function(){return fn.Name}});Object.defineProperty(Se,"CodeGen",{enumerable:!0,get:function(){return fn.CodeGen}});var fA=ai();Object.defineProperty(Se,"ValidationError",{enumerable:!0,get:function(){return fA.default}});var gA=uo();Object.defineProperty(Se,"MissingRefError",{enumerable:!0,get:function(){return gA.default}})});var ub=q(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.formatNames=Nt.fastFormats=Nt.fullFormats=void 0;function Ot(t,e){return{validate:t,compare:e}}Nt.fullFormats={date:Ot(ab,qd),time:Ot(Ud(!0),zd),"date-time":Ot(ob(!0),cb),"iso-time":Ot(Ud(),lb),"iso-date-time":Ot(ob(),db),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:SA,"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:PA,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:kA,int32:{type:"number",validate:xA},int64:{type:"number",validate:$A},float:{type:"number",validate:ib},double:{type:"number",validate:ib},password:!0,binary:!0};Nt.fastFormats={...Nt.fullFormats,date:Ot(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,qd),time:Ot(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,zd),"date-time":Ot(/^\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,cb),"iso-time":Ot(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,lb),"iso-date-time":Ot(/^\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,db),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};Nt.formatNames=Object.keys(Nt.fullFormats);function yA(t){return t%4===0&&(t%100!==0||t%400===0)}var bA=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,wA=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ab(t){let e=bA.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&yA(r)?29:wA[n])}function qd(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Dd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Ud(t){return function(r){let n=Dd.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],l=n[5]==="-"?-1:1,u=+(n[6]||0),p=+(n[7]||0);if(u>23||p>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let g=s-p*l,k=o-u*l-(g<0?1:0);return(k===23||k===-1)&&(g===59||g===-1)&&i<61}}function zd(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 lb(t,e){if(!(t&&e))return;let r=Dd.exec(t),n=Dd.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 Md=/t|\s/i;function ob(t){let e=Ud(t);return function(n){let o=n.split(Md);return o.length===2&&ab(o[0])&&e(o[1])}}function cb(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function db(t,e){if(!(t&&e))return;let[r,n]=t.split(Md),[o,s]=e.split(Md),i=qd(r,o);if(i!==void 0)return i||zd(n,s)}var vA=/\/|:/,_A=/^(?:[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 SA(t){return vA.test(t)&&_A.test(t)}var sb=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function kA(t){return sb.lastIndex=0,sb.test(t)}var TA=-(2**31),RA=2**31-1;function xA(t){return Number.isInteger(t)&&t<=RA&&t>=TA}function $A(t){return Number.isInteger(t)}function ib(){return!0}var EA=/[^\\]\\Z/;function PA(t){if(EA.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var pb=q(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.formatLimitDefinition=void 0;var AA=jd(),Tt=re(),dr=Tt.operators,Ai={formatMaximum:{okStr:"<=",ok:dr.LTE,fail:dr.GT},formatMinimum:{okStr:">=",ok:dr.GTE,fail:dr.LT},formatExclusiveMaximum:{okStr:"<",ok:dr.LT,fail:dr.GTE},formatExclusiveMinimum:{okStr:">",ok:dr.GT,fail:dr.LTE}},CA={message:({keyword:t,schemaCode:e})=>(0,Tt.str)`should be ${Ai[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Tt._)`{comparison: ${Ai[t].okStr}, limit: ${e}}`};gn.formatLimitDefinition={keyword:Object.keys(Ai),type:"string",schemaType:"string",$data:!0,error:CA,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let l=new AA.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let k=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),b=e.const("fmt",(0,Tt._)`${k}[${l.schemaCode}]`);t.fail$data((0,Tt.or)((0,Tt._)`typeof ${b} != "object"`,(0,Tt._)`${b} instanceof RegExp`,(0,Tt._)`typeof ${b}.compare != "function"`,g(b)))}function p(){let k=l.schema,b=a.formats[k];if(!b||b===!0)return;if(typeof b!="object"||b instanceof RegExp||typeof b.compare!="function")throw new Error(`"${o}": format "${k}" does not define "compare" function`);let R=e.scopeValue("formats",{key:k,ref:b,code:i.code.formats?(0,Tt._)`${i.code.formats}${(0,Tt.getProperty)(k)}`:void 0});t.fail$data(g(R))}function g(k){return(0,Tt._)`${k}.compare(${r}, ${n}) ${Ai[o].fail} 0`}},dependencies:["format"]};var IA=t=>(t.addKeyword(gn.formatLimitDefinition),t);gn.default=IA});var gb=q((Ro,fb)=>{"use strict";Object.defineProperty(Ro,"__esModule",{value:!0});var yn=ub(),OA=pb(),Bd=re(),hb=new Bd.Name("fullFormats"),NA=new Bd.Name("fastFormats"),Fd=(t,e={keywords:!0})=>{if(Array.isArray(e))return mb(t,e,yn.fullFormats,hb),t;let[r,n]=e.mode==="fast"?[yn.fastFormats,NA]:[yn.fullFormats,hb],o=e.formats||yn.formatNames;return mb(t,o,r,n),e.keywords&&(0,OA.default)(t),t};Fd.get=(t,e="full")=>{let n=(e==="fast"?yn.fastFormats:yn.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function mb(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Bd._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}fb.exports=Ro=Fd;Object.defineProperty(Ro,"__esModule",{value:!0});Ro.default=Fd});function LA(){let t=new yb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,bb.default)(t),t}var yb,bb,Ci,wb=j(()=>{yb=iu(jd(),1),bb=iu(gb(),1);Ci=class{constructor(e){this._ajv=e??LA()}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 Ii,vb=j(()=>{Qr();Ii=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(p=>p.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,l=a?Array.isArray(a.content)?a.content:[a.content]:[],u=l.some(p=>p.type==="tool_use");if(i){if(s.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let p=new Set(l.filter(k=>k.type==="tool_use").map(k=>k.id)),g=new Set(s.filter(k=>k.type==="tool_result").map(k=>k.toolUseId));if(p.size!==g.size||![...p].every(k=>g.has(k)))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},Gn,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},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 _b(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 Sb(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 kb=j(()=>{});var Oi,Tb=j(()=>{$f();Qr();wb();Dn();vb();kb();Oi=class extends Ws{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Vn.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Ci,this.setRequestHandler(nl,n=>this._oninitialize(n)),this.setNotificationHandler(ol,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(ul,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Vn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Ii(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=xf(this._capabilities,e)}setRequestHandler(e,r){let o=Qt(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Gr(o);if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(l,u)=>{let p=Zt(Xr,l);if(!p.success){let R=p.error instanceof Error?p.error.message:String(p.error);throw new F(W.InvalidParams,`Invalid tools/call request: ${R}`)}let{params:g}=p.data,k=await Promise.resolve(r(l,u));if(g.task){let R=Zt(Jr,k);if(!R.success){let x=R.error instanceof Error?R.error.message:String(R.error);throw new F(W.InvalidParams,`Invalid task creation result: ${x}`)}return R.data}let b=Zt(js,k);if(!b.success){let R=b.error instanceof Error?b.error.message:String(b.error);throw new F(W.InvalidParams,`Invalid tools/call result: ${R}`)}return b.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){Sb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&_b(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:Tm.includes(r)?r:Za,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},vs)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],l=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!l)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(l){let u=new Set(a.filter(g=>g.type==="tool_use").map(g=>g.id)),p=new Set(o.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},pl,r):this.request({method:"sampling/createMessage",params:e},Gn,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Zr,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Zr,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new F(W.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof F?i:new F(W.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},hl,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 Hd(t){return!!t&&typeof t=="object"&&xb in t}function $b(t){return t[xb]?.complete}var xb,Rb,Eb=j(()=>{xb=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(Rb||(Rb={}))});var Pb=j(()=>{});function DA(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"),!jA.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function UA(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 Kd(t){let e=DA(t);return UA(t,e.warnings),e.isValid}var jA,Ab=j(()=>{jA=/^[A-Za-z0-9._-]{1,128}$/});var Ni,Cb=j(()=>{Ni=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});import{ZodOptional as MA}from"zod";function Nb(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Lb(t){return"_def"in t||"_zod"in t||Nb(t)}function Vd(t){return typeof t!="object"||t===null||Lb(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Nb)}function Ib(t){if(t){if(Vd(t))return wr(t);if(!Lb(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function zA(t){let e=Qt(t);return e?Object.entries(e).map(([r,n])=>{let o=Sm(n),s=km(n);return{name:r,description:o,required:!s}}):[]}function ur(t){let r=Qt(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Gr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Ob(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Li,qA,xo,jb=j(()=>{Tb();Dn();Yl();Qr();Eb();Pb();Ab();Cb();Li=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 Oi(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ni(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ur(Ls)),this.server.assertCanSetRequestHandler(ur(Xr)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ls,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Vr(r.inputSchema);return o?Gl(o,{strictUnions:!0,pipeStrategy:"input"}):qA})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Vr(r.outputSchema);o&&(n.outputSchema=Gl(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Xr,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new F(W.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new F(W.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new F(W.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new F(W.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,e.params.name),l}catch(n){if(n instanceof F&&n.code===W.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Vr(e.inputSchema)??e.inputSchema,i=await fs(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",l=gs(a);throw new F(W.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new F(W.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Vr(e.outputSchema),s=await fs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=gs(i);throw new F(W.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),l=a.task.taskId,u=a.task,p=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(k=>setTimeout(k,p));let g=await n.taskStore.getTask(l);if(!g)throw new F(W.InternalError,`Task ${l} not found during polling`);u=g}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ur(Ds)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ds,async e=>{switch(e.params.ref.type){case"ref/prompt":return qm(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return zm(e),this.handleResourceCompletion(e,e.params.ref);default:throw new F(W.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new F(W.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new F(W.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return xo;let s=Qt(n.argsSchema)?.[e.params.argument.name];if(!Hd(s))return xo;let i=$b(s);if(!i)return xo;let a=await i(e.params.argument.value,e.params.context);return Ob(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 xo;throw new F(W.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return xo;let s=await o(e.params.argument.value,e.params.context);return Ob(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ur(As)),this.server.assertCanSetRequestHandler(ur(Cs)),this.server.assertCanSetRequestHandler(ur(Is)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(As,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Cs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Is,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new F(W.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new F(W.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ur(Os)),this.server.assertCanSetRequestHandler(ur(Ns)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Os,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?zA(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ns,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new F(W.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new F(W.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Vr(n.argsSchema),s=await fs(o,e.params.arguments);if(!s.success){let l="error"in s?s.error:"Unknown error",u=gs(l);throw new F(W.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:wr(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=wr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(l=>{let u=l instanceof MA?l._def?.innerType:l;return Hd(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,l,u){Kd(e);let p={title:r,description:n,inputSchema:Ib(o),outputSchema:Ib(s),annotations:i,execution:a,_meta:l,handler:u,enabled:!0,disable:()=>p.update({enabled:!1}),enable:()=>p.update({enabled:!0}),remove:()=>p.update({name:null}),update:g=>{typeof g.name<"u"&&g.name!==e&&(typeof g.name=="string"&&Kd(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=wr(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=wr(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,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(Vd(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Vd(r[0])&&(i=r.shift());else if(typeof l=="object"&&l!==null){if(Object.values(l).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:l,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,l,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},qA={type:"object",properties:{}};xo={completion:{values:[],hasMore:!1}}});function FA(t){return Im.parse(JSON.parse(t))}function Db(t){return JSON.stringify(t)+`
2370
+ `}var BA,ji,Ub=j(()=>{Qr();BA=10*1024*1024,ji=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??BA}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(`
2371
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),FA(r)}clear(){this._buffer=void 0}}});import Mb from"node:process";var Di,qb=j(()=>{Ub();Di=class{constructor(e=Mb.stdin,r=Mb.stdout,n){this._stdin=e,this._stdout=r,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new ji({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=Db(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var zb,Bb=j(()=>{zb=[]});var Xb={};su(Xb,{AUTHORING_MCP_SERVER_NAME:()=>Vb,AUTHORING_MCP_SERVER_VERSION:()=>Gb,AUTHORING_RESOURCES:()=>YA,AUTHORING_TOOLS:()=>JA,AUTHORING_TOOLS_PUBLIC:()=>Yb,buildAuthoringMcpServer:()=>Jb,resolveSamplesDir:()=>Wb,runAuthoringMcpServer:()=>XA});import{promises as HA}from"node:fs";import{isAbsolute as KA,resolve as Ui,sep as VA}from"node:path";import{z as U}from"zod";function Kb(){return Hb??=import("../mcp/grounding.js").then(e=>e,()=>null),Hb}function Wb(t,e){if(e===void 0)return Ui(process.cwd(),t??"samples");let r=Ui(e);if(t===void 0)return r;if(KA(t))return null;let n=Ui(r,t);return n===r||n.startsWith(r+VA)?n:null}function ke(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}async function WA(t,e={}){let r=e.fetchImpl??fetch;try{let n=await r(`${t.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${t.token}`,Accept:"application/json"}});return n.ok?((await n.json()).extensions??[]).map(s=>s.hookId).filter(s=>typeof s=="string"):null}catch{return null}}async function Jb(t={}){async function e(){if(t.resolveTenant)return t.resolveTenant();let b=await ft(t.baseUrl);if(!b)throw new Error("not signed in \u2014 run `turbobase auth login` (or set a single stored instance).");return{baseUrl:b.baseUrl,token:b.token}}let r=t.grounding??{},n=await Kb(),o=null;if(n)try{let b=await e();o={surface:"mcp-authoring",baseUrl:b.baseUrl,token:b.token}}catch{o=null}let s=n&&o?await n.loadActiveSources(o,r):[],i={...r,loadActiveSourcesImpl:async()=>s},a=[],l=[];if(n&&o){try{a=await n.listMcpPromptSkills(o,i)}catch{a=[]}try{l=(await n.listRecipesForSurface(o,i)).map(b=>({id:b.id,record_type:b.record_type,intent:b.intent}))}catch{l=[]}}let u=o?await WA(o,r):null,p=new Li({name:Vb,version:Gb},n?{instructions:n.renderAuthoringInstructions({baseUrl:t.displayBaseUrl??o?.baseUrl??t.baseUrl??"this instance",sources:s,recipeIntents:l,promptNames:a.map(b=>b.id),deployedExtensions:u,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let b=o;for(let R of a)p.registerPrompt(R.id,{title:R.name,description:R.description},async()=>{let x=await n.getMcpPromptSkill(b,R.id,r);if(!x)throw new Error(`unknown prompt: ${R.id}`);return{description:x.description,messages:[{role:"user",content:{type:"text",text:(x.prompts??[]).join(`
2313
2372
 
2314
- `)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:x}=await e(),R=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return xe(await R.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType:M.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:M.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:y,source:x})=>{let{baseUrl:R,token:E}=await e(),P=x?`?source=${encodeURIComponent(x)}`:"",I=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return xe(await I.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes:M.array(M.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:M.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:y,source:x})=>{let{baseUrl:R,token:E}=await e(),P=new URLSearchParams({types:y.join(",")});x&&P.set("source",x);let I=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return xe(await I.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:y,token:x}=await e(),R=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return xe(await R.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:M.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:M.enum(Mb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:M.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:y,kind:x,limit:R})=>{let{baseUrl:E,token:P}=await e(),I=new URLSearchParams({q:y});x&&I.set("kind",x),R!==void 0&&I.set("limit",String(R));let D=await fetch(`${E}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return xe(await D.json())}),p.registerTool("explain_object",{title:"Explain one catalog object",description:"Fetch ONE customization-catalog object in depth: its captured definition (or script source, or a bundle\u2019s membership), human label, the generated plain-English explanation (tldr + markdown) of what it is for, and its OWNERSHIP \u2014 `modifiability` plus a one-line reason saying whether this account can change it at all. Address it by the {kind, externalId} a search_catalog hit returns. For a FIELD it also reports `selectTarget`: where a List/Record field ACTUALLY points, resolved to a mirrored table plus the filter needed to read it correctly. Do not infer a target from the field name \u2014 a carrier-named field can point at `entity` (vendors), and building on the wrong guess resolves nothing while looking like an empty table.",inputSchema:{kind:M.enum(Mb),externalId:M.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:x})=>{let{baseUrl:R,token:E}=await e(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(x)}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${x} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return xe(await P.json())}),p.registerTool("search_documentation",{title:"Search the knowledge base",description:'Search this instance\'s published knowledge base \u2014 internal documentation: processes, policies, playbooks, how-tos. Route questions about how the ORGANISATION works here ("what\'s our receiving process", "how do we handle returns"), and ALWAYS search it before building UI over a custom record \u2014 the KB is the only spec a custom record has. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_document for the full text. Published release only \u2014 drafts are never returned.',inputSchema:{query:M.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:M.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:y,limit:x})=>{let{baseUrl:R,token:E}=await e(),P=new URLSearchParams({q:y});x!==void 0&&P.set("limit",String(x));let I=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return xe(await I.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:M.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:x,token:R}=await e(),E=await fetch(`${x}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!E.ok&&E.status!==404)throw new Error(`kb document fetch failed: ${E.status}`);return xe(await E.json())}),p.registerTool("generate_types",{title:"Generate types.ts",description:"Generate the instance's types.ts (record shapes + PostgREST ops). Returns the source.",inputSchema:{recordsOnly:M.boolean().optional()}},async({recordsOnly:y})=>{let{baseUrl:x,token:R}=await e();return{content:[{type:"text",text:await mr({baseUrl:x,token:R,recordsOnly:y})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:M.string(),event:M.string().optional(),template:M.enum(["require-field","enforce-format","blank"]).optional(),field:M.string().optional(),regex:M.string().optional(),source:M.string().optional(),id:M.string().optional()}},async y=>{let x=$t("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return xe({path:x.relativePath,content:x.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:M.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:M.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:M.string().optional().describe("Target record type (defaults to the trigger record type)."),event:M.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:M.string().optional()}},async y=>{let x=$t("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return xe({path:x.relativePath,content:x.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:M.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:M.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:M.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:M.string().optional()}},async y=>{let x=$t("process",{recordType:y.recordType,then:y.then,onFailure:y.onFailure,id:y.id});return xe({path:x.relativePath,content:x.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:M.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:M.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:M.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:M.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:M.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:M.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:M.array(M.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async y=>{let{baseUrl:x,token:R}=await e(),E=new q({baseUrl:x,token:R});return xe(await E.authorConduit({intent:y.intent,from:{source:y.fromSource,recordType:y.fromRecordType},to:{source:y.toSource,recordType:y.toRecordType},...y.intentId?{intentId:y.intentId}:{},...y.columns?.length?{columns:y.columns}:{}}))}),p.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:M.string().describe("The extension TS source."),samplesDir:M.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:x})=>{let R=Hb(x,t.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:LA})}],isError:!0};let E;try{E=await kn(R)}catch(D){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw D}let P=await Vo(y,E.map(D=>D.fixture)),I=P.filter(D=>!D.pass).length;return xe({total:P.length,passed:P.length-I,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:M.string(),recordType:M.string(),event:M.string(),source:M.string().describe('Adapter id or "standalone".'),sourceCode:M.string().describe("The verbatim extension TS."),extensionKind:M.string().optional()}},async y=>{let{baseUrl:x,token:R}=await e(),P=await new q({baseUrl:x,token:R}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.extensionKind});return xe(P)}),p.registerTool("tail_logs",{title:"Tail an extension's logs",description:"Read an extension's log ring buffer (GET /v1/extensions/:id/logs).",inputSchema:{id:M.string(),limit:M.number().int().positive().optional()}},async({id:y,limit:x})=>{let{baseUrl:R,token:E}=await e(),P=new q({baseUrl:R,token:E});return xe({id:y,logs:await P.logs(y,x)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:y,token:x}=await e(),R=new q({baseUrl:y,token:x});return xe(await R.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug:M.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:M.string().optional().describe("Display name (defaults to the slug)."),description:M.string().optional().describe("Short description.")}},async({slug:y,name:x,description:R})=>{let{baseUrl:E,token:P}=await e(),I=new q({baseUrl:E,token:P});return xe(await I.appsCreate({slug:y,name:x,description:R}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:M.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:x,token:R}=await e(),E=new q({baseUrl:x,token:R});return xe(await E.appsPull(y))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:M.string().describe("App slug or id."),files:M.record(M.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:M.string().optional().describe("Short note stored with the revision.")}},async({app:y,files:x,note:R})=>{let{baseUrl:E,token:P}=await e(),I=new q({baseUrl:E,token:P});return xe(await I.appsPush(y,x,{note:R}))});let g=M.object({name:M.string().describe("Field name (lowercase identifier)."),type:M.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:M.boolean().optional()}),S=M.object({slug:M.string().describe("Table slug; the physical table is cr_<slug>."),displayName:M.string().optional(),fields:M.array(g).describe("At least one field."),rowLevelOwner:M.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:y,token:x}=await e(),R=new q({baseUrl:y,token:x});return xe(await R.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:M.array(S),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:x})=>{let{baseUrl:R,token:E}=await e(),P=new q({baseUrl:R,token:E});return xe(await P.tablesPlan({tables:y,claimedBy:x}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:M.array(S),claimedBy:M.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:x})=>{let{baseUrl:R,token:E}=await e(),P=new q({baseUrl:R,token:E});return xe(await P.tablesApply({tables:y,claimedBy:x}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:x,token:R}=await e(),P=await(await fetch(`${x}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}})).text();return{contents:[{uri:y.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async y=>{let{baseUrl:x,token:R}=await e(),E=await mr({baseUrl:x,token:R});return{contents:[{uri:y.href,mimeType:"text/plain",text:E}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let x=Li(process.cwd(),"samples"),R=[];try{R=(await IA.readdir(x)).filter(P=>P.endsWith(".json"))}catch{R=[]}let E=await kn(x);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:R,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 y=>{let x=await zb(),R=[];if(x){let{baseUrl:E,token:P}=await e();R=await x.listRecipesForSurface({surface:"mcp-authoring",baseUrl:E,token:P},r)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function MA(t={}){let e=await Kb(t),r=new Ni;await e.connect(r)}var Mb,qb,Bb,Fb,LA,Vb,DA,UA,Wb=j(()=>{Ib();jb();ta();vn();mt();pa();Zo();Ub();Mb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Bb="turbobase-authoring",Fb="0.1.0";LA="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";Vb=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],DA=[...Vb,...Db],UA=["catalog:///","types://all","samples:///","recipes:///"]});ta();vn();mt();pa();import{spawn as Jd}from"node:child_process";import{promises as ie}from"node:fs";import{homedir as qA}from"node:os";import{basename as Xb,dirname as Ft,join as et,relative as Di,resolve as oe,sep as Wd}from"node:path";import{Command as zA}from"commander";Ko();import{promises as Fu}from"node:fs";var ov=/^[a-z][a-z0-9_]+$/;function Uu(t,e){if(typeof t!="string"||!ov.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var sv="customrecord",iv="customlist";function av(t){return t.startsWith("customrecord_")?t.slice(13):t}function lv(t){return t.startsWith("customlist_")?t.slice(11):t}function cv(t){return Uu(t,"custom_record scriptId"),`cr_${av(t)}`}function dv(t){return Uu(t,"custom_list scriptId"),`cl_${lv(t)}`}function Mu(t){return t.startsWith(sv)?cv(t):t.startsWith(iv)?dv(t):null}var uv={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function qu(t,e){let r=e?hv[`${e}:${t}`]:void 0;if(r)return r;let n=uv[t];if(n)return n;let o=Mu(t);return o?{table:o}:void 0}var pv={accountingPeriod:"accounting_period",printer:"printer"};var hv={...Object.fromEntries(Object.entries(pv).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"azure_blob:file":{table:"source_file"}};function zu(t,e){let r=qu(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function Bu(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=zu(t,n),i=zu(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Hu=4;function ha(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Nr(t,"id"),r=Nr(t,"on"),n=Nr(t,"source"),o=Nr(t,"recordType"),s=[];for(let u of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let p=Nr(u[1]??"","source"),g=Nr(u[1]??"","recordType");p&&g&&s.push({source:p,recordType:g})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t),l=/^[ \t]*reads\s*:\s*\[\s*\{/m.test(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):Hu,declaresReads:l}}function Nr(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function mv(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}function fv(t,e){let r=t.queryRows;if(!(!r||!Object.prototype.hasOwnProperty.call(r,e)))return r[e]}async function Ku(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=ha(t)}catch(g){return{fixtureName:o,conduit:yv(),guards:s,whenPassed:!1,atlasResolutions:[],queryReads:[],wouldWriteBindings:[],targets:[],logs:[],error:g instanceof Error?g.message:String(g)}}let a=mv(e),l=Object.entries(e.atlasLinks??{}).map(([g,S])=>({key:g,resolved:S})),u=[],p=i.declaresReads?async g=>{let S=fv(e,g);return u.push({query:g,served:S!==void 0,rowCount:S?.length??0}),S??[]}:void 0;try{for(let[D,F]of Object.entries(e.queryRows??{}))if(!Array.isArray(F))throw new Error(`fixture queryRows['${D}'] must be an array of rows \u2014 ctx.query answers a row list, and a ${F===null?"null":typeof F} reaches the conduit as one`);let g=await Ho(t,{resolveDir:n.resolveDir}),y=!!(await Sn(g,a,{member:"when",timeoutMs:Fo,query:p})).whenResult;s.push({name:"from.when",status:y?"passed":"failed",detail:y?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let x=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${x} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!y)return{fixtureName:o,conduit:i,guards:s,whenPassed:y,atlasResolutions:l,queryReads:u,wouldWriteBindings:[],targets:[],logs:[]};let R=[],E=[],P=[];for(let D=0;D<i.targets.length;D+=1){let F=i.targets[D],K=await Sn(g,{...a,materialized:P.map(dr=>({...dr}))},{member:"transform",stepIndex:D,timeoutMs:Fo,query:p});R.push(...K.effects.logs);let Ce=K.effects.result;if(!Ce||typeof Ce!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${D+1})`:""} returned no result (expected { patch, createdFrom? })`);let Ie=Ce,Nt=Bu(i.fromRecordType,F.recordType,{fromSource:i.fromSource,toSource:F.source}),{wouldWriteBindings:Ht,masterAction:Tt}=gv(i,F,Nt,e);E.push({to:F,transformResult:Ie,applyBranch:Nt,wouldWriteBindings:Ht,masterAction:Tt}),P.push({source:F.source,recordType:F.recordType,masterTable:`<${F.recordType} master, dry-run>`,masterRowId:`<dry-run target ${D+1}>`,externalId:null})}let I=E[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:y,atlasResolutions:l,queryReads:u,transformResult:I.transformResult,applyBranch:I.applyBranch,wouldWriteBindings:I.wouldWriteBindings,masterAction:I.masterAction,targets:E,logs:R}}catch(g){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:l,queryReads:u,wouldWriteBindings:[],targets:[],logs:[],error:g instanceof Error?g.message:String(g)}}}function gv(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function yv(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Hu,declaresReads:!1}}async function Vu(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 Gu(t){let e=await Fu.readFile(t,"utf8");return JSON.parse(e)}function Wu(t){return Fu.readFile(t,"utf8")}function Ju(t,e){let r=t.conduit,n=`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`,o=t.targets.length>1;if(!e){if(t.error)return n;if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(o){let l=t.targets.reduce((u,p)=>u+p.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${l} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}if(t.error&&!r.id)return n;let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${r.id}`);let i=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(l=>`${l.source}.${l.recordType}`).join(" \u2192 ");s.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${i}${r.on?` on=${r.on}`:""}`),s.push(""),s.push("guards (dispatch order):"),t.guards.length===0&&s.push(" (none ran \u2014 the replay stopped before dispatch)");for(let l of t.guards){let u=l.status==="passed"?"\u2713":l.status==="failed"?"\u2717":"\u2298";s.push(` ${u} ${l.name} [${l.status}] \u2014 ${l.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let l of t.atlasResolutions)s.push(` ${l.key} \u2192 ${l.resolved===null?"null (no Atlas link \u2014 noted)":l.resolved}`);if(s.push(""),s.push("ctx.query (declared reads):"),!r.declaresReads)s.push(" (no `reads` declared \u2014 ctx.query is not defined in the isolate, exactly as in production)");else if(t.queryReads.length===0)s.push(" (declared, but this replay made no read)");else for(let l of t.queryReads)s.push(` ${l.query} \u2192 ${l.served?"served":"not served by the fixture"}, ${l.rowCount} row(s)`);if(t.error)return s.push(""),s.push(`ERROR \u2014 ${t.error}`),s.join(`
2373
+ `)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:b,token:R}=await e(),x=await fetch(`${b}/v1/catalog/records`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!x.ok)throw new Error(`catalog fetch failed: ${x.status}`);return ke(await x.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:U.string().describe('The catalog recordType, e.g. "purchaseOrder" or "customrecord_inbound_shipment".'),source:U.string().optional().describe('Which connector publishes this recordType, e.g. "netsuite" or "stripe". 29 record types are published by more than one source ("customer" by six) and each is a different shape behind the same name. Omit it and the catalog collapse rule picks one; the answer names its choice in `source`.')}},async({recordType:b,source:R})=>{let{baseUrl:x,token:E}=await e(),P=R?`?source=${encodeURIComponent(R)}`:"",I=await fetch(`${x}/v1/catalog/records/${encodeURIComponent(b)}${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(I.status===404)throw new Error(`unknown record type "${b}" \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`record anatomy fetch failed: ${I.status}`);return ke(await I.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:U.array(U.string()).min(1).describe('Catalog recordTypes, e.g. ["purchaseOrder","vendorBill","itemReceipt"].'),source:U.string().optional().describe("Pin every requested type to ONE connector, e.g. \"netsuite\". Without it each name collapses by the catalog rule, so an intersection can silently mix two sources' tables for the same name. The response's `resolvedSources` names what it used.")}},async({recordTypes:b,source:R})=>{let{baseUrl:x,token:E}=await e(),P=new URLSearchParams({types:b.join(",")});R&&P.set("source",R);let I=await fetch(`${x}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(I.status===404)throw new Error(`none of those record types resolved: ${b.join(", ")} \u2014 list them with catalog_get.`);if(!I.ok)throw new Error(`common columns fetch failed: ${I.status}`);return ke(await I.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:b,token:R}=await e(),x=await fetch(`${b}/v1/catalog/census`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!x.ok)throw new Error(`catalog census failed: ${x.status}`);return ke(await x.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:U.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:U.enum(Fb).optional().describe("Narrow to one catalog kind (omit to search all)."),limit:U.number().int().min(1).max(200).optional().describe("Max hits (default 50, max 200). The result reports the true total either way.")}},async({query:b,kind:R,limit:x})=>{let{baseUrl:E,token:P}=await e(),I=new URLSearchParams({q:b});R&&I.set("kind",R),x!==void 0&&I.set("limit",String(x));let D=await fetch(`${E}/v1/catalog/objects?${I}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!D.ok)throw new Error(`catalog object search failed: ${D.status}`);return ke(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:U.enum(Fb),externalId:U.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:b,externalId:R})=>{let{baseUrl:x,token:E}=await e(),P=await fetch(`${x}/v1/catalog/objects/${encodeURIComponent(b)}/${encodeURIComponent(R)}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${b}:${R} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return ke(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:U.string().describe('Words or a phrase, e.g. "inbound shipment receiving".'),limit:U.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:b,limit:R})=>{let{baseUrl:x,token:E}=await e(),P=new URLSearchParams({q:b});R!==void 0&&P.set("limit",String(R));let I=await fetch(`${x}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!I.ok)throw new Error(`kb search failed: ${I.status}`);return ke(await I.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:U.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:b})=>{let{baseUrl:R,token:x}=await e(),E=await fetch(`${R}/v1/kb/document/${encodeURIComponent(b)}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"}});if(!E.ok&&E.status!==404)throw new Error(`kb document fetch failed: ${E.status}`);return ke(await E.json())}),p.registerTool("search_turbobase_docs",{title:"Search Turbobase's documentation",description:'Search Turbobase\'s own published documentation \u2014 the product manual the instance you are connected to shipped with: hooks, conduits, apps, the source sync, the CLI, the REST surface. Route questions about the PLATFORM here ("how do I read the mirror from an app", "what does a hook receive"), as opposed to search_documentation, which searches the TENANT\'s own processes and policies. Returns up to `limit` {slug, title, snippet} hits; pass a slug to read_turbobase_doc for the whole page. The answer names the release the pages came from.',inputSchema:{query:U.string().describe('Words or a phrase, e.g. "writing hooks".'),limit:U.number().int().min(1).max(25).optional().describe("Max results (default 8).")}},async({query:b,limit:R})=>{let{baseUrl:x,token:E}=await e(),P=new URLSearchParams({q:b});R!==void 0&&P.set("limit",String(R));let I=await fetch(`${x}/v1/catalog/docs/search?${P}`,{headers:{Authorization:`Bearer ${E}`,Accept:"application/json"}});if(!I.ok)throw new Error(`turbobase docs search failed: ${I.status}`);return ke(await I.json())}),p.registerTool("read_turbobase_doc",{title:"Read a page of Turbobase's documentation",description:"Read one page of Turbobase's own published documentation in full by its slug (from a search_turbobase_docs hit). Returns {found, slug, title, body_markdown, currentVersion}. A slug that is not one of our pages comes back as found:false rather than as an error. Distinct from read_document, which reads a page of the TENANT's own knowledge base.",inputSchema:{slug:U.string().describe("The page slug, e.g. one returned by search_turbobase_docs.")}},async({slug:b})=>{let{baseUrl:R,token:x}=await e(),E=await fetch(`${R}/v1/catalog/docs/document/${encodeURIComponent(b)}`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"}});if(!E.ok&&E.status!==404)throw new Error(`turbobase doc fetch failed: ${E.status}`);return ke(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:U.boolean().optional()}},async({recordsOnly:b})=>{let{baseUrl:R,token:x}=await e();return{content:[{type:"text",text:await fr({baseUrl:R,token:x,recordsOnly:b})}]}}),p.registerTool("scaffold_hook",{title:"Scaffold a hook",description:"Generate a hook file body (does not write to disk; returns path + content).",inputSchema:{recordType:U.string(),event:U.string().optional(),template:U.enum(["require-field","enforce-format","blank"]).optional(),field:U.string().optional(),regex:U.string().optional(),source:U.string().optional(),id:U.string().optional()}},async b=>{let R=Et("hook",{recordType:b.recordType,event:b.event,template:b.template,field:b.field,regex:b.regex,source:b.source,id:b.id});return ke({path:R.relativePath,content:R.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:U.string().describe('Origin source the record arrives from, e.g. "shopify".'),recordType:U.string().describe('Canonical record type the conduit triggers on, e.g. "order".'),to:U.string().describe('Target source the conduit bridges into, e.g. "netsuite".'),toRecordType:U.string().optional().describe("Target record type (defaults to the trigger record type)."),event:U.enum(["after_canonicalize_inbound","after_sync_success_outbound"]).optional().describe("Cross-source lifecycle event (default after_canonicalize_inbound)."),id:U.string().optional()}},async b=>{let R=Et("conduit",{recordType:b.recordType,source:b.source,to:b.to,toRecordType:b.toRecordType,event:b.event,id:b.id});return ke({path:R.relativePath,content:R.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType:U.string().describe('Record type the first step writes, e.g. "purchaseOrder".'),then:U.string().optional().describe('Record type of a second step that waits for the first, e.g. "vendorBill".'),onFailure:U.enum(["stop","rollback"]).optional().describe("What the engine does when a step fails (default stop)."),id:U.string().optional()}},async b=>{let R=Et("process",{recordType:b.recordType,then:b.then,onFailure:b.onFailure,id:b.id});return ke({path:R.relativePath,content:R.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent:U.string().describe(`What the bridge should do, in the operator's words, e.g. "when a shopify order is paid, raise the matching NetSuite sales order".`),fromSource:U.string().describe('Origin source the record arrives from, e.g. "shopify".'),fromRecordType:U.string().describe('Canonical record type the bridge triggers on, e.g. "order".'),toSource:U.string().describe('Target source the bridge writes into, e.g. "netsuite".'),toRecordType:U.string().describe('Canonical record type written on the target, e.g. "salesOrder".'),intentId:U.string().optional().describe("Correlation id for the audit trail. The instance mints one when omitted."),columns:U.array(U.string()).optional().describe("Narrow the target columns the transform may write. Defaults to the target record's own.")}},async b=>{let{baseUrl:R,token:x}=await e(),E=new z({baseUrl:R,token:x});return ke(await E.authorConduit({intent:b.intent,from:{source:b.fromSource,recordType:b.fromRecordType},to:{source:b.toSource,recordType:b.toRecordType},...b.intentId?{intentId:b.intentId}:{},...b.columns?.length?{columns:b.columns}:{}}))}),p.registerTool("mock_test",{title:"Dry-run an extension against samples",description:"Bundle the given source through the production sandbox and run it against samples/ fixtures.",inputSchema:{source:U.string().describe("The extension TS source."),samplesDir:U.string().optional().describe('Samples directory (default "samples").')}},async({source:b,samplesDir:R})=>{let x=Wb(R,t.samplesRoot);if(x===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:GA})}],isError:!0};let E;try{E=await Tn(x)}catch(D){if(t.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw D}let P=await Jo(b,E.map(D=>D.fixture)),I=P.filter(D=>!D.pass).length;return ke({total:P.length,passed:P.length-I,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id:U.string(),recordType:U.string(),event:U.string(),source:U.string().describe('Adapter id or "standalone".'),sourceCode:U.string().describe("The verbatim extension TS."),extensionKind:U.string().optional()}},async b=>{let{baseUrl:R,token:x}=await e(),P=await new z({baseUrl:R,token:x}).deploy({id:b.id,recordType:b.recordType,event:b.event,source:b.source,sourceCode:b.sourceCode,extensionKind:b.extensionKind});return ke(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:U.string(),limit:U.number().int().positive().optional()}},async({id:b,limit:R})=>{let{baseUrl:x,token:E}=await e(),P=new z({baseUrl:x,token:E});return ke({id:b,logs:await P.logs(b,R)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:b,token:R}=await e(),x=new z({baseUrl:b,token:R});return ke(await x.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:U.string().describe("URL slug for the app (lowercased; served at /a/<slug>)."),name:U.string().optional().describe("Display name (defaults to the slug)."),description:U.string().optional().describe("Short description.")}},async({slug:b,name:R,description:x})=>{let{baseUrl:E,token:P}=await e(),I=new z({baseUrl:E,token:P});return ke(await I.appsCreate({slug:b,name:R,description:x}))}),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:U.string().describe("App slug or id.")}},async({app:b})=>{let{baseUrl:R,token:x}=await e(),E=new z({baseUrl:R,token:x});return ke(await E.appsPull(b))}),p.registerTool("apps_push",{title:"Push a hosted app's source",description:"Record an edited source tree as the app's NEW source revision, so the instance holds the source of record rather than one laptop. Send the whole tree ({path \u2192 contents}, relative POSIX paths, no node_modules/dist/.git). SOURCE ONLY \u2014 this does not build and does not change what is live; run `turbobase apps deploy <slug>` for that. POST /v1/apps/:id/push.",inputSchema:{app:U.string().describe("App slug or id."),files:U.record(U.string()).describe("The full source tree: relative path \u2192 file contents (text only)."),note:U.string().optional().describe("Short note stored with the revision.")}},async({app:b,files:R,note:x})=>{let{baseUrl:E,token:P}=await e(),I=new z({baseUrl:E,token:P});return ke(await I.appsPush(b,R,{note:x}))});let g=U.object({name:U.string().describe("Field name (lowercase identifier)."),type:U.enum(["text","number","date","bool","select"]).describe("Customer-facing type, NOT a Postgres type."),required:U.boolean().optional()}),k=U.object({slug:U.string().describe("Table slug; the physical table is cr_<slug>."),displayName:U.string().optional(),fields:U.array(g).describe("At least one field."),rowLevelOwner:U.boolean().optional().describe("Restrict non-admins to rows they created.")});return p.registerTool("tables_list",{title:"List custom tables",description:"The instance's customer-authored tables, their fields, and which apps claim each one. Read the `column` on each field \u2014 that is the actual Postgres column an app SELECTs (cf_sa_<name>), which is not the same string as the field name. GET /v1/tables.",inputSchema:{}},async()=>{let{baseUrl:b,token:R}=await e(),x=new z({baseUrl:b,token:R});return ke(await x.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:U.array(k),claimedBy:U.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:R})=>{let{baseUrl:x,token:E}=await e(),P=new z({baseUrl:x,token:E});return ke(await P.tablesPlan({tables:b,claimedBy:R}))}),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:U.array(k),claimedBy:U.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:b,claimedBy:R})=>{let{baseUrl:x,token:E}=await e(),P=new z({baseUrl:x,token:E});return ke(await P.tablesApply({tables:b,claimedBy:R}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async b=>{let{baseUrl:R,token:x}=await e(),P=await(await fetch(`${R}/v1/catalog/records`,{headers:{Authorization:`Bearer ${x}`,Accept:"application/json"}})).text();return{contents:[{uri:b.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async b=>{let{baseUrl:R,token:x}=await e(),E=await fr({baseUrl:R,token:x});return{contents:[{uri:b.href,mimeType:"text/plain",text:E}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async b=>{let R=Ui(process.cwd(),"samples"),x=[];try{x=(await HA.readdir(R)).filter(P=>P.endsWith(".json"))}catch{x=[]}let E=await Tn(R);return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({files:x,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 b=>{let R=await Kb(),x=[];if(R){let{baseUrl:E,token:P}=await e();x=await R.listRecipesForSurface({surface:"mcp-authoring",baseUrl:E,token:P},r)}return{contents:[{uri:b.href,mimeType:"application/json",text:JSON.stringify({recipes:x})}]}}),p}async function XA(t={}){let e=await Jb(t),r=new Di;await e.connect(r)}var Fb,Hb,Vb,Gb,GA,Yb,JA,YA,Zb=j(()=>{jb();qb();na();_n();gt();ma();ts();Bb();Fb=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Vb="turbobase-authoring",Gb="0.1.0";GA="samplesDir must be a relative path inside the samples directory this server serves; absolute paths and paths that leave it are refused over the network.";Yb=["catalog_get","record_anatomy","common_columns","search_documentation","read_document","search_turbobase_docs","read_turbobase_doc","search_catalog","catalog_census","explain_object","generate_types","scaffold_hook","scaffold_conduit","scaffold_process","author_conduit","mock_test","deploy","tail_logs","apps_list","apps_create","apps_pull","apps_push","tables_list","tables_plan","tables_apply"],JA=[...Yb,...zb],YA=["catalog:///","types://all","samples:///","recipes:///"]});na();_n();gt();ma();import{spawn as Zd}from"node:child_process";import{promises as ie}from"node:fs";import{homedir as ZA}from"node:os";import{basename as tw,dirname as Ht,join as tt,relative as qi,resolve as oe,sep as Xd}from"node:path";import{Command as QA}from"commander";Wo();import{promises as Wu}from"node:fs";var gv=/^[a-z][a-z0-9_]+$/;function Fu(t,e){if(typeof t!="string"||!gv.test(t))throw new Error(`${e} ${JSON.stringify(t)} must match /^[a-z][a-z0-9_]+$/ (NS scriptid form). This restriction is what lets reconcile safely splice it as a SQL identifier; refusing to emit DDL.`);return t}var yv="customrecord",bv="customlist";function wv(t){return t.startsWith("customrecord_")?t.slice(13):t}function vv(t){return t.startsWith("customlist_")?t.slice(11):t}function _v(t){return Fu(t,"custom_record scriptId"),`cr_${wv(t)}`}function Sv(t){return Fu(t,"custom_list scriptId"),`cl_${vv(t)}`}function Hu(t){return t.startsWith(yv)?_v(t):t.startsWith(bv)?Sv(t):null}var kv={salesOrder:{table:"order"},invoice:{table:"invoice"},itemFulfillment:{table:"order_fulfillment"},customerPayment:{table:"customer_payment"},cashSale:{table:"cash_sale"},cashRefund:{table:"cash_refund"},opportunity:{table:"opportunity"},estimate:{table:"estimate"},customerDeposit:{table:"customer_deposit"},creditMemo:{table:"credit_memo"},customer:{table:"entity",typeColumn:"entity_type",typeValue:"customer"},vendor:{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},contact:{table:"entity",typeColumn:"entity_type",typeValue:"contact"},employee:{table:"entity",typeColumn:"entity_type",typeValue:"employee"},partner:{table:"entity",typeColumn:"entity_type",typeValue:"partner"},inventoryItem:{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},serviceSaleItem:{table:"item",typeColumn:"item_type",typeValue:"serviceSaleItem"},nonInventoryResaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventoryResaleItem"},kitItem:{table:"item",typeColumn:"item_type",typeValue:"kitItem"},assemblyItem:{table:"item",typeColumn:"item_type",typeValue:"assemblyItem"},lotNumberedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedInventoryItem"},serializedInventoryItem:{table:"item",typeColumn:"item_type",typeValue:"serializedInventoryItem"},lotNumberedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"lotNumberedAssemblyItem"},serializedAssemblyItem:{table:"item",typeColumn:"item_type",typeValue:"serializedAssemblyItem"},nonInventorySaleItem:{table:"item",typeColumn:"item_type",typeValue:"nonInventorySaleItem"},otherChargeSaleItem:{table:"item",typeColumn:"item_type",typeValue:"otherChargeSaleItem"},discountItem:{table:"item",typeColumn:"item_type",typeValue:"discountItem"},location:{table:"location"},department:{table:"department"},classification:{table:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_bill"},expenseReport:{table:"expense_report"},itemReceipt:{table:"item_receipt"},vendorReturnAuthorization:{table:"vendor_return_authorization"},transferOrder:{table:"transfer_order"},check:{table:"check"},customerRefund:{table:"customer_refund"},project:{table:"project"},projectTask:{table:"work_item",typeColumn:"item_type",typeValue:"project_task"},supportCase:{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},caseMessage:{table:"activity",typeColumn:"activity_type",typeValue:"case_message_outgoing",alsoAddresses:["case_message_incoming"]},shippingItem:{table:"shipping_item"},unitsType:{table:"units_type"},returnAuthorization:{table:"return_authorization"},inventoryAdjustment:{table:"inventory_adjustment"},vendorCredit:{table:"vendor_credit"},deposit:{table:"deposit"},account:{table:"account"},channel_message:{table:"activity",typeColumn:"activity_type",typeValue:"message"},social_post:{table:"activity",typeColumn:"activity_type",typeValue:"social_post"},reaction:{table:"reaction"},esignSubmission:{table:"esign_submission"},esignSubmitter:{table:"esign_submitter"},workflow_run:{table:"automation_run"},printer:{table:"printer"},printJob:{table:"print_job"},label:{table:"label"},call:{table:"activity",typeColumn:"activity_type",typeValue:"call"},quote:{table:"estimate"},tag:{table:"label"},request:{table:"request"}};function Ku(t,e){let r=e?Rv[`${e}:${t}`]:void 0;if(r)return r;let n=kv[t];if(n)return n;let o=Hu(t);return o?{table:o}:void 0}var Tv={accountingPeriod:"accounting_period",printer:"printer"};var Rv={...Object.fromEntries(Object.entries(Tv).map(([t,e])=>[`standalone:${t}`,{table:e}])),"google_workspace:doc":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"google_workspace:email":{table:"memory_document",typeColumn:"kind",typeValue:"email"},"google_workspace:file":{table:"memory_document",typeColumn:"kind",typeValue:"file"},"google_workspace:sheet":{table:"memory_document",typeColumn:"kind",typeValue:"sheet"},"google_workspace:slide":{table:"memory_document",typeColumn:"kind",typeValue:"slide"},"salesforce:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"salesforce:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"salesforce:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"salesforce:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"salesforce:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"intercom:admin":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"hubspot:owner":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"intercom:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"intercom:ticket":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"github:issue":{table:"work_item",typeColumn:"item_type",typeValue:"issue"},"github:pull_request":{table:"work_item",typeColumn:"item_type",typeValue:"pull_request"},"github:comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"zendesk:organization":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"getsales:company":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"xero:supplier":{table:"entity",typeColumn:"entity_type",typeValue:"vendor"},"zoho_crm:account":{table:"entity",typeColumn:"entity_type",typeValue:"customer"},"zoho_crm:lead":{table:"entity",typeColumn:"entity_type",typeValue:"lead"},"zoho_crm:case":{table:"work_item",typeColumn:"item_type",typeValue:"ticket"},"slack:user":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"slack:channel":{table:"channel"},"slack:reaction":{table:"reaction"},"quickbooks:bill":{table:"vendor_bill"},"quickbooks:payment":{table:"customer_payment"},"quickbooks:billPayment":{table:"vendor_payment"},"quickbooks:item":{table:"item"},"zoho_crm:task":{table:"activity",typeColumn:"activity_type",typeValue:"task"},"zoho_crm:event":{table:"activity",typeColumn:"activity_type",typeValue:"event"},"zoho_crm:product":{table:"item",typeColumn:"item_type",typeValue:"inventoryItem"},"xero:bill":{table:"vendor_bill"},"xero:billPayment":{table:"vendor_payment"},"xero:creditNote":{table:"credit_memo"},"xero:item":{table:"item"},"xero:manualJournal":{table:"journal_entry"},"xero:payment":{table:"customer_payment"},"xero:receiveMoney":{table:"deposit"},"xero:spendMoney":{table:"check"},"xero:supplierCreditNote":{table:"vendor_credit"},"azure_blob:file":{table:"source_file"}};function Vu(t,e){let r=Ku(t,e);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function Gu(t,e,r){if(e===t)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=Vu(t,n),i=Vu(e,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var Ju=4;function fa(t){if(!/\bdefineConduit\s*[<(]/.test(t))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let e=Lr(t,"id"),r=Lr(t,"on"),n=Lr(t,"source"),o=Lr(t,"recordType"),s=[];for(let u of t.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let p=Lr(u[1]??"","source"),g=Lr(u[1]??"","recordType");p&&g&&s.push({source:p,recordType:g})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(t),l=/^[ \t]*reads\s*:\s*\[\s*\{/m.test(t);if(!e||!n||!o||!i)throw new Error("could not parse id/from.{source,recordType}/to.{source,recordType} \u2014 is it a reference-shape defineConduit({...})?");return{id:e,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):Ju,declaresReads:l}}function Lr(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function xv(t){return{recordType:t.recordType,event:t.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:t.fromSource,payload:t.payload??{},tenantConfig:t.tenantConfig??{},metadata:{externalId:t.externalId,lines:t.lines??[]},bindings:t.bindings??[],atlasLinks:t.atlasLinks??{}}}function $v(t,e){let r=t.queryRows;if(!(!r||!Object.prototype.hasOwnProperty.call(r,e)))return r[e]}async function Yu(t,e,r="fixture",n={}){let o=e.name??r,s=[],i;try{i=fa(t)}catch(g){return{fixtureName:o,conduit:Pv(),guards:s,whenPassed:!1,atlasResolutions:[],queryReads:[],wouldWriteBindings:[],targets:[],logs:[],error:g instanceof Error?g.message:String(g)}}let a=xv(e),l=Object.entries(e.atlasLinks??{}).map(([g,k])=>({key:g,resolved:k})),u=[],p=i.declaresReads?async g=>{let k=$v(e,g);return u.push({query:g,served:k!==void 0,rowCount:k?.length??0}),k??[]}:void 0;try{for(let[D,H]of Object.entries(e.queryRows??{}))if(!Array.isArray(H))throw new Error(`fixture queryRows['${D}'] must be an array of rows \u2014 ctx.query answers a row list, and a ${H===null?"null":typeof H} reaches the conduit as one`);let g=await Go(t,{resolveDir:n.resolveDir}),b=!!(await kn(g,a,{member:"when",timeoutMs:Vo,query:p})).whenResult;s.push({name:"from.when",status:b?"passed":"failed",detail:b?"gate returned true (or no gate) \u2014 conduit fires":"gate returned false \u2014 conduit short-circuits (dispatch records no ledger row)"});let R=e.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${R} vs cycleBudget=${i.cycleBudget} is computable, but the chain's true hop count requires live conduit_event state \u2014 requires live sandbox state (skipped in fixture mode)`}),s.push({name:"opposite-direction-loop",status:"skipped-offline",detail:"reads committed conduit_event rows for the reverse leg \u2014 requires live sandbox state (skipped in fixture mode)"}),s.push({name:"idempotency",status:"skipped-offline",detail:"INSERT conduit_event ON CONFLICT (idempotency_key) \u2014 requires live sandbox state (skipped in fixture mode)"}),!b)return{fixtureName:o,conduit:i,guards:s,whenPassed:b,atlasResolutions:l,queryReads:u,wouldWriteBindings:[],targets:[],logs:[]};let x=[],E=[],P=[];for(let D=0;D<i.targets.length;D+=1){let H=i.targets[D],G=await kn(g,{...a,materialized:P.map(Vt=>({...Vt}))},{member:"transform",stepIndex:D,timeoutMs:Vo,query:p});x.push(...G.effects.logs);let xe=G.effects.result;if(!xe||typeof xe!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${D+1})`:""} returned no result (expected { patch, createdFrom? })`);let qe=xe,Rt=Gu(i.fromRecordType,H.recordType,{fromSource:i.fromSource,toSource:H.source}),{wouldWriteBindings:Kt,masterAction:xt}=Ev(i,H,Rt,e);E.push({to:H,transformResult:qe,applyBranch:Rt,wouldWriteBindings:Kt,masterAction:xt}),P.push({source:H.source,recordType:H.recordType,masterTable:`<${H.recordType} master, dry-run>`,masterRowId:`<dry-run target ${D+1}>`,externalId:null})}let I=E[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:b,atlasResolutions:l,queryReads:u,transformResult:I.transformResult,applyBranch:I.applyBranch,wouldWriteBindings:I.wouldWriteBindings,masterAction:I.masterAction,targets:E,logs:x}}catch(g){return{fixtureName:o,conduit:i,guards:s,whenPassed:!1,atlasResolutions:l,queryReads:u,wouldWriteBindings:[],targets:[],logs:[],error:g instanceof Error?g.message:String(g)}}}function Ev(t,e,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${t.fromRecordType} master (firing source '${t.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:t.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:e.source,externalId:null,role:"replica",why:"target source bound to the SAME master; external_id null until writeback mints it"}]}:{masterAction:`would MINT a new ${e.recordType} master (source_system='${e.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:e.source,externalId:null,role:"origin",why:"this conduit CREATED the new master, so the target is its origin; external_id null until writeback mints it"}]}}function Pv(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:Ju,declaresReads:!1}}async function Xu(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 Zu(t){let e=await Wu.readFile(t,"utf8");return JSON.parse(e)}function Qu(t){return Wu.readFile(t,"utf8")}function ep(t,e){let r=t.conduit,n=`replay ${t.fixtureName}: ERROR \u2014 ${t.error}`,o=t.targets.length>1;if(!e){if(t.error)return n;if(!t.whenPassed)return`replay ${t.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(o){let l=t.targets.reduce((u,p)=>u+p.wouldWriteBindings.length,0);return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.targets.length} targets in sequence (${l} binding(s) would be written)`}return`replay ${t.fixtureName} [${r.id}]: OK \u2014 ${t.applyBranch} (${t.wouldWriteBindings.length} binding(s) would be written)`}if(t.error&&!r.id)return n;let s=[];s.push(`\u2501\u2501 replay ${t.fixtureName} \u2501\u2501`),s.push(`conduit: ${r.id}`);let i=(r.targets.length>0?r.targets:[{source:r.toSource,recordType:r.toRecordType}]).map(l=>`${l.source}.${l.recordType}`).join(" \u2192 ");s.push(`route: ${r.fromSource}.${r.fromRecordType} \u2192 ${i}${r.on?` on=${r.on}`:""}`),s.push(""),s.push("guards (dispatch order):"),t.guards.length===0&&s.push(" (none ran \u2014 the replay stopped before dispatch)");for(let l of t.guards){let u=l.status==="passed"?"\u2713":l.status==="failed"?"\u2717":"\u2298";s.push(` ${u} ${l.name} [${l.status}] \u2014 ${l.detail}`)}if(s.push(""),s.push("atlas.resolve (used by transform):"),t.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let l of t.atlasResolutions)s.push(` ${l.key} \u2192 ${l.resolved===null?"null (no Atlas link \u2014 noted)":l.resolved}`);if(s.push(""),s.push("ctx.query (declared reads):"),!r.declaresReads)s.push(" (no `reads` declared \u2014 ctx.query is not defined in the isolate, exactly as in production)");else if(t.queryReads.length===0)s.push(" (declared, but this replay made no read)");else for(let l of t.queryReads)s.push(` ${l.query} \u2192 ${l.served?"served":"not served by the fixture"}, ${l.rowCount} row(s)`);if(t.error)return s.push(""),s.push(`ERROR \u2014 ${t.error}`),s.join(`
2315
2374
  `);if(!t.whenPassed)return s.push(""),s.push("transform: SKIPPED (from.when gate did not fire)."),s.join(`
2316
- `);let a=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(a.forEach((l,u)=>{let p=o?` (target ${u+1}/${a.length}: ${l.to.source}.${l.to.recordType})`:"";s.push(""),s.push(`transform${p} \u2192 patch:`),s.push(bv(JSON.stringify(l.transformResult.patch??{},null,2)," ")),l.transformResult.createdFrom&&s.push(` createdFrom: ${JSON.stringify(l.transformResult.createdFrom)}`),s.push(""),s.push(`apply-branch${p}: ${l.applyBranch}`),s.push(` ${l.masterAction}`),s.push(""),s.push(`bindings that WOULD be written (txn_source_link)${p}:`);for(let g of l.wouldWriteBindings)s.push(` ${g.source} role=${g.role} external_id=${g.externalId??"null"} \u2014 ${g.why}`)}),t.logs.length>0){s.push(""),s.push("conduit logs:");for(let l of t.logs)s.push(` [${l.level}] ${l.message}${l.meta?` ${JSON.stringify(l.meta)}`:""}`)}return s.join(`
2317
- `)}function bv(t,e){return t.split(`
2375
+ `);let a=t.targets.length>0?t.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:t.transformResult??{patch:{}},applyBranch:t.applyBranch??"different-type-mint",wouldWriteBindings:t.wouldWriteBindings,masterAction:t.masterAction??""}];if(a.forEach((l,u)=>{let p=o?` (target ${u+1}/${a.length}: ${l.to.source}.${l.to.recordType})`:"";s.push(""),s.push(`transform${p} \u2192 patch:`),s.push(Av(JSON.stringify(l.transformResult.patch??{},null,2)," ")),l.transformResult.createdFrom&&s.push(` createdFrom: ${JSON.stringify(l.transformResult.createdFrom)}`),s.push(""),s.push(`apply-branch${p}: ${l.applyBranch}`),s.push(` ${l.masterAction}`),s.push(""),s.push(`bindings that WOULD be written (txn_source_link)${p}:`);for(let g of l.wouldWriteBindings)s.push(` ${g.source} role=${g.role} external_id=${g.externalId??"null"} \u2014 ${g.why}`)}),t.logs.length>0){s.push(""),s.push("conduit logs:");for(let l of t.logs)s.push(` [${l.level}] ${l.message}${l.meta?` ${JSON.stringify(l.meta)}`:""}`)}return s.join(`
2376
+ `)}function Av(t,e){return t.split(`
2318
2377
  `).map(r=>e+r).join(`
2319
- `)}var wv="2026-01-01",Yu="2026-01-01T00:00:00.000Z";function vv(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"?wv:r.startsWith("timestamp")?Yu: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:Yu}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function _v(t){let e={};for(let r of t.columns)e[r.name]=vv(r.pgType,r.name);return e}function Sv(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:_v(t)},expect:e.expect??"pass"}}function Xu(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:Sv(r,e)}))}import{promises as Zu}from"node:fs";import{join as Qu,relative as kv,sep as Tv}from"node:path";var xv=67324752,Rv=33639248,$v=101010256,Ev=(()=>{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 Pv(t){let e=4294967295;for(let r=0;r<t.length;r++)e=Ev[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function Av(t){let e=[];async function r(n){let o=await Zu.readdir(n,{withFileTypes:!0});for(let s of o){let i=Qu(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(kv(t,i).split(Tv).join("/"))}}return await r(t),e.sort(),e}async function ep(t){let e=await Av(t),r=[],n=[],o=0;for(let a of e){let l=Buffer.from(a,"utf8"),u=await Zu.readFile(Qu(t,a)),p=Pv(u),g=Buffer.alloc(30+l.length);g.writeUInt32LE(xv,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 S=Buffer.alloc(46+l.length);S.writeUInt32LE(Rv,0),S.writeUInt16LE(20,4),S.writeUInt16LE(20,6),S.writeUInt16LE(0,10),S.writeUInt32LE(p,16),S.writeUInt32LE(u.length,20),S.writeUInt32LE(u.length,24),S.writeUInt16LE(l.length,28),S.writeUInt32LE(o,42),l.copy(S,46),n.push(S),o+=g.length+u.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE($v,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}aa();function Cv(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function Go(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Iv(t){let e=Ov(t,"from"),n=tp(t,"to").map(o=>({source:Go(o,"source"),recordType:Go(o,"recordType")}));return{fromSource:e?Go(e,"source"):void 0,fromRecordType:e?Go(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function Ov(t,e){return tp(t,e)[0]??null}function tp(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let l=t[a];if(l==="{")s+=1;else if(l==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function Nv(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let l=t[s];if(o){l==="\\"?s+=1:l===o&&(o=null);continue}if(l==="'"||l==='"'||l==="`"){o=l;continue}if(l==="("||l==="{"||l==="[")n+=1;else if(l===")"||l==="}"||l==="]"){if(n===0)break;n-=1}else if(l===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function Lv(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function jv(t){return/\bcreatedFrom\b/.test(t)}function Dv(t){let e=/\bdefine(?:Hook|Conduit|Process)\s*(?:<[^>]*>)?\s*\(\s*\{/.exec(t);if(!e)return null;let r=0,n=null,o=!1;for(let s=e.index+e[0].length-1;s<t.length;s+=1){let i=t[s];if(n){i==="\\"?s+=1:i===n&&(n=null);continue}if(i==="/"&&t[s+1]==="/"){let a=t.indexOf(`
2320
- `,s);s=a<0?t.length:a;continue}if(i==="/"&&t[s+1]==="*"){let a=t.indexOf("*/",s+2);s=a<0?t.length:a+1;continue}if(i==="'"||i==='"'||i==="`"){n=i,o=!1;continue}if(i==="{"||i==="("||i==="["){r+=1,o=r===1;continue}if(i==="}"||i===")"||i==="]"){if(r-=1,r===0)return{};continue}if(r===1&&i===","){o=!0;continue}if(!(r===1&&o&&/\s/.test(i))&&r===1&&o){o=!1;let a=/^id\s*:\s*/.exec(t.slice(s));if(!a)continue;let l=/^(['"`])([^'"`]+)\1/.exec(t.slice(s+a[0].length));return l?{literal:l[2],index:s}:{}}}return{}}function Uv(t){let e=/id\s*:\s*(['"`])([^'"`]+)\1/.exec(t),r=Dv(t);if(!e||!r||r.index===e.index)return null;let n=e[2];return{rule:"id-not-first-literal",message:r.literal===void 0?`the define call's own \`id\` is not a string literal, so the deploy keys this file on the first \`id:\` literal it finds, '${n}' \u2014 the deploy will refuse it with extension_id_mismatch unless that is the module's id.`:`the first \`id:\` literal in the file is '${n}', not the define call's own '${r.literal}' \u2014 the deploy keys the file on the first one and refuses the mismatch (extension_id_mismatch).`,fix:"Write the extension's own id as a string literal on the define call (`id: '<your-id>'`), and keep any comment, constant, step or helper that carries an `id:` literal below it."}}function rp(t){let e=Cv(t),r=[],n=Uv(t);if(n&&r.push(n),e==="hook")return{kind:e,warnings:r};let{fromSource:o,fromRecordType:s,toRecordType:i,targets:a}=Iv(t);for(let g of a)if(o&&g.source&&o===g.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${o}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let l=Nv(t);if(l!==null){let g=/\bexternalId\b/.test(l),S=/\bfromSource\b/.test(l);!g&&!S&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}let u=a.find(g=>g.recordType&&s&&g.recordType!==s)?.recordType??(s!==i?i:void 0);s&&u&&!jv(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${u}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${u} 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 p=Lv(t,"cycleBudget");return p!==void 0&&(p<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${p} 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)."}):p>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${p} 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 np(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
2378
+ `)}var Cv="2026-01-01",tp="2026-01-01T00:00:00.000Z";function Iv(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"?Cv:r.startsWith("timestamp")?tp: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:tp}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:e?`sample ${e}`:"sample text"}function Ov(t){let e={};for(let r of t.columns)e[r.name]=Iv(r.pgType,r.name);return e}function Nv(t,e={}){let r=e.event??"before_save";return{name:`${t.recordType} ${r} (generated)`,context:{recordType:t.recordType,event:r,source:t.source,payload:Ov(t)},expect:e.expect??"pass"}}function rp(t,e={}){return t.map(r=>({recordType:r.recordType,fixture:Nv(r,e)}))}import{promises as np}from"node:fs";import{join as op,relative as Lv,sep as jv}from"node:path";var Dv=67324752,Uv=33639248,Mv=101010256,qv=(()=>{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 zv(t){let e=4294967295;for(let r=0;r<t.length;r++)e=qv[(e^t[r])&255]^e>>>8;return(e^4294967295)>>>0}async function Bv(t){let e=[];async function r(n){let o=await np.readdir(n,{withFileTypes:!0});for(let s of o){let i=op(n,s.name);s.isDirectory()?await r(i):s.isFile()&&e.push(Lv(t,i).split(jv).join("/"))}}return await r(t),e.sort(),e}async function sp(t){let e=await Bv(t),r=[],n=[],o=0;for(let a of e){let l=Buffer.from(a,"utf8"),u=await np.readFile(op(t,a)),p=zv(u),g=Buffer.alloc(30+l.length);g.writeUInt32LE(Dv,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 k=Buffer.alloc(46+l.length);k.writeUInt32LE(Uv,0),k.writeUInt16LE(20,4),k.writeUInt16LE(20,6),k.writeUInt16LE(0,10),k.writeUInt32LE(p,16),k.writeUInt32LE(u.length,20),k.writeUInt32LE(u.length,24),k.writeUInt16LE(l.length,28),k.writeUInt32LE(o,42),l.copy(k,46),n.push(k),o+=g.length+u.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE(Mv,0),i.writeUInt16LE(e.length,8),i.writeUInt16LE(e.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:e.length}}ca();function Fv(t){return/\bdefineConduit\s*[<(]/.test(t)?"conduit":/\bdefineProcess\s*[<(]/.test(t)?"process":"hook"}function Yo(t,e){let r=new RegExp(`${e}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return r?r[2]:void 0}function Hv(t){let e=Kv(t,"from"),n=ip(t,"to").map(o=>({source:Yo(o,"source"),recordType:Yo(o,"recordType")}));return{fromSource:e?Yo(e,"source"):void 0,fromRecordType:e?Yo(e,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function Kv(t,e){return ip(t,e)[0]??null}function ip(t,e){let r=[],n=new RegExp(`\\b${e}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(t))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<t.length;a+=1){let l=t[a];if(l==="{")s+=1;else if(l==="}"&&(s-=1,s===0)){r.push(t.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function Vv(t){let e=/idempotencyKey\s*:/.exec(t);if(!e)return null;let r=e.index+e[0].length,n=0,o=null,s=r;for(;s<t.length;s+=1){let l=t[s];if(o){l==="\\"?s+=1:l===o&&(o=null);continue}if(l==="'"||l==='"'||l==="`"){o=l;continue}if(l==="("||l==="{"||l==="[")n+=1;else if(l===")"||l==="}"||l==="]"){if(n===0)break;n-=1}else if(l===","&&n===0)break}let i=t.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function Gv(t,e){let r=new RegExp(`${e}\\s*:\\s*(-?\\d+)`).exec(t);return r?Number(r[1]):void 0}function Wv(t){return/\bcreatedFrom\b/.test(t)}function Jv(t){let e=/\bdefine(?:Hook|Conduit|Process)\s*(?:<[^>]*>)?\s*\(\s*\{/.exec(t);if(!e)return null;let r=0,n=null,o=!1;for(let s=e.index+e[0].length-1;s<t.length;s+=1){let i=t[s];if(n){i==="\\"?s+=1:i===n&&(n=null);continue}if(i==="/"&&t[s+1]==="/"){let a=t.indexOf(`
2379
+ `,s);s=a<0?t.length:a;continue}if(i==="/"&&t[s+1]==="*"){let a=t.indexOf("*/",s+2);s=a<0?t.length:a+1;continue}if(i==="'"||i==='"'||i==="`"){n=i,o=!1;continue}if(i==="{"||i==="("||i==="["){r+=1,o=r===1;continue}if(i==="}"||i===")"||i==="]"){if(r-=1,r===0)return{};continue}if(r===1&&i===","){o=!0;continue}if(!(r===1&&o&&/\s/.test(i))&&r===1&&o){o=!1;let a=/^id\s*:\s*/.exec(t.slice(s));if(!a)continue;let l=/^(['"`])([^'"`]+)\1/.exec(t.slice(s+a[0].length));return l?{literal:l[2],index:s}:{}}}return{}}function Yv(t){let e=/id\s*:\s*(['"`])([^'"`]+)\1/.exec(t),r=Jv(t);if(!e||!r||r.index===e.index)return null;let n=e[2];return{rule:"id-not-first-literal",message:r.literal===void 0?`the define call's own \`id\` is not a string literal, so the deploy keys this file on the first \`id:\` literal it finds, '${n}' \u2014 the deploy will refuse it with extension_id_mismatch unless that is the module's id.`:`the first \`id:\` literal in the file is '${n}', not the define call's own '${r.literal}' \u2014 the deploy keys the file on the first one and refuses the mismatch (extension_id_mismatch).`,fix:"Write the extension's own id as a string literal on the define call (`id: '<your-id>'`), and keep any comment, constant, step or helper that carries an `id:` literal below it."}}function ap(t){let e=Fv(t),r=[],n=Yv(t);if(n&&r.push(n),e==="hook")return{kind:e,warnings:r};let{fromSource:o,fromRecordType:s,toRecordType:i,targets:a}=Hv(t);for(let g of a)if(o&&g.source&&o===g.source){r.push({rule:"same-source-conduit",message:`from.source and to.source are both '${o}' \u2014 a conduit that doesn't cross sources isn't a conduit.`,fix:`Make 'to.source' a DIFFERENT source than 'from.source', or rewrite this as a hook (\`turbobase ext new hook --record ${s??"<type>"}\`) \u2014 a same-source transform belongs on the write path, not the cross-source bridge.`});break}let l=Vv(t);if(l!==null){let g=/\bexternalId\b/.test(l),k=/\bfromSource\b/.test(l);!g&&!k&&r.push({rule:"weak-idempotency-key",message:"idempotencyKey omits both ctx.externalId and ctx.fromSource \u2014 two distinct re-fires (different records, or the same record from different sources) collapse onto one conduit_event ledger row and one of them is silently dropped as a duplicate.",fix:"Include `ctx.externalId` (and, for multi-source triggers, `ctx.fromSource`) in the key, e.g. `idempotencyKey: (ctx) => `${ctx.fromSource}:${ctx.externalId}``."})}let u=a.find(g=>g.recordType&&s&&g.recordType!==s)?.recordType??(s!==i?i:void 0);s&&u&&!Wv(t)&&r.push({rule:"missing-created-from",message:`this conduit bridges '${s}' \u2192 '${u}' (different record types) but its transform never returns 'createdFrom' \u2014 the created ${u} 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 p=Gv(t,"cycleBudget");return p!==void 0&&(p<1?r.push({rule:"cycle-budget-too-low",message:`cycleBudget=${p} 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)."}):p>20&&r.push({rule:"cycle-budget-too-high",message:`cycleBudget=${p} 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 lp(t,e,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${t} (${e.kind})`),e.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
2321
2380
  `);for(let a of e.warnings)i.push(` ${n("WARN")} ${s(`[${a.rule}]`)} ${a.message}`),i.push(` ${s("\u2192 fix:")} ${a.fix}`);return i.push(`
2322
2381
  lint: ${n(`${e.warnings.length} warning(s).`)}`),i.join(`
2323
- `)}function op(t){return t.cases.filter(e=>e.status==="failed").length}function xn(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Mv(t){let e=op(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${xn(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${xn(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${xn(n.type)}"`:"";r.push(` <failure${i} message="${xn(s)}">${xn(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2382
+ `)}function cp(t){return t.cases.filter(e=>e.status==="failed").length}function xn(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}function Xv(t){let e=cp(t),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${xn(t.name)}" tests="${t.cases.length}" failures="${e}">`);for(let n of t.cases){let o=` <testcase name="${xn(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${xn(n.type)}"`:"";r.push(` <failure${i} message="${xn(s)}">${xn(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
2324
2383
  `)}
2325
- `}function qv(t){let e={suite:t.name,tests:t.cases.length,failures:op(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2326
- `}function Wo(t,e){return e==="junit"?Mv(t):qv(t)}var Ge={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"},Ee={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},Lr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],nt={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},sp=/\x1b\[[0-9;]*m/g;function jt(t){return t.replace(sp,"").length}function ma(t,e){return e<=0?1:Math.max(1,Math.ceil(jt(t)/e))}function zv(){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 fa=zv();function Oe(){return fa}function ga(t){fa=t}function Ne(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function ot(t,e){return fa?`${t}${e}${Ge.reset}`:e}var m={bold:t=>ot(Ge.bold,t),dim:t=>ot(Ge.dim,t),red:t=>ot(Ge.red,t),green:t=>ot(Ge.green,t),yellow:t=>ot(Ge.yellow,t),blue:t=>ot(Ge.blue,t),magenta:t=>ot(Ge.magenta,t),cyan:t=>ot(Ge.cyan,t),grey:t=>ot(Ge.grey,t)};var _e={success:t=>`${m.green("\u2713")} ${t}`,error:t=>`${m.red("\u2716")} ${t}`,warn:t=>`${m.yellow("\u26A0")} ${t}`,info:t=>`${m.dim("\xB7")} ${t}`,step:t=>`${m.cyan("\u25B8")} ${t}`},Vt={add:t=>m.green(`+ ${t}`),change:t=>m.yellow(`~ ${t}`),destroy:t=>m.red(`- ${t}`)},Bv=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),Fv=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),Hv=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function jr(t){let e=t.toLowerCase();return Bv.has(e)?m.green(t):Fv.has(e)?m.red(t):Hv.has(e)?m.yellow(t):t}function Gt(t,e=[]){let r=Math.max(jt(t),...e.map(jt),0),n=r+2,o=m.cyan(nt.v),s=a=>` ${a}${" ".repeat(r-jt(a))} `,i=[m.cyan(`${nt.tl}${nt.h.repeat(n)}${nt.tr}`),`${o}${m.bold(s(t))}${o}`];if(e.length){i.push(`${m.cyan(nt.ml)}${m.dim(nt.h.repeat(n))}${m.cyan(nt.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(m.cyan(`${nt.bl}${nt.h.repeat(n)}${nt.br}`)),i.join(`
2327
- `)}function ft(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(u=>u.length)),i=[];for(let u=0;u<s;u+=1)i[u]=Math.max(0,...o.map(p=>jt(p[u]??"")));let a=u=>{let p=u.map((g,S)=>{let y=g??"";return S===u.length-1?y:y+" ".repeat(Math.max(0,i[S]-jt(y)))});return r+p.join(n)},l=[];e.head&&(l.push(a(e.head.map(u=>m.bold(u)))),l.push(a(e.head.map((u,p)=>m.dim("\u2500".repeat(i[p]??jt(u)))))));for(let u of t)l.push(a(u));return l.join(`
2328
- `)}function ya(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`${Oe()?e.map(n=>ot(Ge.cyan,n)).join(`
2384
+ `}function Zv(t){let e={suite:t.name,tests:t.cases.length,failures:cp(t),cases:t.cases};return`${JSON.stringify(e,null,2)}
2385
+ `}function Xo(t,e){return e==="junit"?Xv(t):Zv(t)}var We={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"},Ee={hideCursor:"\x1B[?25l",showCursor:"\x1B[?25h",clearLine:"\x1B[2K",clearToEnd:"\x1B[0J",col0:"\r",cursorUp:t=>`\x1B[${t}A`},jr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],ot={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},dp=/\x1b\[[0-9;]*m/g;function Dt(t){return t.replace(dp,"").length}function ga(t,e){return e<=0?1:Math.max(1,Math.ceil(Dt(t)/e))}function Qv(){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 ya=Qv();function Oe(){return ya}function ba(t){ya=t}function Ne(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function st(t,e){return ya?`${t}${e}${We.reset}`:e}var m={bold:t=>st(We.bold,t),dim:t=>st(We.dim,t),red:t=>st(We.red,t),green:t=>st(We.green,t),yellow:t=>st(We.yellow,t),blue:t=>st(We.blue,t),magenta:t=>st(We.magenta,t),cyan:t=>st(We.cyan,t),grey:t=>st(We.grey,t)};var ve={success:t=>`${m.green("\u2713")} ${t}`,error:t=>`${m.red("\u2716")} ${t}`,warn:t=>`${m.yellow("\u26A0")} ${t}`,info:t=>`${m.dim("\xB7")} ${t}`,step:t=>`${m.cyan("\u25B8")} ${t}`},Wt={add:t=>m.green(`+ ${t}`),change:t=>m.yellow(`~ ${t}`),destroy:t=>m.red(`- ${t}`)},e_=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),t_=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),r_=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Dr(t){let e=t.toLowerCase();return e_.has(e)?m.green(t):t_.has(e)?m.red(t):r_.has(e)?m.yellow(t):t}function Jt(t,e=[]){let r=Math.max(Dt(t),...e.map(Dt),0),n=r+2,o=m.cyan(ot.v),s=a=>` ${a}${" ".repeat(r-Dt(a))} `,i=[m.cyan(`${ot.tl}${ot.h.repeat(n)}${ot.tr}`),`${o}${m.bold(s(t))}${o}`];if(e.length){i.push(`${m.cyan(ot.ml)}${m.dim(ot.h.repeat(n))}${m.cyan(ot.mr)}`);for(let a of e)i.push(`${o}${s(a)}${o}`)}return i.push(m.cyan(`${ot.bl}${ot.h.repeat(n)}${ot.br}`)),i.join(`
2386
+ `)}function it(t,e={}){let r=e.indent??" ",n=e.gap??" ",o=e.head?[e.head,...t]:t,s=Math.max(0,...o.map(u=>u.length)),i=[];for(let u=0;u<s;u+=1)i[u]=Math.max(0,...o.map(p=>Dt(p[u]??"")));let a=u=>{let p=u.map((g,k)=>{let b=g??"";return k===u.length-1?b:b+" ".repeat(Math.max(0,i[k]-Dt(b)))});return r+p.join(n)},l=[];e.head&&(l.push(a(e.head.map(u=>m.bold(u)))),l.push(a(e.head.map((u,p)=>m.dim("\u2500".repeat(i[p]??Dt(u)))))));for(let u of t)l.push(a(u));return l.join(`
2387
+ `)}function wa(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`${Oe()?e.map(n=>st(We.cyan,n)).join(`
2329
2388
  `):e.join(`
2330
2389
  `)}
2331
- ${m.dim(` ${t}`)}`}var st=t=>{process.stderr.write(t)};function Jo(){return Oe()&&process.stderr.isTTY===!0}function ip(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${m.dim("\u2591".repeat(e-n))}`}async function X(t,e){let r=Jo(),n=0,o;r&&(st(Ee.hideCursor),o=setInterval(()=>{st(`${Ee.col0}${Ee.clearLine}${m.magenta(Lr[n++%Lr.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&st(`${Ee.col0}${Ee.clearLine}${Ee.showCursor}`)};try{let i=await e();return s(),r&&st(`${_e.success(t)}
2332
- `),i}catch(i){throw s(),r&&st(`${_e.error(t)}
2333
- `),i}}function ba(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let l=m.magenta(Lr[e%Lr.length]),u=m.cyan(r.stage),p=r.runStatus?` ${m.dim(`(${r.runStatus})`)}`:"",g=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${t} ${m.dim("\u25B8")} ${u}${p} ${ip(r.percent)} ${g}`},s=()=>{st(`${Ee.col0}${Ee.clearLine}${o()}`),n=!0},i=()=>{n&&st(`${Ee.col0}${Ee.clearLine}`),n=!1};st(Ee.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(l){i(),st(`${l}
2334
- `),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),st(Ee.showCursor);let u=l.stage!=="failed",p=`${t} ${m.dim("\u25B8")} ${Kv(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;st(`${u?_e.success(p):_e.error(p)}
2335
- `)},stop(){clearInterval(a),i(),st(Ee.showCursor)}}}function Kv(t){return t==="completed"?m.green(t):t==="failed"?m.red(t):m.cyan(t)}function Le(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(R=>!R.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=R=>{process.stderr.write(R)},l=process.stdin,u=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${m.bold(m.cyan("?"))} ${m.bold(t)}
2390
+ ${m.dim(` ${t}`)}`}var at=t=>{process.stderr.write(t)};function Zo(){return Oe()&&process.stderr.isTTY===!0}function up(t,e=15){let r=Math.max(0,Math.min(100,t??0)),n=Math.round(r/100*e);return`${"\u2588".repeat(n)}${m.dim("\u2591".repeat(e-n))}`}async function X(t,e){let r=Zo(),n=0,o;r&&(at(Ee.hideCursor),o=setInterval(()=>{at(`${Ee.col0}${Ee.clearLine}${m.magenta(jr[n++%jr.length])} ${t}`)},80));let s=()=>{o&&clearInterval(o),r&&at(`${Ee.col0}${Ee.clearLine}${Ee.showCursor}`)};try{let i=await e();return s(),r&&at(`${ve.success(t)}
2391
+ `),i}catch(i){throw s(),r&&at(`${ve.error(t)}
2392
+ `),i}}function va(t){let e=0,r={stage:"queued"},n=!1,o=()=>{let l=m.magenta(jr[e%jr.length]),u=m.cyan(r.stage),p=r.runStatus?` ${m.dim(`(${r.runStatus})`)}`:"",g=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${t} ${m.dim("\u25B8")} ${u}${p} ${up(r.percent)} ${g}`},s=()=>{at(`${Ee.col0}${Ee.clearLine}${o()}`),n=!0},i=()=>{n&&at(`${Ee.col0}${Ee.clearLine}`),n=!1};at(Ee.hideCursor);let a=setInterval(()=>{e+=1,s()},80);return{log(l){i(),at(`${l}
2393
+ `),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),at(Ee.showCursor);let u=l.stage!=="failed",p=`${t} ${m.dim("\u25B8")} ${n_(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;at(`${u?ve.success(p):ve.error(p)}
2394
+ `)},stop(){clearInterval(a),i(),at(Ee.showCursor)}}}function n_(t){return t==="completed"?m.green(t):t==="failed"?m.red(t):m.cyan(t)}function Le(t,e,r={}){return new Promise((n,o)=>{let s=e.findIndex(x=>!x.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!e[r.defaultIndex]?.disabled?r.defaultIndex:s,a=x=>{process.stderr.write(x)},l=process.stdin,u=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${m.bold(m.cyan("?"))} ${m.bold(t)}
2336
2395
  `),a(`${m.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
2337
- `),a(Ee.hideCursor);let p=0,g=()=>{let R=process.stderr.columns??process.stdout.columns??80;p>0&&(a(Ee.cursorUp(p)),a(Ee.clearToEnd));let E=0;for(let P=0;P<e.length;P+=1){let I=e[P],D=P===i,F=D?m.cyan("\u25B6"):" ",K=I.disabled?m.grey(I.label):D?m.bold(m.cyan(I.label)):I.label,Ce=I.description?` ${m.dim(I.description)}`:"",Ie=` ${F} ${K}${Ce}`;a(`\r${Ie}
2338
- `),E+=ma(Ie,R)}p=E},S=()=>{l.removeListener("data",x),l.setRawMode?.(u??!1),l.pause(),a(Ee.showCursor)},y=R=>{let E=i;for(let P=0;P<e.length;P+=1)if(E=(E+R+e.length)%e.length,!e[E].disabled){i=E;return}},x=R=>{let E=R.toString("utf8");if(E===""||E==="q"){S(),a(`
2396
+ `),a(Ee.hideCursor);let p=0,g=()=>{let x=process.stderr.columns??process.stdout.columns??80;p>0&&(a(Ee.cursorUp(p)),a(Ee.clearToEnd));let E=0;for(let P=0;P<e.length;P+=1){let I=e[P],D=P===i,H=D?m.cyan("\u25B6"):" ",G=I.disabled?m.grey(I.label):D?m.bold(m.cyan(I.label)):I.label,xe=I.description?` ${m.dim(I.description)}`:"",qe=` ${H} ${G}${xe}`;a(`\r${qe}
2397
+ `),E+=ga(qe,x)}p=E},k=()=>{l.removeListener("data",R),l.setRawMode?.(u??!1),l.pause(),a(Ee.showCursor)},b=x=>{let E=i;for(let P=0;P<e.length;P+=1)if(E=(E+x+e.length)%e.length,!e[E].disabled){i=E;return}},R=x=>{let E=x.toString("utf8");if(E===""||E==="q"){k(),a(`
2339
2398
  `),o(new Error("aborted"));return}if(E==="\r"||E===`
2340
- `){let I=e[i];if(I.disabled)return;S(),n(I.value);return}if(E==="\x1B[A"||E==="k"){y(-1),g();return}if(E==="\x1B[B"||E==="j"){y(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",x),g()})}function Yo(t,e){return`${jr(t)}${" ".repeat(Math.max(0,e-t.length))}`}var lp=t=>new Promise(e=>setTimeout(e,t));function ap(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Yo(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function cp(t,e,r={}){let n=r.sink??(p=>{process.stdout.write(`${p}
2341
- `)}),o=r.sleep??lp,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,l="";for(let p of[...i].reverse())n(ap(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!r.follow)return a;let u=r.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<u;p+=1){await o(s);let g=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let S of[...g].reverse())n(ap(S)),a+=1,S.updatedAt>l&&(l=S.updatedAt)}return a}function Vv(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Yo(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function dp(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2342
- `)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(Vv(o));return r(`
2343
- binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function Gv(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",o=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",s=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Yo(t.severity,5)} ${Yo(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function up(t,e={}){let r=e.sink??(P=>{process.stdout.write(`${P}
2344
- `)}),n=e.sleep??lp,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:l,sleep:u,intervalMs:p,...g}=e,S=P=>{r(a?JSON.stringify(P):Gv(P))},y=await t.platformEvents({...g,limit:g.limit??100});if(y.length===0&&!s)return r("logs: no events matched."),0;let x=0,R="";for(let P of[...y].reverse())S(P),x+=1,P.ts>R&&(R=P.ts);if(!s)return x;let E=i??Number.POSITIVE_INFINITY;for(let P=0;P<E;P+=1){await n(o);let I=await t.platformEvents({...g,...R?{after:R,since:void 0}:{},limit:200});for(let D of[...I].reverse())S(D),x+=1,D.ts>R&&(R=D.ts)}return x}var pp=new Set(["committed","failed","rolled_back","cancelled"]),Rn=t=>{process.stdout.write(`${t}
2345
- `)},Wv=t=>new Promise(e=>setTimeout(e,t));function Jv(t){return t==null?"\u2014":t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}m${Math.round(t%6e4/1e3)}s`}function hp(t){let e=t.startedAt??"not started",r=t.outcome&&t.outcome!==t.state?` ${t.outcome}`:"",n=t.scheduleId?" (scheduled)":"";return` ${t.runId} ${t.state.padEnd(11)} ${e} ${Jv(t.durationMs)}${n}${r}`}function Yv(t){if(t.trigger.kind!=="scheduled")return"manual";let e=t.trigger.timezone?` ${t.trigger.timezone}`:"",r=t.trigger.status&&t.trigger.status!=="active"?` (${t.trigger.status})`:"";return`scheduled ${t.trigger.cron??"?"}${e}${r}`}function mp(t,e=Rn){if(t.length===0){e("No processes are deployed on this instance."),e("Author one with `turbobase ext new process` and ship it with `turbobase ext deploy`.");return}for(let r of t){if(e(`${r.id}${r.enabled?"":" [off]"}`),e(` trigger: ${Yv(r)}`),r.runs.length===0)e(" never run");else for(let n of r.runs)e(hp(n));e("")}e(`${t.length} process(es).`)}function fp(t,e,r=Rn){if(r(t),e.length===0){r(" no runs yet.");return}for(let n of e)r(hp(n));r(`
2346
- ${e.length} run(s).`)}function Xo(t,e=Rn){let r=t.run?.runId??t.runId??"(unknown run)",n=t.run?.processId??t.processId??"",o=t.run?.state??t.state??"",s=t.run?.reason??t.reason??null,i=t.run?.outstanding??t.outstanding??null;e(`${r} ${o}${n?` ${n}`:""}`),s&&e(` ${s}`),i!==null&&i>0&&e(` ${i} still outstanding`);let a=t.steps??[];if(a.length===0){e(" no steps recorded yet.");return}for(let l of a){let u=l.externalId??l.pgRowId??"\u2014",p=l.refusal?.message?` ${l.refusal.message}`:"";e(` ${String(l.sequence).padStart(3)} ${l.stepId.padEnd(16)} ${l.disposition.padEnd(12)} ${l.recordType}/${u}${p}`)}}async function gp(t,e,r={}){let n=r.sink??Rn,o=r.sleep??Wv,s=r.intervalMs??2e3,i=r.maxPolls??Number.POSITIVE_INFINITY,a=new Set,l=p=>{let g=[];Xo(p,S=>g.push(S));for(let S of g)a.has(S)||(a.add(S),n(S));return p.run?.state??p.state??""},u=l(await t.processRun(e));if(!r.follow)return u;for(let p=0;p<i;p+=1){if(pp.has(u))return u;await o(s),u=l(await t.processRun(e))}return pp.has(u)?u:null}function yp(t,e){let r;try{r=JSON.parse(t)}catch(n){return{ok:!1,message:`${e} must be valid JSON: ${n instanceof Error?n.message:String(n)}`}}return typeof r!="object"||r===null||Array.isArray(r)?{ok:!1,message:`${e} must be a JSON object (the process input), e.g. '{"customerId":"42"}'.`}:{ok:!0,input:r}}function bp(t,e,r,n=Rn){let o=t.runId??"(unknown run)",s=`${r} logs --process-run ${o} --follow`;if(t.error==="sync_budget_exceeded"){n(`${o} still running ${t.processId??e}`),n(" It did not settle within the instance's synchronous budget. It has not failed \u2014 it is still going."),n(` Watch it: ${s}`);return}if(t.steps!==void 0){Xo(t,n);return}n(`${o} ${t.state??"queued"} ${t.processId??e}`),n(` Watch it: ${s}`)}Zo();Ko();function vp(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 kp=9,$n=" ".repeat(2+kp);function Dr(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,kp-t.length))}function t_(t,e,r){return t===1?e:r}function Tp(t){return t?m.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function xp(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function r_(t){if(!t)return[];let e=[],r=t.addedGrants??[],n=t.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];e.push(`content ${s.join(" ")}`)}let o=t.setRestrictions??{};for(let s of Object.keys(o).sort())e.push(`${s} \u2192 ${xp(o[s]??[])}`);return e}function _p(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:m.dim(`${$n}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=t.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())e.push({stream:"out",text:m.dim(`${$n}adopted ${s} ${xp(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...t.keptRemovedCapabilities??[],...t.scopeChanges?.keptRemovedGrants??[]];o.length>0&&e.push({stream:"out",text:m.dim(`${$n}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:m.dim(`${$n}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:m.yellow(`${$n}! ${s}`)});return e}function Rp(t){return(t.warnings?.length??0)>0||(t.keptRemovedCapabilities?.length??0)>0||(t.scopeChanges?.keptRemovedGrants?.length??0)>0||(t.scopeChanges?.keptAdminRestrictions?.length??0)>0}function Sp(t){return Rp(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function n_(t,e,r){let n=r==="applied",o=r_(t.scopeChanges),s=n?Tp(t.holdersRestamped):"",i=l=>{let u=[...l,...o];return u.length>0?` ${m.dim(u.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${Dr("ERROR",m.bold)}${e} \u2014 ${t.message??"cannot be created"}`},..._p(t)];let a;if(t.action==="create"){let l=t.addCapabilities?.length??0;a=` ${Dr(n?"created":"create")}${e}${i([`${l} ${t_(l,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let l=(t.addCapabilities??[]).map(u=>`+${u}`).join(", ");a=` ${Dr(n?"updated":"add")}${e}${i([l])}${s}`}else t.action==="update_scopes"?a=` ${Dr(n?"updated":"update")}${e}${o.length>0?i([]):` ${m.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${Dr("ok",m.dim)}${e} ${m.dim("already up to date")}`:a=` ${Dr(n?"changed":"change")}${e}${i([])} ${m.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},..._p(t)]}function o_(t,e){let r=[];for(let n of t){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=e==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${m.dim(o)}${e==="applied"?Tp(n.holdersRestamped):""}`})}return r}function $p(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(u=>u.action!=="noop"||Sp(u)),o=o_(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:m.bold(e==="preview"?"roles (preview \u2014 not applied)":"roles")}],i=n.length>0?Math.max(...n.map(u=>u.name.length)):0;for(let u of n)s.push(...n_(u,u.name.padEnd(i),e));s.push(...o);let a=n.some(u=>s_.has(u.action)),l=n.every(u=>u.action==="noop");if(a){let u=e==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":e==="preview"?" nothing was created \u2014 promoting this preview applies them.":" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.";s.push({stream:"out",text:m.dim(u)})}else if(o.length===0&&l&&n.some(u=>Sp(u))){let u=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",p=n.some(g=>Rp(g))?"each note above recurs on every deploy until the manifest or the role is changed.":"the adopted values were already on the roles.";s.push({stream:"out",text:m.dim(` ${u} \u2014 ${p}`)})}return s}var s_=new Set(["create","add_capabilities","update_scopes"]);function wa(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:m.yellow(`! ${o}`)},{stream:"out",text:m.dim(` ${s}`)}];if(r.length===0){let o='"roles": [] retires the content values this app added to roles on an earlier deploy.';return e===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(t.retired)?t.retired.some(s=>(s.removedGrants?.length??0)>0)?[]:[{stream:"out",text:""},{stream:"out",text:m.dim(' "roles": [] \u2014 no content value this app added is on a role, so a deploy retires nothing.')}]:n(o,"this instance's plan does not list them \u2014 read the roles section the deploy prints.")}return e===null&&r.some(o=>o.scopes!==void 0&&o.scopes!==null)?n("a declared role carries scopes, but no app was named \u2014 pass --app <slug> (or --as app:<slug>).","without it this plan cannot tell this app's earlier declarations from another app's: a scope another deploy declared on the same role is not planned (the deploy decides it, and may refuse), and content values the deploy would retire are not listed."):[]}function Ep(t){let e=t.roles;return Array.isArray(e)?{verdicts:e,retired:t.rolesRetired??[]}:e&&typeof e=="object"?{verdicts:e.verdicts??[],retired:e.retired??t.rolesRetired??[]}:{verdicts:[],retired:t.rolesRetired??[]}}var va=".github/workflows/turbobase-release-deploy.yml",i_=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2399
+ `){let I=e[i];if(I.disabled)return;k(),n(I.value);return}if(E==="\x1B[A"||E==="k"){b(-1),g();return}if(E==="\x1B[B"||E==="j"){b(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",R),g()})}function Qo(t,e){return`${Dr(t)}${" ".repeat(Math.max(0,e-t.length))}`}var hp=t=>new Promise(e=>setTimeout(e,t));function pp(t){let e=t.toRecordType?`${t.toSource}/${t.toRecordType}`:t.toSource,r=t.reason?` reason="${t.reason}"`:"",n=t.fromExternalId?` ext=${t.fromExternalId}`:"",o=t.toMasterTable&&t.toMasterRowId?` master=${t.toMasterTable}/${t.toMasterRowId}`:"";return`[${t.updatedAt}] ${Qo(t.state,9)} ${t.conduitId} \u2192 ${e}${n} hop=${t.hop}${o}${r}`}async function mp(t,e,r={}){let n=r.sink??(p=>{process.stdout.write(`${p}
2400
+ `)}),o=r.sleep??hp,s=r.intervalMs??2e3,i=await t.conduitEvents(e,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${e}.`),0;let a=0,l="";for(let p of[...i].reverse())n(pp(p)),a+=1,p.updatedAt>l&&(l=p.updatedAt);if(!r.follow)return a;let u=r.maxPolls??Number.POSITIVE_INFINITY;for(let p=0;p<u;p+=1){await o(s);let g=await t.conduitEvents(e,{since:l||void 0,limit:200});for(let k of[...g].reverse())n(pp(k)),a+=1,k.updatedAt>l&&(l=k.updatedAt)}return a}function o_(t){let e=t.externalId??"\u2014",r=t.createdByConduit?` via=${t.createdByConduit}`:"",n=t.lastError?` last_error="${t.lastError}"`:"";return`${t.id} ${Qo(t.writeStatus,9)} ${t.sourceSystem}/${e} role=${t.role} master=${t.masterTable}/${t.masterRowId}${r}${n}`}async function fp(t,e={}){let r=e.sink??(o=>{process.stdout.write(`${o}
2401
+ `)});if(e.retry){let o=await t.retryBinding(e.retry);return r(`binding: re-enqueued fan-out for ${o.id} \u2192 ${o.sourceSystem} (master ${o.masterTable}/${o.masterRowId}).`),{mode:"retry",id:o.id,retried:o.retried}}let n=await t.bindings({status:e.status,limit:e.limit});if(n.length===0)return r(e.status?`binding: no bindings with write_status='${e.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(o_(o));return r(`
2402
+ binding: ${n.length} binding(s)${e.status?` (write_status='${e.status}')`:""}.`),{mode:"list",count:n.length}}function s_(t){let e=Object.entries(t.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[t.sourceSystem,t.recordType,t.subjectId].filter(Boolean).join("/"),n=t.occurrences>1?` x${t.occurrences}`:"",o=t.redaction?.length?` redacted=[${t.redaction.join(",")}]`:"",s=t.correlationId?` corr=${t.correlationId}`:"";return`[${t.ts}] ${Qo(t.severity,5)} ${Qo(t.outcome,8)} ${t.code}${n}${r?` ${r}`:""}${s}${e?` ${e}`:""}${o}`}async function gp(t,e={}){let r=e.sink??(P=>{process.stdout.write(`${P}
2403
+ `)}),n=e.sleep??hp,o=e.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:l,sleep:u,intervalMs:p,...g}=e,k=P=>{r(a?JSON.stringify(P):s_(P))},b=await t.platformEvents({...g,limit:g.limit??100});if(b.length===0&&!s)return r("logs: no events matched."),0;let R=0,x="";for(let P of[...b].reverse())k(P),R+=1,P.ts>x&&(x=P.ts);if(!s)return R;let E=i??Number.POSITIVE_INFINITY;for(let P=0;P<E;P+=1){await n(o);let I=await t.platformEvents({...g,...x?{after:x,since:void 0}:{},limit:200});for(let D of[...I].reverse())k(D),R+=1,D.ts>x&&(x=D.ts)}return R}var yp=new Set(["committed","failed","rolled_back","cancelled"]),$n=t=>{process.stdout.write(`${t}
2404
+ `)},i_=t=>new Promise(e=>setTimeout(e,t));function a_(t){return t==null?"\u2014":t<1e3?`${t}ms`:t<6e4?`${(t/1e3).toFixed(1)}s`:`${Math.floor(t/6e4)}m${Math.round(t%6e4/1e3)}s`}function bp(t){let e=t.startedAt??"not started",r=t.outcome&&t.outcome!==t.state?` ${t.outcome}`:"",n=t.scheduleId?" (scheduled)":"";return` ${t.runId} ${t.state.padEnd(11)} ${e} ${a_(t.durationMs)}${n}${r}`}function l_(t){if(t.trigger.kind!=="scheduled")return"manual";let e=t.trigger.timezone?` ${t.trigger.timezone}`:"",r=t.trigger.status&&t.trigger.status!=="active"?` (${t.trigger.status})`:"";return`scheduled ${t.trigger.cron??"?"}${e}${r}`}function wp(t,e=$n){if(t.length===0){e("No processes are deployed on this instance."),e("Author one with `turbobase ext new process` and ship it with `turbobase ext deploy`.");return}for(let r of t){if(e(`${r.id}${r.enabled?"":" [off]"}`),e(` trigger: ${l_(r)}`),r.runs.length===0)e(" never run");else for(let n of r.runs)e(bp(n));e("")}e(`${t.length} process(es).`)}function vp(t,e,r=$n){if(r(t),e.length===0){r(" no runs yet.");return}for(let n of e)r(bp(n));r(`
2405
+ ${e.length} run(s).`)}function es(t,e=$n){let r=t.run?.runId??t.runId??"(unknown run)",n=t.run?.processId??t.processId??"",o=t.run?.state??t.state??"",s=t.run?.reason??t.reason??null,i=t.run?.outstanding??t.outstanding??null;e(`${r} ${o}${n?` ${n}`:""}`),s&&e(` ${s}`),i!==null&&i>0&&e(` ${i} still outstanding`);let a=t.steps??[];if(a.length===0){e(" no steps recorded yet.");return}for(let l of a){let u=l.externalId??l.pgRowId??"\u2014",p=l.refusal?.message?` ${l.refusal.message}`:"";e(` ${String(l.sequence).padStart(3)} ${l.stepId.padEnd(16)} ${l.disposition.padEnd(12)} ${l.recordType}/${u}${p}`)}}async function _p(t,e,r={}){let n=r.sink??$n,o=r.sleep??i_,s=r.intervalMs??2e3,i=r.maxPolls??Number.POSITIVE_INFINITY,a=new Set,l=p=>{let g=[];es(p,k=>g.push(k));for(let k of g)a.has(k)||(a.add(k),n(k));return p.run?.state??p.state??""},u=l(await t.processRun(e));if(!r.follow)return u;for(let p=0;p<i;p+=1){if(yp.has(u))return u;await o(s),u=l(await t.processRun(e))}return yp.has(u)?u:null}function Sp(t,e){let r;try{r=JSON.parse(t)}catch(n){return{ok:!1,message:`${e} must be valid JSON: ${n instanceof Error?n.message:String(n)}`}}return typeof r!="object"||r===null||Array.isArray(r)?{ok:!1,message:`${e} must be a JSON object (the process input), e.g. '{"customerId":"42"}'.`}:{ok:!0,input:r}}function kp(t,e,r,n=$n){let o=t.runId??"(unknown run)",s=`${r} logs --process-run ${o} --follow`;if(t.error==="sync_budget_exceeded"){n(`${o} still running ${t.processId??e}`),n(" It did not settle within the instance's synchronous budget. It has not failed \u2014 it is still going."),n(` Watch it: ${s}`);return}if(t.steps!==void 0){es(t,n);return}n(`${o} ${t.state??"queued"} ${t.processId??e}`),n(` Watch it: ${s}`)}ts();Wo();function Rp(t,e={}){if(t.learningIngestError)return{level:"warn",message:`warning: learning ingest was not queued (${t.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`};if(t.learningIngestTaskId){let r=typeof e.recordedSourceRev=="number"?e.recordedSourceRev:null,n=r??t.learningSourceRev;return n===null?{level:"warn",message:"warning: this app has no pushed source, so the ingest has nothing to read. The findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT ingested \u2014 deploy uploads the built bundle, `apps push` records the markdown. Run `turbobase apps push <app> .`, then deploy again."}:typeof n=="number"?r===null&&e.localDocsModifiedAt&&t.learningSourceAt&&e.localDocsModifiedAt.getTime()>Date.parse(t.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${t.learningIngestTaskId}), but it reads source rev ${n} and your standing markdown has changed since that push. Those findings will NOT be ingested. Run \`turbobase apps push <app> .\`, then deploy again.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}) \u2014 reading source rev ${n}.`}:{level:"info",message:`learning ingest queued (task ${t.learningIngestTaskId}).`}}return null}var Ep=9,En=" ".repeat(2+Ep);function Ur(t,e=r=>r){return e(t)+" ".repeat(Math.max(1,Ep-t.length))}function h_(t,e,r){return t===1?e:r}function Pp(t){return t?m.dim(` (${t} holder${t===1?"":"s"} re-stamped)`):""}function Ap(t){return t.length>0?`[${t.join(", ")}]`:"unrestricted"}function m_(t){if(!t)return[];let e=[],r=t.addedGrants??[],n=t.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];e.push(`content ${s.join(" ")}`)}let o=t.setRestrictions??{};for(let s of Object.keys(o).sort())e.push(`${s} \u2192 ${Ap(o[s]??[])}`);return e}function xp(t){let e=[],r=t.scopeChanges?.adoptedGrants??[];r.length>0&&e.push({stream:"out",text:m.dim(`${En}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=t.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())e.push({stream:"out",text:m.dim(`${En}adopted ${s} ${Ap(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...t.keptRemovedCapabilities??[],...t.scopeChanges?.keptRemovedGrants??[]];o.length>0&&e.push({stream:"out",text:m.dim(`${En}kept (admin removed): ${o.join(", ")}`)});for(let s of t.scopeChanges?.keptAdminRestrictions??[])e.push({stream:"out",text:m.dim(`${En}kept admin value for ${s}`)});for(let s of t.warnings??[])e.push({stream:"out",text:m.yellow(`${En}! ${s}`)});return e}function Cp(t){return(t.warnings?.length??0)>0||(t.keptRemovedCapabilities?.length??0)>0||(t.scopeChanges?.keptRemovedGrants?.length??0)>0||(t.scopeChanges?.keptAdminRestrictions?.length??0)>0}function $p(t){return Cp(t)||(t.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(t.scopeChanges?.adoptedRestrictions??{}).length>0}function f_(t,e,r){let n=r==="applied",o=m_(t.scopeChanges),s=n?Pp(t.holdersRestamped):"",i=l=>{let u=[...l,...o];return u.length>0?` ${m.dim(u.join(" "))}`:""};if(t.action==="error")return[{stream:"err",text:` ${Ur("ERROR",m.bold)}${e} \u2014 ${t.message??"cannot be created"}`},...xp(t)];let a;if(t.action==="create"){let l=t.addCapabilities?.length??0;a=` ${Ur(n?"created":"create")}${e}${i([`${l} ${h_(l,"capability","capabilities")}`])}${s}`}else if(t.action==="add_capabilities"){let l=(t.addCapabilities??[]).map(u=>`+${u}`).join(", ");a=` ${Ur(n?"updated":"add")}${e}${i([l])}${s}`}else t.action==="update_scopes"?a=` ${Ur(n?"updated":"update")}${e}${o.length>0?i([]):` ${m.dim("scopes changed")}`}${s}`:t.action==="noop"?a=` ${Ur("ok",m.dim)}${e} ${m.dim("already up to date")}`:a=` ${Ur(n?"changed":"change")}${e}${i([])} ${m.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...xp(t)]}function g_(t,e){let r=[];for(let n of t){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=e==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${m.dim(o)}${e==="applied"?Pp(n.holdersRestamped):""}`})}return r}function Ip(t){let{mode:e}=t,r=t.verdicts??[],n=e==="plan"?r:r.filter(u=>u.action!=="noop"||$p(u)),o=g_(t.retired??[],e);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:m.bold(e==="preview"?"roles (preview \u2014 not applied)":"roles")}],i=n.length>0?Math.max(...n.map(u=>u.name.length)):0;for(let u of n)s.push(...f_(u,u.name.padEnd(i),e));s.push(...o);let a=n.some(u=>y_.has(u.action)),l=n.every(u=>u.action==="noop");if(a){let u=e==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":e==="preview"?" nothing was created \u2014 promoting this preview applies them.":" assign these in Admin \u2192 Users \u2014 a declared role has no holders until you do.";s.push({stream:"out",text:m.dim(u)})}else if(o.length===0&&l&&n.some(u=>$p(u))){let u=e==="applied"?"no role changed":e==="preview"?"no role would change on promote":"no role would change",p=n.some(g=>Cp(g))?"each note above recurs on every deploy until the manifest or the role is changed.":"the adopted values were already on the roles.";s.push({stream:"out",text:m.dim(` ${u} \u2014 ${p}`)})}return s}var y_=new Set(["create","add_capabilities","update_scopes"]);function _a(t){let{app:e,roles:r}=t;if(r===null)return[];let n=(o,s)=>[{stream:"out",text:""},{stream:"out",text:m.yellow(`! ${o}`)},{stream:"out",text:m.dim(` ${s}`)}];if(r.length===0){let o='"roles": [] retires the content values this app added to roles on an earlier deploy.';return e===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(t.retired)?t.retired.some(s=>(s.removedGrants?.length??0)>0)?[]:[{stream:"out",text:""},{stream:"out",text:m.dim(' "roles": [] \u2014 no content value this app added is on a role, so a deploy retires nothing.')}]:n(o,"this instance's plan does not list them \u2014 read the roles section the deploy prints.")}return e===null&&r.some(o=>o.scopes!==void 0&&o.scopes!==null)?n("a declared role carries scopes, but no app was named \u2014 pass --app <slug> (or --as app:<slug>).","without it this plan cannot tell this app's earlier declarations from another app's: a scope another deploy declared on the same role is not planned (the deploy decides it, and may refuse), and content values the deploy would retire are not listed."):[]}function Op(t){let e=t.roles;return Array.isArray(e)?{verdicts:e,retired:t.rolesRetired??[]}:e&&typeof e=="object"?{verdicts:e.verdicts??[],retired:e.retired??t.rolesRetired??[]}:{verdicts:[],retired:t.rolesRetired??[]}}var Sa=".github/workflows/turbobase-release-deploy.yml",b_=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2347
2406
  # Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
2348
2407
  #
2349
2408
  # Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
@@ -2445,7 +2504,7 @@ jobs:
2445
2504
  --ref "\${{ github.sha }}" \\
2446
2505
  --project . \\
2447
2506
  --follow
2448
- `,a_=".github/workflows/turbobase-app-deploy.yml",l_=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2507
+ `,w_=".github/workflows/turbobase-app-deploy.yml",v_=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
2449
2508
  # Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
2450
2509
  #
2451
2510
  # What ships from this repo, and when:
@@ -2665,14 +2724,14 @@ jobs:
2665
2724
  else
2666
2725
  echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
2667
2726
  fi
2668
- `;function Pp(){return[{path:va,content:i_}]}function Ap(){return[{path:a_,content:l_}]}Zo();var c_=[".mcp.json"];function Op(t,e=c_){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2727
+ `;function Np(){return[{path:Sa,content:b_}]}function Lp(){return[{path:w_,content:v_}]}ts();var __=[".mcp.json"];function Up(t,e=__){let r=i=>i.replace(/^\//,""),n=new Set(t.split(`
2669
2728
  `).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),o=e.filter(i=>!n.has(r(i)));return o.length===0?null:`${t===""||t.endsWith(`
2670
2729
  `)?t:`${t}
2671
2730
  `}
2672
2731
  # Added by the Turbobase scaffold.
2673
2732
  ${o.join(`
2674
2733
  `)}
2675
- `}var d_=`# Turbobase Extensions \u2014 extension project
2734
+ `}var S_=`# Turbobase Extensions \u2014 extension project
2676
2735
 
2677
2736
  This directory authors **Turbobase extensions** (hooks today; conduits later)
2678
2737
  against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
@@ -2741,8 +2800,8 @@ order is the signal, and it is the part the product team reads first.
2741
2800
 
2742
2801
  Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
2743
2802
  updating a test. It is checked into the repo so the whole team sees it.
2744
- `,u_=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)+`
2745
- `;function p_(t){return`---
2803
+ `,k_=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)+`
2804
+ `;function T_(t){return`---
2746
2805
  name: generate-types
2747
2806
  description: Regenerate ${t} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
2748
2807
  ---
@@ -2753,7 +2812,7 @@ write \`${t}\`. Import the generated record interfaces for typed rows.
2753
2812
 
2754
2813
  The OpenAPI half is cookie-session-gated, so a headless run with a stored token
2755
2814
  degrades to record shapes only and says so \u2014 that is expected, not a failure.
2756
- `}var h_=`---
2815
+ `}var R_=`---
2757
2816
  name: mock-test
2758
2817
  description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
2759
2818
  ---
@@ -2762,7 +2821,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
2762
2821
  self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
2763
2822
  against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
2764
2823
  fixture for each branch (a passing record and a rejecting record).
2765
- `,m_=`---
2824
+ `,x_=`---
2766
2825
  name: deploy
2767
2826
  description: Deploy a hook to your instance. Use only after mock-test is green.
2768
2827
  ---
@@ -2770,7 +2829,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
2770
2829
  Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
2771
2830
  /v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
2772
2831
  the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
2773
- `;function f_(t){return`# ${t} \u2014 Turbobase app
2832
+ `;function $_(t){return`# ${t} \u2014 Turbobase app
2774
2833
 
2775
2834
  This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
2776
2835
  same-origin by the instance at \`/a/${t}\`. The \`turbobase\` CLI ships it; you
@@ -2791,6 +2850,11 @@ Ground first, code second \u2014 the instance already knows this business.
2791
2850
  - \`search_documentation\` / \`read_document\` (authoring MCP) \u2014 the published
2792
2851
  knowledge base: how this business runs its processes. For a CUSTOM record
2793
2852
  the KB + \`search_catalog\`/\`explain_object\` are the only spec that exists.
2853
+ - \`search_turbobase_docs\` / \`read_turbobase_doc\` (both MCPs) \u2014 Turbobase's
2854
+ own documentation, as the instance's release shipped it. Platform questions
2855
+ go here ("how do I read the mirror", "what does a hook receive") rather than
2856
+ to the pair above, which reads what this BUSINESS wrote. No web access
2857
+ needed, and the answer matches the version you are building against.
2794
2858
  - \`list_records\` / \`get_record\` (data MCP) \u2014 real rows, through the signed-in
2795
2859
  user's row-level security. What you can't see here, the app can't see either.
2796
2860
 
@@ -2873,10 +2937,15 @@ remove, and leaves it alone. A human takes it with
2873
2937
  \`turbobase ext deploy --to prod --prune\`.
2874
2938
 
2875
2939
  That default exists because this repo may not yet declare everything already
2876
- running on your instance \u2014 hooks somebody deployed by hand, a schedule set up in
2877
- the console. An automatic prune would delete them on the first merge. Run
2878
- \`turbobase ext export\` to pull the instance's current config down into this repo,
2879
- and once it is the whole truth, add \`--prune\` to the workflow.
2940
+ running on your instance \u2014 a hook somebody deployed by hand, a promoted field, a
2941
+ mirrored table, a recurring job an earlier deploy wrote. An automatic prune would
2942
+ delete them on the first merge. Run \`turbobase ext export\` to pull the instance's
2943
+ current config down into this repo, and once it is the whole truth, add
2944
+ \`--prune\` to the workflow.
2945
+
2946
+ A recurring job somebody created in the app is the exception: it is not in the
2947
+ export and a prune cannot remove it, so it is never yours to lose. Delete one on
2948
+ the Scheduled tasks page instead.
2880
2949
 
2881
2950
  ### Guardrails: you DECLARE, an admin GRANTS
2882
2951
 
@@ -3133,7 +3202,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
3133
3202
  review, so what you write reaches the knowledge base and the product team instead
3134
3203
  of evaporating at the end of the session. Keep the section headings exactly as
3135
3204
  they are \u2014 the ingest finds entries by heading, not by filename.
3136
- `}var Ur="customer",fr="email",g_="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",y_=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
3205
+ `}var Mr="customer",gr="email",E_="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",P_=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
3137
3206
  //
3138
3207
  // It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
3139
3208
  // the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
@@ -3152,8 +3221,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
3152
3221
  // Pure and credentials-free: no secrets, no network, no Node builtins, one
3153
3222
  // concern per file, nothing factored into a shared module (the sandbox fences
3154
3223
  // every import except the SDK).
3155
- `;function b_(){let t=$t("hook",{recordType:Ur,event:"before_save",template:"enforce-format",field:fr,regex:g_,id:`app:${Ur}:${fr}-format`,description:`Reject a ${Ur} write whose ${fr} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:Ur,event:"before_save",payload:r},expect:n},null,2)+`
3156
- `;return[{path:t.relativePath,content:`${y_}${t.content}`},{path:`samples/${Ur}.${fr}-ok.json`,content:e({company_name:"Acme Supply",[fr]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${Ur}.${fr}-malformed.json`,content:e({company_name:"Acme Supply",[fr]:"ada-at-example"},"reject","a malformed address is rejected")}]}var w_="---\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",v_=`---
3224
+ `;function A_(){let t=Et("hook",{recordType:Mr,event:"before_save",template:"enforce-format",field:gr,regex:E_,id:`app:${Mr}:${gr}-format`,description:`Reject a ${Mr} write whose ${gr} is not an address.`}),e=(r,n,o)=>JSON.stringify({name:o,context:{recordType:Mr,event:"before_save",payload:r},expect:n},null,2)+`
3225
+ `;return[{path:t.relativePath,content:`${P_}${t.content}`},{path:`samples/${Mr}.${gr}-ok.json`,content:e({company_name:"Acme Supply",[gr]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${Mr}.${gr}-malformed.json`,content:e({company_name:"Acme Supply",[gr]:"ada-at-example"},"reject","a malformed address is rejected")}]}var C_="---\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",I_=`---
3157
3226
  name: ship-app
3158
3227
  description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
3159
3228
  ---
@@ -3196,7 +3265,7 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
3196
3265
  non-text, so images and fonts belong in the build pipeline or object storage, not
3197
3266
  the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
3198
3267
  project root and DO travel \u2014 deploy reads them.
3199
- `,__=`---
3268
+ `,O_=`---
3200
3269
  name: business-rule-to-hook
3201
3270
  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.
3202
3271
  ---
@@ -3264,7 +3333,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
3264
3333
  standing rules for every agent on the instance \u2014 see the record-learning skill.
3265
3334
  A rule enforced in code and nowhere written down gets re-litigated by the next
3266
3335
  person.
3267
- `,S_="---\nname: write-a-process\ndescription: Write, deploy and run a Turbobase process (defineProcess) \u2014 a chain of record writes, or an eachRow migration that moves many records. Use whenever you create or change a file under processes/, call POST /v1/processes/:id, or debug a process run.\n---\n\nThe contract is the published guide \u2014 read it before writing one:\n`https://docs.turbobase.io/extending/writing-processes/`, and for moving data\nbetween connected systems `https://docs.turbobase.io/extending/migrating-between-systems/`.\nStart from its **A migration recipe** section for any `eachRow` process.\n\nCheck these before you conclude the platform is wrong:\n\n1. **Instance version.** `update` steps, `ctx.row` in a deployed process,\n slices that queue themselves and `{ kind: 'process' }` schedules all need\n **v1.38.0** or later. On an older instance an `update` step CREATES a row.\n2. **Changing a row = `update:` on the step**, e.g.\n `update: { pgRowId: (ctx) => ctx.row.pg_row_id }`, with `pg_row_id` in the\n `outstanding` select. `build` returns `{ parent, lines? }` only \u2014 an id\n returned from `build` is ignored and the step creates.\n3. **The first `id: '\u2026'` in the file must be the process id**, as a literal.\n `ext deploy` stores the file under that string and refuses it with\n `extension_id_mismatch` when the module defines another id \u2014 fix the file,\n do not rename the deploy. `(replaced existing)` in its output means an\n existing copy was replaced, and the line names the id it used.\n4. **The invoke body IS the input** \u2014 no `{ input: \u2026 }` envelope.\n5. **A run continues itself.** Invoke once (async); it queues its own next\n slice. For unattended runs use a `{ kind: 'process' }` entry in\n `turbobase/schedules.json`. From a terminal, `turbobase processes invoke\n <id> --input '<json>'` starts one (an administrator's `extensions:deploy`\n token; the run writes as that person). A process cannot start a process.\n6. **`outstanding` is read once per slice**, and must stop returning a row once\n it is done \u2014 otherwise update steps re-run every slice.\n7. **NetSuite transaction creates need `lines`** (`ATOMIC_WRITE_REQUIRED`).\n On `write_settle_conflict` the record EXISTS upstream: never re-save it; the\n id is on `record_write_state.external_id`. Link the row to it with\n `turbobase data settle <recordType> <pgRowId>`\n (`POST /v1/data/<recordType>/settle`).\n8. **Undo a finished run with `turbobase processes rollback <runId>`** \u2014 it\n deletes only records that run created (never one an `update` step changed),\n paced by its own rollback cap rather than the customer delete cap. Until\n every source delete is sent, the run's `reason` says so.\n";function k_(t){return`---
3336
+ `,N_="---\nname: write-a-process\ndescription: Write, deploy and run a Turbobase process (defineProcess) \u2014 a chain of record writes, or an eachRow migration that moves many records. Use whenever you create or change a file under processes/, call POST /v1/processes/:id, or debug a process run.\n---\n\nThe contract is the published guide \u2014 read it before writing one:\n`https://docs.turbobase.io/extending/writing-processes/`, and for moving data\nbetween connected systems `https://docs.turbobase.io/extending/migrating-between-systems/`.\nStart from its **A migration recipe** section for any `eachRow` process.\n\nCheck these before you conclude the platform is wrong:\n\n1. **Instance version.** `update` steps, `ctx.row` in a deployed process,\n slices that queue themselves and `{ kind: 'process' }` schedules all need\n **v1.38.0** or later. On an older instance an `update` step CREATES a row.\n2. **Changing a row = `update:` on the step**, e.g.\n `update: { pgRowId: (ctx) => ctx.row.pg_row_id }`, with `pg_row_id` in the\n `outstanding` select. `build` returns `{ parent, lines? }` only \u2014 an id\n returned from `build` is ignored and the step creates.\n3. **The first `id: '\u2026'` in the file must be the process id**, as a literal.\n `ext deploy` stores the file under that string and refuses it with\n `extension_id_mismatch` when the module defines another id \u2014 fix the file,\n do not rename the deploy. `(replaced existing)` in its output means an\n existing copy was replaced, and the line names the id it used.\n4. **The invoke body IS the input** \u2014 no `{ input: \u2026 }` envelope.\n5. **A run continues itself.** Invoke once (async); it queues its own next\n slice. For unattended runs use a `{ kind: 'process' }` entry in\n `turbobase/schedules.json`. From a terminal, `turbobase processes invoke\n <id> --input '<json>'` starts one (an administrator's `extensions:deploy`\n token; the run writes as that person). A process cannot start a process.\n6. **`outstanding` is read once per slice**, and must stop returning a row once\n it is done \u2014 otherwise update steps re-run every slice.\n7. **NetSuite transaction creates need `lines`** (`ATOMIC_WRITE_REQUIRED`).\n On `write_settle_conflict` the record EXISTS upstream: never re-save it; the\n id is on `record_write_state.external_id`. Link the row to it with\n `turbobase data settle <recordType> <pgRowId>`\n (`POST /v1/data/<recordType>/settle`).\n8. **Undo a finished run with `turbobase processes rollback <runId>`** \u2014 it\n deletes only records that run created (never one an `update` step changed),\n paced by its own rollback cap rather than the customer delete cap. Until\n every source delete is sent, the run's `reason` says so.\n";function L_(t){return`---
3268
3337
  name: record-learning
3269
3338
  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.
3270
3339
  ---
@@ -3319,7 +3388,7 @@ earlier claim" and still publish.
3319
3388
 
3320
3389
  Do not reword the three headings. The deploy-side ingest recognises entries by
3321
3390
  heading, not by filename, so a renamed section is a finding nobody receives.
3322
- `}function T_(t){return`# What this instance's source system actually does
3391
+ `}function j_(t){return`# What this instance's source system actually does
3323
3392
 
3324
3393
  Findings from ${t?`building the ${t.slug} app against the live mirror`:"authoring extensions against the live instance"}.
3325
3394
  Written for the knowledge base, and **everything here is verified against real
@@ -3450,7 +3519,7 @@ finding has not been handed to the knowledge base yet.
3450
3519
  and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
3451
3520
  already live, which is worth reading before adding another rule. -->
3452
3521
 
3453
- `}function x_(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3522
+ `}function D_(t){return`# Feedback for the Turbobase team \u2014 what ${t?`building the ${t.slug} app`:"authoring extensions here"} actually hit
3454
3523
 
3455
3524
  Everything below cost time or produced a wrong result. Not speculation, and not
3456
3525
  a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
@@ -3530,7 +3599,7 @@ Expected / happened / cost / fix.
3530
3599
  and what it would replace. These are the highest-signal entries in the file:
3531
3600
  each one is a page downloading rows to fold that it could have asked for
3532
3601
  folded. -->
3533
- `}function R_(t,e){let r=e?`
3602
+ `}function U_(t,e){let r=e?`
3534
3603
  # INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
3535
3604
  # --records focus a previous run stamped into the file, so a refresh never
3536
3605
  # narrows what an agent deliberately widened.
@@ -3561,8 +3630,8 @@ ${r}
3561
3630
  # surface unticked items at the start of a session.
3562
3631
  turbobase project adopt -o ADOPT.md >/dev/null \\
3563
3632
  || echo "turbobase: \\\`turbobase project adopt\\\` failed (its error is above) \u2014 ADOPT.md was NOT refreshed." >&2
3564
- `}var Np="Turbobase consultant",$_="turbobase-consultant",E_=`---
3565
- name: ${Np}
3633
+ `}var Mp="Turbobase consultant",M_="turbobase-consultant",q_=`---
3634
+ name: ${Mp}
3566
3635
  description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
3567
3636
  keep-coding-instructions: true
3568
3637
  ---
@@ -3635,8 +3704,8 @@ exists on purpose.
3635
3704
  - Do not show a stack trace. Say what broke and what you are doing about it.
3636
3705
  - Do not apologise repeatedly or pad with "great question".
3637
3706
  - Do not use a table when a sentence works.
3638
- `,P_=JSON.stringify({outputStyle:Np,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)+`
3639
- `,A_=`#!/usr/bin/env bash
3707
+ `,z_=JSON.stringify({outputStyle:Mp,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)+`
3708
+ `,B_=`#!/usr/bin/env bash
3640
3709
  # PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
3641
3710
  #
3642
3711
  # Advisory only: exits 0 always, and adds a note for the agent when the edited
@@ -3653,7 +3722,7 @@ set -uo pipefail
3653
3722
  command -v node >/dev/null 2>&1 || exit 0
3654
3723
 
3655
3724
  exec node "$(dirname "$0")/check-rule-placement.mjs"
3656
- `,C_=String.raw`/**
3725
+ `,F_=String.raw`/**
3657
3726
  * Is the file that was just edited enforcing a business rule inside the SPA?
3658
3727
  *
3659
3728
  * Reads the PostToolUse payload on stdin, and when BOTH signals are present —
@@ -3722,7 +3791,7 @@ process.stdout.write(
3722
3791
  },
3723
3792
  }),
3724
3793
  );
3725
- `,I_=`---
3794
+ `,H_=`---
3726
3795
  name: roles-and-permissions
3727
3796
  description: Decide who can open a screen and who can change a record \u2014 declare roles (and their scopes \u2014 row restrictions and Slack channel content grants) in public/turbobase.json, gate the UI on capabilities, and turn a denial into a message that names the role to ask for. Use when adding a screen, a nav item, a write button, a role, a scope, a screen that reads Slack history, or answering "who can see/do X".
3728
3797
  ---
@@ -3955,7 +4024,7 @@ a denial look like emptiness.
3955
4024
  - Does every write catch \`TurbobasePermissionError\`?
3956
4025
  - Did you run \`turbobase apps plan . --app <slug>\`?
3957
4026
  - Did you tell the user their administrator still has to ASSIGN the role?
3958
- `,O_=`---
4027
+ `,K_=`---
3959
4028
  name: app-design
3960
4029
  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.
3961
4030
  ---
@@ -4050,7 +4119,7 @@ The design system covers the look. Two rules it does not:
4050
4119
  Load it in the browser and check: does it render with ZERO rows, with ONE row,
4051
4120
  and with several hundred? Does it survive the query failing? Does tab reach every
4052
4121
  control, with a visible focus ring? A green \`npm run build\` proves none of these.
4053
- `,Qo="",Cp=String.raw`{
4122
+ `,rs="",jp=String.raw`{
4054
4123
  "_comment": [
4055
4124
  "Declarative sync config — part of this repo's desired state.",
4056
4125
  " turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
@@ -4072,7 +4141,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
4072
4141
  "fields": [],
4073
4142
  "tables": []
4074
4143
  }
4075
- `,Ip=String.raw`{
4144
+ `,Dp=String.raw`{
4076
4145
  "_comment": [
4077
4146
  "Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
4078
4147
  "Removing an entry does NOT remove the schedule unless you pass --prune.",
@@ -4088,57 +4157,57 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
4088
4157
  ],
4089
4158
  "schedules": []
4090
4159
  }
4091
- `,N_=t=>`node_modules/
4160
+ `,V_=t=>`node_modules/
4092
4161
 
4093
4162
  # Holds a live personal access token (written by \`turbobase ${t?"apps":"project"} init\`).
4094
4163
  .mcp.json
4095
4164
 
4096
4165
  .DS_Store
4097
- `;function _a(t={}){let e=u_.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:N_(r)},{path:"INSTANCE-LEARNINGS.md",content:T_(o)},{path:"TURBOBASE-FEEDBACK.md",content:x_(o)},{path:".claude/settings.json",content:P_},{path:`.claude/output-styles/${$_}.md`,content:E_},{path:".claude/skills/generate-types/SKILL.md",content:p_(n)},{path:".claude/skills/record-learning/SKILL.md",content:k_(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:__},{path:".claude/skills/write-a-process/SKILL.md",content:S_},{path:".claude/hooks/session-start-refresh-types.sh",content:R_(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:A_,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:C_}];return r?[{path:"CLAUDE.md",content:f_(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:w_},{path:".claude/skills/ship-app/SKILL.md",content:v_},{path:".claude/skills/app-design/SKILL.md",content:O_},{path:".claude/skills/roles-and-permissions/SKILL.md",content:I_},...b_(),{path:"conduits/.gitkeep",content:Qo},{path:"turbobase/sync.json",content:Cp},{path:"turbobase/schedules.json",content:Ip},...Ap()]:[{path:"CLAUDE.md",content:d_},...s,{path:".claude/skills/mock-test/SKILL.md",content:h_},{path:".claude/skills/deploy/SKILL.md",content:m_},{path:"hooks/.gitkeep",content:Qo},{path:"conduits/.gitkeep",content:Qo},{path:"samples/.gitkeep",content:Qo},{path:"turbobase/sync.json",content:Cp},{path:"turbobase/schedules.json",content:Ip}]}import{promises as ka}from"node:fs";import{dirname as L_,join as gt,resolve as Mp}from"node:path";function jp(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var En="bundle.json",es="turbobase";function Dp(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=l=>Array.isArray(l)?l:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return Sa(a)}function Sa(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(Lp)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(Lp)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function Lp(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Up(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 rs="hooks",ns="conduits",qp="processes",Wt="turbobase/sync.json",Jt="turbobase/schedules.json";function Ta(t){let e=u=>{let p=new RegExp(`${u}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return p?p[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let u=e("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:u,extensionKind:"process"}:null}if(r){let u=e("on"),p=e("source");return!s||!i||!u||!p?null:{id:s,recordType:i,event:u,source:p,extensionKind:"conduit"}}let a=e("event"),l=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:l,extensionKind:"hook"}}function xa(t,e){if(!t||typeof t!="object")return null;let r=t;if(r.error!=="extension_id_mismatch")return null;let n=String(r.claimed??""),o=String(r.definitionId??"");return`${e?`${e}: `:""}refused (extension_id_mismatch) \u2014 the first \`id:\` literal in the file is '${n}', but the module defines '${o}'. Nothing was deployed.
4166
+ `;function ka(t={}){let e=k_.replace(/__BASE_URL__/g,t.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,t.token??"tb_pat_\u2026"),r=!!t.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:t.appSlug}:void 0,s=[{path:".mcp.json",content:e,mode:384},{path:".gitignore",content:V_(r)},{path:"INSTANCE-LEARNINGS.md",content:j_(o)},{path:"TURBOBASE-FEEDBACK.md",content:D_(o)},{path:".claude/settings.json",content:z_},{path:`.claude/output-styles/${M_}.md`,content:q_},{path:".claude/skills/generate-types/SKILL.md",content:T_(n)},{path:".claude/skills/record-learning/SKILL.md",content:L_(o)},{path:".claude/skills/business-rule-to-hook/SKILL.md",content:O_},{path:".claude/skills/write-a-process/SKILL.md",content:N_},{path:".claude/hooks/session-start-refresh-types.sh",content:U_(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:B_,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:F_}];return r?[{path:"CLAUDE.md",content:$_(t.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:C_},{path:".claude/skills/ship-app/SKILL.md",content:I_},{path:".claude/skills/app-design/SKILL.md",content:K_},{path:".claude/skills/roles-and-permissions/SKILL.md",content:H_},...A_(),{path:"conduits/.gitkeep",content:rs},{path:"turbobase/sync.json",content:jp},{path:"turbobase/schedules.json",content:Dp},...Lp()]:[{path:"CLAUDE.md",content:S_},...s,{path:".claude/skills/mock-test/SKILL.md",content:R_},{path:".claude/skills/deploy/SKILL.md",content:x_},{path:"hooks/.gitkeep",content:rs},{path:"conduits/.gitkeep",content:rs},{path:"samples/.gitkeep",content:rs},{path:"turbobase/sync.json",content:jp},{path:"turbobase/schedules.json",content:Dp}]}import{promises as Ra}from"node:fs";import{dirname as G_,join as yt,resolve as Hp}from"node:path";function zp(t){return{version:1,...t?{tenant:t}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var Pn="bundle.json",ns="turbobase";function Bp(t){let e;try{e=JSON.parse(t)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`)}if(typeof e!="object"||e===null||Array.isArray(e))throw new Error("bundle.json must be a JSON object");let r=e,n=typeof r.version=="number"?r.version:0;if(n!==1)throw new Error(`bundle.json version ${n} is unsupported (expected 1)`);let o=l=>Array.isArray(l)?l:[],s=r.sync??{},i=r.guardrails??{},a={version:1,...typeof r.tenant=="string"?{tenant:r.tenant}:{},hooks:o(r.hooks),conduits:o(r.conduits),sync:{fields:o(s.fields),tables:o(s.tables)},guardrails:{validationHooks:o(i.validationHooks),fieldRules:o(i.fieldRules),conduits:o(i.conduits)},schedules:o(r.schedules)};return Ta(a)}function Ta(t){let e=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...t.tenant?{tenant:t.tenant}:{},hooks:[...t.hooks].sort(e(r=>r.id)),conduits:[...t.conduits].sort(e(r=>r.id)),sync:{fields:[...t.sync.fields].sort(e(qp)),tables:[...t.sync.tables].sort(e(r=>r.sourceRecordType))},guardrails:{validationHooks:[...t.guardrails.validationHooks].sort(),fieldRules:[...t.guardrails.fieldRules].sort(e(qp)),conduits:[...t.guardrails.conduits].sort(e(r=>r.conduitId))},schedules:[...t.schedules].sort(e(r=>r.name))}}function qp(t){return`${t.sourceSystem}::${t.recordType}::${t.fieldName}`}function Fp(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 ss="hooks",is="conduits",Kp="processes",Yt="turbobase/sync.json",Xt="turbobase/schedules.json";function xa(t){let e=u=>{let p=new RegExp(`${u}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return p?p[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(t),n=/\bdefineProcess\s*[<(]/.test(t),o=/\bdefineHook\s*[<(]/.test(t);if(!r&&!o&&!n)return null;let s=e("id"),i=e("recordType");if(n){let u=e("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:u,extensionKind:"process"}:null}if(r){let u=e("on"),p=e("source");return!s||!i||!u||!p?null:{id:s,recordType:i,event:u,source:p,extensionKind:"conduit"}}let a=e("event"),l=e("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:l,extensionKind:"hook"}}function $a(t,e){if(!t||typeof t!="object")return null;let r=t;if(r.error!=="extension_id_mismatch")return null;let n=String(r.claimed??""),o=String(r.definitionId??"");return`${e?`${e}: `:""}refused (extension_id_mismatch) \u2014 the first \`id:\` literal in the file is '${n}', but the module defines '${o}'. Nothing was deployed.
4098
4167
  The deploy is stored under the first \`id:\` literal, and the runtime serves the module's own id, so the two have to agree.
4099
- Fix: write \`id: '${o}'\` as a string literal on the define call, and make sure no comment, constant, step or inlined helper above it carries an \`id:\` literal.`}function zp(t){return t==="written"?"new":t==="duplicate"?"replaced existing":t}function Ra(t){return/\bdefineProcess\s*[<(]/.test(t)?"could not read a quoted id \u2014 is it a defineProcess({...}) file? A process binds to no single record type; its steps carry their own.":/\bdefineConduit\s*[<(]/.test(t)?"could not read id / on / from.source / from.recordType \u2014 is it a defineConduit({...}) file?":"could not read id / recordType / event \u2014 is it a defineHook({...}) file?"}async function Pn(t){let e;try{e=await ka.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await Pn(gt(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function ts(t,e){let r;try{r=await ka.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 j_(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function D_(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function U_(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 Bp(t=process.cwd()){let e=Mp(t),[r,n,o]=await Promise.all([Pn(gt(e,rs)),Pn(gt(e,ns)),Pn(gt(e,qp))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([ts(gt(e,Wt),Wt).catch(()=>{}),ts(gt(e,Jt),Jt).catch(()=>{})]);return s!==void 0||i!==void 0}async function Fp(t=process.cwd(),e={}){let r=Mp(t),n=jp(e.tenant),o=[],s=[];for(let l of[rs,ns,qp])for(let u of await Pn(gt(r,l))){let p=`${l}/${u}`,g=await ka.readFile(gt(r,l,u),"utf8"),S=e.inline?await e.inline(g,L_(gt(r,l,u))):g,y=Ta(S);if(!y){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(S)&&s.push({file:p,reason:Ra(S)});continue}let x={id:y.id,kind:y.extensionKind,recordType:y.recordType,event:y.event,source:y.source,sourceCode:S};y.extensionKind==="conduit"?n.conduits.push(x):n.hooks.push(x),o.push(p)}let i=await ts(gt(r,Wt),Wt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Wt} must be a JSON object with "fields" and/or "tables".`);let l=i;for(let u of Array.isArray(l.fields)?l.fields:[])n.sync.fields.push(j_(u));for(let u of Array.isArray(l.tables)?l.tables:[])n.sync.tables.push(D_(u));o.push(Wt)}let a=await ts(gt(r,Jt),Jt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Jt} must be a JSON array, or an object with a "schedules" array.`);for(let u of l)n.schedules.push(U_(u));o.push(Jt)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:Sa(n),contributed:o,unparsed:s}}import{promises as Pa}from"node:fs";import{resolve as H_}from"node:path";var M_="For app developers \u2014 adopt these";function Hp(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 Kp(t,e){let r=Hp(t),n=Hp(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let o=0;o<3;o++){let s=(r.core[o]??0)-(n.core[o]??0);if(s!==0)return s}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function q_(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var uO=q_(M_);vn();mt();var z_=t=>new Promise(e=>setTimeout(e,t));function Vp(t){return t.stage==="completed"||t.stage==="failed"}function B_(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function F_(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
4100
- `))r(i)}return n}async function $a(t,e={}){let r=e.sink??(S=>{process.stdout.write(`${S}
4101
- `)}),n=e.sleep??z_,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(S=>r(B_(S))),a=e.onPoll,l="",u="",p=S=>{a?.(S),S.stage!==u&&i(S),l=F_(S,l,r),u=S.stage},g=await t();if(p(g),Vp(g))return g;for(let S=0;S<s;S+=1)if(await n(o),g=await t(),p(g),Vp(g))return g;return g}var b=t=>{process.stdout.write(`${t}
4102
- `)},L=t=>{process.stderr.write(`${t}
4103
- `)};function v(t){L(m.red(`turbobase: ${t}`)),process.exit(1)}var Mr=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Gp(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&ga(!1)}async function z(t){let e=await ht(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await Lt();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";v(`not signed in to ${rt(t)}.${n} Run \`turbobase auth login --base-url ${rt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne())try{let n=await Le("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await Uo(n);let o=await ht();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}v(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function V(t,e,r){if(!(t instanceof Y)||t.status!==403)return;t.body?.error==="approval_required"&&v(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),v(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Ea(t,e,r){let n=r?Number(r):void 0;if(Jo()){let s=ba(e),i;try{i=await $a(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),v(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await $a(t,{sink:b,intervalMs:n})}catch(s){v(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&v(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),b(`${e} ${o.stage}.`)}var K_=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function V_(t){try{let e=await Pa.readFile(t,"utf8");return K_.exec(e)?.[1]??null}catch{return null}}var G_=/GENERATED by `turbobase project adopt`/,Jp=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,W_=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Wp(t){let e=[],r=null;for(let n of t.split(`
4104
- `)){let o=Jp.exec(n);if(o){r={version:o[1],items:[]},e.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let s=W_.exec(n);if(s){let a=s[2].trim();r.items.push({key:a.replace(/\s+/g," "),done:s[1]!==" ",text:a,extra:[]});continue}let i=r.items[r.items.length-1];i&&n.trim()!==""&&i.extra.push(n)}return e}function J_(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
4168
+ Fix: write \`id: '${o}'\` as a string literal on the define call, and make sure no comment, constant, step or inlined helper above it carries an \`id:\` literal.`}function Vp(t){return t==="written"?"new":t==="duplicate"?"replaced existing":t}function Ea(t){return/\bdefineProcess\s*[<(]/.test(t)?"could not read a quoted id \u2014 is it a defineProcess({...}) file? A process binds to no single record type; its steps carry their own.":/\bdefineConduit\s*[<(]/.test(t)?"could not read id / on / from.source / from.recordType \u2014 is it a defineConduit({...}) file?":"could not read id / recordType / event \u2014 is it a defineHook({...}) file?"}async function An(t){let e;try{e=await Ra.readdir(t,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of e){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await An(yt(t,n.name)))r.push(`${n.name}/${o}`);continue}n.name.endsWith(".ts")&&(n.name.endsWith(".test.ts")||n.name.endsWith(".d.ts")||r.push(n.name))}return r.sort()}async function os(t,e){let r;try{r=await Ra.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 W_(t){return{sourceSystem:String(t.sourceSystem??""),recordType:String(t.recordType??""),fieldName:String(t.fieldName??""),owningSide:t.owningSide==="pg"?"pg":"source",caseSensitive:!!t.caseSensitive}}function J_(t){return{sourceRecordType:String(t.sourceRecordType??""),kind:String(t.kind??""),sourceSystem:String(t.sourceSystem??"")}}function Y_(t){let e={name:String(t.name??""),scheduleKind:String(t.scheduleKind??"cron"),scheduleExpr:String(t.scheduleExpr??""),scheduleTz:String(t.scheduleTz??"UTC"),body:t.body??{}};return typeof t.status=="string"&&(e.status=t.status),e}async function Gp(t=process.cwd()){let e=Hp(t),[r,n,o]=await Promise.all([An(yt(e,ss)),An(yt(e,is)),An(yt(e,Kp))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([os(yt(e,Yt),Yt).catch(()=>{}),os(yt(e,Xt),Xt).catch(()=>{})]);return s!==void 0||i!==void 0}async function Wp(t=process.cwd(),e={}){let r=Hp(t),n=zp(e.tenant),o=[],s=[];for(let l of[ss,is,Kp])for(let u of await An(yt(r,l))){let p=`${l}/${u}`,g=await Ra.readFile(yt(r,l,u),"utf8"),k=e.inline?await e.inline(g,G_(yt(r,l,u))):g,b=xa(k);if(!b){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(k)&&s.push({file:p,reason:Ea(k)});continue}let R={id:b.id,kind:b.extensionKind,recordType:b.recordType,event:b.event,source:b.source,sourceCode:k};b.extensionKind==="conduit"?n.conduits.push(R):n.hooks.push(R),o.push(p)}let i=await os(yt(r,Yt),Yt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Yt} 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(W_(u));for(let u of Array.isArray(l.tables)?l.tables:[])n.sync.tables.push(J_(u));o.push(Yt)}let a=await os(yt(r,Xt),Xt);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${Xt} must be a JSON array, or an object with a "schedules" array.`);for(let u of l)n.schedules.push(Y_(u));o.push(Xt)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:Ta(n),contributed:o,unparsed:s}}import{promises as Ca}from"node:fs";import{resolve as rS}from"node:path";var X_="For app developers \u2014 adopt these";function Jp(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 Yp(t,e){let r=Jp(t),n=Jp(e);if(!r&&!n)return 0;if(!r)return-1;if(!n)return 1;for(let o=0;o<3;o++){let s=(r.core[o]??0)-(n.core[o]??0);if(s!==0)return s}return r.prerelease===n.prerelease?0:r.prerelease?n.prerelease?r.prerelease<n.prerelease?-1:1:-1:1}function Z_(t){return t.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var kO=Z_(X_);_n();gt();var Q_=t=>new Promise(e=>setTimeout(e,t));function Xp(t){return t.stage==="completed"||t.stage==="failed"}function eS(t){return`[${t.stage}] ${t.percent}%${t.runStatus?` (${t.runStatus})`:""}`}function tS(t,e,r){let n=t.outputTail??"";if(n&&n!==e){let s=(n.startsWith(e)?n.slice(e.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
4169
+ `))r(i)}return n}async function Pa(t,e={}){let r=e.sink??(k=>{process.stdout.write(`${k}
4170
+ `)}),n=e.sleep??Q_,o=e.intervalMs??2e3,s=e.maxPolls??Number.POSITIVE_INFINITY,i=e.onStage??(k=>r(eS(k))),a=e.onPoll,l="",u="",p=k=>{a?.(k),k.stage!==u&&i(k),l=tS(k,l,r),u=k.stage},g=await t();if(p(g),Xp(g))return g;for(let k=0;k<s;k+=1)if(await n(o),g=await t(),p(g),Xp(g))return g;return g}var y=t=>{process.stdout.write(`${t}
4171
+ `)},O=t=>{process.stderr.write(`${t}
4172
+ `)};function v(t){O(m.red(`turbobase: ${t}`)),process.exit(1)}var qr=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function Zp(t,e){let r=e.json===!0||typeof e.reporter=="string";(t.color===!1||r)&&ba(!1)}async function B(t){let e=await ft(t);if(e)return{baseUrl:e.baseUrl,token:e.token};let r=await jt();if(t){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";v(`not signed in to ${nt(t)}.${n} Run \`turbobase auth login --base-url ${nt(t)} --token tb_pat_\u2026\`.`)}if(r.length===0&&v("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne())try{let n=await Le("Multiple instances stored \u2014 pick the active one:",r.map(s=>({value:s.baseUrl,label:s.baseUrl,description:`updated ${s.updatedAt}`})));await zo(n);let o=await ft();if(o)return{baseUrl:o.baseUrl,token:o.token}}catch{}v(`multiple instances stored (${r.map(n=>n.baseUrl).join(", ")}) and no active default. Run \`turbobase auth use <base-url>\` to pick one, or pass --base-url.`)}function V(t,e,r){if(!(t instanceof Y)||t.status!==403)return;t.body?.error==="approval_required"&&v(`${r} denied (403): an approval-gated deploy needs a recorded approval \u2014 pass --approved-by <email>.`),v(`${r} forbidden (403) \u2014 the stored PAT lacks the '${e}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Aa(t,e,r){let n=r?Number(r):void 0;if(Zo()){let s=va(e),i;try{i=await Pa(t,{intervalMs:n,sink:a=>s.log(a),onStage:()=>{},onPoll:a=>s.status({stage:a.stage,percent:a.percent??void 0,runStatus:a.runStatus??void 0})})}catch(a){s.stop(),v(`${e} --follow failed: ${a instanceof Error?a.message:String(a)}`)}s.done({stage:i.stage,percent:i.percent??void 0,runStatus:i.runStatus??void 0}),i.stage==="failed"&&process.exit(1);return}let o;try{o=await Pa(t,{sink:y,intervalMs:n})}catch(s){v(`${e} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&v(`${e} failed${o.runStatus?` (${o.runStatus})`:""}.`),y(`${e} ${o.stage}.`)}var nS=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function oS(t){try{let e=await Ca.readFile(t,"utf8");return nS.exec(e)?.[1]??null}catch{return null}}var sS=/GENERATED by `turbobase project adopt`/,eh=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,iS=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function Qp(t){let e=[],r=null;for(let n of t.split(`
4173
+ `)){let o=eh.exec(n);if(o){r={version:o[1],items:[]},e.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let s=iS.exec(n);if(s){let a=s[2].trim();r.items.push({key:a.replace(/\s+/g," "),done:s[1]!==" ",text:a,extra:[]});continue}let i=r.items[r.items.length-1];i&&n.trim()!==""&&i.extra.push(n)}return e}function aS(t){let e=t.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
4105
4174
  `)).join(`
4106
4175
  `);return`## v${t.version}
4107
4176
 
4108
- ${e}`}function Y_(t,e){let r=Wp(t);if(r.length===0&&!G_.test(t))return null;let n=new Map(r.map(p=>[p.version,p])),o=[],s=0;for(let p of Wp(e)){let g=n.get(p.version);n.delete(p.version);let S=new Set(p.items.map(x=>x.key)),y=p.items.map(x=>{let R=g?.items.find(E=>E.key===x.key);return R?{...x,done:R.done,extra:R.extra}:x});for(let x of g?.items??[])S.has(x.key)||x.done||(y.push(x),s+=1);o.push({version:p.version,items:y})}for(let p of n.values()){let g=p.items.filter(S=>!S.done);g.length!==0&&(s+=g.length,o.push({version:p.version,items:g}))}o.sort((p,g)=>Kp(g.version,p.version));let i=e.split(`
4109
- `),a=i.findIndex(p=>Jp.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
4177
+ ${e}`}function lS(t,e){let r=Qp(t);if(r.length===0&&!sS.test(t))return null;let n=new Map(r.map(p=>[p.version,p])),o=[],s=0;for(let p of Qp(e)){let g=n.get(p.version);n.delete(p.version);let k=new Set(p.items.map(R=>R.key)),b=p.items.map(R=>{let x=g?.items.find(E=>E.key===R.key);return x?{...R,done:x.done,extra:x.extra}:R});for(let R of g?.items??[])k.has(R.key)||R.done||(b.push(R),s+=1);o.push({version:p.version,items:b})}for(let p of n.values()){let g=p.items.filter(k=>!k.done);g.length!==0&&(s+=g.length,o.push({version:p.version,items:g}))}o.sort((p,g)=>Yp(g.version,p.version));let i=e.split(`
4178
+ `),a=i.findIndex(p=>eh.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
4110
4179
  `).replace(/\s+$/,"");return{markdown:o.length===0?`${l}
4111
4180
  `:`${l}
4112
4181
 
4113
- ${o.map(J_).join(`
4182
+ ${o.map(aS).join(`
4114
4183
 
4115
4184
  `)}
4116
- `,carried:s}}function Yp(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 z(e.baseUrl),o=H_(process.cwd(),e.out),s=e.since?.trim()||await V_(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),l=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});l.ok||v(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let u=await l.json();if(!u.available){b(`${r} ships no release notes to adopt from (nothing written).`);return}let p=u.releases.reduce((E,P)=>E+P.items.length,0);if(p===0){b(`up to date${s?` since v${s.replace(/^v/,"")}`:""}${u.currentVersion?` (instance is on v${u.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let g=u.currentVersion??u.releases[0]?.version??"",S=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${g}. Re-run to refresh; delete this file once every line is done. -->
4117
-
4118
- `,y=await Pa.readFile(o,"utf8").catch(()=>null),x=u.markdown,R=0;if(y!==null&&y.trim()!==""){let E=Y_(y,u.markdown);E||v(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),x=E.markdown,R=E.carried}await Pa.writeFile(o,S+x,"utf8"),b(`wrote ${o} \u2014 ${p} item(s) across ${u.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${R>0?`, keeping ${R} unticked item(s) already in the file`:""}.`)})}mt();var An=["suggested_kb_edit","kb_correction"];var X_=[{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 Z_(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var TO=new Map(X_.map(t=>[Z_(t.heading),t]));var xO=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 Q_(t){return t.diff??!!t.dryRun}var eS={update_page:"append to the existing page",new_page:"create a NEW page"},Dt=(t,e)=>` ${m.dim(t.padEnd(11))}${e}`,Qp=t=>t.ownerEmail??t.ownerId;function qr(t){return!t.needsPageRef&&!t.blockedBy}var os=t=>m.green(t?` + ${t}`:" +"),tS=t=>m.red(t?` - ${t}`:" -"),gr=t=>m.dim(` ${t}`),rS=` ${m.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Aa=80;function nS(t){let e=[rS];t.target?(e.push(gr(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(tS(`visibility: ${t.target.visibility}`)),e.push(os("visibility: admin"))):e.push(gr(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(gr("title, slug, evidence: untouched")),e.push(gr("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(gr("turbobase.document \xB7 new")),e.push(os(`title: ${t.pageTitle}`)),e.push(os("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(gr('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(gr('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
4119
- `);for(let n of r.slice(0,Aa))e.push(os(n?` ${n}`:""));return r.length>Aa&&e.push(m.yellow(` \u2026 ${r.length-Aa} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function oS(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${m.bold(n.pageTitle)}`),r.push(Dt("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:m.dim("new \u2014 no existing page matches"))),r.push(Dt("action",qr(n)?eS[n.action]:m.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(Dt("unresolved",m.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(Dt("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let l=a.verdict?` ${m.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${m.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${m.dim("\xB7")} ${a.title.trim()}${u}${l}`)}),r.push(Dt("confidence",n.withdraws?m.red("WITHDRAWN from readers (text untouched)"):m.dim("untouched"))),n.supersedes&&r.push(Dt("supersedes",m.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(Dt("blocked",m.red(`unpublished work on this page belongs to ${Qp(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Dt("ambiguous",m.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(Dt("similar",m.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&qr(n)&&r.push(...nS(n)),r.push("")}),r}function sS(t){let e=u=>t.filter(u).length,r=t.reduce((u,p)=>u+p.entries.length,0),n=e(u=>u.withdraws),o=e(u=>u.blockedBy!=null),s=e(u=>u.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(qr)} page(s)`,`${e(u=>u.action==="update_page"&&qr(u))} appended`,`${e(u=>u.action==="new_page"&&qr(u))} created (unpublished)`,...s>0?[m.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?m.red(`${n} page(s) WITHDRAWN from readers`):m.dim("no page withdrawn"),l=o>0?` \xB7 ${m.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function iS(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${m.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?Qp(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let l=[...new Set((s?.entries??[]).map(u=>u.kb_page_ref?.trim()).filter(u=>!!u))];n.push(`${m.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(u=>`"${u}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${m.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?m.green("created "):m.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${m.bold(o.documentId??"?")}`+(o.created?m.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${m.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${m.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${m.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function Xp(t){if(t instanceof Y){let e=t.body;t.status===403&&e?.reason==="admin_required"&&v("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&v("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}V(t,"extensions:deploy","learnings push-kb")}async function Cn(t,e){let r;try{r=await X("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof Y&&o.status===404?L(m.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):Cu(o)?L(m.yellow(Zp(o))):L(m.yellow(`could not re-read the pushed markdown: ${Zp(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return L(m.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),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(m.yellow(`${r.parseSkipped} unparseable`)),L(m.dim(n.join(" \xB7 "))),r}function Zp(t){return t instanceof Error?t.message:String(t)}async function eh(t,e=r=>new q(r)){t.section&&!An.includes(t.section.trim())&&v(`unknown --section "${t.section}" \u2014 expected one of ${An.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await z(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await Cn(n,t.app),i;try{i=await X("reading the pending queue",()=>n.learningsPending(o))}catch(u){Xp(u),v(`could not read the pending queue: ${u instanceof Error?u.message:String(u)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){L(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}L(i.pendingTotal===0?"nothing pending \u2014 no ingested findings are waiting on a knowledge-base decision.":`nothing matched \u2014 ${i.pendingTotal} pending finding(s) exist but not under these filters.`);return}if(b(oS(i.items,{diff:Q_(t)}).join(`
4120
- `)),b(sS(i.items)),t.dryRun){L(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(qr);if(a.length===0){L(m.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let l=a.reduce((u,p)=>u+p.entries.length,0);if(!t.yes){if(!Ne()){L(m.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Le(`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 X("writing pages",()=>n.learningsPushKb(i.planToken,o));b(iS(u.applied,i.items).join(`
4121
- `))}catch(u){if(u instanceof Y&&u.status===409){L(m.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),L(`re-run \`${Mr} kb push\` to review the current plan.`),process.exitCode=2;return}Xp(u),L(m.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}mt();var zr=t=>new q(t);async function Br(t,e){let r=await z(t.baseUrl);return e(r)}async function ss(t,e,r,n){return n.yes?!0:Ne()?await Le(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(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function aS(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function th(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function lS(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${th(m.bold(s.slug),e)} ${th(aS(s),10)} ${m.dim(s.path)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function rh(t,e=zr){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Br(t,e),o;try{o=await X("reading the knowledge base",()=>n.docsList(r))}catch(s){V(s,"docs:publish","read the knowledge base"),v(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}b(lS(o).join(`
4122
- `))}async function nh(t,e,r=zr){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Br(e,r);if(!await ss(`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 X("publishing",()=>o.docsPublish(n))}catch(l){V(l,"docs:publish","publish a page"),v(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);b(m.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(L(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),L(m.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function oh(t,e,r=zr){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Br(e,r);if(!await ss(`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 X("unpublishing",()=>o.docsUnpublish(n))}catch(l){V(l,"docs:publish","unpublish a page"),v(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);b(m.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),L(m.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(L(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function sh(t,e=zr){let r=await Br(t,e),n;try{n=await X("reading the releases",()=>r.docsVersions())}catch(o){V(o,"docs:publish","read the knowledge-base releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){b("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?m.green("current"):m.dim(" ");b(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${m.dim(o.published_by)}`:""}`),o.release_note&&b(` ${m.dim(o.release_note)}`)}}async function ih(t,e,r=zr){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await Br(e,r);if(await ss(`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 X("rolling back",()=>o.docsRollback(n));b(m.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){V(i,"docs:publish","roll the knowledge base back"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function ah(t,e,r=zr){let n=(t??"").trim();n||v("name the page slug to delete. `turbobase kb list` shows them.");let o=await Br(e,r);if(await ss(`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 X("deleting",()=>o.docsDelete(n));b(m.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){V(i,"docs:publish","delete a page"),v(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}mt();function cS(t){return t.diff??!!t.dryRun}function dS(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?m.green("new rule"):m.yellow("amend rule"),i=n.targetPublished?` ${m.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${m.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${m.dim(n.description)}`);for(let a of n.entries)r.push(` ${m.dim("\xB7")} ${m.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
4123
- `))r.push(` ${m.dim("|")} ${a}`)}r.push("")}),r}function uS(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(m.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function lh(t,e=r=>new q(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await z(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await Cn(n,t.app),i;try{i=await X("reading the pending rules",()=>n.rulesPending(o))}catch(l){V(l,"extensions:deploy","read the pending rules"),v(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){L(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}L(i.pendingTotal===0?"nothing pending \u2014 no findings are waiting under `## Agent rules`.":`nothing matched \u2014 ${i.pendingTotal} pending rule finding(s) exist but not under these filters.`);return}if(b(dS(i.items,{diff:cS(t)}).join(`
4124
- `)),b(uS(i.items)),t.dryRun){L(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!Ne()){L(m.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Le(`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 X("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(l){l instanceof Y&&l.status===409&&v("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),v(`push failed: ${l instanceof Error?l.message:String(l)}`)}b(m.green(`wrote ${i.items.length} draft rule(s).`)),L(m.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as yS,readFile as bS,stat as wS}from"node:fs/promises";import{join as uh,resolve as vS}from"node:path";var Ut=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},pS=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function ch(t){let e=t.replace(/^/,""),r=pS.exec(e);if(!r)throw new Ut("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=hS(n??""),i=s.name,a=s.description;if(!i)throw new Ut("SKILL.md frontmatter is missing required `name`");if(!a)throw new Ut("SKILL.md frontmatter is missing required `description`");let l=new Set(["name","description","license","version"]),u=Object.entries(s).filter(([g])=>!l.has(g));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...u.length?{extra:Object.fromEntries(u)}:{}},body:(o??"").trim()}}function hS(t){let e={},r=t.split(/\r?\n/),n=0;for(;n<r.length;){let o=r[n]??"";if(!o.trim()||o.trim().startsWith("#")){n+=1;continue}if(/^\s/.test(o))throw new Ut(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Ut(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=fS(a),a===">"||a==="|"){let l=[];for(n+=1;n<r.length;){let u=r[n]??"";if(u.length===0||/^\s/.test(u))l.push(u.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?l.join(" "):l.join(`
4125
- `)).trim();continue}e[i]=mS(a),n+=1}return e}function mS(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function fS(t){let e=!1,r=!1;for(let n=0;n<t.length;n+=1){let o=t[n];if(o==="'"&&!r)e=!e;else if(o==='"'&&!e)r=!r;else if(o==="#"&&!e&&!r)return t.slice(0,n).trim()}return t}var gS=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function dh(t){let e=[];t.length===0&&e.push("no skill files: expected <dir>/<slug>/SKILL.md"),t.length>50&&e.push(`${t.length} skill files; at most 50 per push`);let r=new Set;for(let n of t){let o=n.slug||"(unnamed)";gS.test(n.slug??"")||e.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&e.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&e.push(`${o}: \`name\` is over 200 characters`):e.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&e.push(`${o}: \`description\` is over 1024 characters`):e.push(`${o}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),n.body?.trim()?Buffer.byteLength(n.body,"utf8")>65536&&e.push(`${o}: the body is over ${65536/1024} KB`):e.push(`${o}: the body after the frontmatter is empty`)}return e}mt();async function _S(t){let e=vS(t),r;try{r=(await yS(e)).sort()}catch{v(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=uh(e,o,"SKILL.md");if(await wS(s).then(a=>a.isFile()).catch(()=>!1))try{let a=ch(await bS(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Ut&&v(`${uh(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var is={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},SS={slug_taken:"a skill with this slug exists and was not written by this app \u2014 rename the directory",owned_by_another_app:"another app owns a skill with this slug \u2014 rename the directory"};function kS(t){let e=[];for(let r of t.items){let n=r.action==="refused"?m.red(is.refused):r.action==="unchanged"?m.dim(is.unchanged):r.action==="new"?m.green(is.new):m.yellow(is.update),o=r.targetPublished?` ${m.yellow("[currently live]")}`:"";e.push(`${n} ${m.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${m.red(SS[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${m.yellow("orphan")} ${m.bold(r)} \u2014 this app wrote it and no file names it now; left as it is (\`skills unpublish\` / \`skills delete\` to remove it)`);return e}async function ph(t,e=r=>new q(r)){t.app||v("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await _S(t.from),n=dh(r);n.length>0&&v(`nothing was sent:
4185
+ `,carried:s}}function th(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 B(e.baseUrl),o=rS(process.cwd(),e.out),s=e.since?.trim()||await oS(o),i=new URLSearchParams;s&&i.set("since",s);let a=i.toString(),l=await fetch(`${r}/v1/catalog/adopt-notes${a?`?${a}`:""}`,{headers:{Authorization:`Bearer ${n}`,Accept:"application/json"}});l.ok||v(`adopt fetch failed: GET /v1/catalog/adopt-notes \u2192 ${l.status}`);let u=await l.json();if(!u.available){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${s?` since v${s.replace(/^v/,"")}`:""}${u.currentVersion?` (instance is on v${u.currentVersion})`:""} \u2014 ${o} left untouched.`);return}let g=u.currentVersion??u.releases[0]?.version??"",k=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${g}. Re-run to refresh; delete this file once every line is done. -->
4186
+
4187
+ `,b=await Ca.readFile(o,"utf8").catch(()=>null),R=u.markdown,x=0;if(b!==null&&b.trim()!==""){let E=lS(b,u.markdown);E||v(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),R=E.markdown,x=E.carried}await Ca.writeFile(o,k+R,"utf8"),y(`wrote ${o} \u2014 ${p} item(s) across ${u.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${x>0?`, keeping ${x} unticked item(s) already in the file`:""}.`)})}gt();var Cn=["suggested_kb_edit","kb_correction"];var cS=[{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 dS(t){return t.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var jO=new Map(cS.map(t=>[dS(t.heading),t]));var DO=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 uS(t){return t.diff??!!t.dryRun}var pS={update_page:"append to the existing page",new_page:"create a NEW page"},Ut=(t,e)=>` ${m.dim(t.padEnd(11))}${e}`,oh=t=>t.ownerEmail??t.ownerId;function zr(t){return!t.needsPageRef&&!t.blockedBy}var as=t=>m.green(t?` + ${t}`:" +"),hS=t=>m.red(t?` - ${t}`:" -"),yr=t=>m.dim(` ${t}`),mS=` ${m.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Ia=80;function fS(t){let e=[mS];t.target?(e.push(yr(`turbobase.document \xB7 ${t.target.slug}`)),t.withdraws?(e.push(hS(`visibility: ${t.target.visibility}`)),e.push(as("visibility: admin"))):e.push(yr(`visibility: ${t.target.visibility} \u2014 unchanged`)),e.push(yr("title, slug, evidence: untouched")),e.push(yr("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(e.push(yr("turbobase.document \xB7 new")),e.push(as(`title: ${t.pageTitle}`)),e.push(as("visibility: admin \u2014 unpublished, outside the reader surface")),e.push(yr('filed under "From app developers" until an editor moves it'))),e.push(""),e.push(yr('appended under "## From app developers":'));let r=(t.appendedMarkdown??"").replace(/\s+$/,"").split(`
4188
+ `);for(let n of r.slice(0,Ia))e.push(as(n?` ${n}`:""));return r.length>Ia&&e.push(m.yellow(` \u2026 ${r.length-Ia} more line(s) not shown \u2014 the full text lands on the page`)),e.push(""),e}function gS(t,e={}){let r=[];return t.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${m.bold(n.pageTitle)}`),r.push(Ut("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:m.dim("new \u2014 no existing page matches"))),r.push(Ut("action",zr(n)?pS[n.action]:m.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(Ut("unresolved",m.red((a.length>0?`no page matches ${a.map(l=>`"${l}"`).join(", ")}`:"the correction names no page at all")+" \u2014 a correction needs a page to correct, so this group is SKIPPED and its findings stay pending. Fix the ref (or write the page) and re-run.")))}if(r.push(Ut("findings",`${i.length} ${i.length===1?"finding":"findings"} from ${[...new Set(i.map(a=>a.app_slug))].join(", ")}`)),i.forEach(a=>{let l=a.verdict?` ${m.dim(`\xB7 ${a.verdict}`)}`:"",u=a.kb_page_ref?` ${m.dim(`(${a.kb_page_ref})`)}`:"";r.push(` ${m.dim("\xB7")} ${a.title.trim()}${u}${l}`)}),r.push(Ut("confidence",n.withdraws?m.red("WITHDRAWN from readers (text untouched)"):m.dim("untouched"))),n.supersedes&&r.push(Ut("supersedes",m.yellow("a finding here AMENDS an earlier claim \u2014 its block is appended and marked, and nothing already on the page is reordered or removed"))),n.blockedBy&&r.push(Ut("blocked",m.red(`unpublished work on this page belongs to ${oh(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(Ut("ambiguous",m.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(Ut("similar",m.yellow(`this new page looks related to ${a.join(", ")} \u2014 nothing was merged. If they are one page, push one now and re-run: the rest will resolve onto it.`)))}e.diff&&zr(n)&&r.push(...fS(n)),r.push("")}),r}function yS(t){let e=u=>t.filter(u).length,r=t.reduce((u,p)=>u+p.entries.length,0),n=e(u=>u.withdraws),o=e(u=>u.blockedBy!=null),s=e(u=>u.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${e(zr)} page(s)`,`${e(u=>u.action==="update_page"&&zr(u))} appended`,`${e(u=>u.action==="new_page"&&zr(u))} created (unpublished)`,...s>0?[m.red(`${s} SKIPPED \u2014 correction with no page to correct`)]:[]],a=n>0?m.red(`${n} page(s) WITHDRAWN from readers`):m.dim("no page withdrawn"),l=o>0?` \xB7 ${m.red(`${o} page(s) BLOCKED by another editor`)}`:"";return`${i.join(" \xB7 ")} \xB7 ${a}${l}`}function bS(t,e){let r=new Map(e.map(o=>[o.key,o])),n=[];for(let o of t){let s=r.get(o.key),i=o.pageTitle||s?.pageTitle||o.key;if(o.skipped==="blocked_by_draft_owner"){n.push(`${m.yellow("skipped")} ${i} \u2014 unpublished work belongs to ${o.blockedBy?oh(o.blockedBy):"another editor"}; its findings stay pending`);continue}if(o.skipped==="unresolved_page_ref"){let l=[...new Set((s?.entries??[]).map(u=>u.kb_page_ref?.trim()).filter(u=>!!u))];n.push(`${m.yellow("skipped")} ${i} \u2014 `+(l.length>0?`no page matches ${l.map(u=>`"${u}"`).join(", ")}`:"the correction names no page")+"; nothing was written and its findings stay pending");continue}if(o.skipped){n.push(`${m.yellow("skipped")} ${i} \u2014 ${o.skipped.replace(/_/g," ")}`);continue}let a=o.created?m.green("created "):m.green("appended");n.push(`${a} ${i} \u2014 ${o.appliedEntryIds.length} finding(s) \u2192 page ${m.bold(o.documentId??"?")}`+(o.created?m.dim(" (unpublished)"):"")),o.confidence==="downgraded"?n.push(` ${m.red("withdrawn from readers:")} ${i}`):o.confidence==="already_withdrawn"?n.push(` ${m.dim("page was already unpublished \u2014 left as is")}`):o.confidence==="missing"&&n.push(` ${m.yellow("page vanished between plan and push \u2014 nothing withdrawn")}`)}return n}function rh(t){if(t instanceof Y){let e=t.body;t.status===403&&e?.reason==="admin_required"&&v("learnings push-kb is admin-only \u2014 the stored token belongs to a non-admin user. Ask an instance administrator to run it, or to grant the role."),t.status===404&&v("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}V(t,"extensions:deploy","learnings push-kb")}async function In(t,e){let r;try{r=await X("re-reading pushed markdown",()=>t.learningsIngest(e))}catch(o){return o instanceof Y&&o.status===404?O(m.dim("this instance ingests on deploy only \u2014 planning against the queue as it stands. If a recent edit is missing, run `turbobase apps push` then `apps deploy`.")):ju(o)?O(m.yellow(nh(o))):O(m.yellow(`could not re-read the pushed markdown: ${nh(o)} \u2014 planning anyway.`)),null}if(r.filesScanned===0)return O(m.yellow("no markdown found in this app\u2019s pushed source \u2014 nothing can be ingested. Run `turbobase apps push` (a deploy uploads the built bundle, not your .md files).")),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(m.yellow(`${r.parseSkipped} unparseable`)),O(m.dim(n.join(" \xB7 "))),r}function nh(t){return t instanceof Error?t.message:String(t)}async function sh(t,e=r=>new z(r)){t.section&&!Cn.includes(t.section.trim())&&v(`unknown --section "${t.section}" \u2014 expected one of ${Cn.join(" | ")}.`),t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await B(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.section?{section:t.section.trim()}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{}},s=await In(n,t.app),i;try{i=await X("reading the pending queue",()=>n.learningsPending(o))}catch(u){rh(u),v(`could not read the pending queue: ${u instanceof Error?u.message:String(u)}`)}if(i.items.length===0){if(i.pendingTotal===0&&s&&s.entriesDuplicate>0){O(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already dealt with. Materially reword one to file it again, or see \`--reapply\` on \`skills push\` to re-emit a rule without changing its text.`);return}O(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(gS(i.items,{diff:uS(t)}).join(`
4189
+ `)),y(yS(i.items)),t.dryRun){O(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(zr);if(a.length===0){O(m.yellow(`nothing to write \u2014 all ${i.items.length} group(s) are skipped (see the plan above): a correction with no page to correct, or a page whose unpublished work belongs to another editor. Fix the refs (or wait for the draft) and re-run; the findings stay pending.`));return}let l=a.reduce((u,p)=>u+p.entries.length,0);if(!t.yes){if(!Ne()){O(m.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Le(`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"){O("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{let u=await X("writing pages",()=>n.learningsPushKb(i.planToken,o));y(bS(u.applied,i.items).join(`
4190
+ `))}catch(u){if(u instanceof Y&&u.status===409){O(m.red("turbobase: the pending queue changed while you were reading the plan \u2014 nothing was written.")),O(`re-run \`${qr} kb push\` to review the current plan.`),process.exitCode=2;return}rh(u),O(m.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}gt();var Br=t=>new z(t);async function Fr(t,e){let r=await B(t.baseUrl);return e(r)}async function ls(t,e,r,n){return n.yes?!0:Ne()?await Le(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(O("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(O(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function wS(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function ih(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function vS(t){if(t.items.length===0)return["no pages in this knowledge base."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${ih(m.bold(s.slug),e)} ${ih(wS(s),10)} ${m.dim(s.path)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function ah(t,e=Br){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Fr(t,e),o;try{o=await X("reading the knowledge base",()=>n.docsList(r))}catch(s){V(s,"docs:publish","read the knowledge base"),v(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}y(vS(o).join(`
4191
+ `))}async function lh(t,e,r=Br){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Fr(e,r);if(!await ls(`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 X("publishing",()=>o.docsPublish(n))}catch(l){V(l,"docs:publish","publish a page"),v(`publish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.published.map(l=>l.slug);y(m.green(`published ${a.length} page(s) \u2014 readable now.`)),i.missing.length>0&&(O(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),O(m.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function ch(t,e,r=Br){let n=[...new Set(t.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Fr(e,r);if(!await ls(`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 X("unpublishing",()=>o.docsUnpublish(n))}catch(l){V(l,"docs:publish","unpublish a page"),v(`unpublish failed: ${l instanceof Error?l.message:String(l)}`)}let a=i.unpublished.map(l=>l.slug);y(m.green(`unpublished ${a.length} page(s) \u2014 retracted now.`)),O(m.dim(`re-publish with: turbobase kb publish ${a.join(" ")}`)),i.missing.length>0&&(O(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1)}async function dh(t,e=Br){let r=await Fr(t,e),n;try{n=await X("reading the releases",()=>r.docsVersions())}catch(o){V(o,"docs:publish","read the knowledge-base releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){y("no releases yet \u2014 nothing has been published.");return}for(let o of n.items){let s=o.is_current?m.green("current"):m.dim(" ");y(`v${String(o.version_no).padEnd(4)} ${s} ${o.published_at} ${o.node_count} page(s)${o.published_by?` ${m.dim(o.published_by)}`:""}`),o.release_note&&y(` ${m.dim(o.release_note)}`)}}async function uh(t,e,r=Br){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`version must be a release number (got '${t}'). \`turbobase kb versions\` lists them.`);let o=await Fr(e,r);if(await ls(`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 X("rolling back",()=>o.docsRollback(n));y(m.green(`rolled back \u2014 release v${i.version.version_no} is current.`))}catch(i){V(i,"docs:publish","roll the knowledge base back"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function ph(t,e,r=Br){let n=(t??"").trim();n||v("name the page slug to delete. `turbobase kb list` shows them.");let o=await Fr(e,r);if(await ls(`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 X("deleting",()=>o.docsDelete(n));y(m.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){V(i,"docs:publish","delete a page"),v(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}gt();function _S(t){return t.diff??!!t.dryRun}function SS(t,e){let r=[];return t.forEach((n,o)=>{let s=n.action==="new_rule"?m.green("new rule"):m.yellow("amend rule"),i=n.targetPublished?` ${m.yellow("[currently live]")}`:"";r.push(`${o+1}. ${s} ${m.bold(n.slug)}${i}`),r.push(` ${n.name}`),n.description&&r.push(` ${m.dim(n.description)}`);for(let a of n.entries)r.push(` ${m.dim("\xB7")} ${m.dim(a.app_slug)} ${a.title}`);if(e.diff){r.push("");for(let a of n.bodyMarkdown.split(`
4192
+ `))r.push(` ${m.dim("|")} ${a}`)}r.push("")}),r}function kS(t){let e=t.reduce((o,s)=>o+s.entries.length,0),r=t.filter(o=>o.targetPublished).length,n=[`${e} finding(s) \u2192 ${t.length} rule(s)`];return r>0&&n.push(m.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function hh(t,e=r=>new z(r)){t.limit!==void 0&&(!Number.isFinite(t.limit)||t.limit<1)&&v("--limit must be a positive integer.");let r=await B(t.baseUrl),n=e(r),o={...t.app?{app:t.app}:{},...t.limit!==void 0?{limit:t.limit}:{},...t.group===!1?{group:!1}:{},...t.reapply?{reapply:!0}:{}},s=await In(n,t.app),i;try{i=await X("reading the pending rules",()=>n.rulesPending(o))}catch(l){V(l,"extensions:deploy","read the pending rules"),v(`could not read the pending queue: ${l instanceof Error?l.message:String(l)}`)}if(i.items.length===0){if(i.pendingTotal===0&&!t.reapply&&s&&s.entriesDuplicate>0){O(`nothing pending \u2014 all ${s.entriesDuplicate} finding(s) in your markdown were already applied. A regroup or a cosmetic edit is the same finding by design; re-run with --reapply to re-emit them (picking up a changed \`###\` grouping), or materially reword a rule to file it as a new one.`);return}O(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(SS(i.items,{diff:_S(t)}).join(`
4193
+ `)),y(kS(i.items)),t.dryRun){O(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,u)=>l+u.entries.length,0);if(!t.yes){if(!Ne()){O(m.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes (or --dry-run to review the plan).")),process.exitCode=1;return}if(await Le(`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"){O("aborted \u2014 nothing was written."),process.exitCode=1;return}}try{await X("writing the rules",()=>n.rulesPush(i.planToken,o))}catch(l){l instanceof Y&&l.status===409&&v("the pending queue changed while you were reading the plan \u2014 nothing was written. Re-run to see the new plan."),v(`push failed: ${l instanceof Error?l.message:String(l)}`)}y(m.green(`wrote ${i.items.length} draft rule(s).`)),O(m.dim("They are DRAFT \u2014 nothing is injected yet. An admin reviews and publishes them under Settings \u203A Skills."))}import{readdir as PS,readFile as AS,stat as CS}from"node:fs/promises";import{join as gh,resolve as IS}from"node:path";var Mt=class extends Error{constructor(e){super(e),this.name="SkillParseError"}},TS=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function mh(t){let e=t.replace(/^/,""),r=TS.exec(e);if(!r)throw new Mt("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=RS(n??""),i=s.name,a=s.description;if(!i)throw new Mt("SKILL.md frontmatter is missing required `name`");if(!a)throw new Mt("SKILL.md frontmatter is missing required `description`");let l=new Set(["name","description","license","version"]),u=Object.entries(s).filter(([g])=>!l.has(g));return{frontmatter:{name:i,description:a,...s.license?{license:s.license}:{},...s.version?{version:s.version}:{},...u.length?{extra:Object.fromEntries(u)}:{}},body:(o??"").trim()}}function RS(t){let e={},r=t.split(/\r?\n/),n=0;for(;n<r.length;){let o=r[n]??"";if(!o.trim()||o.trim().startsWith("#")){n+=1;continue}if(/^\s/.test(o))throw new Mt(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Mt(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=$S(a),a===">"||a==="|"){let l=[];for(n+=1;n<r.length;){let u=r[n]??"";if(u.length===0||/^\s/.test(u))l.push(u.replace(/^\s{0,2}/,"")),n+=1;else break}e[i]=(a===">"?l.join(" "):l.join(`
4194
+ `)).trim();continue}e[i]=xS(a),n+=1}return e}function xS(t){return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function $S(t){let e=!1,r=!1;for(let n=0;n<t.length;n+=1){let o=t[n];if(o==="'"&&!r)e=!e;else if(o==='"'&&!e)r=!r;else if(o==="#"&&!e&&!r)return t.slice(0,n).trim()}return t}var ES=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function fh(t){let e=[];t.length===0&&e.push("no skill files: expected <dir>/<slug>/SKILL.md"),t.length>50&&e.push(`${t.length} skill files; at most 50 per push`);let r=new Set;for(let n of t){let o=n.slug||"(unnamed)";ES.test(n.slug??"")||e.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&e.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&e.push(`${o}: \`name\` is over 200 characters`):e.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&e.push(`${o}: \`description\` is over 1024 characters`):e.push(`${o}: frontmatter \`description\` is empty \u2014 it is what an MCP client reads to choose the skill`),n.body?.trim()?Buffer.byteLength(n.body,"utf8")>65536&&e.push(`${o}: the body is over ${65536/1024} KB`):e.push(`${o}: the body after the frontmatter is empty`)}return e}gt();async function OS(t){let e=IS(t),r;try{r=(await PS(e)).sort()}catch{v(`--from ${t}: no such directory.`)}let n=[];for(let o of r){let s=gh(e,o,"SKILL.md");if(await CS(s).then(a=>a.isFile()).catch(()=>!1))try{let a=mh(await AS(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Mt&&v(`${gh(t,o,"SKILL.md")}: ${a.message}`),a}}return n}var cs={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},NS={slug_taken:"a skill with this slug exists and was not written by this app \u2014 rename the directory",owned_by_another_app:"another app owns a skill with this slug \u2014 rename the directory"};function LS(t){let e=[];for(let r of t.items){let n=r.action==="refused"?m.red(cs.refused):r.action==="unchanged"?m.dim(cs.unchanged):r.action==="new"?m.green(cs.new):m.yellow(cs.update),o=r.targetPublished?` ${m.yellow("[currently live]")}`:"";e.push(`${n} ${m.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&e.push(` ${m.red(NS[r.reason]??r.reason)}`)}for(let r of t.orphans)e.push(`${m.yellow("orphan")} ${m.bold(r)} \u2014 this app wrote it and no file names it now; left as it is (\`skills unpublish\` / \`skills delete\` to remove it)`);return e}async function yh(t,e=r=>new z(r)){t.app||v("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await OS(t.from),n=fh(r);n.length>0&&v(`nothing was sent:
4126
4195
  ${n.join(`
4127
- `)}`);let o=await z(t.baseUrl),s=e(o),i=async S=>{try{return await X(S?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,S))}catch(y){if(V(y,"extensions:deploy","push skill files"),y instanceof Y&&y.status===404){let x=y.body;v(x?.error==="app_not_found"?String(x.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}v(`push failed: ${y instanceof Error?y.message:String(y)}`)}},a=await i(!0);b(kS(a).join(`
4128
- `));let l=a.items.filter(S=>S.action==="new"||S.action==="update").length,u=a.items.filter(S=>S.action==="refused").length;if(t.dryRun){L(m.dim("dry run \u2014 nothing was written.")),u>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!t.yes){if(!Ne()){L(m.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await Le(`Write ${l} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){L("aborted \u2014 nothing was written."),process.exitCode=1;return}}p=await i(!1)}let g=p.items.filter(S=>S.action==="new"||S.action==="update").map(S=>S.slug);if(b(`${g.length} written, ${p.items.filter(S=>S.action==="unchanged").length} unchanged, ${p.items.filter(S=>S.action==="refused").length} refused.`),t.publish&&g.length>0){let S;try{S=await X("publishing",()=>s.skillsPublish(g))}catch(y){V(y,"skills:publish","publish the pushed skills"),v(`the skills were written as drafts but publishing failed: ${y instanceof Error?y.message:String(y)}`)}b(m.green(`published ${S.published.join(", ")} \u2014 live as of release ${S.version.version_no}.`))}else t.publish?b(m.dim("nothing changed \u2014 nothing to publish.")):g.length>0&&L(m.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));p.items.some(S=>S.action==="refused")&&(L(m.red("one or more skill files were refused and not written.")),process.exitCode=1)}mt();var TS=["proposed","active","rejected"],xS=["mechanic","operator","learning","code-baseline"],as=t=>new q(t);async function ls(t,e){let r=await z(t.baseUrl);return e(r)}function hh(t,e,r){if(!t)return;let n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)e.includes(o)||v(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function RS(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&v("--limit must be a positive number."),Math.floor(e)}function gh(t){let e=hh(t.status,TS,"--status"),r=hh(t.provenance,xS,"--provenance"),n=RS(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function mh(t){return!!(t.provenance?.length||t.recordType||t.source)}var yh=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function $S(t){return t.status==="active"?m.green("active"):t.status==="rejected"?m.dim("rejected"):m.yellow("proposed")}function ES(t){return t.message?t.message:t.kind&&t.field?m.dim(`${t.kind} ${t.field}`):t.kind?m.dim(t.kind):m.dim("(no description)")}function bh(t){return[t.hookId,$S(t),t.provenance==="learning"?m.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),ES(t)]}async function wh(t={},e=as){let r=await ls(t,e),n=gh(t),o;try{o=await r.proposals(n)}catch(i){V(i,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return b(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return b(`no ${i} hook proposals.
4129
- `+m.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}b(ft(o.map(bh),{head:yh})),b(m.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let s=o.filter(i=>i.provenance==="learning"&&i.status==="proposed");s.length>0&&b(m.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function PS(t,e,r){return r.yes?!0:Ne()?await Le(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(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function AS(t){return!(t instanceof Y)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Ca(t,e){AS(t)&&V(t,"extensions:deploy",e)}function Ia(t,e){let r=e instanceof Y?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(_e.error(`${m.bold(t)} \u2014 ${s}`))}async function fh(t,e){try{let r=await t.proposalPromote(e);return b(_e.success(`${m.bold(e)} ${m.dim(`${r.previousStatus} \u2192`)} ${m.green(r.status)}`)),!0}catch(r){return Ca(r,"promote a hook proposal"),Ia(e,r),!1}}async function vh(t,e={},r=as){!e.auto&&t.length===0&&v("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&v("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&v("promote: --apply / --all only mean something with --auto.");let n=await ls(e,r);if(!e.auto){let p=0;for(let g of t)await fh(n,g)&&(p+=1);p>0&&b(m.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let o=gh({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&v("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),o.status?.some(p=>p!=="proposed")&&v("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(p){V(p,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=s.filter(p=>p.provenance==="learning"),a=s.filter(p=>p.provenance!=="learning");if(e.json&&(b(JSON.stringify({apply:!!e.apply,plan:a,skipped:i},null,2)),!e.apply))return;if(a.length===0){e.json||(b(`nothing to promote${mh(o)?" for that filter":""}.`),i.length>0&&b(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(b(e.apply?`promoting ${m.bold(String(a.length))} hook proposal(s):`:`${m.bold("dry run")} \u2014 would promote ${m.bold(String(a.length))} hook proposal(s):`),b(ft(a.map(bh),{head:yh})),i.length>0&&b(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!e.apply){b(""),b(_e.info("nothing was changed. Re-run with --apply to arm these."));return}if(!mh(o)&&!e.all&&v(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await PS(`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 fh(n,p.hookId)&&(u+=1);b(m.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 _h(t,e={},r=as){t.length===0&&v("retract: name at least one proposal id.");let n=await ls(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);b(_e.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.yellow(i.status)}`)),o+=1}catch(i){Ca(i,"retract a hook proposal"),Ia(s,i)}o>0&&b(m.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function Sh(t,e={},r=as){t.length===0&&v("reject: name at least one proposal id.");let n=await ls(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);b(_e.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.dim(i.status)}`)),o+=1}catch(i){Ca(i,"reject a hook proposal"),Ia(s,i)}o<t.length&&(process.exitCode=1)}mt();var Oa=t=>new q(t);async function CS(t,e){let r=await z(t.baseUrl);return e(r)}function IS(t){return!(t instanceof Y)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function OS(t,e){let r=e instanceof Y?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{not_found:"no extension with that id",wrong_kind:"that id is not an extension this instance manages",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);L(_e.error(`${m.bold(t)} \u2014 ${s}`))}async function Na(t,e,r,n,o,s,i){e.length===0&&v(`${t}: name at least one extension id.`);let a=await CS(r,n),l=[];for(let u of e)try{let p=await o(a,u);l.push(p),r.json||b(s(p))}catch(p){IS(p)&&V(p,"extensions:deploy",`${t} an extension`),OS(u,p)}if(r.json)b(JSON.stringify(l,null,2));else{let u=i(l.length);u&&b(m.dim(u))}l.length<e.length&&(process.exitCode=1)}async function kh(t,e={},r=Oa){await Na("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>_e.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.yellow(n.status)}`),n=>n>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function Th(t,e={},r=Oa){await Na("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>_e.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function xh(t,e={},r=Oa){await Na("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>_e.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}mt();var Fr=t=>new q(t);async function Hr(t,e){let r=await z(t.baseUrl);return e(r)}async function cs(t,e,r,n){return n.yes?!0:Ne()?await Le(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(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function NS(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function Rh(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function LS(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${Rh(m.bold(s.slug),e)} ${Rh(NS(s),10)} ${s.surfaces.join(",")||m.dim("none")}`),s.description&&r.push(` ${m.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function $h(t,e=Fr){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Hr(t,e),o;try{o=await X("reading the skills",()=>n.skillsList(r))}catch(s){V(s,"skills:publish","read the instance skills"),v(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}b(LS(o).join(`
4130
- `))}async function Eh(t,e,r=Fr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Hr(e,r);if(!await cs(`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 X("publishing",()=>o.skillsPublish(n))}catch(a){V(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),L(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Ph(t,e,r=Fr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Hr(e,r);if(!await cs(`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 X("unpublishing",()=>o.skillsUnpublish(n))}catch(a){V(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}b(m.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),L(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(L(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Ah(t,e,r=Fr){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await Hr(e,r);if(await cs(`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 X("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Ch(t,e=Fr){let r=await Hr(t,e),n;try{n=await X("reading the releases",()=>r.skillsReleases())}catch(o){V(o,"skills:publish","read the skills releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){L("no releases yet.");return}for(let o of n.items){let s=o.is_current?m.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";b(`${s} v${o.version_no} ${o.skill_count} skill(s) ${m.dim(o.published_at)}${o.published_by?m.dim(` by ${o.published_by}`):""}${m.dim(i)}`)}}async function Ih(t,e,r=Fr){let n=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await Hr(e,r);if(!await cs(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
4196
+ `)}`);let o=await B(t.baseUrl),s=e(o),i=async k=>{try{return await X(k?"reading the plan":"writing the skills",()=>s.appSkillsPush(t.app,r,k))}catch(b){if(V(b,"extensions:deploy","push skill files"),b instanceof Y&&b.status===404){let R=b.body;v(R?.error==="app_not_found"?String(R.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}v(`push failed: ${b instanceof Error?b.message:String(b)}`)}},a=await i(!0);y(LS(a).join(`
4197
+ `));let l=a.items.filter(k=>k.action==="new"||k.action==="update").length,u=a.items.filter(k=>k.action==="refused").length;if(t.dryRun){O(m.dim("dry run \u2014 nothing was written.")),u>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!t.yes){if(!Ne()){O(m.red("turbobase: refusing to write without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1;return}if(await Le(`Write ${l} skill(s)${t.publish?" and publish them":" as drafts"}?`,[{value:"yes",label:"Yes"},{value:"no",label:"No \u2014 write nothing"}],{defaultIndex:1}).catch(()=>"no")!=="yes"){O("aborted \u2014 nothing was written."),process.exitCode=1;return}}p=await i(!1)}let g=p.items.filter(k=>k.action==="new"||k.action==="update").map(k=>k.slug);if(y(`${g.length} written, ${p.items.filter(k=>k.action==="unchanged").length} unchanged, ${p.items.filter(k=>k.action==="refused").length} refused.`),t.publish&&g.length>0){let k;try{k=await X("publishing",()=>s.skillsPublish(g))}catch(b){V(b,"skills:publish","publish the pushed skills"),v(`the skills were written as drafts but publishing failed: ${b instanceof Error?b.message:String(b)}`)}y(m.green(`published ${k.published.join(", ")} \u2014 live as of release ${k.version.version_no}.`))}else t.publish?y(m.dim("nothing changed \u2014 nothing to publish.")):g.length>0&&O(m.dim("They are DRAFT \u2014 nothing is served yet. Publish with `turbobase skills publish <slug>` (needs `skills:publish`), or re-run with --publish."));p.items.some(k=>k.action==="refused")&&(O(m.red("one or more skill files were refused and not written.")),process.exitCode=1)}gt();var jS=["proposed","active","rejected"],DS=["mechanic","operator","learning","code-baseline"],ds=t=>new z(t);async function us(t,e){let r=await B(t.baseUrl);return e(r)}function bh(t,e,r){if(!t)return;let n=t.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)e.includes(o)||v(`${r}: unknown value '${o}' \u2014 expected one of ${e.join(", ")}.`);return n}}function US(t){if(t===void 0)return;let e=Number(t);return(!Number.isFinite(e)||e<=0)&&v("--limit must be a positive number."),Math.floor(e)}function _h(t){let e=bh(t.status,jS,"--status"),r=bh(t.provenance,DS,"--provenance"),n=US(t.limit);return{...e?{status:e}:{},...r?{provenance:r}:{},...t.recordType?{recordType:t.recordType}:{},...t.source?{source:t.source}:{},...n?{limit:n}:{}}}function wh(t){return!!(t.provenance?.length||t.recordType||t.source)}var Sh=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function MS(t){return t.status==="active"?m.green("active"):t.status==="rejected"?m.dim("rejected"):m.yellow("proposed")}function qS(t){return t.message?t.message:t.kind&&t.field?m.dim(`${t.kind} ${t.field}`):t.kind?m.dim(t.kind):m.dim("(no description)")}function kh(t){return[t.hookId,MS(t),t.provenance==="learning"?m.yellow(t.provenance):t.provenance,t.recordType,t.event,t.source,String(t.taughtBy.length),qS(t)]}async function Th(t={},e=ds){let r=await us(t,e),n=_h(t),o;try{o=await r.proposals(n)}catch(i){V(i,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(t.json)return y(JSON.stringify(o,null,2));if(o.length===0){let i=n.status?.length?n.status.join("/"):"proposed";return y(`no ${i} hook proposals.
4198
+ `+m.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}y(it(o.map(kh),{head:Sh})),y(m.dim(" EVIDENCE = distinct sync failures that taught the rule. Arm one with `turbobase ext proposals promote <id>`."));let s=o.filter(i=>i.provenance==="learning"&&i.status==="proposed");s.length>0&&y(m.dim(` ${s.length} learning-provenance row(s) shown \u2014 those are armed through sign-off in the console, not from here.`))}async function zS(t,e,r){return r.yes?!0:Ne()?await Le(t,[{value:"yes",label:e},{value:"no",label:"No \u2014 leave them alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(O("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(O(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function BS(t){return!(t instanceof Y)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function Oa(t,e){BS(t)&&V(t,"extensions:deploy",e)}function Na(t,e){let r=e instanceof Y?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",not_found:"no hook proposal with that id",wrong_kind:"that id is not a hook (conduits have their own review surface)",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);O(ve.error(`${m.bold(t)} \u2014 ${s}`))}async function vh(t,e){try{let r=await t.proposalPromote(e);return y(ve.success(`${m.bold(e)} ${m.dim(`${r.previousStatus} \u2192`)} ${m.green(r.status)}`)),!0}catch(r){return Oa(r,"promote a hook proposal"),Na(e,r),!1}}async function Rh(t,e={},r=ds){!e.auto&&t.length===0&&v("promote: name at least one proposal id, or pass --auto with a filter."),e.auto&&t.length>0&&v("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!e.auto&&(e.apply||e.all)&&v("promote: --apply / --all only mean something with --auto.");let n=await us(e,r);if(!e.auto){let p=0;for(let g of t)await vh(n,g)&&(p+=1);p>0&&y(m.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<t.length&&(process.exitCode=1);return}let o=_h({...e,status:e.status??"proposed"});o.provenance?.includes("learning")&&v("promote --auto: learning-provenance proposals are armed through sign-off in the console, not from the CLI. Drop `learning` from --provenance."),o.status?.some(p=>p!=="proposed")&&v("promote --auto: only `--status proposed` rows can be armed in bulk.");let s;try{s=await n.proposals(o)}catch(p){V(p,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${p instanceof Error?p.message:String(p)}`)}let i=s.filter(p=>p.provenance==="learning"),a=s.filter(p=>p.provenance!=="learning");if(e.json&&(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${wh(o)?" for that filter":""}.`),i.length>0&&y(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(e.json||(y(e.apply?`promoting ${m.bold(String(a.length))} hook proposal(s):`:`${m.bold("dry run")} \u2014 would promote ${m.bold(String(a.length))} hook proposal(s):`),y(it(a.map(kh),{head:Sh})),i.length>0&&y(m.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(!wh(o)&&!e.all&&v(`promote --auto --apply with no filter would arm all ${a.length} proposal(s) in the queue. Narrow it with --provenance / --record-type / --source, or pass --all to mean it.`),!await zS(`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 vh(n,p.hookId)&&(u+=1);y(m.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 xh(t,e={},r=ds){t.length===0&&v("retract: name at least one proposal id.");let n=await us(e,r),o=0;for(let s of t)try{let i=await n.proposalRetract(s);y(ve.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.yellow(i.status)}`)),o+=1}catch(i){Oa(i,"retract a hook proposal"),Na(s,i)}o>0&&y(m.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<t.length&&(process.exitCode=1)}async function $h(t,e={},r=ds){t.length===0&&v("reject: name at least one proposal id.");let n=await us(e,r),o=0;for(let s of t)try{let i=await n.proposalReject(s,e.reason);y(ve.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.dim(i.status)}`)),o+=1}catch(i){Oa(i,"reject a hook proposal"),Na(s,i)}o<t.length&&(process.exitCode=1)}gt();var La=t=>new z(t);async function FS(t,e){let r=await B(t.baseUrl);return e(r)}function HS(t){return!(t instanceof Y)||t.status!==403?!1:t.body?.error==="insufficient_scope"}function KS(t,e){let r=e instanceof Y?e.body:void 0,n=r?.error==="forbidden"?r.reason??r.error:r?.error,s=n?{not_found:"no extension with that id",wrong_kind:"that id is not an extension this instance manages",system_reserved:"a managed-service guardrail \u2014 contact support to adjust its feature flag",learning_requires_signoff:"learning-provenance rows are armed through sign-off in the console, not from the CLI",provenance_unverified:"the instance could not read the row back \u2014 refused rather than guessed",admin_required:"the PAT resolves to a non-admin user on this instance"}[n]??n:e instanceof Error?e.message:String(e);O(ve.error(`${m.bold(t)} \u2014 ${s}`))}async function ja(t,e,r,n,o,s,i){e.length===0&&v(`${t}: name at least one extension id.`);let a=await FS(r,n),l=[];for(let u of e)try{let p=await o(a,u);l.push(p),r.json||y(s(p))}catch(p){HS(p)&&V(p,"extensions:deploy",`${t} an extension`),KS(u,p)}if(r.json)y(JSON.stringify(l,null,2));else{let u=i(l.length);u&&y(m.dim(u))}l.length<e.length&&(process.exitCode=1)}async function Eh(t,e={},r=La){await ja("disable",t,e,r,(n,o)=>n.extensionDisable(o),n=>ve.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.yellow(n.status)}`),n=>n>0?" definition kept \u2014 the loader drops it on its next reload. Put it back with `turbobase ext enable <id>`.":null)}async function Ph(t,e={},r=La){await ja("enable",t,e,r,(n,o)=>n.extensionEnable(o),n=>ve.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.green(n.status)}`),n=>n>0?" the loader compiles it on its next reload.":null)}async function Ah(t,e={},r=La){await ja("remove",t,e,r,(n,o)=>n.extensionRemove(o),n=>ve.success(`${m.bold(n.id)} ${m.dim(`${n.previousStatus} \u2192`)} ${m.dim(n.status)}`),n=>n>0?" run history and everything it already wrote are kept. Redeploy the same id to bring it back.":null)}gt();var Hr=t=>new z(t);async function Kr(t,e){let r=await B(t.baseUrl);return e(r)}async function ps(t,e,r,n){return n.yes?!0:Ne()?await Le(t,[{value:"yes",label:e,description:r},{value:"no",label:"No \u2014 leave it alone"}],{defaultIndex:1}).catch(()=>"no")!=="yes"?(O("aborted \u2014 nothing changed."),process.exitCode=1,!1):!0:(O(m.red("turbobase: refusing to act without confirmation on a non-interactive terminal. Re-run with --yes.")),process.exitCode=1,!1)}function VS(t){return t.visibility!=="published"?m.dim("draft"):t.in_current_release?m.green("live"):m.yellow("unreleased")}function Ch(t,e){let r=t.replace(/\x1b\[[0-9;]*m/g,"").length;return t+" ".repeat(Math.max(0,e-r))}function GS(t){if(t.items.length===0)return["no skills on this instance."];let e=Math.max(4,...t.items.map(s=>s.slug.length)),r=[];for(let s of t.items)r.push(`${Ch(m.bold(s.slug),e)} ${Ch(VS(s),10)} ${s.surfaces.join(",")||m.dim("none")}`),s.description&&r.push(` ${m.dim(s.description)}`);r.push("");let n=t.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=t.items.filter(s=>s.visibility!=="published").length;return r.push(`${t.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(t.currentVersion==null?"":` \xB7 release v${t.currentVersion}`)),r}async function Ih(t,e=Hr){let r={};t.status&&(t.status!=="draft"&&t.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${t.status}').`),r.status=t.status);let n=await Kr(t,e),o;try{o=await X("reading the skills",()=>n.skillsList(r))}catch(s){V(s,"skills:publish","read the instance skills"),v(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}y(GS(o).join(`
4199
+ `))}async function Oh(t,e,r=Hr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Kr(e,r);if(!await ps(`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 X("publishing",()=>o.skillsPublish(n))}catch(a){V(a,"skills:publish","publish a skill"),v(`publish failed: ${a instanceof Error?a.message:String(a)}`)}y(m.green(`published ${i.published.length} skill(s) \u2014 live now.`)),i.unknown.length>0&&(O(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1),O(m.dim(`release v${i.version.version_no} \xB7 undo with: turbobase skills unpublish ${i.published.join(" ")}`))}async function Nh(t,e,r=Hr){let n=[...new Set(t.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Kr(e,r);if(!await ps(`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 X("unpublishing",()=>o.skillsUnpublish(n))}catch(a){V(a,"skills:publish","unpublish a skill"),v(`unpublish failed: ${a instanceof Error?a.message:String(a)}`)}y(m.green(`unpublished ${i.unpublished.length} skill(s) \u2014 retracted now.`)),O(m.dim(`release v${i.version.version_no} \xB7 re-publish with: turbobase skills publish ${i.unpublished.join(" ")}`)),i.unknown.length>0&&(O(m.yellow(`no such skill: ${i.unknown.join(", ")}`)),process.exitCode=1)}async function Lh(t,e,r=Hr){let n=Number(t);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${t}'). \`turbobase skills releases\` lists them.`);let o=await Kr(e,r);if(await ps(`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 X("rolling back",()=>o.skillsRollback(n));y(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){V(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function jh(t,e=Hr){let r=await Kr(t,e),n;try{n=await X("reading the releases",()=>r.skillsReleases())}catch(o){V(o,"skills:publish","read the skills releases"),v(`could not read the releases: ${o instanceof Error?o.message:String(o)}`)}if(n.items.length===0){O("no releases yet.");return}for(let o of n.items){let s=o.is_current?m.green("*"):" ",i=o.release_note?` \u2014 ${o.release_note}`:"";y(`${s} v${o.version_no} ${o.skill_count} skill(s) ${m.dim(o.published_at)}${o.published_by?m.dim(` by ${o.published_by}`):""}${m.dim(i)}`)}}async function Dh(t,e,r=Hr){let n=[...new Set((t??[]).map(u=>u.trim()).filter(Boolean))];n.length===0&&v("name at least one skill to delete. `turbobase skills list` shows the slugs.");let o=await Kr(e,r);if(!await ps(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
4131
4200
  ${n.join(`
4132
- `)}`,"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 X(`deleting ${u}`,()=>o.skillsDelete(u)))}catch(p){if(p instanceof Y&&p.status===404){a.push(u);continue}i.length>0&&L(m.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),v(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&b(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&L(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(L(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Oh}from"node:fs";import{join as jS,relative as DS,resolve as US,sep as MS}from"node:path";var qS=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),zS=new Set([".mcp.json",".env"]);function BS(t){return zS.has(t)||t.startsWith(".env.")&&t!==".env.example"}function FS(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function HS(t){return t.includes(0)}async function Nh(t){let e=US(t),r={},n=[],o=[],s=[];async function i(a){let l=await Oh.readdir(a,{withFileTypes:!0});for(let u of l){let p=jS(a,u.name);if(qS.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=DS(e,p).split(MS).join("/");if(BS(u.name)){o.push(g);continue}let S=await Oh.readFile(p);if(!FS(S)){n.push(g);continue}HS(S)&&s.push(g),r[g]=S.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as KS}from"node:crypto";var VS="/_tb/app-assets",GS=16,WS=/^[0-9a-f]{32}$/;function Lh(){return KS(GS).toString("hex")}function JS(t){return WS.test(t)}function jh(t){if(!JS(t))throw new Error(`not a build id: ${t}`);return`${VS}/${t}/`}var Dh=7;ja();var Da=50*1024*1024;import ds from"node:fs/promises";import In from"node:path";var Ua={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ma="@turbobase/isolated-vm-prebuilds";function qa(t,e){return`${t}-${e}`}function za(t=process.versions){return`abi${t.modules}`}var Uh=["darwin-x64","win32-arm64"];async function Mh(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=qa(e,r),o=In.join(t.home,"node_modules"),s=In.join(o,...Ma.split("/"),"prebuilds",n),i=In.join(o,"isolated-vm","prebuilds",n),a;try{a=await ds.readdir(s)}catch{return[]}let l=[];await ds.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=In.join(i,u);try{await ds.copyFile(In.join(s,u),p,ds.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as YS}from"node:os";import{join as qh}from"node:path";import{promises as Ba}from"node:fs";function Bh(){let t=process.env.TURBOBASE_HOME??qh(YS(),".turbobase");return{dir:t,file:qh(t,"sandboxes.json")}}var XS={s:1e3,m:6e4,h:36e5,d:864e5};function ZS(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*XS[e[2]]}function QS(t,e=Date.now()){return new Date(e+ZS(t)).toISOString()}function ek(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function tk(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 rk(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var nk="[REDACTED]",On=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 ok(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Fa(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:nk:n[o]=s}return n}function sk(t,e,r){return e.map(n=>ok(t,n,r))}var zh=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),ik=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function ak(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Ha(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 ik)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=ak(t);if(!zh.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...zh].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function lk(t,e=ck){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function ck(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function dk(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function uk(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Ka(){let{file:t}=Bh();try{let e=await Ba.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Fh(t){let{dir:e,file:r}=Bh();await Ba.mkdir(e,{recursive:!0}),await Ba.writeFile(r,`${JSON.stringify(t,null,2)}
4133
- `,{mode:384})}async function pk(t){let e=await Ka();e.push(t),await Fh(e)}async function Hh(t){let e=await Ka(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Fh(e),n??null}async function us(){return Ka()}function Va(t,e=Date.now()){let r=[],n=[];for(let o of t)ek(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Kh(t,e){Ha(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new On(r);let n=tk(e.sample),o=e.now??Date.now(),s=(e.nameGen??(u=>lk(u)))(e.fromTenant),i=dk(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=rk(u.rows,n),g=sk(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:QS(e.ttl,o),sampleFraction:n,url:uk(s,e.baseUrl)};return await pk(l),l}async function Vh(t,e){Ha(t.target());let n=(await us()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Hh(e),n):null}async function Ga(t,e=Date.now()){Ha(t.target());let r=await us(),{expired:n}=Va(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Hh(s.name),o.push(s)}return o}var Nn={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},LN=Object.keys(Nn).filter(t=>Nn[t].mintable);var UN=Nn.pat.prefix,hk=Object.entries(Nn).map(([t,e])=>[e.prefix,t]),mk=/^[A-Za-z0-9_-]{20,}$/;function fk(t){if(typeof t!="string")return null;for(let[e,r]of hk)if(t.startsWith(e)&&mk.test(t.slice(e.length)))return r;return null}function Gh(t){return fk(t)==="pat"}vn();var gk=8e3,yk={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 bk(t){return yk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function wk(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(gk)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Wh(t){return t.state==="accepted"?Oe()?m.green("accepted"):"accepted":t.state==="rejected"?Oe()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function Jh(t={},e=fetch){let r=await Lt(),{file:n}=Do();if(r.length===0){b("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),L(m.dim(`no sign-ins stored in ${n}.`));return}let o=await ht(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await wk(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(ft(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Wh(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Wh(i.check)} (updated ${i.updatedAt})`);L(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(L(m.red(`${i.baseUrl}: ${bk(i.check.reason)}.`)),L(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&L(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||L("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function BA(t){let e=await Lt();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function FA(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function HA(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 KA(t,e,r){let n=await Ru({baseUrl:t,token:e}),o=(await Lt()).length-1;if(b(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),HA(n.baseUrl),!r)return;let s=await FA(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(L(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),L(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),L(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?L(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):L(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function VA(t){let e=await da(await Tn(t),Ft(t)),r=Ta(e);return r||v(`${t}: ${Ra(e)}`),{...r,sourceCode:e}}async function Ar(t,e,r,n){try{return await ie.access(t),"skipped"}catch{}return await ie.mkdir(Ft(t),{recursive:!0}),await ie.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(t,n),"wrote"}async function Jb(t,e){if(Xb(t)!==".gitignore")return Ar(t,e.content,e.executable,e.mode);let r=await ie.readFile(t,"utf8").catch(()=>null);if(r===null)return Ar(t,e.content,e.executable,e.mode);let n=Op(r);return n===null?"skipped":(await ie.writeFile(t,n,"utf8"),"merged")}function Hd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function ji(t){process.exit(t)}function GA(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function WA(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 JA(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 Yb(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Yd({includeInternal:t=!0}={}){let e=new zA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.40.1").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${ya()}
4134
- `),e.hook("preAction",(d,h)=>{Gp(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=rt(d.baseUrl);d.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
4135
- ${Mr} auth login --base-url ${h} --token tb_pat_\u2026`),Gh(d.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await KA(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=>Jh({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 BA("Pick the active instance:"),w=await Uo(h);if(!w){let T=await Lt();v(`no stored sign-in for ${rt(h)}.`+(T.length?` Stored: ${T.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${rt(h)} --token tb_pat_\u2026\`.`)}b(`active instance \u2192 ${w.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let T=await Lt();for(let _ of T)await oa(_.baseUrl);b(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await oa(d.baseUrl);h||v(d.baseUrl?`no stored sign-in for ${rt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await ht();b(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T;try{T=await mr({baseUrl:h,token:w,recordsOnly:d.recordsOnly})}catch(f){let k=f instanceof Error?f.message:String(f);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(k)){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{T=await mr({baseUrl:h,token:w,recordsOnly:!0})}catch($){v(`types generation failed: ${$ instanceof Error?$.message:String($)}`)}}else v(`types generation failed: ${k}`)}let _=oe(process.cwd(),d.out);await ie.writeFile(_,T,"utf8"),b(`wrote ${_} (${T.split(`
4136
- `).length} lines).`)}),Yp(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:w}=await z(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let _=T.toString(),f=await fetch(`${h}/v1/catalog/grounding${_?`?${_}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});f.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${f.status}`);let $=((await f.json()).markdown??"").trim(),A=oe(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",O=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
4201
+ `)}`,"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 X(`deleting ${u}`,()=>o.skillsDelete(u)))}catch(p){if(p instanceof Y&&p.status===404){a.push(u);continue}i.length>0&&O(m.dim(`deleted before the error: ${i.map(g=>g.slug).join(", ")}`)),V(p,"skills:publish","delete a skill"),v(`delete failed on '${u}': ${p instanceof Error?p.message:String(p)}`)}i.length>0&&y(m.green(`deleted ${i.length} skill(s).`));let l=i.filter(u=>u.wasPublished).map(u=>u.slug);l.length>0&&O(m.yellow(`Published until now, so no longer injected: ${l.join(", ")}`)),a.length>0&&(O(m.yellow(`no such skill: ${a.join(", ")}`)),process.exitCode=1)}import{promises as Uh}from"node:fs";import{join as WS,relative as JS,resolve as YS,sep as XS}from"node:path";var ZS=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),QS=new Set([".mcp.json",".env"]);function ek(t){return QS.has(t)||t.startsWith(".env.")&&t!==".env.example"}function tk(t){return Buffer.compare(Buffer.from(t.toString("utf8"),"utf8"),t)===0}function rk(t){return t.includes(0)}async function Da(t){let e=YS(t),r={},n=[],o=[],s=[];async function i(a){let l=await Uh.readdir(a,{withFileTypes:!0});for(let u of l){let p=WS(a,u.name);if(ZS.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=JS(e,p).split(XS).join("/");if(ek(u.name)){o.push(g);continue}let k=await Uh.readFile(p);if(!tk(k)){n.push(g);continue}rk(k)&&s.push(g),r[g]=k.toString("utf8")}}return await i(e),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as nk}from"node:crypto";var ok="/_tb/app-assets",sk=16,ik=/^[0-9a-f]{32}$/;function Mh(){return nk(sk).toString("hex")}function ak(t){return ik.test(t)}function qh(t){if(!ak(t))throw new Error(`not a build id: ${t}`);return`${ok}/${t}/`}var zh=7;Ma();var qa=50*1024*1024;import hs from"node:fs/promises";import On from"node:path";var za={esbuild:"0.28.1","isolated-vm":"6.1.2"},Ba="@turbobase/isolated-vm-prebuilds";function Fa(t,e){return`${t}-${e}`}function Ha(t=process.versions){return`abi${t.modules}`}var Bh=["darwin-x64","win32-arm64"];async function Fh(t){let e=t.platform??process.platform,r=t.arch??process.arch,n=Fa(e,r),o=On.join(t.home,"node_modules"),s=On.join(o,...Ba.split("/"),"prebuilds",n),i=On.join(o,"isolated-vm","prebuilds",n),a;try{a=await hs.readdir(s)}catch{return[]}let l=[];await hs.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=On.join(i,u);try{await hs.copyFile(On.join(s,u),p,hs.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as lk}from"node:os";import{join as Hh}from"node:path";import{promises as Ka}from"node:fs";function Vh(){let t=process.env.TURBOBASE_HOME??Hh(lk(),".turbobase");return{dir:t,file:Hh(t,"sandboxes.json")}}var ck={s:1e3,m:6e4,h:36e5,d:864e5};function dk(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*ck[e[2]]}function uk(t,e=Date.now()){return new Date(e+dk(t)).toISOString()}function pk(t,e=Date.now()){let r=Date.parse(t);return Number.isNaN(r)?!0:r<=e}function hk(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 mk(t,e){if(e>=1)return[...t];if(e<=0||t.length===0)return[];let r=Math.max(1,Math.round(1/e)),n=[];for(let o=0;o<t.length;o+=r)n.push(t[o]);return n}var fk="[REDACTED]",Nn=class extends Error{constructor(e){super(e),this.name="SandboxDataCopyUnavailableError"}},Va=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 gk(t,e,r){let n={};for(let[o,s]of Object.entries(e)){let i=r[o];if(i===void 0)throw new Va(t,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:fk:n[o]=s}return n}function yk(t,e,r){return e.map(n=>gk(t,n,r))}var Kh=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),bk=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function wk(t){let e=t.trim();try{let o=new URL(e);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=e.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function Ga(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 bk)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=wk(t);if(!Kh.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...Kh].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function vk(t,e=_k){return`sbx-${t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${e()}`}function _k(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function Sk(t){return`turbobase_${t.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function kk(t,e){return`${(e??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(t)}`}async function Wa(){let{file:t}=Vh();try{let e=await Ka.readFile(t,"utf8"),r=JSON.parse(e);return Array.isArray(r)?r:[]}catch(e){if(e.code==="ENOENT")return[];throw e}}async function Gh(t){let{dir:e,file:r}=Vh();await Ka.mkdir(e,{recursive:!0}),await Ka.writeFile(r,`${JSON.stringify(t,null,2)}
4202
+ `,{mode:384})}async function Tk(t){let e=await Wa();e.push(t),await Gh(e)}async function Wh(t){let e=await Wa(),r=e.findIndex(o=>o.name===t);if(r===-1)return null;let[n]=e.splice(r,1);return await Gh(e),n??null}async function ms(){return Wa()}function Ja(t,e=Date.now()){let r=[],n=[];for(let o of t)pk(o.expiresAt,e)?n.push(o):r.push(o);return{active:r,expired:n}}async function Jh(t,e){Ga(t.target());let r=t.dataCopyUnavailable?.();if(r)throw new Nn(r);let n=hk(e.sample),o=e.now??Date.now(),s=(e.nameGen??(u=>vk(u)))(e.fromTenant),i=Sk(s);await t.createDatabase(i),await t.replayMigrations(i);let a=await t.readSourceTables(e.fromTenant);for(let u of a){let p=mk(u.rows,n),g=yk(u.table,p,u.classification);g.length>0&&await t.copyRows(i,u.table,g)}let l={name:s,fromTenant:e.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:uk(e.ttl,o),sampleFraction:n,url:kk(s,e.baseUrl)};return await Tk(l),l}async function Yh(t,e){Ga(t.target());let n=(await ms()).find(o=>o.name===e);return n?(await t.dropDatabase(n.database),await Wh(e),n):null}async function Ya(t,e=Date.now()){Ga(t.target());let r=await ms(),{expired:n}=Ja(r,e),o=[];for(let s of n){try{await t.dropDatabase(s.database)}catch{continue}await Wh(s.name),o.push(s)}return o}var Ln={pat:{prefix:"tb_pat_",defaultScopes:["extensions:deploy"],allowedScopes:["extensions:deploy","catalog:read","mcp:authoring","analyzer:run","releases:write","solutions:write","skills:publish","docs:publish","mcp:data","mcp:write","rest:read","rest:write","ai:invoke"],defaultTtlDays:90,mintable:!0,label:"Personal access token"},catalog:{prefix:"tb_cat_",defaultScopes:["catalog:read"],allowedScopes:["catalog:read"],defaultTtlDays:null,mintable:!0,label:"AI / catalog token"}},GN=Object.keys(Ln).filter(t=>Ln[t].mintable);var YN=Ln.pat.prefix,Rk=Object.entries(Ln).map(([t,e])=>[e.prefix,t]),xk=/^[A-Za-z0-9_-]{20,}$/;function $k(t){if(typeof t!="string")return null;for(let[e,r]of Rk)if(t.startsWith(e)&&xk.test(t.slice(e.length)))return r;return null}function Xh(t){return $k(t)==="pat"}_n();var Ek=8e3,Pk={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 Ak(t){return Pk[t]??`the instance rejected this token (${t}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Ck(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(Ek)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Zh(t){return t.state==="accepted"?Oe()?m.green("accepted"):"accepted":t.state==="rejected"?Oe()?m.red(`rejected \xB7 ${t.reason}`):`rejected \xB7 ${t.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function Qh(t={},e=fetch){let r=await jt(),{file:n}=qo();if(r.length===0){y("not signed in. Run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),O(m.dim(`no sign-ins stored in ${n}.`));return}let o=await ft(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:t.probe===!1?{state:"accepted"}:await Ck(i.baseUrl,i.token,e)})));if(t.probe===!1)for(let i of s)y(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())y(it(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Zh(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)y(`${i.active?"* ":" "}${i.baseUrl} ${Zh(i.check)} (updated ${i.updatedAt})`);O(m.dim(`tokens read from ${n}`));for(let i of s)i.check.state==="rejected"?(O(m.red(`${i.baseUrl}: ${Ak(i.check.reason)}.`)),O(m.dim(" then re-run `turbobase project init` \u2014 .mcp.json holds its own copy of the token, and until it is rewritten the authoring MCP tools stay absent from your session."))):i.check.state==="unreachable"&&O(m.yellow(`${i.baseUrl}: could not reach the instance (${i.check.detail}).`));o||O("no active default \u2014 run `turbobase auth use <base-url>` or pass --base-url.")}async function eC(t){let e=await jt();e.length===0&&v("no stored sign-ins \u2014 run `turbobase auth login --base-url <instance> --token tb_pat_\u2026`."),Ne()||v("this command needs an explicit <base-url> in a non-interactive shell.");try{return await Le(t,e.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function tC(t,e){let r;try{r=await fetch(`${t}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Accept:"application/json"},signal:AbortSignal.timeout(8e3)})}catch(o){return{ok:!1,kind:"unreachable",detail:o instanceof Error?o.message:String(o)}}let n=(r.headers.get("content-type")??"").includes("application/json");return r.status===200||r.status===403?{ok:!0}:r.status===401?{ok:!1,kind:"bad-token",detail:`HTTP ${r.status}`}:n?{ok:!0}:{ok:!1,kind:"wrong-host",detail:`HTTP ${r.status}`}}function rC(t){O(""),O("Sharing is ON. Two things reach the Turbobase product team from this instance:"),O(" \xB7 anonymized pattern cards from your proposals, solutions and INSTANCE-LEARNINGS.md \u2014"),O(" a pattern label, a record class, a fix shape, an outcome. No scripts, values or ids."),O(" \xB7 redacted prose from your projects\u2019 TURBOBASE-FEEDBACK.md \u2014 the findings you write"),O(" about OUR platform, with instance name, user names and ids masked before they leave."),O(`Turn it off: ${t}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),O("")}async function nC(t,e,r){let n=await Cu({baseUrl:t,token:e}),o=(await jt()).length-1;if(y(`signed in to ${n.baseUrl} \u2014 now the active instance`+(o>0?` (${o} other${o===1?"":"s"} stored; commands default here).`:".")),rC(n.baseUrl),!r)return;let s=await tC(n.baseUrl,e);s.ok||(s.kind==="wrong-host"?(O(`warning: ${n.baseUrl} did not respond to the Turbobase API (/v1) \u2014 got ${s.detail}.`),O(" In local dev the Turbobase API is on :4100, not the app dev-server port (e.g. :5173)."),O(" The token is stored, but commands will fail against this base-url until it points at the API.")):s.kind==="bad-token"?O(`warning: ${n.baseUrl} rejected the token (401) \u2014 the PAT may be stale, revoked, or for a different instance.`):O(`warning: could not reach ${n.baseUrl} to verify the token (${s.detail}). Stored anyway.`))}async function oC(t){let e=await pa(await Rn(t),Ht(t)),r=xa(e);return r||v(`${t}: ${Ea(e)}`),{...r,sourceCode:e}}async function Cr(t,e,r,n){try{return await ie.access(t),"skipped"}catch{}return await ie.mkdir(Ht(t),{recursive:!0}),await ie.writeFile(t,e,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(t,n),"wrote"}async function Qb(t,e){if(tw(t)!==".gitignore")return Cr(t,e.content,e.executable,e.mode);let r=await ie.readFile(t,"utf8").catch(()=>null);if(r===null)return Cr(t,e.content,e.executable,e.mode);let n=Up(r);return n===null?"skipped":(await ie.writeFile(t,n,"utf8"),"merged")}function Gd(t){if(t!==void 0){if(t==="junit"||t==="json")return t;v(`unknown --reporter '${t}' (expected 'junit' or 'json').`)}}function Mi(t){process.exit(t)}function sC(t){return{name:"turbobase ext test",cases:t.map(r=>{if(r.pass)return{name:r.name,status:"passed"};let n=r.error?"error":r.rejection?.code??"mismatch",o=r.error?`error: ${r.error}`:r.observed!==r.expected?`expected ${r.expected}, observed ${r.observed}`+(r.rejection?` (rejected: ${r.rejection.code??"rejected"}${r.rejection.message?` \u2014 ${r.rejection.message}`:""})`:""):`rejected: ${r.rejection?.code??"rejected"}${r.rejection?.message?` \u2014 ${r.rejection.message}`:""}`;return{name:r.name,status:"failed",detail:o,type:n}})}}function iC(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 aC(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 ew(t){return`${(Math.ceil(t/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function Qd({includeInternal:t=!0}={}){let e=new QA;e.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.42.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),e.addHelpText("beforeAll",d=>d.command.parent?"":`${wa()}
4203
+ `),e.hook("preAction",(d,h)=>{Zp(e.opts(),h.opts())});let r=e.command("auth").description("Sign in to an instance and manage stored credentials."),n=e.command("project").description("Set up the local project and the files an agent session reads."),o=e.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=e.command("kb").description("Write into the instance's knowledge base."),i=e.command("skills").description("Write standing rules into the instance's agent skills.");r.command("login").description("Sign in to an instance by pasting a personal access token (PAT), stored in ~/.turbobase/credentials.").requiredOption("--base-url <url>","Instance base URL, e.g. https://acme.turbobase.app").option("--token <tb_pat_\u2026>","The PAT to store. Mint one in your app under Settings \u203A Access tokens.").option("--no-verify","Skip the post-login connectivity/token probe.").action(async d=>{let h=nt(d.baseUrl);d.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
4204
+ ${qr} auth login --base-url ${h} --token tb_pat_\u2026`),Xh(d.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await nC(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=>Qh({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 eC("Pick the active instance:"),w=await zo(h);if(!w){let T=await jt();v(`no stored sign-in for ${nt(h)}.`+(T.length?` Stored: ${T.map(_=>_.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${nt(h)} --token tb_pat_\u2026\`.`)}y(`active instance \u2192 ${w.baseUrl}.`)}),r.command("logout").description("Remove a stored sign-in (defaults to the active instance).").option("--base-url <url>","Which instance to remove (defaults to the active/single one).").option("--all","Remove every stored sign-in.").action(async d=>{if(d.all){let T=await jt();for(let _ of T)await ia(_.baseUrl);y(`removed ${T.length} stored sign-in${T.length===1?"":"s"}.`);return}let h=await ia(d.baseUrl);h||v(d.baseUrl?`no stored sign-in for ${nt(d.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await ft();y(`signed out of ${h}.`+(w?` Active instance \u2192 ${w.baseUrl}.`:""))}),n.command("types").description("Generate types.ts from the signed-in instance's catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("-o, --out <file>","Output file","types.ts").option("--records-only","Emit only record-shape interfaces (skip the OpenAPI half).").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T;try{T=await fr({baseUrl:h,token:w,recordsOnly:d.recordsOnly})}catch(f){let S=f instanceof Error?f.message:String(f);if(!d.recordsOnly&&/openapi\.json failed \(401/.test(S)){O("types-gen: /v1/catalog/openapi.json needs a browser session \u2014 emitting record shapes only. The record shapes are the half apps generate against; for the OpenAPI half, run it from a signed-in browser session.");try{T=await fr({baseUrl:h,token:w,recordsOnly:!0})}catch($){v(`types generation failed: ${$ instanceof Error?$.message:String($)}`)}}else v(`types generation failed: ${S}`)}let _=oe(process.cwd(),d.out);await ie.writeFile(_,T,"utf8"),y(`wrote ${_} (${T.split(`
4205
+ `).length} lines).`)}),th(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:w}=await B(d.baseUrl),T=new URLSearchParams;d.records&&T.set("records",d.records),d.query&&T.set("query",d.query);let _=T.toString(),f=await fetch(`${h}/v1/catalog/grounding${_?`?${_}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});f.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${f.status}`);let $=((await f.json()).markdown??"").trim(),A=oe(process.cwd(),d.out),C=d.records?` records=${d.records}`:"",N=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${C} \u2014 do not edit; re-run to refresh. -->
4137
4206
 
4138
- `;await ie.writeFile(A,O+($?`${$}
4207
+ `;await ie.writeFile(A,N+($?`${$}
4139
4208
  `:`(no grounding available yet)
4140
- `),"utf8"),b(`wrote ${A}${$?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${An.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=>eh(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>rh(d)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>nh(d,h)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>oh(d,h)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>sh(d)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>ih(d,h)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>ah(d,h)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>(d.publish&&!d.from&&v("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),d.from?ph({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):lh(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=>$h(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)=>Eh(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)=>Ph(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=>Ch(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)=>Ah(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)=>Ih(d,h));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async d=>{let h;try{h=$t("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),h.relativePath);await Ar(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`wrote ${w}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let h;try{h=$t("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),h.relativePath);await Ar(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`wrote ${w}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let h;try{h=$t("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),h.relativePath);await Ar(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),b(`wrote ${w}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(d,h)=>{let w=Hd(h.reporter),T=await Tn(oe(process.cwd(),d)),_=oe(process.cwd(),h.samples),f=await kn(_);f.length===0&&!w&&b(`no samples found under ${_} \u2014 add JSON fixtures to dry-run against.`);let k;try{k=await Vo(T,f.map(C=>C.fixture),{resolveDir:Ft(oe(process.cwd(),d))})}catch(C){v(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(w){let C=GA(k);b(Wo(C,w)),ji(C.cases.some(O=>O.status==="failed")?1:0)}let $=0;for(let C of k){let O=C.pass?m.green("PASS"):m.red("FAIL");C.pass||($+=1);let W=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";b(` ${O} ${C.name}${W}`)}let A=`${k.length-$}/${k.length} sample(s) passed.`;b(`
4141
- ${$===0?m.green(A):m.yellow(A)}`),ji($>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,h)=>{if(h.to){let k=await Kd(),{baseUrl:$,token:A}=await z(h.baseUrl),C=new q({baseUrl:$,token:A});try{let O=await X(`applying bundle to ${h.to}`,()=>C.configApply(k,{prune:h.prune}));b(`applied bundle to ${h.to}: +${O.applied.add} ~${O.applied.change} -${O.applied.destroy}`+(O.backfillsQueued.length?` (${O.backfillsQueued.length} backfill(s) queued)`:""));let W=O.skippedDestroys??[];if(W.length>0){L(`${W.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let N of W)L(` ${N.kind} ${N.id}`);L("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(O){O instanceof Y&&O.status===403&&v("apply forbidden (403) \u2014 the stored PAT is not for an admin.");let W=O instanceof Y?xa(O.body):null;W&&v(`bundle apply failed \u2014 ${W}`),v(`bundle apply failed: ${O instanceof Error?O.message:String(O)}`)}return}d||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:T}=await z(h.baseUrl),_=await VA(oe(process.cwd(),d)),f=new q({baseUrl:w,token:T});try{let k=await X(`deploying ${Xb(d)}`,()=>f.deploy(_)),$=zp(k.outcome);Oe()?b(Gt("Deployed",[`${m.bold(k.id)} ${jr(k.status)} ${m.dim($)}`])):b(`deployed ${k.id} \u2192 status=${k.status} (${$}).`)}catch(k){k instanceof Y&&k.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin.");let $=k instanceof Y?xa(k.body,d):null;$&&v($),v(`deploy failed: ${k instanceof Error?k.message:String(k)}`)}});let l=e.command("apps").description("Manage hosted apps served in your Turbobase app.");l.command("deploy").description("Build the app (if needed) and deploy it \u2014 cuts a new live version at /a/<slug>.").argument("<app>","App slug or id.").argument("[dir]","Source or built directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--no-build","Upload the directory as-is; it is already a built bundle.").option("--no-install","Skip `npm install` (assume deps are present).").option("--no-pull","Do not pull generated source even when the dir has no package.json.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,h,w)=>{let T=!!(w.preview||w.replace||w.replaceLabel);w.replace&&w.replaceLabel&&v("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let _=oe(process.cwd(),h??".");await ie.mkdir(_,{recursive:!0});let f=w.proposal??await E(_),{baseUrl:k,token:$}=await z(w.baseUrl),A=new q({baseUrl:k,token:$}),C=!1;try{C=(await A.appsList()).some(ae=>ae.slug===d||ae.id===d)}catch(ae){V(ae,"extensions:deploy","deploy"),v(`could not reach ${k}: ${ae instanceof Error?ae.message:String(ae)}`)}if(!C){w.create||v(`no app "${d}" on ${k} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let ae=await X(`creating app ${d}`,()=>g(k,$,{slug:d},{tolerateExisting:!0}));ae.existed||b(`created ${ae.slug??d}.`)}let O;if(w.replace)if(typeof w.replace=="string")O=w.replace;else{let{previews:ae}=await K(k,$,d);if(ae.length===0&&v(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ae.length>1){for(let $e of ae)b(` ${$e.previewId} v${$e.version}${$e.label?` ${$e.label}`:""} ${$e.url}`);v(`${d} has ${ae.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ae[0].previewId}\`.`)}O=ae[0].previewId}let W;if(w.replaceLabel){let ae=w.replaceLabel,{previews:$e}=await K(k,$,d),Rt=$e.filter(qi=>qi.label===ae);Rt.length>0?(O=Rt[0].previewId,Rt.length>1&&L(`${Rt.length} open previews carry the label "${ae}"; replacing the newest (${O}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${ae}" \u2014 opening one.`),W=ae}let N=ae=>ie.stat(et(_,ae)).then(()=>!0).catch(()=>!1),J=d,me=_,Q=w.build!==!1;if(Q&&!await N("package.json"))if(await N("index.html"))b("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Q=!1;else if(w.pull===!1)v(`${_} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ae=await X(`pulling ${d}`,()=>S(k,$,d));J=ae.slug??d,await y(_,ae.files,!0),b(`pulled generated source (rev ${ae.rev}).`)}let be;if(Q){let ae=Lh();if(be={buildId:ae,assetBase:jh(ae)},w.install!==!1&&!await N("node_modules")){b("installing dependencies\u2026");try{await I(["install"],_)}catch($e){v(`npm install failed: ${$e instanceof Error?$e.message:String($e)}`)}}b("building\u2026");try{await I(["run","build"],_,{TURBOBASE_ASSET_BASE:be.assetBase})}catch($e){v(`build failed: ${$e instanceof Error?$e.message:String($e)}`)}await N("dist")||v(`no dist/ after build in ${_} \u2014 check the app's build script.`),me=et(_,"dist")}T&&!be&&v(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${J}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let fe=await Ce(k,$,J,me,w.entry,f,be,T?{label:w.label??W,replacePreviewId:O}:void 0);if(T){let ae=fe.previewUrl??"(no url returned)",$e=fe.expiresAt?new Date(fe.expiresAt).toLocaleDateString():`${Dh} days`,Rt=fe.replacedVersion==null?null:`replaced v${fe.replacedVersion} \u2014 same URL`;if(Oe())b(Gt(Rt?"Preview replaced":"Preview deployed",[`${m.bold(J)} ${m.green(`v${fe.version??"?"}`)} ${m.dim("not live")}`,`${m.bold(ae)}`,...Rt?[m.dim(Rt)]:[],m.dim(`expires ${$e}`)]));else{let qi=Rt?`; ${Rt}`:"";b(`preview ${J} v${fe.version??"?"} \u2192 ${ae} (expires ${$e}; /a/${J} unchanged${qi}).`)}Nt(fe),b(`next: turbobase apps promote ${J} ${fe.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${fe.previewId??"<preview-id>"}`);return}Oe()?b(Gt("Deployed",[`${m.bold(J)} ${m.green(`v${fe.version??"?"}`)} ${m.dim(fe.url??`/a/${J}`)}`])):b(`deployed ${J} \u2192 v${fe.version??"?"} (${fe.url??`/a/${J}`}).`),Nt(fe),Ht(fe),await Tt(fe,_)}),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>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(d,h)=>{let w=h.as?.startsWith("app:")?h.as.slice(4).trim():"";h.app!==void 0&&h.app.trim()===""&&v("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let T=h.app?.trim()??"";T&&w&&T!==w&&v(`--app ${T} and --as app:${w} name two different apps \u2014 pass one slug.`);let _=T||w||null,f=await XA(d??".");f||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`);let k=Array.isArray(f.manifest.tables)?f.manifest.tables:[],$=Array.isArray(f.manifest.writes)?f.manifest.writes:[],A=Array.isArray(f.manifest.roles)?f.manifest.roles:null,C=A??[],O=Array.isArray(f.manifest.labels)?f.manifest.labels:[],W=A!==null&&A.length===0;if(k.length===0&&$.length===0&&C.length===0&&O.length===0){if(!W)return b(`${f.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(_===null){for(let Q of wa({app:null,roles:A}))b(Q.text);return}}let{baseUrl:N,token:J}=await z(h.baseUrl),me=new q({baseUrl:N,token:J});if(k.length>0){let Q;try{Q=await X("planning tables",()=>me.tablesPlan({claimedBy:h.as,tables:k}))}catch(be){V(be,"extensions:deploy","plan tables"),Eo(be)}b(`claiming as ${m.bold(Q.claimedBy)}`);for(let be of Q.tables)$o(be,{showClaimants:!0})}if($.length>0||C.length>0||O.length>0||W&&_!==null){let Q;try{Q=await X("checking declared writes, roles and labels",()=>me.appsPlan({writes:$,...A!==null?{roles:A}:{},labels:O,..._!==null?{app:_}:{}}))}catch(be){V(be,"extensions:deploy","plan writes"),v(`plan writes failed: ${be instanceof Error?be.message:String(be)}`)}Q.roles&&Ie("plan",Q.roles.verdicts,Q.roles.retired);for(let be of wa({app:_,roles:A,retired:Q.roles?.retired??null}))b(be.text);if(Q.labels&&Q.labels.verdicts.length>0){b(""),b(m.bold("labels"));let be=Math.max(...Q.labels.verdicts.map(fe=>fe.name.length));for(let fe of Q.labels.verdicts){let ae=fe.name.padEnd(be);if(fe.action==="create")b(` create ${ae} ${m.dim(fe.color)}`);else{let $e=fe.declaredColor?`${fe.color} \u2014 declared ${fe.declaredColor}, the instance's colour is kept`:fe.color;b(` ${m.dim("ok")} ${ae} ${m.dim($e)}`)}}b(m.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}$.length>0&&b("");for(let be of Q.verdicts){let fe=`${be.source} ${be.recordType}.${be.op}`;be.allowed?be.heldForApproval?b(`${m.dim("HELD")} ${fe} \u2014 allowed, but each write waits for operator approval.`):b(`${m.dim("ok")} ${fe}`):L(`${m.bold("DENIED")} ${fe}${be.rule?` \u2014 guardrail "${be.rule}"`:""} (${be.reason})`)}Q.ok||(b(""),v(Q.message??(Q.roles&&!Q.roles.ok?"one or more declared roles cannot be created.":"a guardrail refuses one or more declared writes \u2014 an admin must allow them, or the app must stop declaring them.")))}b(""),b(m.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await z(w.baseUrl),f=await X(`promoting ${h}`,()=>F(T,_,d,"promote",{previewId:h}));Oe()?b(Gt("Promoted",[`${m.bold(d)} ${m.green(`v${f.version??"?"}`)} ${m.dim(f.url??`/a/${d}`)}`])):b(`promoted ${d} \u2192 v${f.version??"?"} is now live at ${f.url??`/a/${d}`}.`);let k=Ep(f);Ie("applied",k.verdicts,k.retired),Ht({labels:f.labels?{applied:!0,verdicts:f.labels}:null}),await Tt(f)});let u=l.command("preview").description("Inspect and manage an app's open previews.");u.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=await K(w,T,d);if(h.json)return b(JSON.stringify(_.previews,null,2));if(_.previews.length===0){b(`no open previews for ${d}.`);return}for(let f of _.previews){let k=f.label?` ${f.label}`:"",$=f.expiresAt?new Date(f.expiresAt).toLocaleDateString():"?";b(`v${f.version} ${f.previewId}${k} ${f.url} (expires ${$})`)}}),u.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await z(w.baseUrl);await X(`discarding ${h}`,()=>F(T,_,d,"discard",{previewId:h})),b(`discarded ${h}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=await X(`creating ${d}`,()=>g(w,T,{slug:d,name:h.name,description:h.description})),f=_.slug??d;Oe()?b(Gt("Created",[`${m.bold(f)} ${m.dim(_.url??`/a/${f}`)}`])):b(`created ${f} (${_.url??`/a/${f}`}).`),b(`next: turbobase apps push ${f} . # store the source`),b(` turbobase apps deploy ${f} # build + go live`)});let p=Mo(fetch);async function g(d,h,w,T={}){let _=`${d.replace(/\/+$/,"")}/v1/apps`,f;try{f=await p(_,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:w.slug,name:w.name??w.slug,description:w.description})})}catch(k){v(`create request failed: ${k instanceof Error?k.message:String(k)}`)}if(f.status===401&&v("create unauthorized (401) \u2014 re-run `turbobase auth login`."),f.status===403&&v("create forbidden (403) \u2014 the PAT is not for an admin."),f.status===409){if(T.tolerateExisting)return{slug:w.slug,existed:!0};v(`an app with slug "${w.slug}" already exists.`)}return f.ok||v(`create failed: HTTP ${f.status} ${(await f.text().catch(()=>"")).slice(0,200)}`),await f.json().catch(()=>({}))}async function S(d,h,w){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,_;try{_=await p(T,{headers:{Authorization:`Bearer ${h}`}})}catch(f){v(`pull request failed: ${f instanceof Error?f.message:String(f)}`)}return _.status===401&&v("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),_.status===403&&v("pull forbidden (403) \u2014 the PAT is not for an admin."),_.status===404&&v(`no generated source for "${w}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),_.ok||v(`pull failed: HTTP ${_.status} ${(await _.text().catch(()=>"")).slice(0,200)}`),await _.json()}async function y(d,h,w){let T=oe(d),_=0;for(let[f,k]of Object.entries(h)){let $=oe(T,f);$!==T&&!$.startsWith(T+Wd)&&v(`refusing to write outside ${T}: ${f}`),w||await ie.stat($).then(()=>!0).catch(()=>!1)&&v(`${$} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ie.mkdir(Ft($),{recursive:!0}),await ie.writeFile($,k,"utf8"),_+=1}return _}function x(d){let h=d.indexOf(","),w=d.startsWith("data:")?h>=0?d.slice(h+1):"":d;if(!w)return null;try{let T=Buffer.from(w,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function R(d,h,w){let T=oe(d),_=async(k,$)=>{let A=oe(T,k);A!==T&&!A.startsWith(T+Wd)&&v(`refusing to write outside ${T}: ${k}`),w||await ie.stat(A).then(()=>!0).catch(()=>!1)&&v(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ie.mkdir(Ft(A),{recursive:!0}),await ie.writeFile(A,$)},f=`# ${h.title||"App change request"}
4209
+ `),"utf8"),y(`wrote ${A}${$?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${Cn.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=>sh(d)),s.command("list").description("List the knowledge base\u2019s pages and whether each is actually readable. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <draft|published>","Only pages in this state.").action(d=>ah(d)),s.command("publish").argument("<slug...>","Page slugs to publish (see `turbobase kb list`).").description("Publish pages: makes them reader-visible AND cuts a release scoped to them, so they are live when this returns.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>lh(d,h)),s.command("unpublish").argument("<slug...>","Page slugs to retract.").description("Hide pages from readers immediately. The text and its history are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>ch(d,h)),s.command("versions").description("List knowledge-base releases, newest first, marking the current one. Needs `docs:publish`; admin only.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(d=>dh(d)),s.command("rollback").argument("<version>","Release number to restore (see `turbobase kb versions`).").description("Re-point the current knowledge-base release at an earlier one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>uh(d,h)),s.command("delete").argument("<slug>","Page slug to delete (see `turbobase kb list`).").description("Delete a page and its subtree. SOFT \u2014 restorable from the editor\u2019s trash, unlike `skills delete`.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--yes","Skip the confirmation (for scripted runs).").action((d,h)=>ph(d,h)),i.command("push").description("Write pending `## Agent rules` findings as draft agent rules, grouped by their `###` heading. Shows the plan and asks first; rules land unpublished and disabled.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--limit <n>","Cap how many findings to act on.",d=>Number.parseInt(d,10)).option("--dry-run","Print the plan and exit without writing.").option("--diff","Also print each rule\u2019s write-set (default under --dry-run).").option("--no-diff","Suppress the write-set, printing the plan fields only.").option("--no-group","Ignore `###` headings \u2014 write one rule per finding.").option("--reapply","Also re-emit findings already applied \u2014 picks up a corrected `###` grouping or reworded body. Rules stay draft.").option("--from <dir>","Push the SKILL.md files under <dir> (one sub-directory per skill) instead of findings. Needs --app.").option("--publish","With --from: publish the skills this push wrote (new or changed). Needs a token carrying skills:publish.").option("--yes","Skip the confirmation (for scripted runs).").action(d=>(d.publish&&!d.from&&v("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),d.from?yh({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):hh(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=>Ih(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)=>Oh(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)=>Nh(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=>jh(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)=>Lh(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)=>Dh(d,h));let a=o.command("new").description("Scaffold a new extension file.");a.command("hook").description("Scaffold a hook file under hooks/.").requiredOption("--record <type>","Record type the hook targets, e.g. salesOrder").option("--event <event>","Lifecycle event","before_save").option("--template <name>","require-field | enforce-format | blank","require-field").option("--field <name>","Field name (for require-field / enforce-format)").option("--regex <pattern>","Pattern (for enforce-format)").option("--source <source>","Source id (netsuite, stripe, \u2026)").option("--id <id>","Override the generated hook id").action(async d=>{let h;try{h=Et("hook",{recordType:d.record,event:d.event,template:d.template,field:d.field,regex:d.regex,source:d.source,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),h.relativePath);await Cr(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),a.command("conduit").description("Scaffold a conduit file under conduits/ (cross-source bridge).").requiredOption("--source <source>","Origin source the record arrives from, e.g. shopify").requiredOption("--record <type>","Canonical record type the conduit triggers on, e.g. order").requiredOption("--to <source>","Target source the conduit bridges into, e.g. netsuite").option("--to-record <type>","Target record type (defaults to the trigger record type)").option("--event <event>","Cross-source lifecycle event","after_canonicalize_inbound").option("--id <id>","Override the generated conduit id").action(async d=>{let h;try{h=Et("conduit",{recordType:d.record,source:d.source,to:d.to,toRecordType:d.toRecord,event:d.event,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),h.relativePath);await Cr(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),a.command("process").description("Scaffold a process file under processes/ (an invoked multi-record sequence).").requiredOption("--record <type>","Record type the first step writes, e.g. purchaseOrder").option("--then <type>","Record type of a second step that waits for the first, e.g. vendorBill").option("--on-failure <mode>","stop | rollback","stop").option("--id <id>","Override the generated process id").action(async d=>{let h;try{h=Et("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=oe(process.cwd(),h.relativePath);await Cr(w,h.content)==="skipped"&&v(`refusing to overwrite existing file: ${w}`),y(`wrote ${w}`)}),o.command("test").argument("<file>","The extension file to dry-run").description("Dry-run an extension against samples/ fixtures (production sandbox parity).").option("--samples <dir>","Samples directory","samples").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").option("--ci","CI mode \u2014 alias for the non-zero-on-failure exit (always on for `test`).").action(async(d,h)=>{let w=Gd(h.reporter),T=await Rn(oe(process.cwd(),d)),_=oe(process.cwd(),h.samples),f=await Tn(_);f.length===0&&!w&&y(`no samples found under ${_} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await Jo(T,f.map(C=>C.fixture),{resolveDir:Ht(oe(process.cwd(),d))})}catch(C){v(`bundle failed: ${C instanceof Error?C.message:String(C)}`)}if(w){let C=sC(S);y(Xo(C,w)),Mi(C.cases.some(N=>N.status==="failed")?1:0)}let $=0;for(let C of S){let N=C.pass?m.green("PASS"):m.red("FAIL");C.pass||($+=1);let M=C.error?` (error: ${C.error})`:C.observed!==C.expected?` (expected ${C.expected}, observed ${C.observed})`:C.rejection?` (rejected: ${C.rejection.code??"rejected"})`:"";y(` ${N} ${C.name}${M}`)}let A=`${S.length-$}/${S.length} sample(s) passed.`;y(`
4210
+ ${$===0?m.green(A):m.yellow(A)}`),Mi($>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,h)=>{if(h.to){let S=await Wd(),{baseUrl:$,token:A}=await B(h.baseUrl),C=new z({baseUrl:$,token:A});try{let N=await X(`applying bundle to ${h.to}`,()=>C.configApply(S,{prune:h.prune}));y(`applied bundle to ${h.to}: +${N.applied.add} ~${N.applied.change} -${N.applied.destroy}`+(N.backfillsQueued.length?` (${N.backfillsQueued.length} backfill(s) queued)`:""));let M=N.skippedDestroys??[];if(M.length>0){O(`${M.length} resource(s) exist on ${h.to} but are not declared by this project \u2014 NOT removed:`);for(let L of M)O(` ${L.kind} ${L.id}`);O("Add them to this repo (`turbobase ext export` pulls them down), or re-run with --prune to remove them.")}}catch(N){N instanceof Y&&N.status===403&&v("apply forbidden (403) \u2014 the stored PAT is not for an admin.");let M=N instanceof Y?$a(N.body):null;M&&v(`bundle apply failed \u2014 ${M}`),v(`bundle apply failed: ${N instanceof Error?N.message:String(N)}`)}return}d||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:T}=await B(h.baseUrl),_=await oC(oe(process.cwd(),d)),f=new z({baseUrl:w,token:T});try{let S=await X(`deploying ${tw(d)}`,()=>f.deploy(_)),$=Vp(S.outcome);Oe()?y(Jt("Deployed",[`${m.bold(S.id)} ${Dr(S.status)} ${m.dim($)}`])):y(`deployed ${S.id} \u2192 status=${S.status} (${$}).`)}catch(S){S instanceof Y&&S.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin.");let $=S instanceof Y?$a(S.body,d):null;$&&v($),v(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});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("--no-source","Do not record this directory as the app's newest source revision. The app stays un-pullable and a user's change request cannot be applied to it.").option("--entry <file>","SPA entrypoint served for unknown routes.","index.html").option("--create","Create the app first if it does not exist yet.").option("--proposal <id>","Widget proposal this ship realizes (defaults to .turbobase/proposal.json).").option("--preview","Deploy to a preview URL instead of going live. Nothing about /a/<slug> changes until you `apps promote` it.").option("--label <text>","Label for the preview, so several open previews are tellable apart.").option("--replace [preview-id]","Re-deploy onto an OPEN preview instead of opening a second one \u2014 the URL is unchanged, so whoever holds the link sees the new build. Omit the id when the app has exactly one open preview. Implies --preview.").option("--replace-label <text>","Re-deploy onto the open preview carrying this exact --label, opening one if there is none. The idempotent form for CI: one preview per pull request, updated in place. Implies --preview.").action(async(d,h,w)=>{let T=!!(w.preview||w.replace||w.replaceLabel);w.replace&&w.replaceLabel&&v("--replace and --replace-label both name the preview to re-deploy onto; pass one.");let _=oe(process.cwd(),h??".");await ie.mkdir(_,{recursive:!0});let f=w.proposal??await E(_),{baseUrl:S,token:$}=await B(w.baseUrl),A=new z({baseUrl:S,token:$}),C=!1;try{C=(await A.appsList()).some(ue=>ue.slug===d||ue.id===d)}catch(ue){V(ue,"extensions:deploy","deploy"),v(`could not reach ${S}: ${ue instanceof Error?ue.message:String(ue)}`)}if(!C){w.create||v(`no app "${d}" on ${S} \u2014 create it with \`turbobase apps create ${d}\`, or pass --create.`);let ue=await X(`creating app ${d}`,()=>g(S,$,{slug:d},{tolerateExisting:!0}));ue.existed||y(`created ${ue.slug??d}.`)}let N;if(w.replace)if(typeof w.replace=="string")N=w.replace;else{let{previews:ue}=await xe(S,$,d);if(ue.length===0&&v(`no open preview on ${d} to replace \u2014 drop --replace to open the first one, or name a handle from \`turbobase apps preview list\`.`),ue.length>1){for(let Ie of ue)y(` ${Ie.previewId} v${Ie.version}${Ie.label?` ${Ie.label}`:""} ${Ie.url}`);v(`${d} has ${ue.length} open previews \u2014 pass the one to replace, e.g. \`--replace ${ue[0].previewId}\`.`)}N=ue[0].previewId}let M;if(w.replaceLabel){let ue=w.replaceLabel,{previews:Ie}=await xe(S,$,d),$t=Ie.filter(Bi=>Bi.label===ue);$t.length>0?(N=$t[0].previewId,$t.length>1&&O(`${$t.length} open previews carry the label "${ue}"; replacing the newest (${N}). Close the others with \`turbobase apps preview discard\`.`)):y(`no open preview labelled "${ue}" \u2014 opening one.`),M=ue}let L=ue=>ie.stat(tt(_,ue)).then(()=>!0).catch(()=>!1),J=d,fe=_,Q=w.build!==!1,be=!1;if(Q&&!await L("package.json"))if(await L("index.html"))y("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Q=!1;else if(w.pull===!1)v(`${_} has no package.json and --no-pull was set \u2014 nothing to build. Pass --no-build to upload it as-is.`);else{let ue=await X(`pulling ${d}`,()=>k(S,$,d));J=ue.slug??d,await b(_,ue.files,!0),be=!0,y(`pulled generated source (rev ${ue.rev}).`)}let Ce;if(Q){let ue=Mh();if(Ce={buildId:ue,assetBase:qh(ue)},w.install!==!1&&!await L("node_modules")){y("installing dependencies\u2026");try{await D(["install"],_)}catch(Ie){v(`npm install failed: ${Ie instanceof Error?Ie.message:String(Ie)}`)}}y("building\u2026");try{await D(["run","build"],_,{TURBOBASE_ASSET_BASE:Ce.assetBase})}catch(Ie){v(`build failed: ${Ie instanceof Error?Ie.message:String(Ie)}`)}await L("dist")||v(`no dist/ after build in ${_} \u2014 check the app's build script.`),fe=tt(_,"dist")}T&&!Ce&&v(`--preview needs a build this CLI ran: a prebuilt bundle has its asset paths pinned to /a/${J}/, so it would render blank at a preview URL. Drop --no-build, or deploy it to production directly.`);let $e=await qe(S,$,J,fe,w.entry,f,Ce,T?{label:w.label??M,replacePreviewId:N}:void 0),Io=null;if(w.source!==!1&&!be&&await L("package.json")&&(Io=await I(S,$,J,_,f)),T){let ue=$e.previewUrl??"(no url returned)",Ie=$e.expiresAt?new Date($e.expiresAt).toLocaleDateString():`${zh} days`,$t=$e.replacedVersion==null?null:`replaced v${$e.replacedVersion} \u2014 same URL`;if(Oe())y(Jt($t?"Preview replaced":"Preview deployed",[`${m.bold(J)} ${m.green(`v${$e.version??"?"}`)} ${m.dim("not live")}`,`${m.bold(ue)}`,...$t?[m.dim($t)]:[],m.dim(`expires ${Ie}`)]));else{let Bi=$t?`; ${$t}`:"";y(`preview ${J} v${$e.version??"?"} \u2192 ${ue} (expires ${Ie}; /a/${J} unchanged${Bi}).`)}Kt($e),y(`next: turbobase apps promote ${J} ${$e.previewId??"<preview-id>"} # make it live`),y(` turbobase apps preview discard ${$e.previewId??"<preview-id>"}`);return}Oe()?y(Jt("Deployed",[`${m.bold(J)} ${m.green(`v${$e.version??"?"}`)} ${m.dim($e.url??`/a/${J}`)}`])):y(`deployed ${J} \u2192 v${$e.version??"?"} (${$e.url??`/a/${J}`}).`),Kt($e),xt($e),await Vt($e,_,Io)}),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>`.").option("--app <slug>","The app this manifest belongs to (defaults to the slug in `--as app:<slug>`). Lets the plan tell this app's earlier role scopes from another app's, and list the content values a deploy would retire.").action(async(d,h)=>{let w=h.as?.startsWith("app:")?h.as.slice(4).trim():"";h.app!==void 0&&h.app.trim()===""&&v("--app was given an empty slug \u2014 pass the app's slug, or drop the flag.");let T=h.app?.trim()??"";T&&w&&T!==w&&v(`--app ${T} and --as app:${w} name two different apps \u2014 pass one slug.`);let _=T||w||null,f=await cC(d??".");f||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`);let S=Array.isArray(f.manifest.tables)?f.manifest.tables:[],$=Array.isArray(f.manifest.writes)?f.manifest.writes:[],A=Array.isArray(f.manifest.roles)?f.manifest.roles:null,C=A??[],N=Array.isArray(f.manifest.labels)?f.manifest.labels:[],M=A!==null&&A.length===0;if(S.length===0&&$.length===0&&C.length===0&&N.length===0){if(!M)return y(`${f.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(_===null){for(let Q of _a({app:null,roles:A}))y(Q.text);return}}let{baseUrl:L,token:J}=await B(h.baseUrl),fe=new z({baseUrl:L,token:J});if(S.length>0){let Q;try{Q=await X("planning tables",()=>fe.tablesPlan({claimedBy:h.as,tables:S}))}catch(be){V(be,"extensions:deploy","plan tables"),Ao(be)}y(`claiming as ${m.bold(Q.claimedBy)}`);for(let be of Q.tables)Po(be,{showClaimants:!0})}if($.length>0||C.length>0||N.length>0||M&&_!==null){let Q;try{Q=await X("checking declared writes, roles and labels",()=>fe.appsPlan({writes:$,...A!==null?{roles:A}:{},labels:N,..._!==null?{app:_}:{}}))}catch(be){V(be,"extensions:deploy","plan writes"),v(`plan writes failed: ${be instanceof Error?be.message:String(be)}`)}Q.roles&&Rt("plan",Q.roles.verdicts,Q.roles.retired);for(let be of _a({app:_,roles:A,retired:Q.roles?.retired??null}))y(be.text);if(Q.labels&&Q.labels.verdicts.length>0){y(""),y(m.bold("labels"));let be=Math.max(...Q.labels.verdicts.map(Ce=>Ce.name.length));for(let Ce of Q.labels.verdicts){let $e=Ce.name.padEnd(be);if(Ce.action==="create")y(` create ${$e} ${m.dim(Ce.color)}`);else{let Io=Ce.declaredColor?`${Ce.color} \u2014 declared ${Ce.declaredColor}, the instance's colour is kept`:Ce.color;y(` ${m.dim("ok")} ${$e} ${m.dim(Io)}`)}}y(m.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}$.length>0&&y("");for(let be of Q.verdicts){let Ce=`${be.source} ${be.recordType}.${be.op}`;be.allowed?be.heldForApproval?y(`${m.dim("HELD")} ${Ce} \u2014 allowed, but each write waits for operator approval.`):y(`${m.dim("ok")} ${Ce}`):O(`${m.bold("DENIED")} ${Ce}${be.rule?` \u2014 guardrail "${be.rule}"`:""} (${be.reason})`)}Q.ok||(y(""),v(Q.message??(Q.roles&&!Q.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(m.dim("nothing was applied \u2014 this is a preflight. `turbobase apps deploy` runs the same checks and enforces them."))}),l.command("promote").description("Make a preview the live version at /a/<slug>. Promotes the exact reviewed bytes \u2014 no rebuild.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to promote (from `apps preview list`).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await B(w.baseUrl),f=await X(`promoting ${h}`,()=>G(T,_,d,"promote",{previewId:h}));Oe()?y(Jt("Promoted",[`${m.bold(d)} ${m.green(`v${f.version??"?"}`)} ${m.dim(f.url??`/a/${d}`)}`])):y(`promoted ${d} \u2192 v${f.version??"?"} is now live at ${f.url??`/a/${d}`}.`);let S=Op(f);Rt("applied",S.verdicts,S.retired),xt({labels:f.labels?{applied:!0,verdicts:f.labels}:null}),await Vt(f)});let u=l.command("preview").description("Inspect and manage an app's open previews.");u.command("list").description("List an app's open previews (newest first).").argument("<app>","App slug or id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a line per preview.").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=await xe(w,T,d);if(h.json)return y(JSON.stringify(_.previews,null,2));if(_.previews.length===0){y(`no open previews for ${d}.`);return}for(let f of _.previews){let S=f.label?` ${f.label}`:"",$=f.expiresAt?new Date(f.expiresAt).toLocaleDateString():"?";y(`v${f.version} ${f.previewId}${S} ${f.url} (expires ${$})`)}}),u.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await B(w.baseUrl);await X(`discarding ${h}`,()=>G(T,_,d,"discard",{previewId:h})),y(`discarded ${h}.`)}),l.command("create").description("Create a new hosted app (a bare app row) so a build can be shipped to it.").argument("<slug>","URL slug the app is served under: /a/<slug>.").option("--name <name>","Display name (defaults to the slug).").option("--description <text>","Optional description.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=await X(`creating ${d}`,()=>g(w,T,{slug:d,name:h.name,description:h.description})),f=_.slug??d;Oe()?y(Jt("Created",[`${m.bold(f)} ${m.dim(_.url??`/a/${f}`)}`])):y(`created ${f} (${_.url??`/a/${f}`}).`),y(`next: turbobase apps push ${f} . # store the source`),y(` turbobase apps deploy ${f} # build + go live`)});let p=Bo(fetch);async function g(d,h,w,T={}){let _=`${d.replace(/\/+$/,"")}/v1/apps`,f;try{f=await p(_,{method:"POST",headers:{Authorization:`Bearer ${h}`,"content-type":"application/json"},body:JSON.stringify({slug:w.slug,name:w.name??w.slug,description:w.description})})}catch(S){v(`create request failed: ${S instanceof Error?S.message:String(S)}`)}if(f.status===401&&v("create unauthorized (401) \u2014 re-run `turbobase auth login`."),f.status===403&&v("create forbidden (403) \u2014 the PAT is not for an admin."),f.status===409){if(T.tolerateExisting)return{slug:w.slug,existed:!0};v(`an app with slug "${w.slug}" already exists.`)}return f.ok||v(`create failed: HTTP ${f.status} ${(await f.text().catch(()=>"")).slice(0,200)}`),await f.json().catch(()=>({}))}async function k(d,h,w){let T=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,_;try{_=await p(T,{headers:{Authorization:`Bearer ${h}`}})}catch(f){v(`pull request failed: ${f instanceof Error?f.message:String(f)}`)}return _.status===401&&v("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),_.status===403&&v("pull forbidden (403) \u2014 the PAT is not for an admin."),_.status===404&&v(`no generated source for "${w}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),_.ok||v(`pull failed: HTTP ${_.status} ${(await _.text().catch(()=>"")).slice(0,200)}`),await _.json()}async function b(d,h,w){let T=oe(d),_=0;for(let[f,S]of Object.entries(h)){let $=oe(T,f);$!==T&&!$.startsWith(T+Xd)&&v(`refusing to write outside ${T}: ${f}`),w||await ie.stat($).then(()=>!0).catch(()=>!1)&&v(`${$} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ie.mkdir(Ht($),{recursive:!0}),await ie.writeFile($,S,"utf8"),_+=1}return _}function R(d){let h=d.indexOf(","),w=d.startsWith("data:")?h>=0?d.slice(h+1):"":d;if(!w)return null;try{let T=Buffer.from(w,"base64");return T.length>0?new Uint8Array(T):null}catch{return null}}async function x(d,h,w){let T=oe(d),_=async(S,$)=>{let A=oe(T,S);A!==T&&!A.startsWith(T+Xd)&&v(`refusing to write outside ${T}: ${S}`),w||await ie.stat(A).then(()=>!0).catch(()=>!1)&&v(`${A} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ie.mkdir(Ht(A),{recursive:!0}),await ie.writeFile(A,$)},f=`# ${h.title||"App change request"}
4142
4211
 
4143
4212
  > Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
4144
4213
  > \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
@@ -4148,35 +4217,37 @@ ${h.bodyMarkdown||"_No description provided._"}
4148
4217
  ## Screen context
4149
4218
 
4150
4219
  `+(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.
4151
- `);if(await _("PROPOSAL.md",f),h.screenshot){let k=x(h.screenshot);k&&await _("proposal-screenshot.png",k)}await _(et(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
4152
- `)}async function E(d){try{let h=await ie.readFile(et(d,".turbobase","proposal.json"),"utf8"),w=JSON.parse(h);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function P(d,h,w,T,_,f){let k=new q({baseUrl:d,token:h});try{return await k.appsPush(w,T,{note:_,proposalId:f})}catch($){if($ instanceof Y){let A=$.body;if($.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&A?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),$.status===403&&V($,"extensions:deploy","push app source"),$.status===404&&v(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),$.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),$.status===400){let C=A?.path?` in ${A.path}`:"",O=A?.reason?` (${A.reason})`:"";v(`push rejected: ${A?.error??"bad request"}${O}${C}.`)}}v(`push failed: ${$ instanceof Error?$.message:String($)}`)}}function I(d,h,w){return new Promise((T,_)=>{let f=Jd("npm",d,{cwd:h,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});f.on("error",_),f.on("exit",k=>k===0?T():_(new Error(`npm ${d.join(" ")} exited ${k??"?"}`)))})}async function D(d,h,w,T){let _=`${d.replace(/\/+$/,"")}${w}`,f;try{f=await p(_,{method:T.method,headers:{Authorization:`Bearer ${h}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(k){v(`request failed: ${k instanceof Error?k.message:String(k)}`)}if(f.status===401&&v("unauthorized (401) \u2014 re-run `turbobase auth login`."),f.status===403&&v("forbidden (403) \u2014 the PAT is not for an admin."),!f.ok){let k=await f.text().catch(()=>""),$=k.slice(0,300);try{let A=JSON.parse(k);$=A.message??A.error??$}catch{}v(`failed: HTTP ${f.status} ${$}`)}return await f.json().catch(()=>({}))}async function F(d,h,w,T,_){return await D(d,h,`/v1/apps/${encodeURIComponent(w)}/preview/${T}`,{method:"POST",body:_})}async function K(d,h,w){return{previews:(await D(d,h,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function Ce(d,h,w,T,_,f,k,$){let A;try{A=await X(`zipping ${T}`,()=>ep(T))}catch(N){v(`could not zip ${T}: ${N instanceof Error?N.message:String(N)}`)}A.fileCount===0&&v(`${T} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>Da&&v(`${T} zips to ${Yb(A.buffer.byteLength)} \u2014 over the ${Yb(Da)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let C={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};_&&(C["x-app-entry"]=_),f&&(C["x-proposal-id"]=f),k&&(C["x-app-build-id"]=k.buildId,C["x-app-asset-base"]=k.assetBase),$&&(C["x-app-channel"]="preview",$.label&&(C["x-app-preview-label"]=encodeURIComponent($.label)),$.replacePreviewId&&(C["x-app-preview-replace"]=$.replacePreviewId));let O=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,W;try{W=await X(`deploying ${w} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(O,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(N){v(`deploy request failed: ${N instanceof Error?N.message:String(N)}`)}if(W.status===401&&v("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),W.status===403&&v("deploy forbidden (403) \u2014 the PAT is not for an admin."),W.status===404){let N=await W.text().catch(()=>""),J={};try{J=JSON.parse(N)}catch{}J.error==="no_preview"&&v(`${J.message??`no open preview to replace on ${w}`} \u2014 list them with \`turbobase apps preview list ${w}\`.`),v(`no app "${w}" on ${d} \u2014 create it with \`turbobase apps create ${w}\`.`)}if(!W.ok){let N=await W.text().catch(()=>""),J=N.slice(0,300);try{let me=JSON.parse(N);J=me.message??me.error??J}catch{}v(`deploy failed: HTTP ${W.status} ${J}`)}return await W.json().catch(()=>({}))}function Ie(d,h,w){for(let T of $p({mode:d,verdicts:h,retired:w}))(T.stream==="err"?L:b)(T.text)}function Nt(d){let h=d.roles;h&&Ie(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function Ht(d){let h=d.labels;if(!h||h.verdicts.length===0)return;let w=h.verdicts.filter(_=>_.action!=="noop");if(w.length===0)return;b(""),b(m.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(...w.map(_=>_.name.length));for(let _ of w){let f=_.name.padEnd(T);if(_.action==="detach")b(` removed ${f} ${m.dim("no longer declared in the manifest")}`);else if(_.action==="create")b(` created ${f} ${m.dim(_.color)}`);else{let k=_.declaredColor?`${_.color} \u2014 declared ${_.declaredColor}, the instance's colour is kept`:_.color;b(` added ${f} ${m.dim(k)}`)}}b(m.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Tt(d,h){let w=vp(d,{localDocsModifiedAt:await dr(h)});w&&b(w.level==="warn"?m.yellow(w.message):m.dim(w.message))}async function dr(d){if(!d)return null;let h=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await ie.stat(et(d,w));(h===null||T.mtimeMs>h)&&(h=T.mtimeMs)}catch{}return h===null?null:new Date(h)}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await z(w.baseUrl);if(w.proposal){let A=new q({baseUrl:T,token:_}),C;try{C=await X(`fetching proposal ${w.proposal}`,()=>A.appPullContext(w.proposal))}catch(me){V(me,"extensions:deploy","pull proposal"),me instanceof Y&&me.status===404&&v(`no widget proposal "${w.proposal}" on ${T}.`),v(`could not fetch proposal ${w.proposal}: ${me instanceof Error?me.message:String(me)}`)}let O=await X(`pulling ${C.appSlug}`,()=>S(T,_,C.appSlug)),W=h??d,N=oe(process.cwd(),W??C.appSlug);await ie.mkdir(N,{recursive:!0});let J=await y(N,O.files,!!w.force);await R(N,C,!!w.force),b(`pulled ${J} file${J===1?"":"s"} \u2192 ${N} (rev ${O.rev}), linked to proposal ${C.proposalId}.`),b(`next: cd ${Di(process.cwd(),N)||"."} && turbobase apps deploy ${C.appSlug}`);return}d||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let f=await X(`pulling ${d}`,()=>S(T,_,d)),k=oe(process.cwd(),h??f.slug??d);await ie.mkdir(k,{recursive:!0});let $=await y(k,f.files,!!w.force);b(`pulled ${$} file${$===1?"":"s"} \u2192 ${k} (rev ${f.rev}).`),b(`next: cd ${Di(process.cwd(),k)||"."} && turbobase apps deploy ${f.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(d,h,w)=>{let T=oe(process.cwd(),h??d),_=await ht(w.baseUrl).catch(()=>null),{scaffoldAppFiles:f,starterApp:k}=await Promise.resolve().then(()=>(gm(),fm)),$=w.title??d,A=f({slug:d,title:$,appTsx:k($),instanceOrigin:_?.baseUrl});await ie.mkdir(T,{recursive:!0});let C=await y(T,A,!!w.force);if(b(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${T}`),w.claude!==!1){let W=_a({baseUrl:_?.baseUrl,token:_?.token,appSlug:d}),N=0;for(let J of W){let me=await Jb(et(T,J.path),J);(me==="wrote"||me==="merged")&&(N+=1)}b(`wired Claude Code: ${N} file${N===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),_||L("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let O=Di(process.cwd(),T)||".";b(`next: cd ${O} && npm install && npm run dev`),b(` turbobase apps create ${d}`),b(` turbobase apps push ${d} .`),b(` turbobase apps deploy ${d} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.appsList()}catch(f){V(f,"extensions:deploy","list apps"),v(`list apps failed: ${f instanceof Error?f.message:String(f)}`)}if(d.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");b(ft(_.map(f=>[f.slug,f.name,f.deployed?"yes":"no",f.sourceRev===null?"\u2014":`rev ${f.sourceRev}`,f.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(d,h,w)=>{let T=oe(process.cwd(),h??".");await ie.stat(T).then(Q=>Q.isDirectory()).catch(()=>!1)||v(`${T} is not a directory.`);let{baseUrl:f,token:k}=await z(w.baseUrl),$=w.proposal??await E(T),{files:A,skipped:C,secrets:O,unstorable:W}=await Nh(T),N=Object.keys(A).length;if(N===0&&v(`no source files found under ${T} (build output and node_modules are skipped).`),W.length>0){for(let Q of W)L(`${Q} contains a NUL byte (U+0000), which cannot be stored.`);v(`push aborted: ${W.length} ${W.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and push again.`)}for(let Q of C)L(m.dim(`skipped binary file ${Q}`));for(let Q of O)L(m.dim(`skipped ${Q} (holds credentials \u2014 never pushed)`));let J=await X(`pushing ${N} file${N===1?"":"s"}`,()=>P(f,k,d,A,w.note,$));b(`pushed ${J.files} file${J.files===1?"":"s"} \u2192 ${J.slug} rev ${J.rev} (source only, nothing deployed).`);let me=await Cn(new q({baseUrl:f,token:k}),J.slug);me&&me.entriesAdded>0&&b(`${me.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),b(`next: turbobase apps deploy ${J.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let h=await Kd(),{baseUrl:w,token:T}=await z(d.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await X(`planning against ${d.to??w}`,()=>_.configPlan(h))}catch(k){v(`plan failed: ${k instanceof Error?k.message:String(k)}`)}QA(f,d.to??w)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let h=await Kd(),{baseUrl:w,token:T}=await z(d.baseUrl),_=h.tenant??eC(w),f=Up(d.confirm,_);f.ok||v(`promote refused (fail-closed): ${f.reason}`);let k=new q({baseUrl:w,token:T});try{let $=await X(`promoting ${d.from} \u2192 ${d.to} (${_})`,()=>k.configApply(h,{prune:d.prune}));if(Oe()){let C=[`${m.bold(`${d.from} \u2192 ${d.to}`)} ${m.dim(_??"")}`,`${Vt.add(String($.applied.add))} ${Vt.change(String($.applied.change))} ${Vt.destroy(String($.applied.destroy))}`];$.backfillsQueued.length&&C.push(m.dim(`${$.backfillsQueued.length} backfill(s) queued`)),b(Gt("Promoted",C))}else b(`promoted ${d.from} \u2192 ${d.to} (${_}): +${$.applied.add} ~${$.applied.change} -${$.applied.destroy}`+($.backfillsQueued.length?` (${$.backfillsQueued.length} backfill(s) queued)`:""));let A=$.skippedDestroys??[];if(A.length>0){L(`${A.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let C of A)L(` ${C.kind} ${C.id}`);L("Re-run with --prune to remove them, or add them to this repo.")}}catch($){$ instanceof Y&&$.status===403&&v("promote forbidden (403) \u2014 the stored PAT is not for an admin."),v(`promote failed: ${$ instanceof Error?$.message:String($)}`)}}),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(d,h)=>{let w=Hd(h.reporter),T=oe(process.cwd(),d),_=await Tn(T),f=rp(_);w?b(Wo(WA(d,f),w)):b(np(d,f,{warn:m.yellow,ok:m.green,dim:m.dim})),h.ci&&f.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(d,h)=>{let w=Hd(h.reporter),T=await Wu(oe(process.cwd(),d));if(h.against){h.against!=="sandbox"&&v(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Vu(ha(T))}catch(k){v(k instanceof Error?k.message:String(k))}return}h.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let _;try{_=await Gu(oe(process.cwd(),h.fixture))}catch(k){v(`could not read fixture ${h.fixture}: ${k instanceof Error?k.message:String(k)}`)}let f=await Ku(T,_,h.fixture,{resolveDir:Ft(oe(process.cwd(),d))});if(w){let k=JA(f);b(Wo(k,w)),ji(k.cases.some($=>$.status==="failed")?1:0)}b(Ju(f,!!h.trace)),ji(f.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w});try{await dp(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:b})}catch(_){_ instanceof Y&&_.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),_ instanceof Y&&_.status===409&&v("binding is not retryable (only divergent/blocked bindings can be retried)."),v(`ext binding failed: ${_ instanceof Error?_.message:String(_)}`)}});let ur=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");ur.command("list").description("List hook proposals and the evidence behind each (defaults to the pending queue).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <list>","proposed | active | rejected (comma-joined). Default: proposed.").option("--provenance <list>","mechanic | operator | learning | code-baseline (comma-joined).").option("--record-type <type>","Only proposals for this record type.").option("--source <system>","Only proposals for this adapter id.").option("--limit <n>","Max rows listed (default 200).").option("--json","Emit raw JSON instead of a table.").action(async d=>{await wh(d)}),ur.command("promote [ids...]").description("Arm hook proposals so the loader enforces them \u2014 by id, or by filter with --auto.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--auto","Select by filter instead of by id. Prints the plan; writes nothing without --apply.").option("--apply","With --auto: actually arm the planned proposals.").option("--provenance <list>","Restrict --auto to these provenances (mechanic | operator | code-baseline).").option("--record-type <type>","Restrict --auto to this record type.").option("--source <system>","Restrict --auto to this adapter id.").option("--limit <n>","Cap how many proposals --auto considers.").option("--all","Required to --apply an UNFILTERED plan (arm the whole queue).").option("-y, --yes","Skip the confirmation prompt (required on a non-interactive terminal).").option("--json","Emit the plan as JSON.").action(async(d,h)=>{await vh(d??[],h)}),ur.command("retract <ids...>").description("Send armed hooks back to proposed \u2014 inert immediately, source kept, re-promotable.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{await _h(d,h)}),ur.command("reject <ids...>").description("Decline proposals for good \u2014 the id becomes the denylist. Prefer `retract` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--reason <text>","Why \u2014 recorded on the row and in the audit log.").action(async(d,h)=>{await Sh(d,h)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await kh(d,h)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Th(d,h)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await xh(d,h)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(d,h)=>{let w=d.lastIndexOf("@"),T=w>0?d.slice(0,w):d,_=w>0?d.slice(w+1):void 0,f=la();f||v(`marketplace not configured \u2014 set ${Or} and ${qo}.
4153
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let k=ca(f.registryUrl);k&&v(k);let{baseUrl:$,token:A}=await z(h.baseUrl),C=new _n(f),O;try{O=await X(`fetching ${d}`,()=>C.fetchBundle(T,_))}catch(Q){v(`marketplace fetch failed for ${d}: ${Q instanceof Error?Q.message:String(Q)}`)}let W=Ao(O.manifest),N=null;if(W.length>0){if(!h.connection){let Q=W.map(be=>be.source_system).join(", ");v(`${O.name}@${O.version} declares a connection input (source: ${Q}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}N=h.connection}let J=YA(O.bundle,O.name,O.kind),me=new q({baseUrl:$,token:A});try{let Q=await X(`installing ${O.name}@${O.version}`,()=>me.deploy({...J,provenance:"marketplace",...N?{connectionId:N}:{}}));b(`installed ${O.name}@${O.version} \u2192 ${Q.id} (status=${Q.status}, ${Q.outcome})`+(N?` bound to connection ${N}.`:"."))}catch(Q){Q instanceof Y&&Q.status===403&&v("install forbidden (403) \u2014 the stored PAT is not for an admin."),v(`install failed: ${Q instanceof Error?Q.message:String(Q)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(d,h)=>{let w=la();w||v(`marketplace not configured \u2014 set ${Or} and ${qo}.
4154
- Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=ca(w.registryUrl);T&&v(T);let _=oe(process.cwd(),d),f=await Tn(_),k=/\bdefineConduit\s*[<(]/.test(f)?"conduit":"hook",$={};if(h.manifest){let O=oe(process.cwd(),h.manifest),W;try{W=await ie.readFile(O,"utf8")}catch{v(`manifest not found at ${h.manifest}.`)}let N;try{N=JSON.parse(W)}catch{v(`manifest is not valid JSON: ${h.manifest}.`)}(typeof N!="object"||N===null||Array.isArray(N))&&v("manifest must be a JSON object."),$=N}try{Fi($,f)}catch(O){O instanceof Kt&&v(O.message),v(`manifest validation failed: ${O instanceof Error?O.message:String(O)}`)}let A=new _n(w);try{await X(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:k,bundle:f,manifest:$}))}catch(O){O instanceof Y&&O.status===403&&v("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),O instanceof Y&&O.status===409&&v(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),v(`publish failed: ${O instanceof Error?O.message:String(O)}`)}let C=Ao($);b(`published ${h.name}@${h.pkgVersion} (kind=${k}) to the marketplace.`),C.length>0&&b(` declares ${C.length} connection input(s): ${C.map(O=>O.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 ht(d.baseUrl).catch(()=>null),w=_a({baseUrl:h?.baseUrl,token:h?.token}),T=0,_=0,f=0;for(let k of w){let $=oe(process.cwd(),k.path),A=await Jb($,k);A==="wrote"?(T+=1,b(` wrote ${k.path}`)):A==="merged"?(f+=1,b(` merged ${k.path} (added the .mcp.json rule)`)):(_+=1,b(` skipped ${k.path} (exists)`))}b(`
4155
- project init: ${T} written, ${f} merged, ${_} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${va} (non-destructive).`).action(async()=>{let d=Pp(),h=0,w=0;for(let T of d){let _=oe(process.cwd(),T.path);await Ar(_,T.content,T.executable)==="wrote"?(h+=1,b(` wrote ${T.path}`)):(w+=1,b(` skipped ${T.path} (exists)`))}b(`
4156
- project ci: ${h} written, ${w} skipped.`),h>0&&(b(`
4157
- Next: mint a releases:write PAT in your Turbobase app (Settings \u203A Access tokens),`),b("store it as the GitHub Actions secret TURBOBASE_RELEASE_PAT, and set the repo"),b("variable TURBOBASE_BASE_URL \u2014 the workflow header has the step-by-step."))}),n.command("samples").description("Generate samples/<recordType>.json fixtures from the live instance catalog.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Output directory for the fixtures","samples").option("--event <event>","Lifecycle event to stamp on each fixture","before_save").option("--force","Overwrite existing fixture files (default: skip files that exist).").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.catalogRecords()}catch(C){C instanceof Y&&(C.status===401||C.status===403)&&v("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),v(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(_.length===0){b("no records in the instance catalog \u2014 nothing to generate.");return}let f=oe(process.cwd(),d.out),k=Xu(_,{event:d.event}),$=0,A=0;for(let{recordType:C,fixture:O}of k){let W=et(f,`${C}.json`),N=`${JSON.stringify(O,null,2)}
4158
- `;d.force?(await ie.mkdir(Ft(W),{recursive:!0}),await ie.writeFile(W,N,{mode:420}),$+=1,b(` wrote ${d.out}/${C}.json`)):await Ar(W,N)==="wrote"?($+=1,b(` wrote ${d.out}/${C}.json`)):(A+=1,b(` skipped ${d.out}/${C}.json (exists \u2014 use --force to overwrite)`))}b(`
4159
- samples init: ${$} written, ${A} skipped.`)});let xt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),Ui=d=>[d.name??m.dim(d.id.slice(0,8)),d.status==="active"?m.green("active"):d.status==="proposed"?m.yellow("proposed"):m.dim("inactive"),d.decision==="deny"?m.red(d.decision):d.decision==="require_confirm"?m.yellow(d.decision):m.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??m.dim("any"),d.when||m.dim("(always)"),d.reason??""],Zb=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];xt.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.guardrailsList()}catch(f){V(f,"extensions:deploy","list guardrails"),v(`list guardrails failed: ${f instanceof Error?f.message:String(f)}`)}if(d.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b(`no write guardrails \u2014 every record the admin entitlement allows is writable.
4160
- `+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(ft(_.map(Ui),{head:Zb})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),xt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.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(k){V(k,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${k instanceof Error?k.message:String(k)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} created${f.status==="active"?"":m.dim(` (${f.status} \u2014 activate it to take effect)`)}`),b(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.actor?` actor=${f.actor}`:""}${f.when?` where ${f.when}`:""} @prio ${f.priority}`)),b(m.dim(` verify with: turbobase guardrails test --source ${f.source==="*"?"<source>":f.source} --record <record>`))}),xt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.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(k){V(k,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${k instanceof Error?k.message:String(k)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} updated`),b(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.when?` where ${f.when}`:""} @prio ${f.priority}`))});for(let[d,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])xt.command(`${d} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,_)=>{let{baseUrl:f,token:k}=await z(_.baseUrl),$=new q({baseUrl:f,token:k});try{await $.guardrailUpdate(T,{status:h})}catch(A){V(A,"extensions:deploy",`${d} a guardrail`),v(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(T)} ${w}`),h==="inactive"&&b(m.dim(" writes it was gating now fall through to the other rules."))});xt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T});try{await _.guardrailDelete(d)}catch(f){V(f,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${f instanceof Error?f.message:String(f)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(d)} deleted`)}),xt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await _.guardrailPostureGet()}catch(C){V(C,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}b(`guardrail posture: ${m.bold(f(A.mode))}`),b(m.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let k=d.trim().toLowerCase();k!=="allow"&&k!=="deny"&&v("posture must be 'allow' or 'deny'.");let $;try{$=await _.guardrailPostureSet(k)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail posture set to ${m.bold(f($.mode))}`),$.mode==="deny"&&b(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),xt.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($){v(`--fields must be valid JSON: ${$ instanceof Error?$.message:String($)}`)}let{baseUrl:w,token:T}=await z(d.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.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($){V($,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${$ instanceof Error?$.message:String($)}`)}if(d.json)return b(JSON.stringify(f,null,2));let k=`${d.source}/${f.op??d.record}`;f.degraded?(b(`${m.red("\u2717")} ${k} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${f.reason}`))):f.allowed?b(`${m.green("\u2713")} ${k} \u2014 ${f.decision}`+(f.blockedBy?m.dim(` (rule ${f.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${k} \u2014 ${f.decision} by ${m.bold(f.blockedBy??"?")} at the ${f.phase} gate`),f.message&&b(m.dim(` ${f.message}`))),f.decision==="require_confirm"&&b(m.yellow(" this write is HELD for operator approval, not refused.")),f.allowed||(process.exitCode=1)});let yn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),$o=(d,h={})=>{let w=`${m.bold(d.table)} ${m.dim(d.displayName)}`;b(d.exists===!1?`${w} ${m.dim("(new)")}`:w);for(let T of d.fields){let _=[T.required?"required":null].filter(Boolean).join(", "),f=h.showClaimants&&T.claimedBy?.length?` ${m.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";b(` ${T.column.padEnd(28)} ${T.type}${_?` (${_})`:""}${f}`)}h.showClaimants&&d.claimants.length>1&&b(m.dim(` claimed by ${d.claimants.join(", ")}`))};function Eo(d){if(d instanceof Y&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(L(h.message),process.exit(1))}v(`tables: ${d instanceof Error?d.message:String(d)}`)}let Xd=async d=>{let h=et(oe(process.cwd(),d),"public","turbobase.json"),w=await ie.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let T;try{T=JSON.parse(w)}catch(f){v(`${h} is not valid JSON: ${f instanceof Error?f.message:String(f)}`)}let _=T.tables;return _===void 0?{tables:[],manifestPath:h}:(Array.isArray(_)||v(`${h}: "tables" must be an array.`),{tables:_,manifestPath:h})};yn.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.tablesList()}catch(f){V(f,"extensions:deploy","list tables"),v(`list tables failed: ${f instanceof Error?f.message:String(f)}`)}if(d.json)return b(JSON.stringify(_,null,2));if(_.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(ft(_.map(f=>[f.table,f.displayName,String(f.fields.length),f.status,f.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),yn.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,h)=>{let w=await Xd(d??".");if(w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:_}=await z(h.baseUrl),f=new q({baseUrl:T,token:_}),k;try{k=await X("planning tables",()=>f.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch($){V($,"extensions:deploy","plan tables"),Eo($)}b(`claiming as ${m.bold(k.claimedBy)}`);for(let $ of k.tables)$o($,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),yn.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,h)=>{let w=await Xd(d??".");if(w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:_}=await z(h.baseUrl),f=new q({baseUrl:T,token:_}),k;try{k=await X("applying tables",()=>f.tablesApply({claimedBy:h.as,tables:w.tables}))}catch($){V($,"extensions:deploy","apply tables"),Eo($)}for(let $ of k.tables)$o($,{showClaimants:!0});b(`applied ${k.tables.length} table${k.tables.length===1?"":"s"} as ${k.claimedBy}.`)}),yn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let w=h.field.map($=>{let[A,C,O]=$.split(":");return(!A||!C)&&v(`--field "${$}" must be name:type[:required] (e.g. title:text:required).`),O!==void 0&&O!=="required"&&v(`--field "${$}": the third part may only be "required".`),{name:A,type:C,...O==="required"?{required:!0}:{}}}),{baseUrl:T,token:_}=await z(h.baseUrl),f=new q({baseUrl:T,token:_}),k;try{k=await X(`creating cr_${d}`,()=>f.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch($){V($,"extensions:deploy","create a table"),Eo($)}for(let $ of k.tables)$o($);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),yn.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.confirm!==d&&v(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await X(`dropping cr_${d}`,()=>_.tablesDrop(d,h.confirm))}catch(k){V(k,"extensions:deploy","drop a table"),v(`drop failed: ${k instanceof Error?k.message:String(k)}`)}if(!f.removed)return b(`no table named "${d}" on this instance \u2014 nothing dropped.`);b(`dropped ${f.table} and every row in it.`)});let Mi=e.command("sandbox").description("Ephemeral local authoring sandboxes.");Mi.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(),w;try{w=await Kh(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof On&&v(T.message),v(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}b(`sandbox ${w.name} ready.`),b(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),b(` url: ${w.url}`),b(` expires: ${w.expiresAt}`)}),Mi.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 Ga(h).catch(()=>[]);let w;try{w=await Vh(h,d)}catch(T){v(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}w||v(`no sandbox named '${d}'.`),b(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),Mi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Vd(),h=await Ga(d).catch(()=>[]),w=await us(),{active:T}=Va(w);if(T.length===0)b("no active sandboxes.");else{for(let _ of T)b(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);b(`
4161
- ${T.length} active sandbox(es).`)}h.length>0&&b(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",es).action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await X("exporting instance config",()=>T.configExport())}catch($){$ instanceof Y&&($.status===401||$.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${$ instanceof Error?$.message:String($)}`)}let f=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
4162
- `,k=oe(process.cwd(),d.out,En);await ie.mkdir(Ft(k),{recursive:!0}),await ie.writeFile(k,f,"utf8"),b(`wrote ${d.out}/${En} (${f.split(`
4163
- `).length} lines).`)});let Zd=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Qb=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],Qd=()=>process.env.TURBOBASE_HOME?.trim()||et(qA(),".turbobase"),ew=()=>"1.40.1",Po=async()=>Promise.all(Qb.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));Zd.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Po();for(let h of d)b(`${h.present?_e.success("installed"):_e.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&b(`
4164
- run \`${Mr} ext extras install\` to fetch them into ${Qd()}.`)}),Zd.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Po();if(d.every(A=>A.present)){b(_e.success("extras already installed \u2014 nothing to do."));return}let h=Qd();await ie.mkdir(h,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),T=qa(process.platform,process.arch),_=async(A,C)=>{let{code:O,stderr:W}=await Ro("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);O!==0&&v(`extras install failed while installing ${C} (npm exited ${O}).
4165
- ${W.trim()}
4166
- These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},f=w.filter(A=>A!=="isolated-vm");if(f.length>0){let A=f.map(C=>`${C}@${Ua[C]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await _(A,f.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Ua["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await _(["--ignore-scripts",A],"isolated-vm"),Uh.includes(T)){let O=`${Ma}@${ew()}`;b(`fetching ${O} (no upstream binary for ${T}) \u2026`);let{code:W}=await Ro("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",O]);W!==0&&b(_e.warn(`could not fetch ${O} \u2014 falling back to a source build.`))}let C=await Mh({home:h});C.length>0&&b(` ${_e.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let k=await Po(),$=k.filter(A=>!A.present).map(A=>A.name);if($.includes("isolated-vm")){b(_e.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${za()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await Ro("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(k=await Po(),$=k.filter(C=>!C.present).map(C=>C.name))}$.length>0&&v(`npm succeeded but ${$.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${za()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(_e.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let Cr=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");Cr.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||v(`--target must be 'auto' or 'approved' (got '${d.target}').`);let w=await tC(oe(process.cwd(),d.project??".")),T=Object.keys(w).length;!d.solution&&T===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let f=(d.ref?await Gd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Gd(["rev-parse","HEAD"]),k=d.gitRepo??process.env.GITHUB_REPOSITORY??await Gd(["remote","get-url","origin"]),$=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:O}=await z(d.baseUrl),W=new q({baseUrl:C,token:O}),N;try{N=await W.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?w:null,gitRepo:k,gitRef:$,gitSha:f,prUrl:A})}catch(J){V(J,"releases:write","release deploy"),J instanceof Y&&J.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${J instanceof Error?J.message:String(J)}`)}b(`release ${N.releaseId} enqueued \u2192 taskId=${N.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Ea(()=>W.releaseStatus(N.releaseId),`release ${N.releaseId}`,d.intervalMs)}),Cr.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.releaseFiles(d)}catch(A){A instanceof Y&&A.status===404&&v(`release ${d} not found.`),A instanceof Y&&A.status===409&&v(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),V(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let k=oe(process.cwd(),h.dir),$=0;for(let[A,C]of[["owned",f.owned],["context",f.context]])for(let[O,W]of Object.entries(C)){let N=et(k,A,O);await ie.mkdir(Ft(N),{recursive:!0}),await ie.writeFile(N,W,"utf8"),$++}await ie.writeFile(et(k,".turbobase-release.json"),JSON.stringify({releaseId:f.releaseId,version:f.version,contentDigest:f.contentDigest},null,2),"utf8"),b(`pulled release ${f.releaseId} (${f.status}) \u2192 ${k}
4220
+ `);if(await _("PROPOSAL.md",f),h.screenshot){let S=R(h.screenshot);S&&await _("proposal-screenshot.png",S)}await _(tt(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
4221
+ `)}async function E(d){try{let h=await ie.readFile(tt(d,".turbobase","proposal.json"),"utf8"),w=JSON.parse(h);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function P(d,h,w,T,_,f){let S=new z({baseUrl:d,token:h});try{return await S.appsPush(w,T,{note:_,proposalId:f})}catch($){if($ instanceof Y){let A=$.body;if($.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),$.status===403&&A?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),$.status===403&&V($,"extensions:deploy","push app source"),$.status===404&&v(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),$.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),$.status===400){let C=A?.path?` in ${A.path}`:"",N=A?.reason?` (${A.reason})`:"";v(`push rejected: ${A?.error??"bad request"}${N}${C}.`)}}v(`push failed: ${$ instanceof Error?$.message:String($)}`)}}async function I(d,h,w,T,_){let f;try{f=await Da(T)}catch(M){return O(`source not recorded: could not read ${T} (${M instanceof Error?M.message:String(M)}).`),null}let{files:S,skipped:$,secrets:A,unstorable:C}=f,N=Object.keys(S).length;if(N===0)return O(`source not recorded: no source files found under ${T}.`),null;if(C.length>0){for(let M of C)O(`${M} contains a NUL byte (U+0000), which cannot be stored.`);return O(`source not recorded: ${C.length} ${C.length===1?"file holds":"files hold"} a NUL byte. Replace the literal byte with the escape '\\u0000' and run \`turbobase apps push ${w}\`.`),null}for(let M of $)O(m.dim(`skipped binary file ${M}`));for(let M of A)O(m.dim(`skipped ${M} (holds credentials \u2014 never pushed)`));try{let M=await new z({baseUrl:d,token:h}).appsPush(w,S,{..._?{proposalId:_}:{}});return y(`recorded ${N} source file${N===1?"":"s"} on the instance (rev ${M.rev}).`),typeof M.rev=="number"?M.rev:null}catch(M){return O(`source not recorded: ${M instanceof Error?M.message:String(M)} \u2014 the version is live; run \`turbobase apps push ${w}\` to record its source.`),null}}function D(d,h,w){return new Promise((T,_)=>{let f=Zd("npm",d,{cwd:h,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});f.on("error",_),f.on("exit",S=>S===0?T():_(new Error(`npm ${d.join(" ")} exited ${S??"?"}`)))})}async function H(d,h,w,T){let _=`${d.replace(/\/+$/,"")}${w}`,f;try{f=await p(_,{method:T.method,headers:{Authorization:`Bearer ${h}`,...T.body?{"content-type":"application/json"}:{}},...T.body?{body:JSON.stringify(T.body)}:{}})}catch(S){v(`request failed: ${S instanceof Error?S.message:String(S)}`)}if(f.status===401&&v("unauthorized (401) \u2014 re-run `turbobase auth login`."),f.status===403&&v("forbidden (403) \u2014 the PAT is not for an admin."),!f.ok){let S=await f.text().catch(()=>""),$=S.slice(0,300);try{let A=JSON.parse(S);$=A.message??A.error??$}catch{}v(`failed: HTTP ${f.status} ${$}`)}return await f.json().catch(()=>({}))}async function G(d,h,w,T,_){return await H(d,h,`/v1/apps/${encodeURIComponent(w)}/preview/${T}`,{method:"POST",body:_})}async function xe(d,h,w){return{previews:(await H(d,h,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function qe(d,h,w,T,_,f,S,$){let A;try{A=await X(`zipping ${T}`,()=>sp(T))}catch(L){v(`could not zip ${T}: ${L instanceof Error?L.message:String(L)}`)}A.fileCount===0&&v(`${T} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>qa&&v(`${T} zips to ${ew(A.buffer.byteLength)} \u2014 over the ${ew(qa)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let C={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};_&&(C["x-app-entry"]=_),f&&(C["x-proposal-id"]=f),S&&(C["x-app-build-id"]=S.buildId,C["x-app-asset-base"]=S.assetBase),$&&(C["x-app-channel"]="preview",$.label&&(C["x-app-preview-label"]=encodeURIComponent($.label)),$.replacePreviewId&&(C["x-app-preview-replace"]=$.replacePreviewId));let N=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,M;try{M=await X(`deploying ${w} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(N,{method:"POST",headers:C,body:new Uint8Array(A.buffer)}))}catch(L){v(`deploy request failed: ${L instanceof Error?L.message:String(L)}`)}if(M.status===401&&v("deploy unauthorized (401) \u2014 re-run `turbobase auth login`."),M.status===403&&v("deploy forbidden (403) \u2014 the PAT is not for an admin."),M.status===404){let L=await M.text().catch(()=>""),J={};try{J=JSON.parse(L)}catch{}J.error==="no_preview"&&v(`${J.message??`no open preview to replace on ${w}`} \u2014 list them with \`turbobase apps preview list ${w}\`.`),v(`no app "${w}" on ${d} \u2014 create it with \`turbobase apps create ${w}\`.`)}if(!M.ok){let L=await M.text().catch(()=>""),J=L.slice(0,300);try{let fe=JSON.parse(L);J=fe.message??fe.error??J}catch{}v(`deploy failed: HTTP ${M.status} ${J}`)}return await M.json().catch(()=>({}))}function Rt(d,h,w){for(let T of Ip({mode:d,verdicts:h,retired:w}))(T.stream==="err"?O:y)(T.text)}function Kt(d){let h=d.roles;h&&Rt(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function xt(d){let h=d.labels;if(!h||h.verdicts.length===0)return;let w=h.verdicts.filter(_=>_.action!=="noop");if(w.length===0)return;y(""),y(m.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let T=Math.max(...w.map(_=>_.name.length));for(let _ of w){let f=_.name.padEnd(T);if(_.action==="detach")y(` removed ${f} ${m.dim("no longer declared in the manifest")}`);else if(_.action==="create")y(` created ${f} ${m.dim(_.color)}`);else{let S=_.declaredColor?`${_.color} \u2014 declared ${_.declaredColor}, the instance's colour is kept`:_.color;y(` added ${f} ${m.dim(S)}`)}}y(m.dim(h.applied?" labels are launcher navigation only \u2014 they change nothing about who can open this app.":" nothing was changed \u2014 promoting this preview applies them."))}async function Vt(d,h,w){let T=Rp(d,{localDocsModifiedAt:await Eo(h),recordedSourceRev:w});T&&y(T.level==="warn"?m.yellow(T.message):m.dim(T.message))}async function Eo(d){if(!d)return null;let h=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await ie.stat(tt(d,w));(h===null||T.mtimeMs>h)&&(h=T.mtimeMs)}catch{}return h===null?null:new Date(h)}l.command("pull").description("Write an app's generated source tree to disk (from the proposal that generated it).").argument("[app]","App slug or id. Omit when using --proposal (the app is derived from it).").argument("[dir]","Directory to write into (default ./<slug>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--force","Overwrite existing files.").option("--proposal <id>","Pull the app behind a widget proposal + its request context.").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await B(w.baseUrl);if(w.proposal){let A=new z({baseUrl:T,token:_}),C;try{C=await X(`fetching proposal ${w.proposal}`,()=>A.appPullContext(w.proposal))}catch(fe){V(fe,"extensions:deploy","pull proposal"),fe instanceof Y&&fe.status===404&&v(`no widget proposal "${w.proposal}" on ${T}.`),v(`could not fetch proposal ${w.proposal}: ${fe instanceof Error?fe.message:String(fe)}`)}let N=await X(`pulling ${C.appSlug}`,()=>k(T,_,C.appSlug)),M=h??d,L=oe(process.cwd(),M??C.appSlug);await ie.mkdir(L,{recursive:!0});let J=await b(L,N.files,!!w.force);await x(L,C,!!w.force),y(`pulled ${J} file${J===1?"":"s"} \u2192 ${L} (rev ${N.rev}), linked to proposal ${C.proposalId}.`),y(`next: cd ${qi(process.cwd(),L)||"."} && turbobase apps deploy ${C.appSlug}`);return}d||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let f=await X(`pulling ${d}`,()=>k(T,_,d)),S=oe(process.cwd(),h??f.slug??d);await ie.mkdir(S,{recursive:!0});let $=await b(S,f.files,!!w.force);y(`pulled ${$} file${$===1?"":"s"} \u2192 ${S} (rev ${f.rev}).`),y(`next: cd ${qi(process.cwd(),S)||"."} && turbobase apps deploy ${f.slug}`)}),l.command("init").description("Scaffold a new app project locally, wired to your instance and to Claude Code.").argument("<app>","App slug \u2014 also the /a/<slug> mount path the build is pinned to.").argument("[dir]","Directory to scaffold into (default ./<app>).").option("--title <text>","Display title used in index.html and the starter component.").option("--base-url <url>","Instance to wire the project to (defaults to the active instance).").option("--no-claude","Skip the Claude Code wiring (CLAUDE.md, .mcp.json, .claude/).").option("--force","Overwrite existing files.").action(async(d,h,w)=>{let T=oe(process.cwd(),h??d),_=await ft(w.baseUrl).catch(()=>null),{scaffoldAppFiles:f,starterApp:S}=await Promise.resolve().then(()=>(vm(),wm)),$=w.title??d,A=f({slug:d,title:$,appTsx:S($),instanceOrigin:_?.baseUrl});await ie.mkdir(T,{recursive:!0});let C=await b(T,A,!!w.force);if(y(`scaffolded ${C} file${C===1?"":"s"} \u2192 ${T}`),w.claude!==!1){let M=ka({baseUrl:_?.baseUrl,token:_?.token,appSlug:d}),L=0;for(let J of M){let fe=await Qb(tt(T,J.path),J);(fe==="wrote"||fe==="merged")&&(L+=1)}y(`wired Claude Code: ${L} file${L===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),_||O("not signed in \u2014 .mcp.json and the dev proxy carry placeholders. Run `turbobase auth login`, then `turbobase apps init` again (existing files are kept).")}let N=qi(process.cwd(),T)||".";y(`next: cd ${N} && npm install && npm run dev`),y(` turbobase apps create ${d}`),y(` turbobase apps push ${d} .`),y(` turbobase apps deploy ${d} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await T.appsList()}catch(f){V(f,"extensions:deploy","list apps"),v(`list apps failed: ${f instanceof Error?f.message:String(f)}`)}if(d.json)return y(JSON.stringify(_,null,2));if(_.length===0)return y("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");y(it(_.map(f=>[f.slug,f.name,f.deployed?"yes":"no",f.sourceRev===null?"\u2014":`rev ${f.sourceRev}`,f.audience]),{head:["SLUG","NAME","LIVE","SOURCE","AUDIENCE"]}))}),l.command("push").description("Record the local source tree as the app's newest source revision (does NOT deploy).").argument("<app>","App slug or id.").argument("[dir]","Source directory (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--note <text>","Short note stored with the revision.").option("--proposal <id>","Widget proposal this rev works (defaults to .turbobase/proposal.json).").action(async(d,h,w)=>{let T=oe(process.cwd(),h??".");await ie.stat(T).then(Q=>Q.isDirectory()).catch(()=>!1)||v(`${T} is not a directory.`);let{baseUrl:f,token:S}=await B(w.baseUrl),$=w.proposal??await E(T),{files:A,skipped:C,secrets:N,unstorable:M}=await Da(T),L=Object.keys(A).length;if(L===0&&v(`no source files found under ${T} (build output and node_modules are skipped).`),M.length>0){for(let Q of M)O(`${Q} contains a NUL byte (U+0000), which cannot be stored.`);v(`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 Q of C)O(m.dim(`skipped binary file ${Q}`));for(let Q of N)O(m.dim(`skipped ${Q} (holds credentials \u2014 never pushed)`));let J=await X(`pushing ${L} file${L===1?"":"s"}`,()=>P(f,S,d,A,w.note,$));y(`pushed ${J.files} file${J.files===1?"":"s"} \u2192 ${J.slug} rev ${J.rev} (source only, nothing deployed).`);let fe=await In(new z({baseUrl:f,token:S}),J.slug);fe&&fe.entriesAdded>0&&y(`${fe.entriesAdded} new finding(s) queued \u2014 run \`turbobase skills push\` / \`turbobase kb push\` to act on them.`),y(`next: turbobase apps deploy ${J.slug}`)}),o.command("plan").description("Diff this project (hooks/, conduits/, turbobase/) against a target env (no writes).").option("--from <env>","Source env the bundle was authored against (advisory).").option("--to <env>","Target env to diff against (sandbox|prod).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let h=await Wd(),{baseUrl:w,token:T}=await B(d.baseUrl),_=new z({baseUrl:w,token:T}),f;try{f=await X(`planning against ${d.to??w}`,()=>_.configPlan(h))}catch(S){v(`plan failed: ${S instanceof Error?S.message:String(S)}`)}uC(f,d.to??w)}),o.command("promote").description("Promote the bundle from one env to another behind a confirm-slug gate (fail-closed).").requiredOption("--from <env>","Source env (e.g. sandbox).").requiredOption("--to <env>","Target env (e.g. prod).").requiredOption("--confirm <slug>","Type the EXACT target instance slug to confirm (fail-closed).").option("--base-url <url>","Target instance base URL (defaults to the active instance).").option("--prune","Also REMOVE anything on the target this project no longer declares. Off by default.").action(async d=>{let h=await Wd(),{baseUrl:w,token:T}=await B(d.baseUrl),_=h.tenant??pC(w),f=Fp(d.confirm,_);f.ok||v(`promote refused (fail-closed): ${f.reason}`);let S=new z({baseUrl:w,token:T});try{let $=await X(`promoting ${d.from} \u2192 ${d.to} (${_})`,()=>S.configApply(h,{prune:d.prune}));if(Oe()){let C=[`${m.bold(`${d.from} \u2192 ${d.to}`)} ${m.dim(_??"")}`,`${Wt.add(String($.applied.add))} ${Wt.change(String($.applied.change))} ${Wt.destroy(String($.applied.destroy))}`];$.backfillsQueued.length&&C.push(m.dim(`${$.backfillsQueued.length} backfill(s) queued`)),y(Jt("Promoted",C))}else y(`promoted ${d.from} \u2192 ${d.to} (${_}): +${$.applied.add} ~${$.applied.change} -${$.applied.destroy}`+($.backfillsQueued.length?` (${$.backfillsQueued.length} backfill(s) queued)`:""));let A=$.skippedDestroys??[];if(A.length>0){O(`${A.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let C of A)O(` ${C.kind} ${C.id}`);O("Re-run with --prune to remove them, or add them to this repo.")}}catch($){$ instanceof Y&&$.status===403&&v("promote forbidden (403) \u2014 the stored PAT is not for an admin."),v(`promote failed: ${$ instanceof Error?$.message:String($)}`)}}),o.command("lint").argument("<file>","The hook or conduit definition file to lint").description("Statically lint a hook/conduit for semantic foot-guns (offline).").option("--ci","Exit non-zero when any warning fires (else exit 0).").option("--reporter <fmt>","Emit machine-readable output: junit | json (default: human).").action(async(d,h)=>{let w=Gd(h.reporter),T=oe(process.cwd(),d),_=await Rn(T),f=ap(_);w?y(Xo(iC(d,f),w)):y(lp(d,f,{warn:m.yellow,ok:m.green,dim:m.dim})),h.ci&&f.warnings.length>0&&process.exit(1)}),o.command("replay").argument("<file>","The conduit file to replay").description("Dry-run a conduit through dispatch\u2192transform\u2192apply (offline against a fixture).").option("--fixture <file>","JSON conduit-trigger fixture to replay against.").option("--against <target>","Replay against a running sandbox (online; deferred without a local DB).").option("--trace","Emit the per-stage trace (guards, atlas, apply-branch, bindings).").option("--reporter <fmt>","Emit machine-readable output: junit | json (one case per stage).").action(async(d,h)=>{let w=Gd(h.reporter),T=await Qu(oe(process.cwd(),d));if(h.against){h.against!=="sandbox"&&v(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await Xu(fa(T))}catch(S){v(S instanceof Error?S.message:String(S))}return}h.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let _;try{_=await Zu(oe(process.cwd(),h.fixture))}catch(S){v(`could not read fixture ${h.fixture}: ${S instanceof Error?S.message:String(S)}`)}let f=await Yu(T,_,h.fixture,{resolveDir:Ht(oe(process.cwd(),d))});if(w){let S=aC(f);y(Xo(S,w)),Mi(S.cases.some($=>$.status==="failed")?1:0)}y(ep(f,!!h.trace)),Mi(f.error?1:0)}),o.command("binding").description("List conduit source bindings (--status divergent) or re-enqueue one (--retry <id>).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--status <status>","Filter by write_status (ok|pending|blocked|divergent|muted).").option("--retry <id>","Re-enqueue the fan-out write for this binding id (admin-only).").option("--limit <n>","Max rows listed").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w});try{await fp(T,{status:d.status,retry:d.retry,limit:d.limit?Number(d.limit):void 0,sink:y})}catch(_){_ instanceof Y&&_.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),_ instanceof Y&&_.status===409&&v("binding is not retryable (only divergent/blocked bindings can be retried)."),v(`ext binding failed: ${_ instanceof Error?_.message:String(_)}`)}});let pr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");pr.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 Th(d)}),pr.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 Rh(d??[],h)}),pr.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 xh(d,h)}),pr.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 $h(d,h)}),o.command("disable <ids...>").description("Take armed extensions out of service \u2014 inert on the next reload, definition kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Eh(d,h)}),o.command("enable <ids...>").description("Put disabled extensions back into service.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Ph(d,h)}),o.command("remove <ids...>").description("Delete extension definitions. Run history and what they already wrote are kept.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the results as JSON.").action(async(d,h)=>{await Ah(d,h)}),o.command("install").argument("<spec>","Extension name, optionally name@version").description("Install an extension from the marketplace into your instance's extension store.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--connection <id>",'Bind this connection id (required when the extension declares a { type:"connection" } input).').action(async(d,h)=>{let w=d.lastIndexOf("@"),T=w>0?d.slice(0,w):d,_=w>0?d.slice(w+1):void 0,f=da();f||v(`marketplace not configured \u2014 set ${Nr} and ${Fo}.
4222
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let S=ua(f.registryUrl);S&&v(S);let{baseUrl:$,token:A}=await B(h.baseUrl),C=new Sn(f),N;try{N=await X(`fetching ${d}`,()=>C.fetchBundle(T,_))}catch(Q){v(`marketplace fetch failed for ${d}: ${Q instanceof Error?Q.message:String(Q)}`)}let M=Oo(N.manifest),L=null;if(M.length>0){if(!h.connection){let Q=M.map(be=>be.source_system).join(", ");v(`${N.name}@${N.version} declares a connection input (source: ${Q}) \u2014 pass --connection <id> to bind one of this instance's connections.`)}L=h.connection}let J=lC(N.bundle,N.name,N.kind),fe=new z({baseUrl:$,token:A});try{let Q=await X(`installing ${N.name}@${N.version}`,()=>fe.deploy({...J,provenance:"marketplace",...L?{connectionId:L}:{}}));y(`installed ${N.name}@${N.version} \u2192 ${Q.id} (status=${Q.status}, ${Q.outcome})`+(L?` bound to connection ${L}.`:"."))}catch(Q){Q instanceof Y&&Q.status===403&&v("install forbidden (403) \u2014 the stored PAT is not for an admin."),v(`install failed: ${Q instanceof Error?Q.message:String(Q)}`)}}),o.command("publish").description("Publish an authored extension to the public marketplace (publisher allowlist required).").argument("<file>","The extension file to publish (defineHook/defineConduit source).").requiredOption("--name <name>","Marketplace package name (lowercase, e.g. acme-recipes).").requiredOption("--pkg-version <version>","Semver-ish package version (e.g. 1.0.0).").option("--manifest <file>","Path to a JSON manifest (declared inputs[], capabilities).").action(async(d,h)=>{let w=da();w||v(`marketplace not configured \u2014 set ${Nr} and ${Fo}.
4223
+ Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let T=ua(w.registryUrl);T&&v(T);let _=oe(process.cwd(),d),f=await Rn(_),S=/\bdefineConduit\s*[<(]/.test(f)?"conduit":"hook",$={};if(h.manifest){let N=oe(process.cwd(),h.manifest),M;try{M=await ie.readFile(N,"utf8")}catch{v(`manifest not found at ${h.manifest}.`)}let L;try{L=JSON.parse(M)}catch{v(`manifest is not valid JSON: ${h.manifest}.`)}(typeof L!="object"||L===null||Array.isArray(L))&&v("manifest must be a JSON object."),$=L}try{Ki($,f)}catch(N){N instanceof Gt&&v(N.message),v(`manifest validation failed: ${N instanceof Error?N.message:String(N)}`)}let A=new Sn(w);try{await X(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:S,bundle:f,manifest:$}))}catch(N){N instanceof Y&&N.status===403&&v("publish forbidden (403) \u2014 this instance is not an approved publisher. Ask staff to add this slug to the publisher allowlist."),N instanceof Y&&N.status===409&&v(`version already published \u2014 ${h.name}@${h.pkgVersion} exists. Bump the version.`),v(`publish failed: ${N instanceof Error?N.message:String(N)}`)}let C=Oo($);y(`published ${h.name}@${h.pkgVersion} (kind=${S}) to the marketplace.`),C.length>0&&y(` declares ${C.length} connection input(s): ${C.map(N=>N.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async d=>{let h=await ft(d.baseUrl).catch(()=>null),w=ka({baseUrl:h?.baseUrl,token:h?.token}),T=0,_=0,f=0;for(let S of w){let $=oe(process.cwd(),S.path),A=await Qb($,S);A==="wrote"?(T+=1,y(` wrote ${S.path}`)):A==="merged"?(f+=1,y(` merged ${S.path} (added the .mcp.json rule)`)):(_+=1,y(` skipped ${S.path} (exists)`))}y(`
4224
+ project init: ${T} written, ${f} merged, ${_} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Sa} (non-destructive).`).action(async()=>{let d=Np(),h=0,w=0;for(let T of d){let _=oe(process.cwd(),T.path);await Cr(_,T.content,T.executable)==="wrote"?(h+=1,y(` wrote ${T.path}`)):(w+=1,y(` skipped ${T.path} (exists)`))}y(`
4225
+ project ci: ${h} written, ${w} skipped.`),h>0&&(y(`
4226
+ 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:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await T.catalogRecords()}catch(C){C instanceof Y&&(C.status===401||C.status===403)&&v("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),v(`catalog fetch failed: ${C instanceof Error?C.message:String(C)}`)}if(_.length===0){y("no records in the instance catalog \u2014 nothing to generate.");return}let f=oe(process.cwd(),d.out),S=rp(_,{event:d.event}),$=0,A=0;for(let{recordType:C,fixture:N}of S){let M=tt(f,`${C}.json`),L=`${JSON.stringify(N,null,2)}
4227
+ `;d.force?(await ie.mkdir(Ht(M),{recursive:!0}),await ie.writeFile(M,L,{mode:420}),$+=1,y(` wrote ${d.out}/${C}.json`)):await Cr(M,L)==="wrote"?($+=1,y(` wrote ${d.out}/${C}.json`)):(A+=1,y(` skipped ${d.out}/${C}.json (exists \u2014 use --force to overwrite)`))}y(`
4228
+ samples init: ${$} written, ${A} skipped.`)});let Lt=e.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),rw=d=>[d.name??m.dim(d.id.slice(0,8)),d.status==="active"?m.green("active"):d.status==="proposed"?m.yellow("proposed"):m.dim("inactive"),d.decision==="deny"?m.red(d.decision):d.decision==="require_confirm"?m.yellow(d.decision):m.green(d.decision),String(d.priority),d.source,d.record??d.op,d.actor??m.dim("any"),d.when||m.dim("(always)"),d.reason??""],nw=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Lt.command("list").description("List every write guardrail on your instance, in evaluation order.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await T.guardrailsList()}catch(f){V(f,"extensions:deploy","list guardrails"),v(`list guardrails failed: ${f instanceof Error?f.message:String(f)}`)}if(d.json)return y(JSON.stringify(_,null,2));if(_.length===0)return y(`no write guardrails \u2014 every record the admin entitlement allows is writable.
4229
+ `+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));y(it(_.map(rw),{head:nw})),y(m.dim(" first match wins; lower PRIO is evaluated first."))}),Lt.command("create <name>").description("Create a rule gating PG\u2192source writes that match it.").option("--source <system>","Adapter id to scope to, or '*' for every source.","*").option("--record <type>","Record type to scope to, or '*' for every record.","*").option("--op <glob>","Raw op glob, when gating something other than a record write.").option("--target <glob>","Row address glob, e.g. 'salesOrder.12345'.").option("--actor <glob>","Only match this caller, e.g. 'agent:*' to gate AI writes but not human ones.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.","deny").option("--priority <n>","Lower is evaluated first (default 100).",d=>Number(d)).option("--when <expr>","Row predicate, e.g. 'total gt 10000'. Omit to match every row.").option("--reason <text>","Why this rule exists \u2014 shown to a blocked writer and in `list`.").option("--disabled","Create the rule parked, so it takes effect only when activated.").option("--confirm-freeze-all","Required for an unconditional deny across '*'/'*'.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T}),f;try{f=await _.guardrailCreate({name:d,source:h.source,record:h.record,decision:h.decision,...h.op?{op:h.op}:{},...h.target?{target:h.target}:{},...h.actor?{actor:h.actor}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when?{when:h.when}:{},...h.reason?{reason:h.reason}:{},...h.disabled?{enabled:!1}:{},...h.confirmFreezeAll?{confirmFreezeAll:!0}:{}})}catch(S){V(S,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} created${f.status==="active"?"":m.dim(` (${f.status} \u2014 activate it to take effect)`)}`),y(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.actor?` actor=${f.actor}`:""}${f.when?` where ${f.when}`:""} @prio ${f.priority}`)),y(m.dim(` verify with: turbobase guardrails test --source ${f.source==="*"?"<source>":f.source} --record <record>`))}),Lt.command("edit <name>").description("Change a rule \u2014 its decision, priority, predicate or reason.").option("--decision <d>","allow | allow_with_audit | require_confirm | deny.").option("--priority <n>","Lower is evaluated first.",d=>Number(d)).option("--when <expr>","New row predicate. Pass '' to match every row.").option("--reason <text>","Why this rule exists.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.decision===void 0&&h.priority===void 0&&h.when===void 0&&h.reason===void 0&&v("edit: nothing to change \u2014 pass --decision, --priority, --when or --reason.");let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T}),f;try{f=await _.guardrailUpdate(d,{...h.decision!==void 0?{decision:h.decision}:{},...Number.isFinite(h.priority)?{priority:Number(h.priority)}:{},...h.when!==void 0?{when:h.when}:{},...h.reason!==void 0?{reason:h.reason}:{}})}catch(S){V(S,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(f.name??f.id)} updated`),y(m.dim(` ${f.decision} ${f.source}/${f.record??f.op}${f.when?` where ${f.when}`:""} @prio ${f.priority}`))});for(let[d,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Lt.command(`${d} <name>`).description(h==="active"?"Arm a parked or proposed rule.":"Park a rule without deleting it \u2014 the reversible move mid-rollout.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(T,_)=>{let{baseUrl:f,token:S}=await B(_.baseUrl),$=new z({baseUrl:f,token:S});try{await $.guardrailUpdate(T,{status:h})}catch(A){V(A,"extensions:deploy",`${d} a guardrail`),v(`${d} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(T)} ${w}`),h==="inactive"&&y(m.dim(" writes it was gating now fall through to the other rules."))});Lt.command("delete <name>").description("Remove a rule. Prefer `deactivate` if you may want it back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T});try{await _.guardrailDelete(d)}catch(f){V(f,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${f instanceof Error?f.message:String(f)}`)}y(`${m.green("\u2713")} guardrail ${m.bold(d)} deleted`)}),Lt.command("posture [mode]").description("Show or set the GLOBAL default. 'allow' = deny-list (unmatched writes allowed, carve with deny rules). 'deny' = allow-list (unmatched writes denied, open with allow rules).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T}),f=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(d===void 0){let A;try{A=await _.guardrailPostureGet()}catch(C){V(C,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${C instanceof Error?C.message:String(C)}`)}y(`guardrail posture: ${m.bold(f(A.mode))}`),y(m.dim(A.mode==="deny"?" Unmatched writes are DENIED. Open records with `guardrails create <name> --decision allow`.":" Unmatched writes are allowed-with-audit. Freeze records with `guardrails create <name> --decision deny`."));return}let S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&v("posture must be 'allow' or 'deny'.");let $;try{$=await _.guardrailPostureSet(S)}catch(A){V(A,"extensions:deploy","set the guardrail posture"),v(`set posture failed: ${A instanceof Error?A.message:String(A)}`)}y(`${m.green("\u2713")} guardrail posture set to ${m.bold(f($.mode))}`),$.mode==="deny"&&y(m.dim(" Every record with no active ALLOW rule is now frozen for write-back. Verify with `guardrails test --source <s> --record <r>`."))}),Lt.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($){v(`--fields must be valid JSON: ${$ instanceof Error?$.message:String($)}`)}let{baseUrl:w,token:T}=await B(d.baseUrl),_=new z({baseUrl:w,token:T}),f;try{f=await _.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($){V($,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${$ instanceof Error?$.message:String($)}`)}if(d.json)return y(JSON.stringify(f,null,2));let S=`${d.source}/${f.op??d.record}`;f.degraded?(y(`${m.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),y(m.dim(` ${f.reason}`))):f.allowed?y(`${m.green("\u2713")} ${S} \u2014 ${f.decision}`+(f.blockedBy?m.dim(` (rule ${f.blockedBy})`):m.dim(" (no rule matched)"))):(y(`${m.red("\u2717")} ${S} \u2014 ${f.decision} by ${m.bold(f.blockedBy??"?")} at the ${f.phase} gate`),f.message&&y(m.dim(` ${f.message}`))),f.decision==="require_confirm"&&y(m.yellow(" this write is HELD for operator approval, not refused.")),f.allowed||(process.exitCode=1)});let bn=e.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),Po=(d,h={})=>{let w=`${m.bold(d.table)} ${m.dim(d.displayName)}`;y(d.exists===!1?`${w} ${m.dim("(new)")}`:w);for(let T of d.fields){let _=[T.required?"required":null].filter(Boolean).join(", "),f=h.showClaimants&&T.claimedBy?.length?` ${m.dim(`\u2190 ${T.claimedBy.join(", ")}`)}`:"";y(` ${T.column.padEnd(28)} ${T.type}${_?` (${_})`:""}${f}`)}h.showClaimants&&d.claimants.length>1&&y(m.dim(` claimed by ${d.claimants.join(", ")}`))};function Ao(d){if(d instanceof Y&&d.status===409){let h=d.body;h?.error==="table_conflict"&&h.message&&(O(h.message),process.exit(1))}v(`tables: ${d instanceof Error?d.message:String(d)}`)}let eu=async d=>{let h=tt(oe(process.cwd(),d),"public","turbobase.json"),w=await ie.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let T;try{T=JSON.parse(w)}catch(f){v(`${h} is not valid JSON: ${f instanceof Error?f.message:String(f)}`)}let _=T.tables;return _===void 0?{tables:[],manifestPath:h}:(Array.isArray(_)||v(`${h}: "tables" must be an array.`),{tables:_,manifestPath:h})};bn.command("list").description("List the custom tables on your instance and who claims each one.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await T.tablesList()}catch(f){V(f,"extensions:deploy","list tables"),v(`list tables failed: ${f instanceof Error?f.message:String(f)}`)}if(d.json)return y(JSON.stringify(_,null,2));if(_.length===0)return y("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");y(it(_.map(f=>[f.table,f.displayName,String(f.fields.length),f.status,f.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),bn.command("plan").description("Preview what this project's declared tables would do. Writes nothing; exits 1 on a conflict.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: the app slug in .turbobase, else cli).").action(async(d,h)=>{let w=await eu(d??".");if(w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:T,token:_}=await B(h.baseUrl),f=new z({baseUrl:T,token:_}),S;try{S=await X("planning tables",()=>f.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch($){V($,"extensions:deploy","plan tables"),Ao($)}y(`claiming as ${m.bold(S.claimedBy)}`);for(let $ of S.tables)Po($,{showClaimants:!0});y(""),y(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),bn.command("apply").description("Apply this project's declared tables to the instance.").argument("[dir]","Project directory holding public/turbobase.json (default ./).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--as <claimant>","Claim as `cli` or `app:<slug>` (default: cli).").action(async(d,h)=>{let w=await eu(d??".");if(w||v(`no public/turbobase.json under ${oe(process.cwd(),d??".")}.`),w.tables.length===0)return y(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:T,token:_}=await B(h.baseUrl),f=new z({baseUrl:T,token:_}),S;try{S=await X("applying tables",()=>f.tablesApply({claimedBy:h.as,tables:w.tables}))}catch($){V($,"extensions:deploy","apply tables"),Ao($)}for(let $ of S.tables)Po($,{showClaimants:!0});y(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),bn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let w=h.field.map($=>{let[A,C,N]=$.split(":");return(!A||!C)&&v(`--field "${$}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&v(`--field "${$}": the third part may only be "required".`),{name:A,type:C,...N==="required"?{required:!0}:{}}}),{baseUrl:T,token:_}=await B(h.baseUrl),f=new z({baseUrl:T,token:_}),S;try{S=await X(`creating cr_${d}`,()=>f.tablesApply({tables:[{slug:d,displayName:h.name??d,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch($){V($,"extensions:deploy","create a table"),Ao($)}for(let $ of S.tables)Po($);y(""),y(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),bn.command("drop").description("Drop a table and everything in it. Irreversible.").argument("<slug>","Table slug (without the cr_ prefix).").requiredOption("--confirm <slug>","Type the EXACT slug to confirm (fail-closed).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{h.confirm!==d&&v(`drop refused: --confirm "${h.confirm}" does not match "${d}".`);let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T}),f;try{f=await X(`dropping cr_${d}`,()=>_.tablesDrop(d,h.confirm))}catch(S){V(S,"extensions:deploy","drop a table"),v(`drop failed: ${S instanceof Error?S.message:String(S)}`)}if(!f.removed)return y(`no table named "${d}" on this instance \u2014 nothing dropped.`);y(`dropped ${f.table} and every row in it.`)});let zi=e.command("sandbox").description("Ephemeral local authoring sandboxes.");zi.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=Jd(),w;try{w=await Jh(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof Nn&&v(T.message),v(`sandbox create failed: ${T instanceof Error?T.message:String(T)}`)}y(`sandbox ${w.name} ready.`),y(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),y(` url: ${w.url}`),y(` expires: ${w.expiresAt}`)}),zi.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=Jd();await Ya(h).catch(()=>[]);let w;try{w=await Yh(h,d)}catch(T){v(`sandbox destroy failed: ${T instanceof Error?T.message:String(T)}`)}w||v(`no sandbox named '${d}'.`),y(`destroyed sandbox ${w.name} (dropped ${w.database}).`)}),zi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=Jd(),h=await Ya(d).catch(()=>[]),w=await ms(),{active:T}=Ja(w);if(T.length===0)y("no active sandboxes.");else{for(let _ of T)y(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);y(`
4230
+ ${T.length} active sandbox(es).`)}h.length>0&&y(`(reaped ${h.length} expired sandbox(es).)`)}),o.command("export").description("Pull the live instance into turbobase/bundle.json (adopt an instance into a repo).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--out <dir>","Directory to write the bundle into.",ns).action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await X("exporting instance config",()=>T.configExport())}catch($){$ instanceof Y&&($.status===401||$.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${$ instanceof Error?$.message:String($)}`)}let f=typeof _.serialized=="string"?_.serialized:`${JSON.stringify(_.manifest??_,null,2)}
4231
+ `,S=oe(process.cwd(),d.out,Pn);await ie.mkdir(Ht(S),{recursive:!0}),await ie.writeFile(S,f,"utf8"),y(`wrote ${d.out}/${Pn} (${f.split(`
4232
+ `).length} lines).`)});let tu=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),ow=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],ru=()=>process.env.TURBOBASE_HOME?.trim()||tt(ZA(),".turbobase"),sw=()=>"1.42.0",Co=async()=>Promise.all(ow.map(async d=>{try{return await import(d.name),{...d,present:!0}}catch{return{...d,present:!1}}}));tu.command("status").description("Report which optional native packages are installed.").action(async()=>{let d=await Co();for(let h of d)y(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);d.some(h=>!h.present)&&y(`
4233
+ run \`${qr} ext extras install\` to fetch them into ${ru()}.`)}),tu.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let d=await Co();if(d.every(A=>A.present)){y(ve.success("extras already installed \u2014 nothing to do."));return}let h=ru();await ie.mkdir(h,{recursive:!0});let w=d.filter(A=>!A.present).map(A=>A.name),T=Fa(process.platform,process.arch),_=async(A,C)=>{let{code:N,stderr:M}=await $o("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);N!==0&&v(`extras install failed while installing ${C} (npm exited ${N}).
4234
+ ${M.trim()}
4235
+ These are native packages \u2014 they need npm and a working toolchain. Everything except \`test\` and \`replay\` works without them.`)},f=w.filter(A=>A!=="isolated-vm");if(f.length>0){let A=f.map(C=>`${C}@${za[C]??"latest"}`);y(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await _(A,f.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${za["isolated-vm"]}`;if(y(`installing ${A} \u2192 ${h}/node_modules \u2026`),await _(["--ignore-scripts",A],"isolated-vm"),Bh.includes(T)){let N=`${Ba}@${sw()}`;y(`fetching ${N} (no upstream binary for ${T}) \u2026`);let{code:M}=await $o("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",N]);M!==0&&y(ve.warn(`could not fetch ${N} \u2014 falling back to a source build.`))}let C=await Fh({home:h});C.length>0&&y(` ${ve.success("prebuilt")} ${C.join(", ")} \u2192 isolated-vm/prebuilds/${T}`)}let S=await Co(),$=S.filter(A=>!A.present).map(A=>A.name);if($.includes("isolated-vm")){y(ve.warn(`no prebuilt isolated-vm for ${T} / Node ${process.versions.node} (${Ha()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await $o("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(S=await Co(),$=S.filter(C=>!C.present).map(C=>C.name))}$.length>0&&v(`npm succeeded but ${$.join(", ")} still will not load \u2014 no prebuilt binary for ${T} / Node ${process.versions.node} (${Ha()}), 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 Ir=e.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");Ir.command("deploy").description("Enqueue a server-side release deploy. UPLOADS the SDF project src/ from the checkout (the producer swap) when present; else a solution-only live-fetch deploy. An approved target requires --approved-by.").requiredOption("--target <mode>","Deploy posture: auto (apply now) | approved (needs a recorded approval).").option("--solution <id>","The solution id the release delivers (omit for an upload-only deploy).").option("--project <dir>","SDF project dir whose src/ is uploaded (default: cwd).").option("--git-repo <repo>","Git provenance LINK: source repo (default $GITHUB_REPOSITORY or `git remote get-url origin`).").option("--git-ref <ref>","Git provenance LINK: ref/branch/tag (default $GITHUB_REF).").option("--ref <committish>","Git provenance: the ref/branch/tag/sha the upload was built from; resolved to a commit sha via `git rev-parse` (default $GITHUB_SHA or HEAD).").option("--pr-url <url>","Git provenance LINK: the PR this deploy came from (default $PR_URL).").option("--approved-by <email>","Record the approval (REQUIRED for --target approved).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async d=>{let h=d.target==="approved"?"approved":d.target==="auto"?"auto":null;h||v(`--target must be 'auto' or 'approved' (got '${d.target}').`);let w=await hC(oe(process.cwd(),d.project??".")),T=Object.keys(w).length;!d.solution&&T===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let f=(d.ref?await Yd(["rev-parse",d.ref])??d.ref:null)??process.env.GITHUB_SHA??await Yd(["rev-parse","HEAD"]),S=d.gitRepo??process.env.GITHUB_REPOSITORY??await Yd(["remote","get-url","origin"]),$=d.gitRef??process.env.GITHUB_REF??null,A=d.prUrl??process.env.PR_URL??null,{baseUrl:C,token:N}=await B(d.baseUrl),M=new z({baseUrl:C,token:N}),L;try{L=await M.releaseDeploy({solutionId:d.solution??null,target:h,approvedBy:d.approvedBy??null,files:T>0?w:null,gitRepo:S,gitRef:$,gitSha:f,prUrl:A})}catch(J){V(J,"releases:write","release deploy"),J instanceof Y&&J.status===404&&v("solution_not_found \u2014 no solution with that id."),v(`release deploy failed: ${J instanceof Error?J.message:String(J)}`)}y(`release ${L.releaseId} enqueued \u2192 taskId=${L.taskId} (target=${h}`+(T>0?`, uploaded ${T} bundle file(s)`:", live-fetch")+")."),d.follow&&await Aa(()=>M.releaseStatus(L.releaseId),`release ${L.releaseId}`,d.intervalMs)}),Ir.command("pull").argument("<id>","The release id").description("Write the SDF project a FAILED release built into <dir>: owned/ (yours, editable) and context/ (the rest of the bundle, read-only). Edit owned/, then `release push`.").requiredOption("--dir <path>","Directory to write the project into (created if absent).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T}),f;try{f=await _.releaseFiles(d)}catch(A){A instanceof Y&&A.status===404&&v(`release ${d} not found.`),A instanceof Y&&A.status===409&&v(`no built project was retained for release ${d}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),V(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let S=oe(process.cwd(),h.dir),$=0;for(let[A,C]of[["owned",f.owned],["context",f.context]])for(let[N,M]of Object.entries(C)){let L=tt(S,A,N);await ie.mkdir(Ht(L),{recursive:!0}),await ie.writeFile(L,M,"utf8"),$++}await ie.writeFile(tt(S,".turbobase-release.json"),JSON.stringify({releaseId:f.releaseId,version:f.version,contentDigest:f.contentDigest},null,2),"utf8"),y(`pulled release ${f.releaseId} (${f.status}) \u2192 ${S}
4167
4236
  ${Object.keys(f.owned).length} owned file(s), ${Object.keys(f.context).length} context file(s), ${$} total
4168
4237
  `+(f.logTail?`
4169
4238
  the failure these bytes produced:
4170
4239
  ${f.logTail.trim()}
4171
4240
  `:"")+`
4172
4241
  edit the files under owned/, then:
4173
- turbobase release push ${f.releaseId} --dir ${h.dir}`)}),Cr.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f=oe(process.cwd(),h.dir),k;try{k=await _.releaseFiles(d)}catch(N){N instanceof Y&&N.status===404&&v(`release ${d} not found.`),V(N,"releases:write","push a release"),v(`release push failed: ${N instanceof Error?N.message:String(N)}`)}let $=async(N,J)=>{try{return await ie.readFile(et(f,N,J),"utf8")}catch{return null}},A=[];for(let[N,J]of Object.entries(k.context)){let me=await $("context",N);me!==null&&me!==J&&A.push(N)}A.length>0&&v(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
4174
- `+A.map(N=>` context/${N}`).join(`
4175
- `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...k.context},O=0;for(let[N,J]of Object.entries(k.owned)){let me=await $("owned",N);C[N]=me??J,me!==null&&me!==J&&O++}O===0&&b("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let W=h.target==="approved"?"approved":"auto";try{let N=await _.releasePush(d,{files:C,target:W,...h.approvedBy?{approvedBy:h.approvedBy}:{}});b(`pushed ${Object.keys(C).length} file(s) (${O} edited) \u2192 release ${N.releaseId} (task ${N.taskId}).
4242
+ turbobase release push ${f.releaseId} --dir ${h.dir}`)}),Ir.command("push").argument("<id>","The release id the project was pulled from").description("Ship the edited project as a NEW release delivering the same solution. Refuses if a context/ file changed \u2014 those belong to other solutions.").requiredOption("--dir <path>","The directory `release pull` wrote.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--target <target>","'auto' (default) or 'approved'.","auto").option("--approved-by <who>","Required for an approved target (fails closed without it).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T}),f=oe(process.cwd(),h.dir),S;try{S=await _.releaseFiles(d)}catch(L){L instanceof Y&&L.status===404&&v(`release ${d} not found.`),V(L,"releases:write","push a release"),v(`release push failed: ${L instanceof Error?L.message:String(L)}`)}let $=async(L,J)=>{try{return await ie.readFile(tt(f,L,J),"utf8")}catch{return null}},A=[];for(let[L,J]of Object.entries(S.context)){let fe=await $("context",L);fe!==null&&fe!==J&&A.push(L)}A.length>0&&v(`refusing to push \u2014 these context/ files were modified, and they belong to other solutions in the same bundle:
4243
+ `+A.map(L=>` context/${L}`).join(`
4244
+ `)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let C={...S.context},N=0;for(let[L,J]of Object.entries(S.owned)){let fe=await $("owned",L);C[L]=fe??J,fe!==null&&fe!==J&&N++}N===0&&y("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let M=h.target==="approved"?"approved":"auto";try{let L=await _.releasePush(d,{files:C,target:M,...h.approvedBy?{approvedBy:h.approvedBy}:{}});y(`pushed ${Object.keys(C).length} file(s) (${N} edited) \u2192 release ${L.releaseId} (task ${L.taskId}).
4176
4245
  follow it with:
4177
- turbobase release status ${N.releaseId} --follow`)}catch(N){N instanceof Y&&N.status===403&&v("an approved target needs --approved-by (the deploy gate fails closed)."),N instanceof Y&&N.status===409&&v("that solution already has an active release \u2014 roll it back or wait for it."),V(N,"releases:write","push a release"),v(`release push failed: ${N instanceof Error?N.message:String(N)}`)}}),Cr.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T});if(h.follow){await Ea(()=>_.releaseStatus(d),`release ${d}`,h.intervalMs);return}let f;try{f=await _.releaseStatus(d)}catch(k){V(k,"releases:write","release status"),k instanceof Y&&k.status===404&&v(`release ${d} not found.`),v(`release status failed: ${k instanceof Error?k.message:String(k)}`)}b(`release ${d}: status=${f.releaseStatus??"?"} stage=${f.stage} ${f.percent}%`+(f.runStatus?` (${f.runStatus})`:"")),f.outputTail&&b(f.outputTail.replace(/\n+$/,""))}),Cr.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T}),f;try{f=await _.releaseRollback(d)}catch(k){V(k,"releases:write","release rollback"),k instanceof Y&&k.status===404&&v(`release ${d} not found.`),k instanceof Y&&k.status===409&&v(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),v(`release rollback failed: ${k instanceof Error?k.message:String(k)}`)}b(`release ${f.releaseId} rolled back \u2192 status=${f.release?.status??"rolled_back"}.`)}),Cr.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w}),_;try{_=await T.releaseList()}catch(f){V(f,"releases:write","release list"),v(`release list failed: ${f instanceof Error?f.message:String(f)}`)}if(_.length===0){b("no releases.");return}if(Oe())b(ft(_.map(f=>[f.id,jr(f.status),f.target,f.backend,f.solutionTitles?.length?f.solutionTitles.map(k=>`"${k}"`).join(", "):m.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let f of _){let k=f.solutionTitles?.length?` "${f.solutionTitles.join('", "')}"`:"";b(` ${f.id} ${f.status.padEnd(11)} target=${f.target} backend=${f.backend}${k}`)}b(`
4178
- ${_.length} release(s).`)});let Ir=e.command("processes").description("See what processes are deployed, how they are triggered, and what they have done.");return Ir.command("list").description("Every deployed process with its trigger, its schedule and its last runs.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w});try{let _=await T.processes();d.json?b(JSON.stringify(_,null,2)):mp(_,b)}catch(_){v(`processes list failed: ${_ instanceof Error?_.message:String(_)}`)}}),Ir.command("runs").description("One process's run history, newest first.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T});try{let f=await _.processRuns(d);h.json?b(JSON.stringify(f,null,2)):fp(d,f,b)}catch(f){v(`processes runs failed: ${f instanceof Error?f.message:String(f)}`)}}),Ir.command("run").description("One run and its step ledger.").argument("<run-id>","The run id the invoke answered with.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T});try{let f=await _.processRun(d);h.json?b(JSON.stringify(f,null,2)):Xo(f,b)}catch(f){v(`processes run failed: ${f instanceof Error?f.message:String(f)}`)}}),Ir.command("invoke").description("Start a run of a deployed process \u2014 queued by default, or waited for with --sync.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--input <json>",`The process input as a JSON object, e.g. '{"customerId":"42"}'.`).option("--input-file <path>","Read the process input from a JSON file instead.").option("--sync","Wait for the run to settle (bounded by the instance's budget) and print its outcome.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the response as JSON.").action(async(d,h)=>{h.input!==void 0&&h.inputFile!==void 0&&v("pass --input or --input-file, not both.");let w={};if(h.input!==void 0||h.inputFile!==void 0){let k,$=h.input!==void 0?"--input":"--input-file";if(h.input!==void 0)k=h.input;else try{k=await ie.readFile(oe(process.cwd(),h.inputFile),"utf8")}catch{v(`input file not found at ${h.inputFile}.`)}let A=yp(k,$);A.ok||v(A.message),w=A.input}let{baseUrl:T,token:_}=await z(h.baseUrl),f=new q({baseUrl:T,token:_});try{let k=await f.invokeProcess(d,w,h.sync?"sync":"async");h.json?b(JSON.stringify(k,null,2)):bp(k,d,Mr,b)}catch(k){k instanceof Y&&k.status===403&&k.body?.reason==="admin_required"&&v("processes invoke forbidden (403) \u2014 the token's owner must be an administrator to start a process."),V(k,"extensions:deploy","processes invoke"),v(`processes invoke failed: ${k instanceof Error?k.message:String(k)}`)}}),Ir.command("cancel").description("Stop one run \u2014 a queued run never executes, a running one stops at its next step.").argument("<run-id>","The run to stop.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T});try{let f=await _.cancelProcessRun(d);b(`cancelled ${f.runId??d} (${f.state??"cancelled"}).`),b("A run already going stops at its next step boundary; writes it has already made stay.")}catch(f){v(`processes cancel failed: ${f instanceof Error?f.message:String(f)}`)}}),Ir.command("rollback").description("Undo a finished run \u2014 delete, newest first, the records its ledger proves it created.").argument("<run-id>","The finished run to roll back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await z(h.baseUrl),_=new q({baseUrl:w,token:T});try{let f=await _.rollbackProcessRun(d);if(!f.queued){b(`${f.runId??d} is already rolled back \u2014 nothing to do.`);return}b(`rollback queued for ${f.runId??d} (was ${f.state}).`),b(`Only records this run created are deleted; records it updated are left alone. Source deletes are paced by the rollback cap \u2014 follow with \`turbobase processes run ${f.runId??d}\`.`)}catch(f){v(`processes rollback failed: ${f instanceof Error?f.message:String(f)}`)}}),e.command("data").description("Act on one record in your instance \u2014 today, link a row after a settle conflict.").command("settle").description("Link a row to the record the connected system already created, after a write_settle_conflict.").argument("<record-type>","The record type, e.g. salesOrder or nonInventorySaleItem.").argument("<pg-row-id>","The row's pg_row_id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the answer as JSON.").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await z(w.baseUrl),f=new q({baseUrl:T,token:_});try{let k=await f.settleRow(d,h);if(w.json){b(JSON.stringify(k,null,2));return}b(`linked ${d} ${k.pgRowId} to ${k.externalId}.`),k.discarded.length>0&&b(`discarded the inbound copy of the same record: ${k.discarded.join(", ")}.`)}catch(k){v(`data settle failed: ${k instanceof Error?k.message:String(k)}`)}}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--process-run <runId>","One process run's step ledger. With --follow it streams and EXITS when the run finishes.").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:h,token:w}=await z(d.baseUrl),T=new q({baseUrl:h,token:w}),_=d.limit?Number(d.limit):void 0,f=d.intervalMs?Number(d.intervalMs):void 0;if(d.processRun){try{await gp(T,d.processRun,{...d.follow?{follow:!0}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(k){v(`logs --process-run failed: ${k instanceof Error?k.message:String(k)}`)}return}if(d.conduit){try{await cp(T,d.conduit,{...d.follow?{follow:!0}:{},..._!==void 0?{limit:_}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(k){v(`logs --conduit failed: ${k instanceof Error?k.message:String(k)}`)}return}if(d.extension){try{let k=await T.logs(d.extension,_);k.length===0&&b(`no logs for ${d.extension}.`);for(let $ of k)b(` [${$.level}] ${$.ts??""} ${$.message}`)}catch(k){v(`logs --extension failed: ${k instanceof Error?k.message:String(k)}`)}return}try{await up(T,{...d.subsystem?{subsystem:d.subsystem}:{},...d.severity?{severity:d.severity}:{},...d.code?{code:d.code}:{},...d.since?{since:d.since}:{},...d.correlationId?{correlationId:d.correlationId}:{},...d.follow?{follow:!0}:{},...d.json?{json:!0}:{},..._!==void 0?{limit:_}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(k){v(`logs failed: ${k instanceof Error?k.message:String(k)}`)}}),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(()=>(Wb(),Gb));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(`
4179
- `)),t&&void 0,e}function YA(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function XA(t){let e=et(oe(process.cwd(),t),"public","turbobase.json"),r=await ie.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){v(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&v(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function ZA(){let t=oe(process.cwd(),es,En),e;try{e=await ie.readFile(t,"utf8")}catch{v(`no config found \u2014 this project authors none (no ${rs}/, ${ns}/, ${Wt} or ${Jt}) and there is no ${es}/${En}.
4180
- Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Dp(e)}catch(r){v(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function Kd(){let t=process.cwd();if(!await Bp(t))return ZA();let e;try{e=await Fp(t,{inline:da})}catch(r){v(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)L(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&v(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function QA(t,e){b(`plan against ${e}:`);for(let r of t.add)b(` ${Vt.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)b(` ${Vt.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)b(` ${Vt.destroy(`${r.kind} ${r.id}`)}`);b(`
4181
- ${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 eC(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function Ro(t,e,r){return new Promise(n=>{let o=Jd(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function Vd(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await Ro("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await Ro("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(l=>a[l]===null||a[l]===void 0?"NULL":`'${String(a[l]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function tC(t){let e=oe(t,"src"),r={},n=async o=>{let s;try{s=await ie.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=et(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let l=Di(e,a).split(Wd).join("/");r[l]=await ie.readFile(a,"utf8")}}};return await n(e),r}function Gd(t){return new Promise(e=>{let r=Jd("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var rC=!1;rC&&Yd().parseAsync(process.argv).catch(t=>v(t instanceof Error?t.message:String(t)));Yd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
4246
+ turbobase release status ${L.releaseId} --follow`)}catch(L){L instanceof Y&&L.status===403&&v("an approved target needs --approved-by (the deploy gate fails closed)."),L instanceof Y&&L.status===409&&v("that solution already has an active release \u2014 roll it back or wait for it."),V(L,"releases:write","push a release"),v(`release push failed: ${L instanceof Error?L.message:String(L)}`)}}),Ir.command("status").argument("<id>","The release id").description("Show a release deploy job's status; with --follow, poll to completion.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--follow","Poll the release deploy to completion (exit non-zero on failure).").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T});if(h.follow){await Aa(()=>_.releaseStatus(d),`release ${d}`,h.intervalMs);return}let f;try{f=await _.releaseStatus(d)}catch(S){V(S,"releases:write","release status"),S instanceof Y&&S.status===404&&v(`release ${d} not found.`),v(`release status failed: ${S instanceof Error?S.message:String(S)}`)}y(`release ${d}: status=${f.releaseStatus??"?"} stage=${f.stage} ${f.percent}%`+(f.runStatus?` (${f.runStatus})`:"")),f.outputTail&&y(f.outputTail.replace(/\n+$/,""))}),Ir.command("rollback").argument("<id>","The release id to roll back").description("Roll back a live release (LIFO-guarded; server-side reverse deploy).").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T}),f;try{f=await _.releaseRollback(d)}catch(S){V(S,"releases:write","release rollback"),S instanceof Y&&S.status===404&&v(`release ${d} not found.`),S instanceof Y&&S.status===409&&v(`release ${d} cannot be rolled back (not live, or a newer release advanced past it).`),v(`release rollback failed: ${S instanceof Error?S.message:String(S)}`)}y(`release ${f.releaseId} rolled back \u2192 status=${f.release?.status??"rolled_back"}.`)}),Ir.command("list").description("List releases, newest-first, with delivered titles + latest status.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await T.releaseList()}catch(f){V(f,"releases:write","release list"),v(`release list failed: ${f instanceof Error?f.message:String(f)}`)}if(_.length===0){y("no releases.");return}if(Oe())y(it(_.map(f=>[f.id,Dr(f.status),f.target,f.backend,f.solutionTitles?.length?f.solutionTitles.map(S=>`"${S}"`).join(", "):m.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let f of _){let S=f.solutionTitles?.length?` "${f.solutionTitles.join('", "')}"`:"";y(` ${f.id} ${f.status.padEnd(11)} target=${f.target} backend=${f.backend}${S}`)}y(`
4247
+ ${_.length} release(s).`)});let Or=e.command("processes").description("See what processes are deployed, how they are triggered, and what they have done.");Or.command("list").description("Every deployed process with its trigger, its schedule and its last runs.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w});try{let _=await T.processes();d.json?y(JSON.stringify(_,null,2)):wp(_,y)}catch(_){v(`processes list failed: ${_ instanceof Error?_.message:String(_)}`)}}),Or.command("runs").description("One process's run history, newest first.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T});try{let f=await _.processRuns(d);h.json?y(JSON.stringify(f,null,2)):vp(d,f,y)}catch(f){v(`processes runs failed: ${f instanceof Error?f.message:String(f)}`)}}),Or.command("run").description("One run and its step ledger.").argument("<run-id>","The run id the invoke answered with.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the read as JSON.").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T});try{let f=await _.processRun(d);h.json?y(JSON.stringify(f,null,2)):es(f,y)}catch(f){v(`processes run failed: ${f instanceof Error?f.message:String(f)}`)}}),Or.command("invoke").description("Start a run of a deployed process \u2014 queued by default, or waited for with --sync.").argument("<process-id>","The process id, e.g. acme:reorder-suggestions.").option("--input <json>",`The process input as a JSON object, e.g. '{"customerId":"42"}'.`).option("--input-file <path>","Read the process input from a JSON file instead.").option("--sync","Wait for the run to settle (bounded by the instance's budget) and print its outcome.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the response as JSON.").action(async(d,h)=>{h.input!==void 0&&h.inputFile!==void 0&&v("pass --input or --input-file, not both.");let w={};if(h.input!==void 0||h.inputFile!==void 0){let S,$=h.input!==void 0?"--input":"--input-file";if(h.input!==void 0)S=h.input;else try{S=await ie.readFile(oe(process.cwd(),h.inputFile),"utf8")}catch{v(`input file not found at ${h.inputFile}.`)}let A=Sp(S,$);A.ok||v(A.message),w=A.input}let{baseUrl:T,token:_}=await B(h.baseUrl),f=new z({baseUrl:T,token:_});try{let S=await f.invokeProcess(d,w,h.sync?"sync":"async");h.json?y(JSON.stringify(S,null,2)):kp(S,d,qr,y)}catch(S){S instanceof Y&&S.status===403&&S.body?.reason==="admin_required"&&v("processes invoke forbidden (403) \u2014 the token's owner must be an administrator to start a process."),V(S,"extensions:deploy","processes invoke"),v(`processes invoke failed: ${S instanceof Error?S.message:String(S)}`)}}),Or.command("cancel").description("Stop one run \u2014 a queued run never executes, a running one stops at its next step.").argument("<run-id>","The run to stop.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T});try{let f=await _.cancelProcessRun(d);y(`cancelled ${f.runId??d} (${f.state??"cancelled"}).`),y("A run already going stops at its next step boundary; writes it has already made stay.")}catch(f){v(`processes cancel failed: ${f instanceof Error?f.message:String(f)}`)}}),Or.command("rollback").description("Undo a finished run \u2014 delete, newest first, the records its ledger proves it created.").argument("<run-id>","The finished run to roll back.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let{baseUrl:w,token:T}=await B(h.baseUrl),_=new z({baseUrl:w,token:T});try{let f=await _.rollbackProcessRun(d);if(!f.queued){y(`${f.runId??d} is already rolled back \u2014 nothing to do.`);return}y(`rollback queued for ${f.runId??d} (was ${f.state}).`),y(`Only records this run created are deleted; records it updated are left alone. Source deletes are paced by the rollback cap \u2014 follow with \`turbobase processes run ${f.runId??d}\`.`)}catch(f){v(`processes rollback failed: ${f instanceof Error?f.message:String(f)}`)}}),e.command("data").description("Act on one record in your instance \u2014 today, link a row after a settle conflict.").command("settle").description("Link a row to the record the connected system already created, after a write_settle_conflict.").argument("<record-type>","The record type, e.g. salesOrder or nonInventorySaleItem.").argument("<pg-row-id>","The row's pg_row_id.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the answer as JSON.").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await B(w.baseUrl),f=new z({baseUrl:T,token:_});try{let S=await f.settleRow(d,h);if(w.json){y(JSON.stringify(S,null,2));return}y(`linked ${d} ${S.pgRowId} to ${S.externalId}.`),S.discarded.length>0&&y(`discarded the inbound copy of the same record: ${S.discarded.join(", ")}.`)}catch(S){v(`data settle failed: ${S instanceof Error?S.message:String(S)}`)}});let nu=e.command("relationships").description('List the linked record pairs on your instance and switch either "re-read" on or off.'),ou=d=>d===null?m.dim("off"):`${m.green("on")} ${m.dim(new Date(d).toISOString().replace("T"," ").replace(/:\d\d\.\d+Z$/," UTC"))}`,iw=d=>[d.source_system,d.source_table,d.source_jsonb_key??m.dim("(none)"),d.target_table,ou(d.children_refresh_marked_at),ou(d.rollup_marked_at)],aw=["SOURCE","LINE TABLE","LINK FIELD","PARENT","LINES","PARENT RE-READ"];return nu.command("list").description("List every linked record pair, and which of its two re-reads is switched on.").option("--source <system>","Only this connected source (default: every one).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await T.relationshipsList(d.source)}catch(f){V(f,"extensions:deploy","list relationships"),v(`relationships list failed: ${f instanceof Error?f.message:String(f)}`)}if(d.json)return y(JSON.stringify(_,null,2));if(_.length===0)return y(`no linked record pairs are declared on this instance yet.
4248
+ `+m.dim(" pairs are discovered when a source is reconciled; nothing can be switched on until one is."));y(it(_.map(iw),{head:aw})),y(m.dim(" LINES = re-read the lines when their parent is saved. PARENT RE-READ = re-read the parent when one of its lines is saved."))}),nu.command("refresh").description("Switch one of a pair's two re-reads on or off.").argument("<CHILD:KEY:PARENT>","The relation: the line table, the field on it that holds the parent, and the parent table.").option("--children","The re-read of the LINES when their parent is saved.").option("--parent","The re-read of the PARENT when one of its lines is saved.").option("--on","Switch that re-read on.").option("--off","Switch that re-read off.").option("--source <system>","Which connected source declares the link (default: whichever does).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit the answer as JSON.").action(async(d,h)=>{h.children===h.parent&&v("say which re-read: --children (the lines) or --parent (the parent), not both."),h.on===h.off&&v("say which way: --on or --off, not both.");let w=h.children?"children":"parent",{baseUrl:T,token:_}=await B(h.baseUrl),f=new z({baseUrl:T,token:_});try{let S=await f.relationshipRefresh(d,{marker:w,enabled:h.on===!0,...h.source?{source:h.source}:{}});if(h.json)return y(JSON.stringify(S,null,2));let $=w==="children"?"the lines are re-read when their parent is saved":"the parent is re-read when one of its lines is saved";if(!S.changed)return y(`${S.relation.alias} was already ${h.on?"on":"off"} \u2014 nothing changed.
4249
+ `+m.dim(` ${$}: ${h.on?"on":"off"}`));y(`${S.relation.alias}: ${h.on?m.green("on"):m.dim("off")} \u2014 ${$}.`),h.on&&y(m.dim(" this costs one source query per parent commit plus one re-read per line."))}catch(S){V(S,"extensions:deploy","change a relationship refresh"),v(`relationships refresh failed: ${S instanceof Error?S.message:String(S)}`)}}),e.command("logs").description("Read the platform event log \u2014 guardrails, hooks, scheduled tasks, conduits and sync in one stream. Absorbs the old `ext logs` via --extension / --conduit.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--subsystem <s>","guardrails | hooks | tasks | conduits | sync").option("--severity <s>","Minimum severity: debug | info | warn | error (a THRESHOLD \u2014 `warn` includes errors).").option("--code <code>","One event code, e.g. guardrails.write_denied").option("--since <window>","Relative window (10m, 2h, 3d) or an ISO timestamp.").option("--correlation-id <id>","Follow one root action across every subsystem it touched.").option("--extension <id>","One extension's own log ring buffer (was `ext logs <id>`).").option("--conduit <id>","One conduit's run ledger (was `ext logs <id> --follow`).").option("--process-run <runId>","One process run's step ledger. With --follow it streams and EXITS when the run finishes.").option("--follow","Poll for new rows and print them as they land.").option("--interval-ms <ms>","Poll interval for --follow (default 2000).").option("--limit <n>","Max rows on the first read (default 100, max 500).").option("--json","Emit raw rows as JSON, one per line.").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_=d.limit?Number(d.limit):void 0,f=d.intervalMs?Number(d.intervalMs):void 0;if(d.processRun){try{await _p(T,d.processRun,{...d.follow?{follow:!0}:{},...f!==void 0?{intervalMs:f}:{},sink:y})}catch(S){v(`logs --process-run failed: ${S instanceof Error?S.message:String(S)}`)}return}if(d.conduit){try{await mp(T,d.conduit,{...d.follow?{follow:!0}:{},..._!==void 0?{limit:_}:{},...f!==void 0?{intervalMs:f}:{},sink:y})}catch(S){v(`logs --conduit failed: ${S instanceof Error?S.message:String(S)}`)}return}if(d.extension){try{let S=await T.logs(d.extension,_);S.length===0&&y(`no logs for ${d.extension}.`);for(let $ of S)y(` [${$.level}] ${$.ts??""} ${$.message}`)}catch(S){v(`logs --extension failed: ${S instanceof Error?S.message:String(S)}`)}return}try{await gp(T,{...d.subsystem?{subsystem:d.subsystem}:{},...d.severity?{severity:d.severity}:{},...d.code?{code:d.code}:{},...d.since?{since:d.since}:{},...d.correlationId?{correlationId:d.correlationId}:{},...d.follow?{follow:!0}:{},...d.json?{json:!0}:{},..._!==void 0?{limit:_}:{},...f!==void 0?{intervalMs:f}:{},sink:y})}catch(S){v(`logs failed: ${S instanceof Error?S.message:String(S)}`)}}),e.command("mcp").description("Run the local stdio authoring MCP server, for clients pointed at a process rather than a URL. (The .mcp.json that `project init` writes uses the instance's HTTP servers instead.)").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async d=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(Zb(),Xb));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(`
4250
+ `)),t&&void 0,e}function lC(t,e,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(t);return s?s[2]:void 0};return{id:n("id")??`marketplace:${e}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:t,extensionKind:r||"hook"}}async function cC(t){let e=tt(oe(process.cwd(),t),"public","turbobase.json"),r=await ie.readFile(e,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){v(`${e} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&v(`${e} must be a JSON object.`),{manifest:n,manifestPath:e}}async function dC(){let t=oe(process.cwd(),ns,Pn),e;try{e=await ie.readFile(t,"utf8")}catch{v(`no config found \u2014 this project authors none (no ${ss}/, ${is}/, ${Yt} or ${Xt}) and there is no ${ns}/${Pn}.
4251
+ Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return Bp(e)}catch(r){v(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function Wd(){let t=process.cwd();if(!await Gp(t))return dC();let e;try{e=await Wp(t,{inline:pa})}catch(r){v(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of e.unparsed)O(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return e.unparsed.length>0&&v(`${e.unparsed.length} extension file(s) could not be identified. Every hook/conduit needs a literal \`id:\`, \`recordType:\` and \`event:\`/\`on:\` \u2014 run \`turbobase ext lint <file>\` on each.`),e.manifest}function uC(t,e){y(`plan against ${e}:`);for(let r of t.add)y(` ${Wt.add(`${r.kind} ${r.id}`)}`);for(let r of t.change)y(` ${Wt.change(`${r.kind} ${r.id}`)}`);for(let r of t.destroy)y(` ${Wt.destroy(`${r.kind} ${r.id}`)}`);y(`
4252
+ ${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 pC(t){try{let r=new URL(t).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function $o(t,e,r){return new Promise(n=>{let o=Zd(t,e,{stdio:["ignore","inherit","pipe"],env:{...process.env,...r}}),s="";o.stderr?.on("data",i=>{let a=i.toString();s+=a,process.stderr.write(a)}),o.on("error",i=>n({code:-1,stderr:i.message})),o.on("exit",i=>n({code:i??-1,stderr:s}))})}function Jd(){let t=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",e=async(r,n)=>{let o=n?t.replace(/\/[^/]*$/,`/${n}`):t,s=await $o("psql",[o,"-v","ON_ERROR_STOP=1","-c",r]);if(s.code!==0)throw new Error(`psql failed (exit ${s.code}): ${s.stderr.trim()}`)};return{target:()=>t,createDatabase:async r=>{await e(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=t.replace(/\/[^/]*$/,`/${r}`),o=await $o("supabase",["migration","up","--db-url",n]);if(o.code!==0)throw new Error(`supabase migration up failed (exit ${o.code}): ${o.stderr.trim()}`)},dataCopyUnavailable:()=>"seeding a sandbox from an instance is not implemented yet: it needs a per-column PII classification for the source tables, and a sandbox will never copy a column it cannot prove is safe. Nothing was created. Use `turbobase ext test <file>` or `turbobase ext replay <file> --fixture <f>` for the offline paths.",readSourceTables:async r=>{throw new Error("sandbox data copy is not implemented.")},copyRows:async(r,n,o)=>{let s=Object.keys(o[0]??{});if(s.length===0)return;let i=o.map(a=>`(${s.map(l=>a[l]===null||a[l]===void 0?"NULL":`'${String(a[l]).replace(/'/g,"''")}'`).join(", ")})`).join(", ");await e(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await e(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function hC(t){let e=oe(t,"src"),r={},n=async o=>{let s;try{s=await ie.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=tt(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let l=qi(e,a).split(Xd).join("/");r[l]=await ie.readFile(a,"utf8")}}};return await n(e),r}function Yd(t){return new Promise(e=>{let r=Zd("git",t,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>e(null)),r.on("exit",o=>e(o===0&&n.trim()?n.trim():null))})}var mC=!1;mC&&Qd().parseAsync(process.argv).catch(t=>v(t instanceof Error?t.message:String(t)));Qd().parseAsync(process.argv).catch(t=>{process.stderr.write(`turbobase: ${t instanceof Error?t.message:String(t)}
4182
4253
  `),process.exit(1)});