@turbobase/cli 1.48.0 → 1.49.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-standalone.mjs +190 -172
- package/dist/turbobase.js +180 -162
- package/package.json +1 -1
package/dist/turbobase.js
CHANGED
|
@@ -1,38 +1,38 @@
|
|
|
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 Jw=Object.create;var ea=Object.defineProperty;var Yw=Object.getOwnPropertyDescriptor;var Xw=Object.getOwnPropertyNames;var Zw=Object.getPrototypeOf,Qw=Object.prototype.hasOwnProperty;var D=(e,t)=>()=>(e&&(t=e(e=0)),t);var q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),_u=(e,t)=>{for(var r in t)ea(e,r,{get:t[r],enumerable:!0})},ev=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xw(t))!Qw.call(e,o)&&o!==r&&ea(e,o,{get:()=>t[o],enumerable:!(n=Yw(t,o))||n.enumerable});return e};var Su=(e,t,r)=>(r=e!=null?Jw(Zw(e)):{},ev(t||!e||!e.__esModule?ea(r,"default",{value:e,enumerable:!0}):r,e));function gr(e){return Object.freeze({kind:e.kind,define:t=>t,schema:e.schema,factoryName:e.factoryName})}var Tn=D(()=>{});import{z as yr}from"zod";function qo(e){let t=ta.safeParse(e);return t.success?(t.data.inputs??[]).filter(r=>r.type==="connection"):[]}function ra(e,t){let r=ta.safeParse(e);if(!r.success)throw new Yt(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(ku.test(t))throw new Yt('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(ku.test(n))throw new Yt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var xu,Tu,ta,Yt,ku,Ru=D(()=>{xu=yr.object({type:yr.literal("connection"),source_system:yr.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:yr.string().min(1).max(200).optional()}),Tu=yr.discriminatedUnion("type",[xu]),ta=yr.object({inputs:yr.array(Tu).optional()}).passthrough(),Yt=class extends Error{constructor(t){super(t),this.name="ManifestValidationError"}};ku=/\bconnection[_-]?id\b["']?\s*[:=]/i});var zo,na=D(()=>{zo=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Ve}from"zod";var oa,$u,Eu=D(()=>{Tn();na();oa=Ve.object({id:Ve.string().min(1,"hook id must be non-empty"),recordType:Ve.union([Ve.string().min(1),Ve.array(Ve.string().min(1)).min(1),Ve.literal("*")]),event:Ve.enum(zo),source:Ve.string().min(1).optional(),when:Ve.unknown().optional(),run:Ve.unknown(),failClosed:Ve.boolean().optional(),timeoutMs:Ve.number().int().positive().optional(),description:Ve.string().optional(),systemReserved:Ve.boolean().optional()}).superRefine((e,t)=>{typeof e.run!="function"&&t.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in e&&e.when!==void 0&&typeof e.when!="function"&&t.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),$u=gr({kind:"hook",schema:oa,factoryName:"defineHook"})});var Pu=D(()=>{Eu();na()});var Ur,sa=D(()=>{Ur=["after_canonicalize_inbound","after_sync_success_outbound","after_save","after_delete"]});import{z as fe}from"zod";var Au,nv,Cu,ia,Iu,Ou=D(()=>{Tn();sa();Au=fe.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),nv=fe.object({recordType:fe.string().min(1,"reads[].recordType must be non-empty"),source:fe.string().min(1).optional(),columns:fe.array(Au).min(1,"reads[].columns must name at least one column"),by:fe.array(Au).optional(),maxRows:fe.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),Cu=fe.object({source:fe.string().min(1,"to.source must be non-empty"),recordType:fe.string().min(1,"to.recordType must be non-empty"),process:fe.string().min(1,"to.process must be non-empty when present").optional()}),ia=fe.object({id:fe.string().min(1,"conduit id must be non-empty"),on:fe.enum(Ur),from:fe.object({source:fe.string().min(1,"from.source must be non-empty"),recordType:fe.string().min(1,"from.recordType must be non-empty"),when:fe.unknown().optional()}),to:Cu.optional(),mode:fe.enum(["dual-bind","one-shot"]).optional(),transform:fe.unknown().optional(),sequence:fe.array(fe.object({to:Cu,transform:fe.unknown(),awaitSource:fe.boolean().optional()})).optional(),reads:fe.array(nv).optional(),maxQueriesPerRun:fe.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:fe.unknown().optional(),cycleBudget:fe.number().int().positive().optional(),conflictStrategy:fe.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:fe.number().int().positive().optional(),description:fe.string().optional(),systemReserved:fe.boolean().optional()}).superRefine((e,t)=>{let r=e,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?t.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?t.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&t.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((u,p)=>{typeof u.transform!="function"&&t.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&&t.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&&t.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&t.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=e.from?.when;s!==void 0&&typeof s!="function"&&t.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=e.idempotencyKey;i!==void 0&&typeof i!="function"&&t.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&&t.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"})}),Iu=gr({kind:"conduit",schema:ia,factoryName:"defineConduit"})});var Nu=D(()=>{Ou();sa()});import{z as ae}from"zod";function ju(e,t,r){let n=t;if((typeof n.recordType!="string"||n.recordType.length===0)&&e.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),n.when!==void 0&&typeof n.when!="function"&&e.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"}),n.delete!==void 0){pv(e,n,r);return}n.onRefused!==void 0&&e.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"&&e.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"&&e.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&&e.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function pv(e,t,r){t.build!==void 0&&e.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"}),t.rollback==="undo"&&e.addIssue({code:"custom",path:[...r,"rollback"],message:"a delete cannot be undone, so a delete step is always rollback: 'keep'"});let n=t.delete??{};for(let o of["pgRowId","externalId"]){let s=n[o];s!==void 0&&typeof s!="function"&&e.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&&e.addIssue({code:"custom",path:[...r,"delete"],message:"delete must address a record: one of `pgRowId` or `externalId`"})}function hv(e,t,r){t.forEach===void 0&&e.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=t.steps;if(!Array.isArray(n)||n.length===0){e.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)=>{ju(e,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let l=o.get(a);l!==void 0?e.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 Lu,dv,uv,aa,Du,Uu=D(()=>{Tn();Lu={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()},dv=ae.object(Lu),uv=ae.object({...Lu,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(dv).optional()}),aa=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(uv).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((e,t)=>{let r=e.eachRow;r&&typeof r.outstanding!="function"&&t.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=e.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?hv(t,a,i):ju(t,s,["steps",i]),typeof a.id=="string"){let l=o.get(a.id);l!==void 0?t.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)}})});Du=gr({kind:"process",schema:aa,factoryName:"defineProcess"})});var Mu=D(()=>{});var qu=D(()=>{Uu();Mu()});async function bv(e){let t;try{t=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 t.default(e,{defaultNonNullable:!1});return t.astToString(r)}async function Ho(e,t={}){return(t.transform??bv)(e)}var la=D(()=>{});function Vo(e){switch(e.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 Mr(e){return e.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Ko(e){return`${Mr(e.source)}${Mr(e.recordType)}`}function zu(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Bu(e){let t=[e.pgType];return e.label&&t.push(`"${e.label}"`),e.role==="display"&&e.displayFor?t.push(`display column for ${e.displayFor} \u2014 render this, filter/join on ${e.displayFor}`):e.role==="identifier"&&e.idFor?t.push(`identifier \u2014 render ${e.idFor} instead`):e.role&&t.push(e.role),e.format&&t.push(`format: ${e.format}`),e.currencyKey&&t.push(`currency from ${e.currencyKey}`),e.description&&t.push(e.description),t.join(" \xB7 ")}function ca(e){let t=Ko(e),r=[`${e.source}:${e.recordType}`+(e.table?` \u2192 turbobase.${e.table}`:" (no backing table)")+`${e.listOnly?" (list-only)":""} \u2014 origin: ${e.origin}.`];e.description&&r.push(e.description);let n=r.length===1?`/** ${r[0]} */`:`/**
|
|
4
|
+
var Yw=Object.create;var ta=Object.defineProperty;var Xw=Object.getOwnPropertyDescriptor;var Zw=Object.getOwnPropertyNames;var Qw=Object.getPrototypeOf,ev=Object.prototype.hasOwnProperty;var D=(e,t)=>()=>(e&&(t=e(e=0)),t);var q=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Su=(e,t)=>{for(var r in t)ta(e,r,{get:t[r],enumerable:!0})},tv=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Zw(t))!ev.call(e,o)&&o!==r&&ta(e,o,{get:()=>t[o],enumerable:!(n=Xw(t,o))||n.enumerable});return e};var ku=(e,t,r)=>(r=e!=null?Yw(Qw(e)):{},tv(t||!e||!e.__esModule?ta(r,"default",{value:e,enumerable:!0}):r,e));function gr(e){return Object.freeze({kind:e.kind,define:t=>t,schema:e.schema,factoryName:e.factoryName})}var Tn=D(()=>{});import{z as yr}from"zod";function qo(e){let t=ra.safeParse(e);return t.success?(t.data.inputs??[]).filter(r=>r.type==="connection"):[]}function na(e,t){let r=ra.safeParse(e);if(!r.success)throw new Yt(`invalid manifest: ${r.error.issues.map(o=>`${o.path.join(".")||"(root)"}: ${o.message}`).join("; ")}`);if(xu.test(t))throw new Yt('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(xu.test(n))throw new Yt("the manifest carries a literal connection_id \u2014 the connection is bound at install time, never published.")}var Tu,Ru,ra,Yt,xu,$u=D(()=>{Tu=yr.object({type:yr.literal("connection"),source_system:yr.string().min(1).regex(/^[a-z0-9][a-z0-9_-]*$/,{message:"source_system must be a lowercase identifier"}),label:yr.string().min(1).max(200).optional()}),Ru=yr.discriminatedUnion("type",[Tu]),ra=yr.object({inputs:yr.array(Ru).optional()}).passthrough(),Yt=class extends Error{constructor(t){super(t),this.name="ManifestValidationError"}};xu=/\bconnection[_-]?id\b["']?\s*[:=]/i});var zo,oa=D(()=>{zo=["before_read","before_save","after_save","before_delete","after_delete","before_sync","after_sync","on_sync_failure"]});import{z as Ve}from"zod";var sa,Eu,Pu=D(()=>{Tn();oa();sa=Ve.object({id:Ve.string().min(1,"hook id must be non-empty"),recordType:Ve.union([Ve.string().min(1),Ve.array(Ve.string().min(1)).min(1),Ve.literal("*")]),event:Ve.enum(zo),source:Ve.string().min(1).optional(),when:Ve.unknown().optional(),run:Ve.unknown(),failClosed:Ve.boolean().optional(),timeoutMs:Ve.number().int().positive().optional(),description:Ve.string().optional(),systemReserved:Ve.boolean().optional()}).superRefine((e,t)=>{typeof e.run!="function"&&t.addIssue({code:"custom",path:["run"],message:"run must be a function"}),"when"in e&&e.when!==void 0&&typeof e.when!="function"&&t.addIssue({code:"custom",path:["when"],message:"when, when present, must be a function"})}),Eu=gr({kind:"hook",schema:sa,factoryName:"defineHook"})});var Au=D(()=>{Pu();oa()});var Dr,ia=D(()=>{Dr=["after_canonicalize_inbound","after_sync_success_outbound","after_save","after_delete"]});import{z as fe}from"zod";var Cu,ov,Iu,aa,Ou,Nu=D(()=>{Tn();ia();Cu=fe.string().regex(/^[a-z_][a-z0-9_]*$/i,"must be a bare column name (letters, digits, underscore)"),ov=fe.object({recordType:fe.string().min(1,"reads[].recordType must be non-empty"),source:fe.string().min(1).optional(),columns:fe.array(Cu).min(1,"reads[].columns must name at least one column"),by:fe.array(Cu).optional(),maxRows:fe.number().int().positive().max(500,`reads[].maxRows cannot exceed ${500}`).optional()}),Iu=fe.object({source:fe.string().min(1,"to.source must be non-empty"),recordType:fe.string().min(1,"to.recordType must be non-empty"),process:fe.string().min(1,"to.process must be non-empty when present").optional()}),aa=fe.object({id:fe.string().min(1,"conduit id must be non-empty"),on:fe.enum(Dr),from:fe.object({source:fe.string().min(1,"from.source must be non-empty"),recordType:fe.string().min(1,"from.recordType must be non-empty"),when:fe.unknown().optional()}),to:Iu.optional(),mode:fe.enum(["dual-bind","one-shot"]).optional(),transform:fe.unknown().optional(),sequence:fe.array(fe.object({to:Iu,transform:fe.unknown(),awaitSource:fe.boolean().optional()})).optional(),reads:fe.array(ov).optional(),maxQueriesPerRun:fe.number().int().positive().max(32,`maxQueriesPerRun cannot exceed ${32}`).optional(),idempotencyKey:fe.unknown().optional(),cycleBudget:fe.number().int().positive().optional(),conflictStrategy:fe.enum(["skip","merge","overwrite","revert-on-reject"]).optional(),timeoutMs:fe.number().int().positive().optional(),description:fe.string().optional(),systemReserved:fe.boolean().optional()}).superRefine((e,t)=>{let r=e,n=r.to!==void 0||r.transform!==void 0,o=r.sequence!==void 0;n&&o?t.addIssue({code:"custom",path:["sequence"],message:"declare EITHER `to` + `transform` OR `sequence` \u2014 not both"}):!n&&!o?t.addIssue({code:"custom",path:["to"],message:"a conduit needs a target: `to` + `transform`, or an ordered `sequence` of them"}):o?(r.sequence.length===0&&t.addIssue({code:"custom",path:["sequence"],message:"sequence must declare at least one target"}),r.sequence.forEach((u,p)=>{typeof u.transform!="function"&&t.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&&t.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&&t.addIssue({code:"custom",path:["to"],message:"`to` is required beside `transform`"}),typeof r.transform!="function"&&t.addIssue({code:"custom",path:["transform"],message:"transform must be a function"}));let s=e.from?.when;s!==void 0&&typeof s!="function"&&t.addIssue({code:"custom",path:["from","when"],message:"from.when, when present, must be a function"});let i=e.idempotencyKey;i!==void 0&&typeof i!="function"&&t.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&&t.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"})}),Ou=gr({kind:"conduit",schema:aa,factoryName:"defineConduit"})});var Lu=D(()=>{Nu();ia()});import{z as ae}from"zod";function Du(e,t,r){let n=t;if((typeof n.recordType!="string"||n.recordType.length===0)&&e.addIssue({code:"custom",path:[...r,"recordType"],message:"step.recordType must be non-empty"}),n.when!==void 0&&typeof n.when!="function"&&e.addIssue({code:"custom",path:[...r,"when"],message:"when must be a function returning whether this step runs"}),n.delete!==void 0){hv(e,n,r);return}n.onRefused!==void 0&&e.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"&&e.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"&&e.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&&e.addIssue({code:"custom",path:[...r,"update"],message:"update must address a record: one of `step`, `pgRowId` or `externalId`"})}}function hv(e,t,r){t.build!==void 0&&e.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"}),t.rollback==="undo"&&e.addIssue({code:"custom",path:[...r,"rollback"],message:"a delete cannot be undone, so a delete step is always rollback: 'keep'"});let n=t.delete??{};for(let o of["pgRowId","externalId"]){let s=n[o];s!==void 0&&typeof s!="function"&&e.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&&e.addIssue({code:"custom",path:[...r,"delete"],message:"delete must address a record: one of `pgRowId` or `externalId`"})}function mv(e,t,r){t.forEach===void 0&&e.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=t.steps;if(!Array.isArray(n)||n.length===0){e.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)=>{Du(e,s,["steps",r,"steps",i]);let a=s.id;if(typeof a!="string")return;let l=o.get(a);l!==void 0?e.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 ju,uv,pv,la,Uu,Mu=D(()=>{Tn();ju={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()},uv=ae.object(ju),pv=ae.object({...ju,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(uv).optional()}),la=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(pv).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((e,t)=>{let r=e.eachRow;r&&typeof r.outstanding!="function"&&t.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=e.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?mv(t,a,i):Du(t,s,["steps",i]),typeof a.id=="string"){let l=o.get(a.id);l!==void 0?t.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)}})});Uu=gr({kind:"process",schema:la,factoryName:"defineProcess"})});var qu=D(()=>{});var zu=D(()=>{Mu();qu()});async function wv(e){let t;try{t=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 t.default(e,{defaultNonNullable:!1});return t.astToString(r)}async function Ho(e,t={}){return(t.transform??wv)(e)}var ca=D(()=>{});function Vo(e){switch(e.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 Ur(e){return e.replace(/[^A-Za-z0-9]+/g," ").split(" ").filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Ko(e){return`${Ur(e.source)}${Ur(e.recordType)}`}function Bu(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function Fu(e){let t=[e.pgType];return e.label&&t.push(`"${e.label}"`),e.role==="display"&&e.displayFor?t.push(`display column for ${e.displayFor} \u2014 render this, filter/join on ${e.displayFor}`):e.role==="identifier"&&e.idFor?t.push(`identifier \u2014 render ${e.idFor} instead`):e.role&&t.push(e.role),e.format&&t.push(`format: ${e.format}`),e.currencyKey&&t.push(`currency from ${e.currencyKey}`),e.description&&t.push(e.description),t.join(" \xB7 ")}function da(e){let t=Ko(e),r=[`${e.source}:${e.recordType}`+(e.table?` \u2192 turbobase.${e.table}`:" (no backing table)")+`${e.listOnly?" (list-only)":""} \u2014 origin: ${e.origin}.`];e.description&&r.push(e.description);let n=r.length===1?`/** ${r[0]} */`:`/**
|
|
5
5
|
* ${r.join(`
|
|
6
6
|
* `)}
|
|
7
7
|
*/`;if(e.columns.length===0)return`${n}
|
|
8
8
|
export interface ${t} {
|
|
9
9
|
// no columns introspected
|
|
10
10
|
[key: string]: unknown;
|
|
11
|
-
}`;let o=e.columns.map(s=>{let i=Vo(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${
|
|
12
|
-
${
|
|
11
|
+
}`;let o=e.columns.map(s=>{let i=Vo(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${Fu(s)} */
|
|
12
|
+
${Bu(s.name)}${a}: ${i}${l};`});return`${n}
|
|
13
13
|
export interface ${t} {
|
|
14
14
|
${o.join(`
|
|
15
15
|
`)}
|
|
16
|
-
}`}function
|
|
16
|
+
}`}function Hu(e){return e.connected!==!1}function vv(e,t){let r=`${Ur(e.source)}${Ur(t.table)}`,n=`/** ${e.source}:${e.recordType} lines \u2192 turbobase.${t.table}. */`;if(t.columns.length===0)return`${n}
|
|
17
17
|
export interface ${r} {
|
|
18
18
|
// no columns introspected
|
|
19
19
|
[key: string]: unknown;
|
|
20
|
-
}`;let o=t.columns.map(s=>{let i=Vo(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${
|
|
21
|
-
${
|
|
20
|
+
}`;let o=t.columns.map(s=>{let i=Vo(s.pgType),a=s.nullable?"?":"",l=s.nullable?" | null":"";return` /** ${Fu(s)} */
|
|
21
|
+
${Bu(s.name)}${a}: ${i}${l};`});return`${n}
|
|
22
22
|
export interface ${r} {
|
|
23
23
|
${o.join(`
|
|
24
24
|
`)}
|
|
25
|
-
}`}function Wo(e){let t=[...e.records].filter(
|
|
25
|
+
}`}function Wo(e){let t=[...e.records].filter(Hu).sort((o,s)=>`${o.source}:${o.recordType}`.localeCompare(`${s.source}:${s.recordType}`)),r=new Set,n=[];for(let o of t){let s=Ko(o);r.has(s)||(r.add(s),n.push(da(o)));for(let i of o.lines??[]){let a=`${Ur(o.source)}${Ur(i.table)}`;r.has(a)||(r.add(a),n.push(vv(o,i)))}}return n.join(`
|
|
26
26
|
|
|
27
|
-
`)}function
|
|
28
|
-
`)}var
|
|
27
|
+
`)}function Vu(e){let t=new Map,r=(o,s)=>{let i=t.get(o);i||t.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 e.records.filter(Hu)){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[...t].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 _v(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)?e:JSON.stringify(e)}function ua(e){let t=Vu(e);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(t).map(([n,o])=>{let s=Array.isArray(o)?`[${o.map(i=>`'${i}'`).join(", ")}]`:`'${o}'`;return` ${_v(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(`
|
|
28
|
+
`)}var pa=D(()=>{});function Sv(e){let t=e.replace(/\/+$/,"");return{records:`${t}/v1/catalog/records`,openapi:`${t}/v1/catalog/openapi.json`}}async function Ku(e,t,r){let n=await r(e,{headers:{Accept:"application/json",Authorization:`Bearer ${t}`}});if(!n.ok)throw new Error(`types-gen: GET ${e} failed (${n.status} ${n.statusText})`);return n.json()}async function br(e){let t=e.fetchImpl??fetch;if(typeof t!="function")throw new Error("types-gen: no fetch implementation available (pass options.fetchImpl)");let r=Sv(e.baseUrl),n=await Ku(r.records,e.token,t);if(!n||!Array.isArray(n.records))throw new Error("types-gen: /v1/catalog/records did not return a { records: [...] } envelope");let o=Wo(n),s=[kv,"// ----- Record shapes (from /v1/catalog/records) -----",o,"// ----- Keyset seek keys (derived from column nullability) -----",ua(n)];if(!e.recordsOnly){let i=await Ku(r.openapi,e.token,t),a=await Ho(i,e.openApi);s.push("// ----- PostgREST operations (from /v1/catalog/openapi.json) -----",a.trim())}return s.join(`
|
|
29
29
|
|
|
30
30
|
`)+`
|
|
31
|
-
`}var
|
|
32
|
-
`)});var
|
|
33
|
-
`,{mode:384})}async function
|
|
34
|
-
`)}function
|
|
35
|
-
`)}function Yo(e,t={}){let r=t.budgetMs??6e5,n=t.defaultDelayMs??6e4,o=t.sleep??(u=>new Promise(p=>setTimeout(p,u))),s=t.now??(()=>Date.now()),i=t.onWait??Av,a=t.onGiveUp??Cv;return async(u,p)=>{let g=s(),x=0;for(;;){let y=await e(u,p);if(y.status!==503||p&&!Pv(p.body))return y;let k=r-(s()-g),{maintenance:R,delayMs:$,error:P}=await Ev(y,s());if(!R)return y;if(k<=0)return x>0&&a({waitedMs:s()-g,attempts:x,host:Yu(u),error:P}),y;let C=$??n;C=Math.min(Math.max(C,1e3),12e4),C=Math.min(C,k),x+=1,i({attempt:x,delayMs:C,remainingMs:k,host:Yu(u),error:P}),await o(C)}}}var ba=D(()=>{});function Xu(e){if(typeof e=="string")return e.trim();if(!e||typeof e!="object")return"";let t=e;if(typeof t.message=="string"&&t.message.trim())return t.message.trim();let r=typeof t.error=="string"?t.error.trim():"",n=typeof t.reason=="string"?t.reason.trim():"";return n?r?`${r}: ${n}`:n:r}function Iv(e){let t=e.trimStart().slice(0,200).toLowerCase();return t.startsWith("<!doctype")||t.startsWith("<html")||t.startsWith("<")}function Nv(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.error=="string"&&typeof t.reason=="string"&&t.reason.trim()!==""}function Zu(e){let t=Xu(e);return typeof e=="string"&&Iv(t)?Ov:Nv(e)?t.slice(0,jv):t.slice(0,Lv)}function Qu(e,t){return ya(e,t)}function ep(e){return e instanceof Y&&Qu(e.status,e.body)}function Uv(){let e=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"}function tp(e){return e.replace(/\/+$/,"")}function wa(e=process.env){let t=(e[qr]??"").trim(),r=(e[Xo]??"").trim();return!t||!r?null:{registryUrl:t,token:r}}function va(e){let t;try{t=new URL(e)}catch{return`${qr} is not a valid URL: ${e}`}if(t.protocol==="https:")return null;let r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";return t.protocol==="http:"&&r?null:`${qr} must be https:// (got ${t.protocol}//${t.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var Y,Ov,Lv,jv,Dv,z,qr,Xo,En,bt=D(()=>{ba();Y=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Ov="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";Lv=200,jv=2e3;Dv="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";z=class{baseUrl;token;fetchImpl;constructor(t){this.baseUrl=tp(t.baseUrl),this.token=t.token;let r=t.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=t.retry===!1?r:Yo(r,t.retry??{})}async request(t,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:t,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(Uv()){let u=Xu(a);throw new Y(`${t} ${r} \u2192 ${s.status}${u?`: ${u}`:""}`,s.status,a)}if(Qu(s.status,a))throw new Y(Dv,s.status,a);let l=Zu(a);throw new Y(`${t} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}deploy(t){return this.request("POST","/v1/extensions",{id:t.id,recordType:t.recordType,event:t.event,source:t.source,sourceCode:t.sourceCode,extensionKind:t.extensionKind??"hook",provenance:t.provenance??"cli",...t.connectionId?{connectionId:t.connectionId}:{}})}async list(t){let r=t?`?kind=${encodeURIComponent(t)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(t){return this.request("POST","/v1/extensions/test",{id:t.id,recordType:t.recordType,event:t.event,source:t.source,sourceCode:t.sourceCode,extensionKind:t.extensionKind??"hook",provenance:t.provenance??"cli"})}authorConduit(t){return this.request("POST","/v1/extensions/author-conduit",{intent:t.intent,from:t.from,to:t.to,...t.intentId?{intentId:t.intentId}:{},...t.columns?.length?{columns:t.columns}:{}})}async proposals(t={}){let r=new URLSearchParams;t.status?.length&&r.set("status",t.status.join(",")),t.provenance?.length&&r.set("provenance",t.provenance.join(",")),t.recordType&&r.set("recordType",t.recordType),t.source&&r.set("source",t.source),t.limit&&t.limit>0&&r.set("limit",String(Math.floor(t.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(t){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(t)}/promote`,{})}proposalRetract(t){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(t)}/retract`,{})}proposalReject(t,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(t)}/reject`,r?{reason:r}:{})}extensionDisable(t){return this.request("POST",`/v1/extensions/${encodeURIComponent(t)}/disable`,{})}extensionEnable(t){return this.request("POST",`/v1/extensions/${encodeURIComponent(t)}/enable`,{})}extensionRemove(t){return this.request("POST",`/v1/extensions/${encodeURIComponent(t)}/remove`,{})}async logs(t,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(t)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(t,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(t)}/events${o}`)).events??[]}async processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(t){return(await this.request("GET",`/v1/processes/${encodeURIComponent(t)}/runs`)).runs??[]}async processRun(t){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(t)}`)}async invokeProcess(t,r,n="async"){let o=n==="sync"?"?mode=sync":"";return this.request("POST",`/v1/processes/${encodeURIComponent(t)}${o}`,r)}async settleRow(t,r){return this.request("POST",`/v1/data/${encodeURIComponent(t)}/settle`,{pgRowId:r})}async cancelProcessRun(t){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(t)}/cancel`)}async rollbackProcessRun(t){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(t)}/rollback`)}async platformEvents(t={}){let r=new URLSearchParams;t.subsystem&&r.set("subsystem",t.subsystem),t.severity&&r.set("severity",t.severity),t.code&&r.set("code",t.code),t.since&&r.set("since",t.since),t.after&&r.set("after",t.after),t.correlationId&&r.set("correlationId",t.correlationId),t.extension&&r.set("extension",t.extension),t.conduit&&r.set("conduit",t.conduit),t.limit&&t.limit>0&&r.set("limit",String(Math.floor(t.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(t={}){let r=new URLSearchParams;t.status&&r.set("status",t.status),t.limit&&t.limit>0&&r.set("limit",String(Math.floor(t.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(t){return this.request("POST","/v1/apps",{slug:t.slug,name:t.name??t.slug,description:t.description})}appsPull(t){return this.request("GET",`/v1/apps/${encodeURIComponent(t)}/pull`)}appPullContext(t){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(t)}/pull-context`)}appsPush(t,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(t)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(t={}){let r=new URLSearchParams;t.app&&r.set("app",t.app),t.section&&r.set("section",t.section),t.limit!==void 0&&r.set("limit",String(t.limit)),t.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(t){return this.request("POST","/v1/learnings/ingest",{...t?{app:t}:{}})}rulesPending(t={}){let r=new URLSearchParams;t.app&&r.set("app",t.app),t.limit!==void 0&&r.set("limit",String(t.limit)),t.group===!1&&r.set("group","false"),t.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(t,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:t,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(t={}){let r=new URLSearchParams;t.status&&r.set("status",t.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(t,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(t)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(t){return this.request("POST","/v1/skills/publish",{slugs:[...t]})}skillsUnpublish(t){return this.request("POST","/v1/skills/unpublish",{slugs:[...t]})}skillsRollback(t){return this.request("POST","/v1/skills/rollback",{versionNo:t})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(t){return this.request("DELETE",`/v1/skills/${encodeURIComponent(t)}`)}docsList(t={}){let r=new URLSearchParams;t.status&&r.set("status",t.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(t){return this.request("POST","/v1/docs/publish",{slugs:[...t]})}docsUnpublish(t){return this.request("POST","/v1/docs/unpublish",{slugs:[...t]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(t){return this.request("POST","/v1/docs/rollback",{versionNo:t})}docsDelete(t){return this.request("DELETE",`/v1/docs/${encodeURIComponent(t)}`)}learningsPushKb(t,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:t,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(t){return this.request("POST",`/v1/bindings/${encodeURIComponent(t)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(t){return this.request("POST","/v1/config/plan",{bundle:t})}configApply(t,r={}){return this.request("POST","/v1/config/apply",{bundle:t,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(t){return this.request("POST","/v1/tables/plan",t)}appsPlan(t){return this.request("POST","/v1/apps/plan",{writes:t.writes??[],...t.roles!==void 0?{roles:t.roles}:{},labels:t.labels??[],...t.app?{app:t.app}:{}})}tablesApply(t){return this.request("POST","/v1/tables/apply",t)}tablesDrop(t,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(t)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(t){return(await this.request("POST","/v1/guardrails",t)).guardrail}async guardrailUpdate(t,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(t)}`,r)).guardrail}guardrailDelete(t){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(t)}`)}guardrailTest(t){return this.request("POST","/v1/guardrails/test",t)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(t){return this.request("PUT","/v1/guardrails/posture",{mode:t})}async relationshipsList(t){let r=t?`?source=${encodeURIComponent(t)}`:"";return(await this.request("GET",`/v1/relationships${r}`)).relations??[]}relationshipRefresh(t,r){return this.request("PATCH",`/v1/relationships/${encodeURIComponent(t)}`,r)}releaseDeploy(t){return this.request("POST","/v1/releases/deploy",{...t.solutionId?{solutionId:t.solutionId}:{},target:t.target,...t.approvedBy?{approvedBy:t.approvedBy}:{},...t.files?{files:t.files}:{},...t.gitRepo?{gitRepo:t.gitRepo}:{},...t.gitRef?{gitRef:t.gitRef}:{},...t.gitSha?{gitSha:t.gitSha}:{},...t.prUrl?{prUrl:t.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(t){return this.request("GET",`/v1/releases/${encodeURIComponent(t)}`)}releaseFiles(t){return this.request("GET",`/v1/releases/${encodeURIComponent(t)}/files`)}releasePush(t,r){return this.request("POST",`/v1/releases/${encodeURIComponent(t)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(t){return this.request("GET",`/v1/releases/${encodeURIComponent(t)}/status`)}releaseRollback(t){return this.request("POST",`/v1/releases/${encodeURIComponent(t)}/rollback`)}},qr="TURBOBASE_REGISTRY_URL",Xo="TURBOBASE_REGISTRY_TOKEN";En=class{registryUrl;token;fetchImpl;constructor(t){this.registryUrl=tp(t.registryUrl),this.token=t.token;let r=t.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(t,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:t,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=Zu(a);throw new Y(`${t} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(t,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(t)}${n}`)}publish(t){return this.request("POST","/extensions",{name:t.name,version:t.version,kind:t.kind,bundle:t.bundle,...t.manifest?{manifest:t.manifest}:{}})}}});import{existsSync as Mv,statSync as qv}from"node:fs";import{resolve as Zo,sep as rp}from"node:path";function np(e){if(Bv.has(e))return!0;let t=e.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(t)}function Hv(e,t,r){let n=Zo(t,r),o=Zo(e);if(n!==o&&!n.startsWith(o+rp))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+rp)&&Mv(i)&&qv(i).isFile())return i;return null}function op(e){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(np(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&e){let s=Hv(e,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${e?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||Kv(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.`}]}}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Fv,loader:"js"}))}}}function Kv(e){let t=e.startsWith("node:")?e.slice(5):e;return Vv.has(t.split("/")[0])}function sp(e,t){return new Error(`'${e}' 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: ${t instanceof Error?t.message:String(t)})`)}async function ip(){try{return(await import("esbuild")).build}catch(e){throw sp("esbuild",e)}}async function Wv(){try{return(await import("isolated-vm")).default}catch(e){throw sp("isolated-vm",e)}}async function ts(e,t={}){let r=await ip(),n=t.resolveDir?Zo(t.resolveDir):void 0,o;try{o=await r({stdin:{contents:e,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:[op(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new Qo(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function _a(e,t){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(e)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(e))return e;let r=await ip(),n=Zo(t),o=op(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:np(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:e,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 Qo(u||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??e}async function Pn(e,t,r={}){let n=r.timeoutMs??es,o=r.memoryLimitMb??zv,s=r.member??"run",i={patches:[],logs:[]},a=await Wv(),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)}),x=new a.Callback(H=>{i.patches.push(JSON.parse(String(H)))}),y=new a.Callback(H=>{let G=JSON.parse(String(H));i.logs.push(G)}),k=new a.Callback(H=>{i.result=JSON.parse(String(H))}),R=r.query,$=new a.Reference(async H=>{if(!R)throw new Error("ctx.query is not available in this context");return JSON.stringify(await R(String(H)))});await p.set("__tb_reject",g),await p.set("__tb_patch",x),await p.set("__tb_log",y),await p.set("__tb_result",k),await p.set("__tb_query",$),await p.set("__tb_ctx_json",JSON.stringify(Gv(t)));let P=Yv(e,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),j=await(await l.compileScript(P)).run(u,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!j}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Gv(e){return{recordType:e.recordType,event:e.event,direction:e.direction,origin:e.origin,source:e.source,payload:e.payload??null,prior:e.prior??null,user:e.user??null,tenantConfig:e.tenantConfig??{},metadata:e.metadata??null,bindings:e.bindings??null,atlasLinks:e.atlasLinks??null,materialized:e.materialized??null,process:e.process??null}}function Jv(e){return`
|
|
31
|
+
`}var kv,Wu=D(()=>{ca();pa();pa();ca();kv=["/**"," * 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(`
|
|
32
|
+
`)});var ha=D(()=>{Tn();$u();Au();Lu();zu();Wu()});import{homedir as xv}from"node:os";import{join as Gu}from"node:path";import{promises as ma}from"node:fs";function st(e){return e.trim().replace(/\/+$/,"")}function Go(){let e=process.env.TURBOBASE_HOME??Gu(xv(),".turbobase");return{dir:e,file:Gu(e,"credentials")}}function Ju(e){return!!e&&typeof e=="object"&&typeof e.token=="string"}async function Rn(){let{file:e}=Go(),t;try{let s=await ma.readFile(e,"utf8");t=JSON.parse(s)}catch(s){if(s.code==="ENOENT")return{tenants:{}};throw s}if(!t||typeof t!="object")return{tenants:{}};let r=t;if(r.tenants&&typeof r.tenants=="object"){let s={};for(let[a,l]of Object.entries(r.tenants))Ju(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))Ju(i)&&(n[s]={token:i.token,updatedAt:i.updatedAt});return{active:Tv(n),tenants:n}}function Tv(e){let t,r="";for(let[n,o]of Object.entries(e))(!t||String(o.updatedAt)>r)&&(t=n,r=String(o.updatedAt));return t}async function fa(e){let{dir:t,file:r}=Go();await ma.mkdir(t,{recursive:!0,mode:448}),await ma.writeFile(r,JSON.stringify(e,null,2)+`
|
|
33
|
+
`,{mode:384})}async function Yu(e){let t=st(e.baseUrl),r=await Rn(),n=new Date().toISOString();return r.tenants[t]={token:e.token,updatedAt:n},r.active=t,await fa(r),{baseUrl:t,token:e.token,updatedAt:n}}async function yt(e){let t=await Rn();if(e){let s=st(e),i=t.tenants[s];return i?{baseUrl:s,token:i.token,updatedAt:i.updatedAt}:null}let r=Object.keys(t.tenants),n=t.active&&t.tenants[t.active]?t.active:r.length===1?r[0]:void 0;if(!n)return null;let o=t.tenants[n];return{baseUrl:n,token:o.token,updatedAt:o.updatedAt}}async function Jo(e){let t=st(e),r=await Rn(),n=r.tenants[t];return n?(r.active=t,await fa(r),{baseUrl:t,token:n.token,updatedAt:n.updatedAt}):null}async function ga(e){let t=await Rn(),r=e?st(e):t.active&&t.tenants[t.active]?t.active:Object.keys(t.tenants).length===1?Object.keys(t.tenants)[0]:void 0;if(!r||!t.tenants[r])return null;if(delete t.tenants[r],t.active===r){let n=Object.keys(t.tenants);t.active=n.length===1?n[0]:void 0}return await fa(t),r}async function Mt(){let e=await Rn();return Object.entries(e.tenants).map(([t,r])=>({baseUrl:t,token:r.token,updatedAt:r.updatedAt}))}var $n=D(()=>{});function ba(e,t){return e!==503?!1:typeof t=="string"?!0:t?.error==="instance_unavailable"}function Rv(e){if(e)try{return JSON.parse(e)}catch{return e}}function $v(e,t){if(!e)return null;let r=e.trim();if(/^\d+$/.test(r))return Number(r)*1e3;let n=Date.parse(r);return Number.isNaN(n)?null:Math.max(0,n-t)}function Ev(e){let t=/retry\s+after\s+(\d+)\s*s/i.exec(e);return t?Number(t[1])*1e3:null}async function Pv(e,t){let r=$v(e.headers?.get?.("retry-after"),t),n="";try{n=await e.clone().text()}catch{return{maintenance:!1,delayMs:r}}let o=Rv(n),s=ba(e.status,o),i=typeof o?.error=="string"?o.error:void 0;return{maintenance:s,delayMs:r??Ev(n),error:i}}function Av(e){return!!(e==null||typeof e=="string"||typeof ArrayBuffer<"u"&&ArrayBuffer.isView(e)||e instanceof ArrayBuffer||typeof URLSearchParams<"u"&&e instanceof URLSearchParams||typeof Blob<"u"&&e instanceof Blob)}function Xu(e){try{let t=typeof e=="string"?e:e instanceof URL?e.href:e?.url??"";return t?new URL(t).host:"the instance"}catch{return"the instance"}}function ya(e){return`${Math.round(e/1e3)}s`}function Cv(e){let t=e.error?` (${e.error})`:"";process.stderr.write(`turbobase: ${e.host} is unavailable${t} \u2014 waiting ${ya(e.delayMs)} before retrying (${ya(e.remainingMs)} of the retry budget left).
|
|
34
|
+
`)}function Iv(e){let t=e.error?` (${e.error})`:"";process.stderr.write(`turbobase: gave up after ${ya(e.waitedMs)} waiting for ${e.host} to come back${t}; ${e.attempts} ${e.attempts===1?"retry":"retries"} made.
|
|
35
|
+
`)}function Yo(e,t={}){let r=t.budgetMs??6e5,n=t.defaultDelayMs??6e4,o=t.sleep??(u=>new Promise(p=>setTimeout(p,u))),s=t.now??(()=>Date.now()),i=t.onWait??Cv,a=t.onGiveUp??Iv;return async(u,p)=>{let g=s(),x=0;for(;;){let y=await e(u,p);if(y.status!==503||p&&!Av(p.body))return y;let k=r-(s()-g),{maintenance:T,delayMs:$,error:P}=await Pv(y,s());if(!T)return y;if(k<=0)return x>0&&a({waitedMs:s()-g,attempts:x,host:Xu(u),error:P}),y;let C=$??n;C=Math.min(Math.max(C,1e3),12e4),C=Math.min(C,k),x+=1,i({attempt:x,delayMs:C,remainingMs:k,host:Xu(u),error:P}),await o(C)}}}var wa=D(()=>{});function Zu(e){if(typeof e=="string")return e.trim();if(!e||typeof e!="object")return"";let t=e;if(typeof t.message=="string"&&t.message.trim())return t.message.trim();let r=typeof t.error=="string"?t.error.trim():"",n=typeof t.reason=="string"?t.reason.trim():"";return n?r?`${r}: ${n}`:n:r}function Ov(e){let t=e.trimStart().slice(0,200).toLowerCase();return t.startsWith("<!doctype")||t.startsWith("<html")||t.startsWith("<")}function Lv(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.error=="string"&&typeof t.reason=="string"&&t.reason.trim()!==""}function Qu(e){let t=Zu(e);return typeof e=="string"&&Ov(t)?Nv:Lv(e)?t.slice(0,Dv):t.slice(0,jv)}function ep(e,t){return ba(e,t)}function tp(e){return e instanceof Y&&ep(e.status,e.body)}function Mv(){let e=(process.env.TURBOBASE_DEBUG??"").trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"}function rp(e){return e.replace(/\/+$/,"")}function va(e=process.env){let t=(e[Mr]??"").trim(),r=(e[Xo]??"").trim();return!t||!r?null:{registryUrl:t,token:r}}function _a(e){let t;try{t=new URL(e)}catch{return`${Mr} is not a valid URL: ${e}`}if(t.protocol==="https:")return null;let r=t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]";return t.protocol==="http:"&&r?null:`${Mr} must be https:// (got ${t.protocol}//${t.hostname}). The registry bearer is sent as an Authorization header and must not cross a plaintext connection.`}var Y,Nv,jv,Dv,Uv,z,Mr,Xo,En,bt=D(()=>{wa();Y=class extends Error{constructor(r,n,o){super(r);this.status=n;this.body=o;this.name="ApiError"}status;body};Nv="the request did not reach the instance \u2014 a proxy or edge answered with an HTML page, so the server gave no detail";jv=200,Dv=2e3;Uv="this instance is temporarily unavailable \u2014 it is upgrading or restarting. Retry shortly.";z=class{baseUrl;token;fetchImpl;constructor(t){this.baseUrl=rp(t.baseUrl),this.token=t.token;let r=t.fetchImpl??fetch;if(typeof r!="function")throw new Error("ExtensionsApi: no fetch implementation available");this.fetchImpl=t.retry===!1?r:Yo(r,t.retry??{})}async request(t,r,n,o){let s=await this.fetchImpl(`${this.baseUrl}${r}`,{method:t,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(Mv()){let u=Zu(a);throw new Y(`${t} ${r} \u2192 ${s.status}${u?`: ${u}`:""}`,s.status,a)}if(ep(s.status,a))throw new Y(Uv,s.status,a);let l=Qu(a);throw new Y(`${t} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}deploy(t){return this.request("POST","/v1/extensions",{id:t.id,recordType:t.recordType,event:t.event,source:t.source,sourceCode:t.sourceCode,extensionKind:t.extensionKind??"hook",provenance:t.provenance??"cli",...t.connectionId?{connectionId:t.connectionId}:{}})}async list(t){let r=t?`?kind=${encodeURIComponent(t)}`:"";return(await this.request("GET",`/v1/extensions${r}`)).extensions??[]}test(t){return this.request("POST","/v1/extensions/test",{id:t.id,recordType:t.recordType,event:t.event,source:t.source,sourceCode:t.sourceCode,extensionKind:t.extensionKind??"hook",provenance:t.provenance??"cli"})}authorConduit(t){return this.request("POST","/v1/extensions/author-conduit",{intent:t.intent,from:t.from,to:t.to,...t.intentId?{intentId:t.intentId}:{},...t.columns?.length?{columns:t.columns}:{}})}async proposals(t={}){let r=new URLSearchParams;t.status?.length&&r.set("status",t.status.join(",")),t.provenance?.length&&r.set("provenance",t.provenance.join(",")),t.recordType&&r.set("recordType",t.recordType),t.source&&r.set("source",t.source),t.limit&&t.limit>0&&r.set("limit",String(Math.floor(t.limit)));let n=r.toString();return(await this.request("GET",`/v1/extensions/proposals${n?`?${n}`:""}`)).proposals??[]}proposalPromote(t){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(t)}/promote`,{})}proposalRetract(t){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(t)}/retract`,{})}proposalReject(t,r){return this.request("POST",`/v1/extensions/proposals/${encodeURIComponent(t)}/reject`,r?{reason:r}:{})}extensionDisable(t){return this.request("POST",`/v1/extensions/${encodeURIComponent(t)}/disable`,{})}extensionEnable(t){return this.request("POST",`/v1/extensions/${encodeURIComponent(t)}/enable`,{})}extensionRemove(t){return this.request("POST",`/v1/extensions/${encodeURIComponent(t)}/remove`,{})}async logs(t,r){let n=r&&r>0?`?limit=${Math.floor(r)}`:"";return(await this.request("GET",`/v1/extensions/${encodeURIComponent(t)}/logs${n}`)).logs??[]}async catalogRecords(){return(await this.request("GET","/v1/catalog/records")).records??[]}async conduitEvents(t,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(t)}/events${o}`)).events??[]}async processes(){return(await this.request("GET","/v1/processes")).processes??[]}async processRuns(t){return(await this.request("GET",`/v1/processes/${encodeURIComponent(t)}/runs`)).runs??[]}async processRun(t){return this.request("GET",`/v1/processes/runs/${encodeURIComponent(t)}`)}async invokeProcess(t,r,n="async"){let o=n==="sync"?"?mode=sync":"";return this.request("POST",`/v1/processes/${encodeURIComponent(t)}${o}`,r)}async settleRow(t,r){return this.request("POST",`/v1/data/${encodeURIComponent(t)}/settle`,{pgRowId:r})}async cancelProcessRun(t){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(t)}/cancel`)}async rollbackProcessRun(t){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(t)}/rollback`)}async resumeProcessRun(t){return this.request("POST",`/v1/processes/runs/${encodeURIComponent(t)}/resume`)}async platformEvents(t={}){let r=new URLSearchParams;t.subsystem&&r.set("subsystem",t.subsystem),t.severity&&r.set("severity",t.severity),t.code&&r.set("code",t.code),t.since&&r.set("since",t.since),t.after&&r.set("after",t.after),t.correlationId&&r.set("correlationId",t.correlationId),t.extension&&r.set("extension",t.extension),t.conduit&&r.set("conduit",t.conduit),t.limit&&t.limit>0&&r.set("limit",String(Math.floor(t.limit)));let n=r.toString()?`?${r.toString()}`:"";return(await this.request("GET",`/v1/events${n}`)).events??[]}async bindings(t={}){let r=new URLSearchParams;t.status&&r.set("status",t.status),t.limit&&t.limit>0&&r.set("limit",String(Math.floor(t.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(t){return this.request("POST","/v1/apps",{slug:t.slug,name:t.name??t.slug,description:t.description})}appsPull(t){return this.request("GET",`/v1/apps/${encodeURIComponent(t)}/pull`)}appPullContext(t){return this.request("GET",`/v1/apps/proposals/${encodeURIComponent(t)}/pull-context`)}appsPush(t,r,n={}){return this.request("POST",`/v1/apps/${encodeURIComponent(t)}/push`,{files:r,...n.note?{note:n.note}:{},...n.meta?{meta:n.meta}:{}},n.proposalId?{"x-proposal-id":n.proposalId}:void 0)}learningsPending(t={}){let r=new URLSearchParams;t.app&&r.set("app",t.app),t.section&&r.set("section",t.section),t.limit!==void 0&&r.set("limit",String(t.limit)),t.group===!1&&r.set("group","false");let n=r.toString();return this.request("GET",`/v1/learnings/pending${n?`?${n}`:""}`)}learningsIngest(t){return this.request("POST","/v1/learnings/ingest",{...t?{app:t}:{}})}rulesPending(t={}){let r=new URLSearchParams;t.app&&r.set("app",t.app),t.limit!==void 0&&r.set("limit",String(t.limit)),t.group===!1&&r.set("group","false"),t.reapply&&r.set("reapply","true");let n=r.toString();return this.request("GET",`/v1/learnings/rules-pending${n?`?${n}`:""}`)}rulesPush(t,r={}){return this.request("POST","/v1/learnings/push-rules",{planToken:t,...r.app?{app:r.app}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{},...r.reapply?{reapply:!0}:{}})}skillsList(t={}){let r=new URLSearchParams;t.status&&r.set("status",t.status);let n=r.toString();return this.request("GET",`/v1/skills${n?`?${n}`:""}`)}appSkillsPush(t,r,n){return this.request("POST",`/v1/apps/${encodeURIComponent(t)}/skills`,{skills:[...r],dryRun:n})}skillsPublish(t){return this.request("POST","/v1/skills/publish",{slugs:[...t]})}skillsUnpublish(t){return this.request("POST","/v1/skills/unpublish",{slugs:[...t]})}skillsRollback(t){return this.request("POST","/v1/skills/rollback",{versionNo:t})}skillsReleases(){return this.request("GET","/v1/skills/releases")}skillsDelete(t){return this.request("DELETE",`/v1/skills/${encodeURIComponent(t)}`)}docsList(t={}){let r=new URLSearchParams;t.status&&r.set("status",t.status);let n=r.toString();return this.request("GET",`/v1/docs${n?`?${n}`:""}`)}docsPublish(t){return this.request("POST","/v1/docs/publish",{slugs:[...t]})}docsUnpublish(t){return this.request("POST","/v1/docs/unpublish",{slugs:[...t]})}docsVersions(){return this.request("GET","/v1/docs/versions")}docsRollback(t){return this.request("POST","/v1/docs/rollback",{versionNo:t})}docsDelete(t){return this.request("DELETE",`/v1/docs/${encodeURIComponent(t)}`)}learningsPushKb(t,r={}){return this.request("POST","/v1/learnings/push-kb",{planToken:t,...r.app?{app:r.app}:{},...r.section?{section:r.section}:{},...r.limit!==void 0?{limit:r.limit}:{},...r.group===!1?{group:!1}:{}})}retryBinding(t){return this.request("POST",`/v1/bindings/${encodeURIComponent(t)}/retry`)}configExport(){return this.request("GET","/v1/config/export")}configPlan(t){return this.request("POST","/v1/config/plan",{bundle:t})}configApply(t,r={}){return this.request("POST","/v1/config/apply",{bundle:t,...r.prune?{prune:!0}:{}})}async tablesList(){return(await this.request("GET","/v1/tables")).tables??[]}tablesPlan(t){return this.request("POST","/v1/tables/plan",t)}appsPlan(t){return this.request("POST","/v1/apps/plan",{writes:t.writes??[],...t.roles!==void 0?{roles:t.roles}:{},labels:t.labels??[],...t.app?{app:t.app}:{}})}tablesApply(t){return this.request("POST","/v1/tables/apply",t)}tablesDrop(t,r){return this.request("DELETE",`/v1/tables/${encodeURIComponent(t)}?confirm=${encodeURIComponent(r)}`)}async guardrailsList(){return(await this.request("GET","/v1/guardrails")).guardrails??[]}async guardrailCreate(t){return(await this.request("POST","/v1/guardrails",t)).guardrail}async guardrailUpdate(t,r){return(await this.request("PATCH",`/v1/guardrails/${encodeURIComponent(t)}`,r)).guardrail}guardrailDelete(t){return this.request("DELETE",`/v1/guardrails/${encodeURIComponent(t)}`)}guardrailTest(t){return this.request("POST","/v1/guardrails/test",t)}guardrailPostureGet(){return this.request("GET","/v1/guardrails/posture")}guardrailPostureSet(t){return this.request("PUT","/v1/guardrails/posture",{mode:t})}async relationshipsList(t){let r=t?`?source=${encodeURIComponent(t)}`:"";return(await this.request("GET",`/v1/relationships${r}`)).relations??[]}relationshipRefresh(t,r){return this.request("PATCH",`/v1/relationships/${encodeURIComponent(t)}`,r)}releaseDeploy(t){return this.request("POST","/v1/releases/deploy",{...t.solutionId?{solutionId:t.solutionId}:{},target:t.target,...t.approvedBy?{approvedBy:t.approvedBy}:{},...t.files?{files:t.files}:{},...t.gitRepo?{gitRepo:t.gitRepo}:{},...t.gitRef?{gitRef:t.gitRef}:{},...t.gitSha?{gitSha:t.gitSha}:{},...t.prUrl?{prUrl:t.prUrl}:{}})}async releaseList(){return(await this.request("GET","/v1/releases")).releases??[]}releaseGet(t){return this.request("GET",`/v1/releases/${encodeURIComponent(t)}`)}releaseFiles(t){return this.request("GET",`/v1/releases/${encodeURIComponent(t)}/files`)}releasePush(t,r){return this.request("POST",`/v1/releases/${encodeURIComponent(t)}/push`,{files:r.files,target:r.target,...r.approvedBy?{approvedBy:r.approvedBy}:{}})}releaseStatus(t){return this.request("GET",`/v1/releases/${encodeURIComponent(t)}/status`)}releaseRollback(t){return this.request("POST",`/v1/releases/${encodeURIComponent(t)}/rollback`)}},Mr="TURBOBASE_REGISTRY_URL",Xo="TURBOBASE_REGISTRY_TOKEN";En=class{registryUrl;token;fetchImpl;constructor(t){this.registryUrl=rp(t.registryUrl),this.token=t.token;let r=t.fetchImpl??fetch;if(typeof r!="function")throw new Error("RegistryApi: no fetch implementation available");this.fetchImpl=r}async request(t,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:t,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=Qu(a);throw new Y(`${t} ${r} \u2192 ${s.status}${l?`: ${l}`:""}`,s.status,a)}return a}async list(){return(await this.request("GET","/extensions")).extensions??[]}fetchBundle(t,r){let n=r?`?version=${encodeURIComponent(r)}`:"";return this.request("GET",`/extensions/${encodeURIComponent(t)}${n}`)}publish(t){return this.request("POST","/extensions",{name:t.name,version:t.version,kind:t.kind,bundle:t.bundle,...t.manifest?{manifest:t.manifest}:{}})}}});import{existsSync as qv,statSync as zv}from"node:fs";import{resolve as Zo,sep as np}from"node:path";function op(e){if(Fv.has(e))return!0;let t=e.replace(/\\/g,"/");return/(^|\/)src\/sync\/(hooks|conduits|processes)(\/index(\.(ts|js|mjs))?)?$/.test(t)}function Vv(e,t,r){let n=Zo(t,r),o=Zo(e);if(n!==o&&!n.startsWith(o+np))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+np)&&qv(i)&&zv(i).isFile())return i;return null}function sp(e){return{name:"extension-self-contained-fence",setup(t){t.onResolve({filter:/.*/},r=>{if(r.kind==="entry-point")return null;if(op(r.path))return{path:r.path,namespace:"extension-sdk"};let n=r.path.startsWith(".")||r.path.startsWith("/");if(n&&e){let s=Vv(e,r.resolveDir,r.path);if(s)return{path:s}}return{errors:[{text:`extension ${n?`imports a sibling/local file ('${r.path}')${e?" that does not resolve inside the extension\u2019s own directory":""}`:r.path.startsWith("node:")||Wv(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.`}]}}),t.onLoad({filter:/.*/,namespace:"extension-sdk"},()=>({contents:Hv,loader:"js"}))}}}function Wv(e){let t=e.startsWith("node:")?e.slice(5):e;return Kv.has(t.split("/")[0])}function ip(e,t){return new Error(`'${e}' 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: ${t instanceof Error?t.message:String(t)})`)}async function ap(){try{return(await import("esbuild")).build}catch(e){throw ip("esbuild",e)}}async function Gv(){try{return(await import("isolated-vm")).default}catch(e){throw ip("isolated-vm",e)}}async function ts(e,t={}){let r=await ap(),n=t.resolveDir?Zo(t.resolveDir):void 0,o;try{o=await r({stdin:{contents:e,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:[sp(n)]})}catch(s){let a=s.errors?.map(l=>l.text).filter(Boolean).join("; ");throw new Qo(a||`extension bundle failed: ${String(s)}`)}return o.outputFiles?.[0]?.text??""}async function Sa(e,t){if(!/(^|\n)\s*(import|export)\s[^;]*?from\s*['"](\.|\/)/.test(e)&&!/\bimport\s*\(\s*['"](\.|\/)/.test(e))return e;let r=await ap(),n=Zo(t),o=sp(n),s={name:"extension-sdk-external",setup(a){a.onResolve({filter:/.*/},l=>l.kind==="entry-point"?null:op(l.path)?{path:l.path,external:!0}:null)}},i;try{i=await r({stdin:{contents:e,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 Qo(u||`extension bundle failed: ${String(a)}`)}return i.outputFiles?.[0]?.text??e}async function Pn(e,t,r={}){let n=r.timeoutMs??es,o=r.memoryLimitMb??Bv,s=r.member??"run",i={patches:[],logs:[]},a=await Gv(),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)}),x=new a.Callback(H=>{i.patches.push(JSON.parse(String(H)))}),y=new a.Callback(H=>{let G=JSON.parse(String(H));i.logs.push(G)}),k=new a.Callback(H=>{i.result=JSON.parse(String(H))}),T=r.query,$=new a.Reference(async H=>{if(!T)throw new Error("ctx.query is not available in this context");return JSON.stringify(await T(String(H)))});await p.set("__tb_reject",g),await p.set("__tb_patch",x),await p.set("__tb_log",y),await p.set("__tb_result",k),await p.set("__tb_query",$),await p.set("__tb_ctx_json",JSON.stringify(Jv(t)));let P=Xv(e,s,r.stepIndex??0,r.stepPath??[r.stepIndex??0],!!r.query),j=await(await l.compileScript(P)).run(u,{timeout:n,promise:!0});return s==="when"?{effects:i,whenResult:!!j}:{effects:i}}finally{l.isDisposed||l.dispose()}}function Jv(e){return{recordType:e.recordType,event:e.event,direction:e.direction,origin:e.origin,source:e.source,payload:e.payload??null,prior:e.prior??null,user:e.user??null,tenantConfig:e.tenantConfig??{},metadata:e.metadata??null,bindings:e.bindings??null,atlasLinks:e.atlasLinks??null,materialized:e.materialized??null,process:e.process??null}}function Yv(e){return`
|
|
36
36
|
"use strict";
|
|
37
37
|
(async () => {
|
|
38
38
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -55,7 +55,7 @@ ${o.join(`
|
|
|
55
55
|
__tb_result(JSON.stringify(out == null ? null : String(out)));
|
|
56
56
|
return undefined;
|
|
57
57
|
})()
|
|
58
|
-
`}function
|
|
58
|
+
`}function Xv(e,t,r,n,o=!1){return t==="build"?Qv(e,n):t==="delete"?e_(e,n):t==="prompt"?Zv(e,n):t==="outstanding"?Yv(e):`
|
|
59
59
|
"use strict";
|
|
60
60
|
(async () => {
|
|
61
61
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -143,7 +143,7 @@ ${o.join(`
|
|
|
143
143
|
${t==="transform"?"__tb_result(JSON.stringify(out == null ? null : out));":t==="idempotencyKey"?"__tb_result(JSON.stringify(out == null ? null : String(out)));":""}
|
|
144
144
|
return ${t==="when"?"out":"undefined"};
|
|
145
145
|
})()
|
|
146
|
-
`}function
|
|
146
|
+
`}function Zv(e,t){let r=JSON.stringify(t.map(n=>Number(n)));return`
|
|
147
147
|
"use strict";
|
|
148
148
|
(async () => {
|
|
149
149
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -188,7 +188,7 @@ ${o.join(`
|
|
|
188
188
|
__tb_result(String(out == null ? '' : out));
|
|
189
189
|
return undefined;
|
|
190
190
|
})()
|
|
191
|
-
`}function
|
|
191
|
+
`}function Qv(e,t){let r=JSON.stringify(t.map(n=>Number(n)));return`
|
|
192
192
|
"use strict";
|
|
193
193
|
(async () => {
|
|
194
194
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -259,7 +259,7 @@ ${o.join(`
|
|
|
259
259
|
__tb_result(JSON.stringify({ declined: out == null, address: address, write: out == null ? null : out }));
|
|
260
260
|
return undefined;
|
|
261
261
|
})()
|
|
262
|
-
`}function
|
|
262
|
+
`}function e_(e,t){let r=JSON.stringify(t.map(n=>Number(n)));return`
|
|
263
263
|
"use strict";
|
|
264
264
|
(async () => {
|
|
265
265
|
const __tb_ctx = JSON.parse(__tb_ctx_json);
|
|
@@ -318,12 +318,12 @@ ${o.join(`
|
|
|
318
318
|
__tb_result(JSON.stringify({ declined: false, address: address }));
|
|
319
319
|
return undefined;
|
|
320
320
|
})()
|
|
321
|
-
`}var es,
|
|
321
|
+
`}var es,Bv,Fv,Hv,Qo,Kv,rs=D(()=>{es=200,Bv=16,Fv=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"]);Hv=`
|
|
322
322
|
export const defineHook = (def) => def;
|
|
323
323
|
export const defineConduit = (def) => def;
|
|
324
324
|
export const defineProcess = (def) => def;
|
|
325
325
|
export default defineHook;
|
|
326
|
-
`;Qo=class extends Error{constructor(t){super(t),this.name="SandboxBundleError"}};
|
|
326
|
+
`;Qo=class extends Error{constructor(t){super(t),this.name="SandboxBundleError"}};Kv=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 ka}from"node:fs";import{join as t_}from"node:path";function r_(e){return{recordType:e.recordType??"unknown",event:e.event??"before_save",direction:e.direction??"standalone",origin:e.origin??"user",source:e.source??null,payload:e.payload??{},prior:e.prior,user:e.user,tenantConfig:e.tenantConfig??{},metadata:e.metadata}}async function n_(e,t,r){let n=t.name??r,o=t.expect??"pass";try{let{effects:s}=await Pn(e,r_(t.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 ns(e,t,r={}){let n=await ts(e,{resolveDir:r.resolveDir}),o=[];for(let s=0;s<t.length;s+=1)o.push(await n_(n,t[s],`sample[${s}]`));return o}async function An(e){let t;try{t=await ka.readdir(e)}catch(n){if(n.code==="ENOENT")return[];throw n}let r=[];for(let n of t.sort()){if(!n.endsWith(".json"))continue;let o=await ka.readFile(t_(e,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 Cn(e){return ka.readFile(e,"utf8")}var xa=D(()=>{rs()});function Ye(e){return e.replace(/[^A-Za-z0-9]+/g,"-").toLowerCase()}function Z_(e){let t=e.recordType;if(!t)throw new Xe("record type is required (e.g. --record=salesOrder)");let r=e.event??"before_save",n=e.template??"require-field",o=e.source,s=o?`
|
|
327
327
|
source: ${JSON.stringify(o)},`:"",i,a;if(n==="blank")i=`
|
|
328
328
|
run: (ctx) => {
|
|
329
329
|
// Validate or mutate ctx.payload here. Reject with ctx.reject({...}); mutate
|
|
@@ -361,7 +361,7 @@ export default defineHook<Record<string, unknown>>({
|
|
|
361
361
|
recordType: ${JSON.stringify(t)},
|
|
362
362
|
event: ${JSON.stringify(r)},${s}${i}
|
|
363
363
|
});
|
|
364
|
-
`;return{relativePath:`hooks/${t}/${r}.${a}.ts`,content:p}}function
|
|
364
|
+
`;return{relativePath:`hooks/${t}/${r}.${a}.ts`,content:p}}function Q_(e){let t=e.recordType;if(!t)throw new Xe("record type is required (e.g. --record=order)");let r=e.source;if(!r)throw new Xe("--source is required (the origin source, e.g. --source=shopify)");let n=e.to;if(!n)throw new Xe("--to is required (the target source, e.g. --to=netsuite)");if(r===n)throw new Xe(`a conduit must bridge two DIFFERENT sources (got --source=${r} --to=${n}); use \`turbobase ext new hook\` for an intra-source transform`);let o=e.toRecordType??t,s=e.event??"after_canonicalize_inbound",i=e.id??`${Ye(r)}2${Ye(n)}:${Ye(t)}`,l=`/**
|
|
365
365
|
* ${e.description??`Bridge ${r} ${t} \u2192 ${n} ${o} (${s}).`}
|
|
366
366
|
*
|
|
367
367
|
* Scaffolded by \`turbobase ext new conduit\`. A conduit is a PURE canonical\u2192canonical
|
|
@@ -404,7 +404,7 @@ export default defineConduit<Record<string, unknown>>({
|
|
|
404
404
|
},
|
|
405
405
|
idempotencyKey: (ctx) => ${JSON.stringify(`${i}:`)} + ctx.externalId,
|
|
406
406
|
});
|
|
407
|
-
`;return{relativePath:`conduits/${Ye(r)}-${Ye(t)}-to-${Ye(n)}-${Ye(o)}.ts`,content:l}}function
|
|
407
|
+
`;return{relativePath:`conduits/${Ye(r)}-${Ye(t)}-to-${Ye(n)}-${Ye(o)}.ts`,content:l}}function eS(e){let t=e.recordType;if(!t)throw new Xe("record type is required (e.g. --record=purchaseOrder)");let r=e.then,n=e.onFailure??"stop";if(n!=="stop"&&n!=="rollback")throw new Xe(`--on-failure must be stop | rollback (got ${n})`);let o=r?`${Ye(t)}-then-${Ye(r)}`:Ye(t),s=e.id??`custom:process:${o}`,i=e.description??(r?`Raise a ${t}, wait for the source, then raise a ${r}.`:`Raise a ${t}.`),a=r?`
|
|
408
408
|
{
|
|
409
409
|
id: ${JSON.stringify(Ye(r))},
|
|
410
410
|
recordType: ${JSON.stringify(r)},
|
|
@@ -457,7 +457,7 @@ export default defineProcess({
|
|
|
457
457
|
],
|
|
458
458
|
onFailure: ${JSON.stringify(n)},
|
|
459
459
|
});
|
|
460
|
-
`;return{relativePath:`processes/${o}.ts`,content:l}}function Ct(e,t){let r=
|
|
460
|
+
`;return{relativePath:`processes/${o}.ts`,content:l}}function Ct(e,t){let r=tS[e];if(!r)throw new Xe(`unknown extension kind '${e}'. Scaffoldable kinds: ${Hp.join(", ")}.`);return r(t)}var Hp,Xe,tS,cs=D(()=>{Hp=["hook","conduit","process"];Xe=class extends Error{};tS={hook:Z_,conduit:Q_,process:eS}});var Ya,Xa=D(()=>{Ya=Object.freeze({instance:!0,platform:!0,share:"inherit"})});function Ex(e){let t=2166136261;for(let r=0;r<e.length;r+=1)t^=e.charCodeAt(r),t=Math.imul(t,16777619)>>>0;return t>>>0}function Px(e){return Tm[Ex(e)%Tm.length]}function Ax(e){let t=e.trim().split(/[\s\-_.]+/).filter(r=>/[a-z0-9]/i.test(r));return t.length===0?e.trim().slice(0,1).toUpperCase()||"\u2022":t.length===1?t[0].slice(0,2).toUpperCase():(t[0][0]+t[1][0]).toUpperCase()}function Rm(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function $m(e,t){let[r,n]=Px(e),o=Rm(Ax(t));return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="${Rm(t)}">
|
|
461
461
|
<defs>
|
|
462
462
|
<linearGradient id="tile" x1="0" y1="0" x2="1" y2="1">
|
|
463
463
|
<stop offset="0" stop-color="${r}"/>
|
|
@@ -467,9 +467,9 @@ export default defineProcess({
|
|
|
467
467
|
<rect width="64" height="64" rx="14" fill="url(#tile)"/>
|
|
468
468
|
<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>
|
|
469
469
|
</svg>
|
|
470
|
-
`}var
|
|
471
|
-
`}function
|
|
472
|
-
`}function
|
|
470
|
+
`}var Tm,Em=D(()=>{Tm=[["#6366f1","#4338ca"],["#0ea5e9","#0369a1"],["#10b981","#047857"],["#f59e0b","#b45309"],["#ef4444","#b91c1c"],["#8b5cf6","#6d28d9"],["#ec4899","#be185d"],["#14b8a6","#0f766e"]]});var Jm={};Su(Jm,{CN_UTIL:()=>Mm,CODE_STANDARDS:()=>vt,CODE_STANDARDS_BASELINE:()=>Nm,CODE_STANDARDS_JSON:()=>Im,COMPONENTS_JSON:()=>Um,KNIP_JSON:()=>Om,MAIN_TSX:()=>zm,OXFMT_CONFIG:()=>Cm,OXLINTRC_JSON:()=>Am,STYLES_CSS:()=>Bm,TSCONFIG:()=>Dm,TURBOBASE_CLIENT:()=>Pm,UI_BADGE:()=>Vm,UI_BUTTON:()=>Fm,UI_CARD:()=>Hm,UI_INPUT:()=>Wm,UI_LABEL:()=>Gm,UI_TABLE:()=>Km,indexHtml:()=>qm,instanceOriginFromEnv:()=>Mx,packageJson:()=>Lm,scaffoldAppFiles:()=>zx,starterApp:()=>Bx,viteConfig:()=>jm});function Ox(e,t){let r=e.trim();if(r.length<=t)return r;let n=r.slice(0,t);return n.replace(/[\s\p{P}\p{S}]+$/u,"")||n}function Nx(e){let t={name:Ox(e.title,Ix)},r=(e.description??"").trim().slice(0,Cx);return r&&(t.description=r),t.icon="favicon.svg",t.learnings={...Ya},JSON.stringify(t,null,2)+`
|
|
471
|
+
`}function Lm(e){return`${JSON.stringify({name:e,private:!0,version:"0.1.0",type:"module",scripts:{dev:"vite",build:"vite build",preview:"vite preview",pretest:Lx,check:`${vt.bin} check`,fix:`${vt.bin} fix`},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",[vt.pkg]:vt.range}},null,2)}
|
|
472
|
+
`}function Ux(e){if(!e)return null;try{let t=new URL(e);return t.protocol!=="http:"&&t.protocol!=="https:"?null:t.origin}catch{return null}}function Mx(e=process.env){let t=(e.TENANT_SLUG??"").trim(),r=(e.TENANT_DOMAIN_ROOT??"").trim();if(!(!t||!r))return`https://${t}.${r}`}function jm(e,t={}){let r=Ux(t.instanceOrigin);return`import { defineConfig } from 'vite';
|
|
473
473
|
import { fileURLToPath, URL } from 'node:url';
|
|
474
474
|
import react from '@vitejs/plugin-react';
|
|
475
475
|
// Tailwind v4 is a Vite PLUGIN, not a PostCSS pass \u2014 there is no
|
|
@@ -488,8 +488,8 @@ import tailwindcss from '@tailwindcss/vite';
|
|
|
488
488
|
// you sign in, and the cookies land on localhost:3000. Override the targets
|
|
489
489
|
// with SUPABASE_URL / TURBOBASE_API_URL without editing this file (Vite reads
|
|
490
490
|
// them at boot; restart the dev server after changing one).
|
|
491
|
-
const TENANT = process.env.SUPABASE_URL || '${r??
|
|
492
|
-
const API = process.env.TURBOBASE_API_URL || '${r??
|
|
491
|
+
const TENANT = process.env.SUPABASE_URL || '${r??jx}'; // /rest + the Realtime WS
|
|
492
|
+
const API = process.env.TURBOBASE_API_URL || '${r??Dx}'; // /v1, /auth, /login, /_app
|
|
493
493
|
|
|
494
494
|
// Where this bundle's assets are requested from. \`turbobase apps deploy\` sets
|
|
495
495
|
// this to /_tb/app-assets/<build-id>/ so the asset URLs name the BUILD, not the
|
|
@@ -527,7 +527,7 @@ export default defineConfig({
|
|
|
527
527
|
},
|
|
528
528
|
build: { outDir: 'dist' },
|
|
529
529
|
});
|
|
530
|
-
`}function
|
|
530
|
+
`}function qm(e){return`<!doctype html>
|
|
531
531
|
<html lang="en">
|
|
532
532
|
<head>
|
|
533
533
|
<meta charset="UTF-8" />
|
|
@@ -540,7 +540,7 @@ export default defineConfig({
|
|
|
540
540
|
<script type="module" src="/src/main.tsx"></script>
|
|
541
541
|
</body>
|
|
542
542
|
</html>
|
|
543
|
-
`}function
|
|
543
|
+
`}function zx(e){return{"package.json":Lm(e.slug),"vite.config.ts":jm(e.slug,{instanceOrigin:e.instanceOrigin}),".gitignore":qx,"tsconfig.json":Dm,".oxlintrc.json":Am,"oxfmt.config.ts":Cm,"code-standards.json":Im,[vt.baseline]:Nm,"knip.json":Om,"index.html":qm(e.title),"public/turbobase.json":Nx(e),"public/favicon.svg":$m(e.slug,e.title),"src/main.tsx":zm,"src/App.tsx":e.appTsx,"src/lib/turbobase.ts":Pm,"src/styles.css":Bm,"components.json":Um,"src/lib/utils.ts":Mm,"src/components/ui/button.tsx":Fm,"src/components/ui/card.tsx":Hm,"src/components/ui/badge.tsx":Vm,"src/components/ui/table.tsx":Km,"src/components/ui/input.tsx":Wm,"src/components/ui/label.tsx":Gm,"README.md":`# ${e.title}
|
|
544
544
|
|
|
545
545
|
\`\`\`sh
|
|
546
546
|
npm install
|
|
@@ -563,7 +563,7 @@ every read comes back "permission denied", which looks like an RLS problem.
|
|
|
563
563
|
|
|
564
564
|
\`CLAUDE.md\` + \`.mcp.json\` wire Claude Code to this instance. \`.mcp.json\` holds a
|
|
565
565
|
live access token and is gitignored \u2014 keep it that way.
|
|
566
|
-
`}}function
|
|
566
|
+
`}}function Bx(e){return`import React from 'react';
|
|
567
567
|
import { Loader2, Trash2 } from 'lucide-react';
|
|
568
568
|
|
|
569
569
|
import { select, write, del } from '@/lib/turbobase';
|
|
@@ -788,7 +788,7 @@ export default function App() {
|
|
|
788
788
|
</main>
|
|
789
789
|
);
|
|
790
790
|
}
|
|
791
|
-
`}var
|
|
791
|
+
`}var Cx,Ix,Pm,Bn,Lx,vt,Am,Cm,Im,Om,Nm,jx,Dx,qx,Dm,Um,Mm,zm,Bm,Fm,Hm,Vm,Km,Wm,Gm,Ym=D(()=>{Em();Xa();Cx=200,Ix=60;Pm=`// Same-origin Turbobase client \u2014 the one file you copy (build-apps/auth).
|
|
792
792
|
// Reads go through PostgREST (RLS-scoped); writes go through POST /v1/data/<recordType>.
|
|
793
793
|
// A cold first paint that fans out many reads should use batch() \u2014 ONE request
|
|
794
794
|
// that multiplexes them, sidestepping the per-request rate limiter.
|
|
@@ -2086,14 +2086,32 @@ export async function rollbackProcessRun(
|
|
|
2086
2086
|
if (!res.ok) throw await writeError(res, 'process run');
|
|
2087
2087
|
return (await res.json()) as { runId: string; state: string; queued: boolean };
|
|
2088
2088
|
}
|
|
2089
|
-
|
|
2090
|
-
|
|
2089
|
+
|
|
2090
|
+
/** Carry on a run that STOPPED waiting on the connected system: the same run picks
|
|
2091
|
+
* up at the step it stopped on, waits again for the answer that was missing, and
|
|
2092
|
+
* runs the rest \u2014 so nothing it already wrote is written again. Offer this instead
|
|
2093
|
+
* of invoking the process a second time, which starts a NEW run and creates the
|
|
2094
|
+
* first records over. Queued \u2014 watch the run until it reads \`committed\` with
|
|
2095
|
+
* \`outstanding: 0\`. Only a run that ended \`committed\` with work outstanding can
|
|
2096
|
+
* be resumed; anything else answers 409 (\`process_run_not_resumable\`, naming the
|
|
2097
|
+
* state), and an \`eachRow\` process answers 409 too \u2014 invoke it again instead. */
|
|
2098
|
+
export async function resumeProcessRun(
|
|
2099
|
+
runId: string,
|
|
2100
|
+
): Promise<{ runId: string; state: string; queued: boolean }> {
|
|
2101
|
+
const res = await req(\`/v1/processes/runs/\${encodeURIComponent(runId)}/resume\`, {
|
|
2102
|
+
method: 'POST',
|
|
2103
|
+
});
|
|
2104
|
+
if (!res.ok) throw await writeError(res, 'process run');
|
|
2105
|
+
return (await res.json()) as { runId: string; state: string; queued: boolean };
|
|
2106
|
+
}
|
|
2107
|
+
`,Bn="src/types.ts",Lx=`turbobase project types -o ${Bn} || node -e "if(require('node:fs').existsSync('${Bn}')){console.error('turbobase: could not refresh ${Bn} (offline or signed out) - testing against the copy on disk, which may be stale.')}else{console.error('turbobase: ${Bn} 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 ${Bn}');process.exit(1)}"`,vt={pkg:"@turbobase/code-standards",range:"^0.1.0",bin:"code-standards",oxlintProfile:"./node_modules/@turbobase/code-standards/oxlint/react.json",oxfmtConfig:"@turbobase/code-standards/oxfmt",ignore:["src/types.ts","src/lib/turbobase.ts","dist/**",".claude/**","node_modules/**"],baseline:"code-standards.baseline.json"},Am=`${JSON.stringify({extends:[vt.oxlintProfile],ignorePatterns:[...vt.ignore]},null,2)}
|
|
2108
|
+
`,Cm=`// The house format, from ${vt.pkg}. Re-exported rather than copied,
|
|
2091
2109
|
// so a new version of the package is the only change a format update needs.
|
|
2092
2110
|
export { default } from '${vt.oxfmtConfig}';
|
|
2093
|
-
`,
|
|
2094
|
-
`,
|
|
2095
|
-
`,
|
|
2096
|
-
`;
|
|
2111
|
+
`,Im=`${JSON.stringify({units:["."],ignore:[...vt.ignore]},null,2)}
|
|
2112
|
+
`,Om=`${JSON.stringify({$schema:"https://unpkg.com/knip@6/schema.json",entry:["{hooks,conduits,processes}/**/*.{ts,js}","oxfmt.config.ts"],ignoreDependencies:["@turbobase/extensions"],ignoreExportsUsedInFile:!0,include:["files","dependencies","unlisted","exports","types","duplicates"]},null,2)}
|
|
2113
|
+
`,Nm=`${JSON.stringify({version:1,findings:{},duplicates:{}},null," ")}
|
|
2114
|
+
`;jx="http://localhost:54331",Dx="http://localhost:4100";qx=`node_modules/
|
|
2097
2115
|
dist/
|
|
2098
2116
|
build/
|
|
2099
2117
|
|
|
@@ -2105,9 +2123,9 @@ build/
|
|
|
2105
2123
|
!.env.example
|
|
2106
2124
|
|
|
2107
2125
|
.DS_Store
|
|
2108
|
-
`,
|
|
2109
|
-
`,
|
|
2110
|
-
`,
|
|
2126
|
+
`,Dm=`${JSON.stringify({compilerOptions:{target:"ES2022",lib:["ES2022","DOM","DOM.Iterable"],module:"ESNext",moduleResolution:"bundler",jsx:"react-jsx",strict:!0,skipLibCheck:!0,noEmit:!0,paths:{"@/*":["./src/*"]}},include:["src"]},null,2)}
|
|
2127
|
+
`,Um=`${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)}
|
|
2128
|
+
`,Mm=`import { clsx, type ClassValue } from 'clsx';
|
|
2111
2129
|
import { twMerge } from 'tailwind-merge';
|
|
2112
2130
|
|
|
2113
2131
|
/**
|
|
@@ -2121,7 +2139,7 @@ import { twMerge } from 'tailwind-merge';
|
|
|
2121
2139
|
export function cn(...inputs: ClassValue[]) {
|
|
2122
2140
|
return twMerge(clsx(inputs));
|
|
2123
2141
|
}
|
|
2124
|
-
`;
|
|
2142
|
+
`;zm=`import React from 'react';
|
|
2125
2143
|
import { createRoot } from 'react-dom/client';
|
|
2126
2144
|
import App from './App';
|
|
2127
2145
|
import './styles.css';
|
|
@@ -2131,7 +2149,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
2131
2149
|
<App />
|
|
2132
2150
|
</React.StrictMode>,
|
|
2133
2151
|
);
|
|
2134
|
-
`,
|
|
2152
|
+
`,Bm=`@import 'tailwindcss';
|
|
2135
2153
|
@import 'tw-animate-css';
|
|
2136
2154
|
|
|
2137
2155
|
/* Inter, self-hosted \u2014 the design system's font.
|
|
@@ -2219,7 +2237,7 @@ createRoot(document.getElementById('root')!).render(
|
|
|
2219
2237
|
transition-duration: 0.01ms !important;
|
|
2220
2238
|
}
|
|
2221
2239
|
}
|
|
2222
|
-
`,
|
|
2240
|
+
`,Fm=`import * as React from 'react';
|
|
2223
2241
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
2224
2242
|
|
|
2225
2243
|
import { cn } from '@/lib/utils';
|
|
@@ -2259,7 +2277,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
|
|
|
2259
2277
|
Button.displayName = 'Button';
|
|
2260
2278
|
|
|
2261
2279
|
export { Button, buttonVariants };
|
|
2262
|
-
`,
|
|
2280
|
+
`,Hm=`import * as React from 'react';
|
|
2263
2281
|
|
|
2264
2282
|
import { cn } from '@/lib/utils';
|
|
2265
2283
|
|
|
@@ -2297,7 +2315,7 @@ const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDi
|
|
|
2297
2315
|
CardContent.displayName = 'CardContent';
|
|
2298
2316
|
|
|
2299
2317
|
export { Card, CardHeader, CardTitle, CardDescription, CardContent };
|
|
2300
|
-
`,
|
|
2318
|
+
`,Vm=`import * as React from 'react';
|
|
2301
2319
|
import { cva, type VariantProps } from 'class-variance-authority';
|
|
2302
2320
|
|
|
2303
2321
|
import { cn } from '@/lib/utils';
|
|
@@ -2332,7 +2350,7 @@ function Badge({ className, variant, ...props }: BadgeProps) {
|
|
|
2332
2350
|
}
|
|
2333
2351
|
|
|
2334
2352
|
export { Badge, badgeVariants };
|
|
2335
|
-
`,
|
|
2353
|
+
`,Km=`import * as React from 'react';
|
|
2336
2354
|
|
|
2337
2355
|
import { cn } from '@/lib/utils';
|
|
2338
2356
|
|
|
@@ -2391,7 +2409,7 @@ const TableCell = React.forwardRef<HTMLTableCellElement, React.TdHTMLAttributes<
|
|
|
2391
2409
|
TableCell.displayName = 'TableCell';
|
|
2392
2410
|
|
|
2393
2411
|
export { Table, TableHeader, TableBody, TableRow, TableHead, TableCell };
|
|
2394
|
-
`,
|
|
2412
|
+
`,Wm=`import * as React from 'react';
|
|
2395
2413
|
|
|
2396
2414
|
import { cn } from '@/lib/utils';
|
|
2397
2415
|
|
|
@@ -2411,7 +2429,7 @@ const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLI
|
|
|
2411
2429
|
Input.displayName = 'Input';
|
|
2412
2430
|
|
|
2413
2431
|
export { Input };
|
|
2414
|
-
`,
|
|
2432
|
+
`,Gm=`import * as React from 'react';
|
|
2415
2433
|
|
|
2416
2434
|
import { cn } from '@/lib/utils';
|
|
2417
2435
|
|
|
@@ -2428,55 +2446,55 @@ const Label = React.forwardRef<HTMLLabelElement, React.LabelHTMLAttributes<HTMLL
|
|
|
2428
2446
|
Label.displayName = 'Label';
|
|
2429
2447
|
|
|
2430
2448
|
export { Label };
|
|
2431
|
-
`});import*as
|
|
2432
|
-
`);if("message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Xm(e){return e.description}function Zm(e){if(It(e))return e._zod?.def?.type==="optional";let t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function Qr(e){if(It(e)){let s=e._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=e._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=e.value;if(n!==void 0)return n}var Fn=D(()=>{});import*as c from"zod/v4";function gf(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function yf(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var cl,Qm,nr,$s,Ae,ef,tf,gj,Fx,Hx,dl,ot,Hn,rf,je,dt,ut,De,Es,nf,ul,of,sf,pl,Vn,V,hl,af,lf,yj,Ps,Vx,As,Kx,Kn,en,cf,Wx,Gx,Jx,Yx,Xx,Zx,ml,Qx,eT,fl,Cs,tT,rT,Is,nT,Wn,Gn,oT,Jn,tn,sT,Yn,Os,Ns,Ls,bj,js,Ds,Us,df,uf,pf,gl,hf,Xn,rn,mf,iT,Ms,aT,qs,lT,yl,cT,zs,dT,uT,pT,hT,mT,fT,gT,yT,bT,wT,Bs,vT,_T,Fs,bl,wl,vl,ST,kT,xT,_l,TT,RT,$T,ET,PT,ff,Hs,AT,Vs,wj,CT,nn,IT,vj,Zn,OT,Sl,NT,LT,jT,DT,UT,MT,qT,Rs,zT,BT,FT,Qn,kl,HT,VT,KT,WT,GT,JT,YT,XT,ZT,QT,eR,tR,rR,nR,oR,sR,iR,aR,on,lR,cR,dR,Ks,uR,pR,hR,xl,mR,_j,Sj,kj,xj,Tj,Rj,F,ll,sn=D(()=>{cl="2025-11-25",Qm=[cl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],nr="io.modelcontextprotocol/related-task",$s="2.0",Ae=c.custom(e=>e!==null&&(typeof e=="object"||typeof e=="function")),ef=c.union([c.string(),c.number().int()]),tf=c.string(),gj=c.looseObject({ttl:c.number().optional(),pollInterval:c.number().optional()}),Fx=c.object({ttl:c.number().optional()}),Hx=c.object({taskId:c.string()}),dl=c.looseObject({progressToken:ef.optional(),[nr]:Hx.optional()}),ot=c.object({_meta:dl.optional()}),Hn=ot.extend({task:Fx.optional()}),rf=e=>Hn.safeParse(e).success,je=c.object({method:c.string(),params:ot.loose().optional()}),dt=c.object({_meta:dl.optional()}),ut=c.object({method:c.string(),params:dt.loose().optional()}),De=c.looseObject({_meta:dl.optional()}),Es=c.union([c.string(),c.number().int()]),nf=c.object({jsonrpc:c.literal($s),id:Es,...je.shape}).strict(),ul=e=>nf.safeParse(e).success,of=c.object({jsonrpc:c.literal($s),...ut.shape}).strict(),sf=e=>of.safeParse(e).success,pl=c.object({jsonrpc:c.literal($s),id:Es,result:De}).strict(),Vn=e=>pl.safeParse(e).success;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(V||(V={}));hl=c.object({jsonrpc:c.literal($s),id:Es.optional(),error:c.object({code:c.number().int(),message:c.string(),data:c.unknown().optional()})}).strict(),af=e=>hl.safeParse(e).success,lf=c.union([nf,of,pl,hl]),yj=c.union([pl,hl]),Ps=De.strict(),Vx=dt.extend({requestId:Es.optional(),reason:c.string().optional()}),As=ut.extend({method:c.literal("notifications/cancelled"),params:Vx}),Kx=c.object({src:c.string(),mimeType:c.string().optional(),sizes:c.array(c.string()).optional(),theme:c.enum(["light","dark"]).optional()}),Kn=c.object({icons:c.array(Kx).optional()}),en=c.object({name:c.string(),title:c.string().optional()}),cf=en.extend({...en.shape,...Kn.shape,version:c.string(),websiteUrl:c.string().optional(),description:c.string().optional()}),Wx=c.intersection(c.object({applyDefaults:c.boolean().optional()}),c.record(c.string(),c.unknown())),Gx=c.preprocess(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,c.intersection(c.object({form:Wx.optional(),url:Ae.optional()}),c.record(c.string(),c.unknown()).optional())),Jx=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()}),Yx=c.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:c.looseObject({tools:c.looseObject({call:Ae.optional()}).optional()}).optional()}),Xx=c.object({experimental:c.record(c.string(),Ae).optional(),sampling:c.object({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:Gx.optional(),roots:c.object({listChanged:c.boolean().optional()}).optional(),tasks:Jx.optional(),extensions:c.record(c.string(),Ae).optional()}),Zx=ot.extend({protocolVersion:c.string(),capabilities:Xx,clientInfo:cf}),ml=je.extend({method:c.literal("initialize"),params:Zx}),Qx=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:Yx.optional(),extensions:c.record(c.string(),Ae).optional()}),eT=De.extend({protocolVersion:c.string(),capabilities:Qx,serverInfo:cf,instructions:c.string().optional()}),fl=ut.extend({method:c.literal("notifications/initialized"),params:dt.optional()}),Cs=je.extend({method:c.literal("ping"),params:ot.optional()}),tT=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}),rT=c.object({...dt.shape,...tT.shape,progressToken:ef}),Is=ut.extend({method:c.literal("notifications/progress"),params:rT}),nT=ot.extend({cursor:tf.optional()}),Wn=je.extend({params:nT.optional()}),Gn=De.extend({nextCursor:tf.optional()}),oT=c.enum(["working","input_required","completed","failed","cancelled"]),Jn=c.object({taskId:c.string(),status:oT,ttl:c.union([c.number(),c.null()]),createdAt:c.string(),lastUpdatedAt:c.string(),pollInterval:c.optional(c.number()),statusMessage:c.optional(c.string())}),tn=De.extend({task:Jn}),sT=dt.merge(Jn),Yn=ut.extend({method:c.literal("notifications/tasks/status"),params:sT}),Os=je.extend({method:c.literal("tasks/get"),params:ot.extend({taskId:c.string()})}),Ns=De.merge(Jn),Ls=je.extend({method:c.literal("tasks/result"),params:ot.extend({taskId:c.string()})}),bj=De.loose(),js=Wn.extend({method:c.literal("tasks/list")}),Ds=Gn.extend({tasks:c.array(Jn)}),Us=je.extend({method:c.literal("tasks/cancel"),params:ot.extend({taskId:c.string()})}),df=De.merge(Jn),uf=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.record(c.string(),c.unknown()).optional()}),pf=uf.extend({text:c.string()}),gl=c.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),hf=uf.extend({blob:gl}),Xn=c.enum(["user","assistant"]),rn=c.object({audience:c.array(Xn).optional(),priority:c.number().min(0).max(1).optional(),lastModified:c.iso.datetime({offset:!0}).optional()}),mf=c.object({...en.shape,...Kn.shape,uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),size:c.optional(c.number()),annotations:rn.optional(),_meta:c.optional(c.looseObject({}))}),iT=c.object({...en.shape,...Kn.shape,uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),annotations:rn.optional(),_meta:c.optional(c.looseObject({}))}),Ms=Wn.extend({method:c.literal("resources/list")}),aT=Gn.extend({resources:c.array(mf)}),qs=Wn.extend({method:c.literal("resources/templates/list")}),lT=Gn.extend({resourceTemplates:c.array(iT)}),yl=ot.extend({uri:c.string()}),cT=yl,zs=je.extend({method:c.literal("resources/read"),params:cT}),dT=De.extend({contents:c.array(c.union([pf,hf]))}),uT=ut.extend({method:c.literal("notifications/resources/list_changed"),params:dt.optional()}),pT=yl,hT=je.extend({method:c.literal("resources/subscribe"),params:pT}),mT=yl,fT=je.extend({method:c.literal("resources/unsubscribe"),params:mT}),gT=dt.extend({uri:c.string()}),yT=ut.extend({method:c.literal("notifications/resources/updated"),params:gT}),bT=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}),wT=c.object({...en.shape,...Kn.shape,description:c.optional(c.string()),arguments:c.optional(c.array(bT)),_meta:c.optional(c.looseObject({}))}),Bs=Wn.extend({method:c.literal("prompts/list")}),vT=Gn.extend({prompts:c.array(wT)}),_T=ot.extend({name:c.string(),arguments:c.record(c.string(),c.string()).optional()}),Fs=je.extend({method:c.literal("prompts/get"),params:_T}),bl=c.object({type:c.literal("text"),text:c.string(),annotations:rn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),wl=c.object({type:c.literal("image"),data:gl,mimeType:c.string(),annotations:rn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),vl=c.object({type:c.literal("audio"),data:gl,mimeType:c.string(),annotations:rn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),ST=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()}),kT=c.object({type:c.literal("resource"),resource:c.union([pf,hf]),annotations:rn.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),xT=mf.extend({type:c.literal("resource_link")}),_l=c.union([bl,wl,vl,xT,kT]),TT=c.object({role:Xn,content:_l}),RT=De.extend({description:c.string().optional(),messages:c.array(TT)}),$T=ut.extend({method:c.literal("notifications/prompts/list_changed"),params:dt.optional()}),ET=c.object({title:c.string().optional(),readOnlyHint:c.boolean().optional(),destructiveHint:c.boolean().optional(),idempotentHint:c.boolean().optional(),openWorldHint:c.boolean().optional()}),PT=c.object({taskSupport:c.enum(["required","optional","forbidden"]).optional()}),ff=c.object({...en.shape,...Kn.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:ET.optional(),execution:PT.optional(),_meta:c.record(c.string(),c.unknown()).optional()}),Hs=Wn.extend({method:c.literal("tools/list")}),AT=Gn.extend({tools:c.array(ff)}),Vs=De.extend({content:c.array(_l).default([]),structuredContent:c.record(c.string(),c.unknown()).optional(),isError:c.boolean().optional()}),wj=Vs.or(De.extend({toolResult:c.unknown()})),CT=Hn.extend({name:c.string(),arguments:c.record(c.string(),c.unknown()).optional()}),nn=je.extend({method:c.literal("tools/call"),params:CT}),IT=ut.extend({method:c.literal("notifications/tools/list_changed"),params:dt.optional()}),vj=c.object({autoRefresh:c.boolean().default(!0),debounceMs:c.number().int().nonnegative().default(300)}),Zn=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),OT=ot.extend({level:Zn}),Sl=je.extend({method:c.literal("logging/setLevel"),params:OT}),NT=dt.extend({level:Zn,logger:c.string().optional(),data:c.unknown()}),LT=ut.extend({method:c.literal("notifications/message"),params:NT}),jT=c.object({name:c.string().optional()}),DT=c.object({hints:c.array(jT).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()}),UT=c.object({mode:c.enum(["auto","required","none"]).optional()}),MT=c.object({type:c.literal("tool_result"),toolUseId:c.string().describe("The unique identifier for the corresponding tool call."),content:c.array(_l).default([]),structuredContent:c.object({}).loose().optional(),isError:c.boolean().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),qT=c.discriminatedUnion("type",[bl,wl,vl]),Rs=c.discriminatedUnion("type",[bl,wl,vl,ST,MT]),zT=c.object({role:Xn,content:c.union([Rs,c.array(Rs)]),_meta:c.record(c.string(),c.unknown()).optional()}),BT=Hn.extend({messages:c.array(zT),modelPreferences:DT.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(ff).optional(),toolChoice:UT.optional()}),FT=je.extend({method:c.literal("sampling/createMessage"),params:BT}),Qn=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:Xn,content:qT}),kl=De.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(c.string())),role:Xn,content:c.union([Rs,c.array(Rs)])}),HT=c.object({type:c.literal("boolean"),title:c.string().optional(),description:c.string().optional(),default:c.boolean().optional()}),VT=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()}),KT=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()}),WT=c.object({type:c.literal("string"),title:c.string().optional(),description:c.string().optional(),enum:c.array(c.string()),default:c.string().optional()}),GT=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()}),JT=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()}),YT=c.union([WT,GT]),XT=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()}),ZT=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()}),QT=c.union([XT,ZT]),eR=c.union([JT,YT,QT]),tR=c.union([eR,HT,VT,KT]),rR=Hn.extend({mode:c.literal("form").optional(),message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),tR),required:c.array(c.string()).optional()})}),nR=Hn.extend({mode:c.literal("url"),message:c.string(),elicitationId:c.string(),url:c.string().url()}),oR=c.union([rR,nR]),sR=je.extend({method:c.literal("elicitation/create"),params:oR}),iR=dt.extend({elicitationId:c.string()}),aR=ut.extend({method:c.literal("notifications/elicitation/complete"),params:iR}),on=De.extend({action:c.enum(["accept","decline","cancel"]),content:c.preprocess(e=>e===null?void 0:e,c.record(c.string(),c.union([c.string(),c.number(),c.boolean(),c.array(c.string())])).optional())}),lR=c.object({type:c.literal("ref/resource"),uri:c.string()}),cR=c.object({type:c.literal("ref/prompt"),name:c.string()}),dR=ot.extend({ref:c.union([cR,lR]),argument:c.object({name:c.string(),value:c.string()}),context:c.object({arguments:c.record(c.string(),c.string()).optional()}).optional()}),Ks=je.extend({method:c.literal("completion/complete"),params:dR});uR=De.extend({completion:c.looseObject({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())})}),pR=c.object({uri:c.string().startsWith("file://"),name:c.string().optional(),_meta:c.record(c.string(),c.unknown()).optional()}),hR=je.extend({method:c.literal("roots/list"),params:ot.optional()}),xl=De.extend({roots:c.array(pR)}),mR=ut.extend({method:c.literal("notifications/roots/list_changed"),params:dt.optional()}),_j=c.union([Cs,ml,Ks,Sl,Fs,Bs,Ms,qs,zs,hT,fT,nn,Hs,Os,Ls,js,Us]),Sj=c.union([As,Is,fl,mR,Yn]),kj=c.union([Ps,Qn,kl,on,xl,Ns,Ds,tn]),xj=c.union([Cs,FT,sR,hR,Os,Ls,js,Us]),Tj=c.union([As,Is,LT,yT,uT,IT,$T,Yn,aR]),Rj=c.union([Ps,eT,uR,RT,vT,aT,lT,dT,Vs,AT,Ns,Ds,tn]),F=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===V.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new ll(o.elicitations,r)}return new e(t,r,n)}},ll=class extends F{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(V.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}});function or(e){return e==="completed"||e==="failed"||e==="cancelled"}var bf=D(()=>{});var vf,wf,_f,Ws=D(()=>{vf=Symbol("Let zodToJsonSchema decide on which parser to use"),wf={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"},_f=e=>typeof e=="string"?{...wf,name:e}:{...wf,...e}});var Sf,Tl=D(()=>{Ws();Sf=e=>{let t=_f(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}}});function Rl(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ce(e,t,r,n,o){e[t]=r,Rl(e,t,n,o)}var sr=D(()=>{});var Gs,Js=D(()=>{Gs=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")}});function xe(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Gs(t,e.currentPath):t.join("/")}}var pt=D(()=>{Js()});import{ZodFirstPartyTypeKind as fR}from"zod/v3";function kf(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==fR.ZodAny&&(r.items=Z(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ce(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ce(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ce(r,"minItems",e.exactLength.value,e.exactLength.message,t),ce(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}var $l=D(()=>{sr();Pe()});function xf(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,t):ce(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,t):ce(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,t));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,t);break}return r}var El=D(()=>{sr()});function Tf(){return{type:"boolean"}}var Pl=D(()=>{});function Ys(e,t){return Z(e.type._def,t)}var Xs=D(()=>{Pe()});var Rf,Al=D(()=>{Pe();Rf=(e,t)=>Z(e.innerType._def,t)});function Cl(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Cl(e,t,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 gR(e,t)}}var gR,Il=D(()=>{sr();gR=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":ce(r,"minimum",n.value,n.message,t);break;case"max":ce(r,"maximum",n.value,n.message,t);break}return r}});function $f(e,t){return{...Z(e.innerType._def,t),default:e.defaultValue()}}var Ol=D(()=>{Pe()});function Ef(e,t){return t.effectStrategy==="input"?Z(e.schema._def,t):xe(t)}var Nl=D(()=>{Pe();pt()});function Pf(e){return{type:"string",enum:Array.from(e.values)}}var Ll=D(()=>{});function Af(e,t){let r=[Z(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Z(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(yR(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 yR,jl=D(()=>{Pe();yR=e=>"type"in e&&e.type==="string"?!1:"allOf"in e});function Cf(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var Dl=D(()=>{});function Zs(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":St(r,"email",n.message,t);break;case"format:idn-email":St(r,"idn-email",n.message,t);break;case"pattern:zod":Ke(r,_t.email,n.message,t);break}break;case"url":St(r,"uri",n.message,t);break;case"uuid":St(r,"uuid",n.message,t);break;case"regex":Ke(r,n.regex,n.message,t);break;case"cuid":Ke(r,_t.cuid,n.message,t);break;case"cuid2":Ke(r,_t.cuid2,n.message,t);break;case"startsWith":Ke(r,RegExp(`^${Ml(n.value,t)}`),n.message,t);break;case"endsWith":Ke(r,RegExp(`${Ml(n.value,t)}$`),n.message,t);break;case"datetime":St(r,"date-time",n.message,t);break;case"date":St(r,"date",n.message,t);break;case"time":St(r,"time",n.message,t);break;case"duration":St(r,"duration",n.message,t);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Ke(r,RegExp(Ml(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&St(r,"ipv4",n.message,t),n.version!=="v4"&&St(r,"ipv6",n.message,t);break}case"base64url":Ke(r,_t.base64url,n.message,t);break;case"jwt":Ke(r,_t.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ke(r,_t.ipv4Cidr,n.message,t),n.version!=="v4"&&Ke(r,_t.ipv6Cidr,n.message,t);break}case"emoji":Ke(r,_t.emoji(),n.message,t);break;case"ulid":{Ke(r,_t.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{St(r,"binary",n.message,t);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Ke(r,_t.base64,n.message,t);break}}break}case"nanoid":Ke(r,_t.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Ml(e,t){return t.patternStrategy==="escape"?wR(e):e}function wR(e){let t="";for(let r=0;r<e.length;r++)bR.has(e[r])||(t+="\\"),t+=e[r];return t}function St(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ce(e,"format",t,r,n)}function Ke(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:If(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(e,"pattern",If(t,n),r,n)}function If(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.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
|
|
2449
|
+
`});import*as Xm from"zod/v3";import*as _r from"zod/v4-mini";function It(e){return!!e._zod}function Sr(e){let t=Object.values(e);if(t.length===0)return _r.object({});let r=t.every(It),n=t.every(o=>!It(o));if(r)return _r.object(e);if(n)return Xm.object(e);throw new Error("Mixed Zod versions detected in object shape.")}function tr(e,t){return It(e)?_r.safeParse(e,t):e.safeParse(t)}async function xs(e,t){return It(e)?await _r.safeParseAsync(e,t):await e.safeParseAsync(t)}function rr(e){if(!e)return;let t;if(It(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}function Xr(e){if(e){if(typeof e=="object"){let t=e,r=e;if(!t._def&&!r._zod){let n=Object.values(e);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 Sr(e)}}if(It(e)){let r=e._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function Fx(e){return e.length===0?"object root":e.reduce((t,r,n)=>n===0?String(r):typeof r=="number"?`${t}[${r}]`:`${t}.${r}`,"")}function Ts(e){if(e&&typeof e=="object"){if("issues"in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(t=>t.path?.length?`${t.message} at ${Fx(t.path)}`:t.message).join(`
|
|
2450
|
+
`);if("message"in e&&typeof e.message=="string")return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function Zm(e){return e.description}function Qm(e){if(It(e))return e._zod?.def?.type==="optional";let t=e;return typeof e.isOptional=="function"?e.isOptional():t._def?.typeName==="ZodOptional"}function Zr(e){if(It(e)){let s=e._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=e._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=e.value;if(n!==void 0)return n}var Fn=D(()=>{});import*as d from"zod/v4";function yf(e){if(e.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function bf(e){if(e.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}var dl,ef,nr,$s,Ae,tf,rf,yj,Hx,Vx,ul,ot,Hn,nf,je,dt,ut,De,Es,of,pl,sf,af,hl,Vn,V,ml,lf,cf,bj,Ps,Kx,As,Wx,Kn,Qr,df,Gx,Jx,Yx,Xx,Zx,Qx,fl,eT,tT,gl,Cs,rT,nT,Is,oT,Wn,Gn,sT,Jn,en,iT,Yn,Os,Ns,Ls,wj,js,Ds,Us,uf,pf,hf,yl,mf,Xn,tn,ff,aT,Ms,lT,qs,cT,bl,dT,zs,uT,pT,hT,mT,fT,gT,yT,bT,wT,vT,Bs,_T,ST,Fs,wl,vl,_l,kT,xT,TT,Sl,RT,$T,ET,PT,AT,gf,Hs,CT,Vs,vj,IT,rn,OT,_j,Zn,NT,kl,LT,jT,DT,UT,MT,qT,zT,Rs,BT,FT,HT,Qn,xl,VT,KT,WT,GT,JT,YT,XT,ZT,QT,eR,tR,rR,nR,oR,sR,iR,aR,lR,nn,cR,dR,uR,Ks,pR,hR,mR,Tl,fR,Sj,kj,xj,Tj,Rj,$j,B,cl,on=D(()=>{dl="2025-11-25",ef=[dl,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],nr="io.modelcontextprotocol/related-task",$s="2.0",Ae=d.custom(e=>e!==null&&(typeof e=="object"||typeof e=="function")),tf=d.union([d.string(),d.number().int()]),rf=d.string(),yj=d.looseObject({ttl:d.number().optional(),pollInterval:d.number().optional()}),Hx=d.object({ttl:d.number().optional()}),Vx=d.object({taskId:d.string()}),ul=d.looseObject({progressToken:tf.optional(),[nr]:Vx.optional()}),ot=d.object({_meta:ul.optional()}),Hn=ot.extend({task:Hx.optional()}),nf=e=>Hn.safeParse(e).success,je=d.object({method:d.string(),params:ot.loose().optional()}),dt=d.object({_meta:ul.optional()}),ut=d.object({method:d.string(),params:dt.loose().optional()}),De=d.looseObject({_meta:ul.optional()}),Es=d.union([d.string(),d.number().int()]),of=d.object({jsonrpc:d.literal($s),id:Es,...je.shape}).strict(),pl=e=>of.safeParse(e).success,sf=d.object({jsonrpc:d.literal($s),...ut.shape}).strict(),af=e=>sf.safeParse(e).success,hl=d.object({jsonrpc:d.literal($s),id:Es,result:De}).strict(),Vn=e=>hl.safeParse(e).success;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(V||(V={}));ml=d.object({jsonrpc:d.literal($s),id:Es.optional(),error:d.object({code:d.number().int(),message:d.string(),data:d.unknown().optional()})}).strict(),lf=e=>ml.safeParse(e).success,cf=d.union([of,sf,hl,ml]),bj=d.union([hl,ml]),Ps=De.strict(),Kx=dt.extend({requestId:Es.optional(),reason:d.string().optional()}),As=ut.extend({method:d.literal("notifications/cancelled"),params:Kx}),Wx=d.object({src:d.string(),mimeType:d.string().optional(),sizes:d.array(d.string()).optional(),theme:d.enum(["light","dark"]).optional()}),Kn=d.object({icons:d.array(Wx).optional()}),Qr=d.object({name:d.string(),title:d.string().optional()}),df=Qr.extend({...Qr.shape,...Kn.shape,version:d.string(),websiteUrl:d.string().optional(),description:d.string().optional()}),Gx=d.intersection(d.object({applyDefaults:d.boolean().optional()}),d.record(d.string(),d.unknown())),Jx=d.preprocess(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,d.intersection(d.object({form:Gx.optional(),url:Ae.optional()}),d.record(d.string(),d.unknown()).optional())),Yx=d.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:d.looseObject({sampling:d.looseObject({createMessage:Ae.optional()}).optional(),elicitation:d.looseObject({create:Ae.optional()}).optional()}).optional()}),Xx=d.looseObject({list:Ae.optional(),cancel:Ae.optional(),requests:d.looseObject({tools:d.looseObject({call:Ae.optional()}).optional()}).optional()}),Zx=d.object({experimental:d.record(d.string(),Ae).optional(),sampling:d.object({context:Ae.optional(),tools:Ae.optional()}).optional(),elicitation:Jx.optional(),roots:d.object({listChanged:d.boolean().optional()}).optional(),tasks:Yx.optional(),extensions:d.record(d.string(),Ae).optional()}),Qx=ot.extend({protocolVersion:d.string(),capabilities:Zx,clientInfo:df}),fl=je.extend({method:d.literal("initialize"),params:Qx}),eT=d.object({experimental:d.record(d.string(),Ae).optional(),logging:Ae.optional(),completions:Ae.optional(),prompts:d.object({listChanged:d.boolean().optional()}).optional(),resources:d.object({subscribe:d.boolean().optional(),listChanged:d.boolean().optional()}).optional(),tools:d.object({listChanged:d.boolean().optional()}).optional(),tasks:Xx.optional(),extensions:d.record(d.string(),Ae).optional()}),tT=De.extend({protocolVersion:d.string(),capabilities:eT,serverInfo:df,instructions:d.string().optional()}),gl=ut.extend({method:d.literal("notifications/initialized"),params:dt.optional()}),Cs=je.extend({method:d.literal("ping"),params:ot.optional()}),rT=d.object({progress:d.number(),total:d.optional(d.number()),message:d.optional(d.string())}),nT=d.object({...dt.shape,...rT.shape,progressToken:tf}),Is=ut.extend({method:d.literal("notifications/progress"),params:nT}),oT=ot.extend({cursor:rf.optional()}),Wn=je.extend({params:oT.optional()}),Gn=De.extend({nextCursor:rf.optional()}),sT=d.enum(["working","input_required","completed","failed","cancelled"]),Jn=d.object({taskId:d.string(),status:sT,ttl:d.union([d.number(),d.null()]),createdAt:d.string(),lastUpdatedAt:d.string(),pollInterval:d.optional(d.number()),statusMessage:d.optional(d.string())}),en=De.extend({task:Jn}),iT=dt.merge(Jn),Yn=ut.extend({method:d.literal("notifications/tasks/status"),params:iT}),Os=je.extend({method:d.literal("tasks/get"),params:ot.extend({taskId:d.string()})}),Ns=De.merge(Jn),Ls=je.extend({method:d.literal("tasks/result"),params:ot.extend({taskId:d.string()})}),wj=De.loose(),js=Wn.extend({method:d.literal("tasks/list")}),Ds=Gn.extend({tasks:d.array(Jn)}),Us=je.extend({method:d.literal("tasks/cancel"),params:ot.extend({taskId:d.string()})}),uf=De.merge(Jn),pf=d.object({uri:d.string(),mimeType:d.optional(d.string()),_meta:d.record(d.string(),d.unknown()).optional()}),hf=pf.extend({text:d.string()}),yl=d.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),mf=pf.extend({blob:yl}),Xn=d.enum(["user","assistant"]),tn=d.object({audience:d.array(Xn).optional(),priority:d.number().min(0).max(1).optional(),lastModified:d.iso.datetime({offset:!0}).optional()}),ff=d.object({...Qr.shape,...Kn.shape,uri:d.string(),description:d.optional(d.string()),mimeType:d.optional(d.string()),size:d.optional(d.number()),annotations:tn.optional(),_meta:d.optional(d.looseObject({}))}),aT=d.object({...Qr.shape,...Kn.shape,uriTemplate:d.string(),description:d.optional(d.string()),mimeType:d.optional(d.string()),annotations:tn.optional(),_meta:d.optional(d.looseObject({}))}),Ms=Wn.extend({method:d.literal("resources/list")}),lT=Gn.extend({resources:d.array(ff)}),qs=Wn.extend({method:d.literal("resources/templates/list")}),cT=Gn.extend({resourceTemplates:d.array(aT)}),bl=ot.extend({uri:d.string()}),dT=bl,zs=je.extend({method:d.literal("resources/read"),params:dT}),uT=De.extend({contents:d.array(d.union([hf,mf]))}),pT=ut.extend({method:d.literal("notifications/resources/list_changed"),params:dt.optional()}),hT=bl,mT=je.extend({method:d.literal("resources/subscribe"),params:hT}),fT=bl,gT=je.extend({method:d.literal("resources/unsubscribe"),params:fT}),yT=dt.extend({uri:d.string()}),bT=ut.extend({method:d.literal("notifications/resources/updated"),params:yT}),wT=d.object({name:d.string(),description:d.optional(d.string()),required:d.optional(d.boolean())}),vT=d.object({...Qr.shape,...Kn.shape,description:d.optional(d.string()),arguments:d.optional(d.array(wT)),_meta:d.optional(d.looseObject({}))}),Bs=Wn.extend({method:d.literal("prompts/list")}),_T=Gn.extend({prompts:d.array(vT)}),ST=ot.extend({name:d.string(),arguments:d.record(d.string(),d.string()).optional()}),Fs=je.extend({method:d.literal("prompts/get"),params:ST}),wl=d.object({type:d.literal("text"),text:d.string(),annotations:tn.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),vl=d.object({type:d.literal("image"),data:yl,mimeType:d.string(),annotations:tn.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),_l=d.object({type:d.literal("audio"),data:yl,mimeType:d.string(),annotations:tn.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),kT=d.object({type:d.literal("tool_use"),name:d.string(),id:d.string(),input:d.record(d.string(),d.unknown()),_meta:d.record(d.string(),d.unknown()).optional()}),xT=d.object({type:d.literal("resource"),resource:d.union([hf,mf]),annotations:tn.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),TT=ff.extend({type:d.literal("resource_link")}),Sl=d.union([wl,vl,_l,TT,xT]),RT=d.object({role:Xn,content:Sl}),$T=De.extend({description:d.string().optional(),messages:d.array(RT)}),ET=ut.extend({method:d.literal("notifications/prompts/list_changed"),params:dt.optional()}),PT=d.object({title:d.string().optional(),readOnlyHint:d.boolean().optional(),destructiveHint:d.boolean().optional(),idempotentHint:d.boolean().optional(),openWorldHint:d.boolean().optional()}),AT=d.object({taskSupport:d.enum(["required","optional","forbidden"]).optional()}),gf=d.object({...Qr.shape,...Kn.shape,description:d.string().optional(),inputSchema:d.object({type:d.literal("object"),properties:d.record(d.string(),Ae).optional(),required:d.array(d.string()).optional()}).catchall(d.unknown()),outputSchema:d.object({type:d.literal("object"),properties:d.record(d.string(),Ae).optional(),required:d.array(d.string()).optional()}).catchall(d.unknown()).optional(),annotations:PT.optional(),execution:AT.optional(),_meta:d.record(d.string(),d.unknown()).optional()}),Hs=Wn.extend({method:d.literal("tools/list")}),CT=Gn.extend({tools:d.array(gf)}),Vs=De.extend({content:d.array(Sl).default([]),structuredContent:d.record(d.string(),d.unknown()).optional(),isError:d.boolean().optional()}),vj=Vs.or(De.extend({toolResult:d.unknown()})),IT=Hn.extend({name:d.string(),arguments:d.record(d.string(),d.unknown()).optional()}),rn=je.extend({method:d.literal("tools/call"),params:IT}),OT=ut.extend({method:d.literal("notifications/tools/list_changed"),params:dt.optional()}),_j=d.object({autoRefresh:d.boolean().default(!0),debounceMs:d.number().int().nonnegative().default(300)}),Zn=d.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),NT=ot.extend({level:Zn}),kl=je.extend({method:d.literal("logging/setLevel"),params:NT}),LT=dt.extend({level:Zn,logger:d.string().optional(),data:d.unknown()}),jT=ut.extend({method:d.literal("notifications/message"),params:LT}),DT=d.object({name:d.string().optional()}),UT=d.object({hints:d.array(DT).optional(),costPriority:d.number().min(0).max(1).optional(),speedPriority:d.number().min(0).max(1).optional(),intelligencePriority:d.number().min(0).max(1).optional()}),MT=d.object({mode:d.enum(["auto","required","none"]).optional()}),qT=d.object({type:d.literal("tool_result"),toolUseId:d.string().describe("The unique identifier for the corresponding tool call."),content:d.array(Sl).default([]),structuredContent:d.object({}).loose().optional(),isError:d.boolean().optional(),_meta:d.record(d.string(),d.unknown()).optional()}),zT=d.discriminatedUnion("type",[wl,vl,_l]),Rs=d.discriminatedUnion("type",[wl,vl,_l,kT,qT]),BT=d.object({role:Xn,content:d.union([Rs,d.array(Rs)]),_meta:d.record(d.string(),d.unknown()).optional()}),FT=Hn.extend({messages:d.array(BT),modelPreferences:UT.optional(),systemPrompt:d.string().optional(),includeContext:d.enum(["none","thisServer","allServers"]).optional(),temperature:d.number().optional(),maxTokens:d.number().int(),stopSequences:d.array(d.string()).optional(),metadata:Ae.optional(),tools:d.array(gf).optional(),toolChoice:MT.optional()}),HT=je.extend({method:d.literal("sampling/createMessage"),params:FT}),Qn=De.extend({model:d.string(),stopReason:d.optional(d.enum(["endTurn","stopSequence","maxTokens"]).or(d.string())),role:Xn,content:zT}),xl=De.extend({model:d.string(),stopReason:d.optional(d.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(d.string())),role:Xn,content:d.union([Rs,d.array(Rs)])}),VT=d.object({type:d.literal("boolean"),title:d.string().optional(),description:d.string().optional(),default:d.boolean().optional()}),KT=d.object({type:d.literal("string"),title:d.string().optional(),description:d.string().optional(),minLength:d.number().optional(),maxLength:d.number().optional(),format:d.enum(["email","uri","date","date-time"]).optional(),default:d.string().optional()}),WT=d.object({type:d.enum(["number","integer"]),title:d.string().optional(),description:d.string().optional(),minimum:d.number().optional(),maximum:d.number().optional(),default:d.number().optional()}),GT=d.object({type:d.literal("string"),title:d.string().optional(),description:d.string().optional(),enum:d.array(d.string()),default:d.string().optional()}),JT=d.object({type:d.literal("string"),title:d.string().optional(),description:d.string().optional(),oneOf:d.array(d.object({const:d.string(),title:d.string()})),default:d.string().optional()}),YT=d.object({type:d.literal("string"),title:d.string().optional(),description:d.string().optional(),enum:d.array(d.string()),enumNames:d.array(d.string()).optional(),default:d.string().optional()}),XT=d.union([GT,JT]),ZT=d.object({type:d.literal("array"),title:d.string().optional(),description:d.string().optional(),minItems:d.number().optional(),maxItems:d.number().optional(),items:d.object({type:d.literal("string"),enum:d.array(d.string())}),default:d.array(d.string()).optional()}),QT=d.object({type:d.literal("array"),title:d.string().optional(),description:d.string().optional(),minItems:d.number().optional(),maxItems:d.number().optional(),items:d.object({anyOf:d.array(d.object({const:d.string(),title:d.string()}))}),default:d.array(d.string()).optional()}),eR=d.union([ZT,QT]),tR=d.union([YT,XT,eR]),rR=d.union([tR,VT,KT,WT]),nR=Hn.extend({mode:d.literal("form").optional(),message:d.string(),requestedSchema:d.object({type:d.literal("object"),properties:d.record(d.string(),rR),required:d.array(d.string()).optional()})}),oR=Hn.extend({mode:d.literal("url"),message:d.string(),elicitationId:d.string(),url:d.string().url()}),sR=d.union([nR,oR]),iR=je.extend({method:d.literal("elicitation/create"),params:sR}),aR=dt.extend({elicitationId:d.string()}),lR=ut.extend({method:d.literal("notifications/elicitation/complete"),params:aR}),nn=De.extend({action:d.enum(["accept","decline","cancel"]),content:d.preprocess(e=>e===null?void 0:e,d.record(d.string(),d.union([d.string(),d.number(),d.boolean(),d.array(d.string())])).optional())}),cR=d.object({type:d.literal("ref/resource"),uri:d.string()}),dR=d.object({type:d.literal("ref/prompt"),name:d.string()}),uR=ot.extend({ref:d.union([dR,cR]),argument:d.object({name:d.string(),value:d.string()}),context:d.object({arguments:d.record(d.string(),d.string()).optional()}).optional()}),Ks=je.extend({method:d.literal("completion/complete"),params:uR});pR=De.extend({completion:d.looseObject({values:d.array(d.string()).max(100),total:d.optional(d.number().int()),hasMore:d.optional(d.boolean())})}),hR=d.object({uri:d.string().startsWith("file://"),name:d.string().optional(),_meta:d.record(d.string(),d.unknown()).optional()}),mR=je.extend({method:d.literal("roots/list"),params:ot.optional()}),Tl=De.extend({roots:d.array(hR)}),fR=ut.extend({method:d.literal("notifications/roots/list_changed"),params:dt.optional()}),Sj=d.union([Cs,fl,Ks,kl,Fs,Bs,Ms,qs,zs,mT,gT,rn,Hs,Os,Ls,js,Us]),kj=d.union([As,Is,gl,fR,Yn]),xj=d.union([Ps,Qn,xl,nn,Tl,Ns,Ds,en]),Tj=d.union([Cs,HT,iR,mR,Os,Ls,js,Us]),Rj=d.union([As,Is,jT,bT,pT,OT,ET,Yn,lR]),$j=d.union([Ps,tT,pR,$T,_T,lT,cT,uT,Vs,CT,Ns,Ds,en]),B=class e extends Error{constructor(t,r,n){super(`MCP error ${t}: ${r}`),this.code=t,this.data=n,this.name="McpError"}static fromError(t,r,n){if(t===V.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new cl(o.elicitations,r)}return new e(t,r,n)}},cl=class extends B{constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(V.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}}});function or(e){return e==="completed"||e==="failed"||e==="cancelled"}var wf=D(()=>{});var _f,vf,Sf,Ws=D(()=>{_f=Symbol("Let zodToJsonSchema decide on which parser to use"),vf={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"},Sf=e=>typeof e=="string"?{...vf,name:e}:{...vf,...e}});var kf,Rl=D(()=>{Ws();kf=e=>{let t=Sf(e),r=t.name!==void 0?[...t.basePath,t.definitionPath,t.name]:t.basePath;return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...t.basePath,t.definitionPath,n],jsonSchema:void 0}]))}}});function $l(e,t,r,n){n?.errorMessages&&r&&(e.errorMessage={...e.errorMessage,[t]:r})}function ce(e,t,r,n,o){e[t]=r,$l(e,t,n,o)}var sr=D(()=>{});var Gs,Js=D(()=>{Gs=(e,t)=>{let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];r++);return[(e.length-r).toString(),...t.slice(r)].join("/")}});function xe(e){if(e.target!=="openAi")return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy==="relative"?Gs(t,e.currentPath):t.join("/")}}var pt=D(()=>{Js()});import{ZodFirstPartyTypeKind as gR}from"zod/v3";function xf(e,t){let r={type:"array"};return e.type?._def&&e.type?._def?.typeName!==gR.ZodAny&&(r.items=Z(e.type._def,{...t,currentPath:[...t.currentPath,"items"]})),e.minLength&&ce(r,"minItems",e.minLength.value,e.minLength.message,t),e.maxLength&&ce(r,"maxItems",e.maxLength.value,e.maxLength.message,t),e.exactLength&&(ce(r,"minItems",e.exactLength.value,e.exactLength.message,t),ce(r,"maxItems",e.exactLength.value,e.exactLength.message,t)),r}var El=D(()=>{sr();Pe()});function Tf(e,t){let r={type:"integer",format:"int64"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"min":t.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,t):ce(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,t):ce(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,t));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,t);break}return r}var Pl=D(()=>{sr()});function Rf(){return{type:"boolean"}}var Al=D(()=>{});function Ys(e,t){return Z(e.type._def,t)}var Xs=D(()=>{Pe()});var $f,Cl=D(()=>{Pe();$f=(e,t)=>Z(e.innerType._def,t)});function Il(e,t,r){let n=r??t.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Il(e,t,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 yR(e,t)}}var yR,Ol=D(()=>{sr();yR=(e,t)=>{let r={type:"integer",format:"unix-time"};if(t.target==="openApi3")return r;for(let n of e.checks)switch(n.kind){case"min":ce(r,"minimum",n.value,n.message,t);break;case"max":ce(r,"maximum",n.value,n.message,t);break}return r}});function Ef(e,t){return{...Z(e.innerType._def,t),default:e.defaultValue()}}var Nl=D(()=>{Pe()});function Pf(e,t){return t.effectStrategy==="input"?Z(e.schema._def,t):xe(t)}var Ll=D(()=>{Pe();pt()});function Af(e){return{type:"string",enum:Array.from(e.values)}}var jl=D(()=>{});function Cf(e,t){let r=[Z(e.left._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),Z(e.right._def,{...t,currentPath:[...t.currentPath,"allOf","1"]})].filter(s=>!!s),n=t.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(bR(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 bR,Dl=D(()=>{Pe();bR=e=>"type"in e&&e.type==="string"?!1:"allOf"in e});function If(e,t){let r=typeof e.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(e.value)?"array":"object"}:t.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[e.value]}:{type:r==="bigint"?"integer":r,const:e.value}}var Ul=D(()=>{});function Zs(e,t){let r={type:"string"};if(e.checks)for(let n of e.checks)switch(n.kind){case"min":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t);break;case"max":ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"email":switch(t.emailStrategy){case"format:email":St(r,"email",n.message,t);break;case"format:idn-email":St(r,"idn-email",n.message,t);break;case"pattern:zod":Ke(r,_t.email,n.message,t);break}break;case"url":St(r,"uri",n.message,t);break;case"uuid":St(r,"uuid",n.message,t);break;case"regex":Ke(r,n.regex,n.message,t);break;case"cuid":Ke(r,_t.cuid,n.message,t);break;case"cuid2":Ke(r,_t.cuid2,n.message,t);break;case"startsWith":Ke(r,RegExp(`^${ql(n.value,t)}`),n.message,t);break;case"endsWith":Ke(r,RegExp(`${ql(n.value,t)}$`),n.message,t);break;case"datetime":St(r,"date-time",n.message,t);break;case"date":St(r,"date",n.message,t);break;case"time":St(r,"time",n.message,t);break;case"duration":St(r,"duration",n.message,t);break;case"length":ce(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,t),ce(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,t);break;case"includes":{Ke(r,RegExp(ql(n.value,t)),n.message,t);break}case"ip":{n.version!=="v6"&&St(r,"ipv4",n.message,t),n.version!=="v4"&&St(r,"ipv6",n.message,t);break}case"base64url":Ke(r,_t.base64url,n.message,t);break;case"jwt":Ke(r,_t.jwt,n.message,t);break;case"cidr":{n.version!=="v6"&&Ke(r,_t.ipv4Cidr,n.message,t),n.version!=="v4"&&Ke(r,_t.ipv6Cidr,n.message,t);break}case"emoji":Ke(r,_t.emoji(),n.message,t);break;case"ulid":{Ke(r,_t.ulid,n.message,t);break}case"base64":{switch(t.base64Strategy){case"format:binary":{St(r,"binary",n.message,t);break}case"contentEncoding:base64":{ce(r,"contentEncoding","base64",n.message,t);break}case"pattern:zod":{Ke(r,_t.base64,n.message,t);break}}break}case"nanoid":Ke(r,_t.nanoid,n.message,t);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ql(e,t){return t.patternStrategy==="escape"?vR(e):e}function vR(e){let t="";for(let r=0;r<e.length;r++)wR.has(e[r])||(t+="\\"),t+=e[r];return t}function St(e,t,r,n){e.format||e.anyOf?.some(o=>o.format)?(e.anyOf||(e.anyOf=[]),e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&n.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ce(e,"format",t,r,n)}function Ke(e,t,r,n){e.pattern||e.allOf?.some(o=>o.pattern)?(e.allOf||(e.allOf=[]),e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&n.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Of(t,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ce(e,"pattern",Of(t,n),r,n)}function Of(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let r={i:e.flags.includes("i"),m:e.flags.includes("m"),s:e.flags.includes("s")},n=r.i?e.source.toLowerCase():e.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
|
|
2433
2451
|
]))`;continue}else if(n[l]==="$"){o+=`($|(?=[\r
|
|
2434
2452
|
]))`;continue}}if(r.s&&n[l]==="."){o+=i?`${n[l]}\r
|
|
2435
2453
|
`:`[${n[l]}\r
|
|
2436
|
-
]`;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 ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}var Ul,_t,bR,Qs=D(()=>{sr();_t={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:()=>(Ul===void 0&&(Ul=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ul),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-_]*$/};bR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as eo}from"zod/v3";function ei(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===eo.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??xe(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===eo.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Zs(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===eo.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===eo.ZodBranded&&e.keyType._def.type._def.typeName===eo.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Ys(e.keyType._def,t);return{...r,propertyNames:o}}}return r}var ti=D(()=>{Pe();Qs();Xs();pt()});function Of(e,t){if(t.mapStrategy==="record")return ei(e,t);let r=Z(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||xe(t),n=Z(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||xe(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var ql=D(()=>{Pe();ti();pt()});function Nf(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[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 zl=D(()=>{});function Lf(e){return e.target==="openAi"?void 0:{not:xe({...e,currentPath:[...e.currentPath,"not"]})}}var Bl=D(()=>{pt()});function jf(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Fl=D(()=>{});function Uf(e,t){if(t.target==="openApi3")return Df(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in to&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=to[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 Df(e,t)}var to,Df,ri=D(()=>{Pe();to={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Df=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Z(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function Mf(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:to[e.innerType._def.typeName],nullable:!0}:{type:[to[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Hl=D(()=>{Pe();ri()});function qf(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",Rl(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,t):ce(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,t):ce(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,t));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,t);break}return r}var Vl=D(()=>{sr()});function zf(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],s=e.shape();for(let a in s){let l=s[a];if(l===void 0||l._def===void 0)continue;let u=_R(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=Z(l._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,u||o.push(a))}o.length&&(n.required=o);let i=vR(e,t);return i!==void 0&&(n.additionalProperties=i),n}function vR(e,t){if(e.catchall._def.typeName!=="ZodNever")return Z(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function _R(e){try{return e.isOptional()}catch{return!0}}var Kl=D(()=>{Pe()});var Bf,Wl=D(()=>{Pe();pt();Bf=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Z(e.innerType._def,t);let r=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:xe(t)},r]}:xe(t)}});var Ff,Gl=D(()=>{Pe();Ff=(e,t)=>{if(t.pipeStrategy==="input")return Z(e.in._def,t);if(t.pipeStrategy==="output")return Z(e.out._def,t);let r=Z(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Z(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Hf(e,t){return Z(e.type._def,t)}var Jl=D(()=>{Pe()});function Vf(e,t){let n={type:"array",uniqueItems:!0,items:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ce(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ce(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}var Yl=D(()=>{sr();Pe()});function Kf(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Z(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Z(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Xl=D(()=>{Pe()});function Wf(e){return{not:xe(e)}}var Zl=D(()=>{pt()});function Gf(e){return xe(e)}var Ql=D(()=>{pt()});var Jf,ec=D(()=>{Pe();Jf=(e,t)=>Z(e.innerType._def,t)});import{ZodFirstPartyTypeKind as le}from"zod/v3";var Yf,tc=D(()=>{pt();$l();El();Pl();Xs();Al();Il();Ol();Nl();Ll();jl();Dl();ql();zl();Bl();Fl();Hl();Vl();Kl();Wl();Gl();Jl();ti();Yl();Qs();Xl();Zl();ri();Ql();ec();Yf=(e,t,r)=>{switch(t){case le.ZodString:return Zs(e,r);case le.ZodNumber:return qf(e,r);case le.ZodObject:return zf(e,r);case le.ZodBigInt:return xf(e,r);case le.ZodBoolean:return Tf();case le.ZodDate:return Cl(e,r);case le.ZodUndefined:return Wf(r);case le.ZodNull:return jf(r);case le.ZodArray:return kf(e,r);case le.ZodUnion:case le.ZodDiscriminatedUnion:return Uf(e,r);case le.ZodIntersection:return Af(e,r);case le.ZodTuple:return Kf(e,r);case le.ZodRecord:return ei(e,r);case le.ZodLiteral:return Cf(e,r);case le.ZodEnum:return Pf(e);case le.ZodNativeEnum:return Nf(e);case le.ZodNullable:return Mf(e,r);case le.ZodOptional:return Bf(e,r);case le.ZodMap:return Of(e,r);case le.ZodSet:return Vf(e,r);case le.ZodLazy:return()=>e.getter()._def;case le.ZodPromise:return Hf(e,r);case le.ZodNaN:case le.ZodNever:return Lf(r);case le.ZodEffects:return Ef(e,r);case le.ZodAny:return xe(r);case le.ZodUnknown:return Gf(r);case le.ZodDefault:return $f(e,r);case le.ZodBranded:return Ys(e,r);case le.ZodReadonly:return Jf(e,r);case le.ZodCatch:return Rf(e,r);case le.ZodPipeline:return Ff(e,r);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(t)}}});function Z(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==vf)return a}if(n&&!r){let a=SR(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let s=Yf(e,e.typeName,t),i=typeof s=="function"?Z(s(),t):s;if(i&&kR(e,t,i),t.postProcess){let a=t.postProcess(i,e,t);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var SR,kR,Pe=D(()=>{Ws();tc();Js();pt();SR=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Gs(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),xe(t)):t.$refStrategy==="seen"?xe(t):void 0}},kR=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r)});var Xf=D(()=>{});var rc,nc=D(()=>{Pe();Tl();pt();rc=(e,t)=>{let r=Sf(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[u,p])=>({...l,[u]:Z(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??xe(r)}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=Z(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??xe(r),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.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 Zf=D(()=>{Ws();Tl();sr();Js();Pe();Xf();pt();$l();El();Pl();Xs();Al();Il();Ol();Nl();Ll();jl();Dl();ql();zl();Bl();Fl();Hl();Vl();Kl();Wl();Gl();Jl();ec();ti();Yl();Qs();Xl();Zl();ri();Ql();tc();nc();nc()});import*as Qf from"zod/v4-mini";function xR(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function oc(e,t){return It(e)?Qf.toJSONSchema(e,{target:xR(t?.target),io:t?.pipeStrategy??"input"}):rc(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function sc(e){let r=rr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Qr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ic(e,t){let r=tr(e,t);if(!r.success)throw r.error;return r.data}var ac=D(()=>{Fn();Zf()});function eg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tg(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];eg(i)&&eg(s)?r[o]={...i,...s}:r[o]=s}return r}var TR,ni,rg=D(()=>{Fn();sn();bf();ac();TR=6e4,ni=class{constructor(t){this._options=t,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(As,r=>{this._oncancel(r)}),this.setNotificationHandler(Is,r=>{this._onprogress(r)}),this.setRequestHandler(Cs,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Os,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new F(V.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ls,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new F(V.InvalidParams,`Task not found: ${s}`);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,x=new F(g.error.code,g.error.message,g.error.data);p(x)}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(V.InvalidParams,`Task not found: ${s}`);if(!or(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(or(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[nr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(js,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(V.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Us,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new F(V.InvalidParams,`Task not found: ${r.params.taskId}`);if(or(o.status))throw new F(V.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,n.sessionId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new F(V.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof F?o:new F(V.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),F.fromError(V.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){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=t;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),Vn(s)||af(s)?this._onresponse(s):ul(s)?this._onrequest(s,i):sf(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let t=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(V.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[nr]?.taskId,i=o?.sessionId,a=this._taskStore,l=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(l=!1,u=(async()=>{if(!await a.getTask(s,i))throw new F(V.InvalidParams,`Task not found: ${s}`);l=!0})()),n===void 0){let k={jsonrpc:"2.0",id:t.id,error:{code:V.MethodNotFound,message:"Method not found"}};if(s&&u){let R={type:"error",message:k,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,R,i),()=>o?.send(k)).catch($=>this._onerror(new Error(`Failed to send an error response: ${$}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:k,timestamp:Date.now()},o?.sessionId).catch(R=>this._onerror(new Error(`Failed to enqueue error response: ${R}`))):o?.send(k).catch(R=>this._onerror(new Error(`Failed to send an error response: ${R}`)));return}let p=new AbortController;this._requestHandlerAbortControllers.set(t.id,p);let g=rf(t.params)?t.params.task:void 0,x=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,y={signal:p.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async k=>{if(p.signal.aborted)return;let R={relatedRequestId:t.id};s&&(R.relatedTask={taskId:s}),await this.notification(k,R)},sendRequest:async(k,R,$)=>{if(p.signal.aborted)throw new F(V.ConnectionClosed,"Request was cancelled");let P={...$,relatedRequestId:t.id};s&&!P.relatedTask&&(P.relatedTask={taskId:s});let C=P.relatedTask?.taskId??s;return C&&x&&await x.updateTaskStatus(C,"input_required"),await this.request(k,R,P)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:x,taskRequestedTtl:g?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&p.signal.aborted)throw new F(V.ConnectionClosed,"Request was cancelled");g&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,y)).then(async k=>{if(p.signal.aborted)return;let R={result:k,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:R,timestamp:Date.now()},o?.sessionId):await o?.send(R)},async k=>{if(p.signal.aborted)return;let R={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(k.code)?k.code:V.InternalError,message:k.message??"Internal error",...k.data!==void 0&&{data:k.data}}};s&&this._taskMessageQueue&&l?await this._enqueueTaskMessage(s,{type:"error",message:R,timestamp:Date.now()},o?.sessionId):await o?.send(R)}).catch(k=>this._onerror(new Error(`Failed to send response: ${k}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===p&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.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(t)}`));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(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Vn(t))n(t);else{let i=new F(t.error.code,t.error.message,t.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(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Vn(t)&&t.result&&typeof t.result=="object"){let i=t.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),Vn(t))o(t);else{let i=F.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(i){yield{type:"error",error:i instanceof F?i:new F(V.InternalError,String(i))}}return}let s;try{let i=await this.request(t,tn,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new F(V.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},or(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(V.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new F(V.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(V.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((u,p)=>{let g=C=>{p(C)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(C){g(C);return}n?.signal?.throwIfAborted();let x=this._requestMessageId++,y={...t,jsonrpc:"2.0",id:x};n?.onprogress&&(this._progressHandlers.set(x,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta||{},progressToken:x}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[nr]:l}});let k=C=>{this._responseHandlers.delete(x),this._progressHandlers.delete(x),this._cleanupTimeout(x),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:x,reason:String(C)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let j=C instanceof F?C:new F(V.RequestTimeout,String(C));p(j)};this._responseHandlers.set(x,C=>{if(!n?.signal?.aborted){if(C instanceof Error)return p(C);try{let j=tr(r,C.result);j.success?u(j.data):p(j.error)}catch(j){p(j)}}}),n?.signal?.addEventListener("abort",()=>{k(n?.signal?.reason)});let R=n?.timeout??TR,$=()=>k(F.fromError(V.RequestTimeout,"Request timed out",{timeout:R}));this._setupTimeout(x,R,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let C=j=>{let H=this._responseHandlers.get(x);H?H(j):this._onerror(new Error(`Response handler missing for side-channeled request ${x}`))};this._requestResolvers.set(x,C),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(j=>{this._cleanupTimeout(x),p(j)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(C=>{this._cleanupTimeout(x),p(C)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Ns,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Ds,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},df,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[nr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[nr]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[nr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=sc(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ic(t,o);return Promise.resolve(r(i,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=sc(t);this._notificationHandlers.set(n,o=>{let s=ic(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,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(t,r,n??this._transport?.sessionId,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&ul(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new F(V.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(t,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new F(V.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new F(V.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new F(V.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=Yn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),or(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(V.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(or(a.status))throw new F(V.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=Yn.parse({method:"notifications/tasks/status",params:l});await this.notification(u),or(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var oo=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 ro=class{};me._CodeOrName=ro;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var kr=class extends ro{constructor(t){if(super(),!me.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};me.Name=kr;var ht=class extends ro{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof kr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=ht;me.nil=new ht("");function ng(e,...t){let r=[e[0]],n=0;for(;n<t.length;)cc(r,t[n]),r.push(e[++n]);return new ht(r)}me._=ng;var lc=new ht("+");function og(e,...t){let r=[no(e[0])],n=0;for(;n<t.length;)r.push(lc),cc(r,t[n]),r.push(lc,no(e[++n]));return RR(r),new ht(r)}me.str=og;function cc(e,t){t instanceof ht?e.push(...t._items):t instanceof kr?e.push(t):e.push(PR(t))}me.addCodeArg=cc;function RR(e){let t=1;for(;t<e.length-1;){if(e[t]===lc){let r=$R(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function $R(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof kr||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof kr))return`"${e}${t.slice(1)}`}function ER(e,t){return t.emptyStr()?e:e.emptyStr()?t:og`${e}${t}`}me.strConcat=ER;function PR(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:no(Array.isArray(e)?e.join(","):e)}function AR(e){return new ht(no(e))}me.stringify=AR;function no(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=no;function CR(e){return typeof e=="string"&&me.IDENTIFIER.test(e)?new ht(`.${e}`):ng`[${e}]`}me.getProperty=CR;function IR(e){if(typeof e=="string"&&me.IDENTIFIER.test(e))return new ht(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}me.getEsmExportName=IR;function OR(e){return new ht(e.toString())}me.regexpCode=OR});var pc=q(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ze=oo(),dc=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},oi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(oi||(Qe.UsedValueState=oi={}));Qe.varKinds={const:new Ze.Name("const"),let:new Ze.Name("let"),var:new Ze.Name("var")};var si=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ze.Name?t:this.name(t)}name(t){return new Ze.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Qe.Scope=si;var ii=class extends Ze.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ze._)`.${new Ze.Name(r)}[${n}]`}};Qe.ValueScopeName=ii;var NR=(0,Ze._)`\n`,uc=class extends si{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?NR:Ze.nil}}get(){return this._scope}name(t){return new ii(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{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(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ze._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let s=Ze.nil;for(let i in t){let a=t[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(u=>{if(l.has(u))return;l.set(u,oi.Started);let p=r(u);if(p){let g=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ze._)`${s}${g} ${u} = ${p};${this.opts._n}`}else if(p=o?.(u))s=(0,Ze._)`${s}${p}${this.opts._n}`;else throw new dc(u);l.set(u,oi.Completed)})}return s}};Qe.ValueScope=uc});var re=q(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.or=oe.and=oe.not=oe.CodeGen=oe.operators=oe.varKinds=oe.ValueScopeName=oe.ValueScope=oe.Scope=oe.Name=oe.regexpCode=oe.stringify=oe.getProperty=oe.nil=oe.strConcat=oe.str=oe._=void 0;var de=oo(),kt=pc(),ir=oo();Object.defineProperty(oe,"_",{enumerable:!0,get:function(){return ir._}});Object.defineProperty(oe,"str",{enumerable:!0,get:function(){return ir.str}});Object.defineProperty(oe,"strConcat",{enumerable:!0,get:function(){return ir.strConcat}});Object.defineProperty(oe,"nil",{enumerable:!0,get:function(){return ir.nil}});Object.defineProperty(oe,"getProperty",{enumerable:!0,get:function(){return ir.getProperty}});Object.defineProperty(oe,"stringify",{enumerable:!0,get:function(){return ir.stringify}});Object.defineProperty(oe,"regexpCode",{enumerable:!0,get:function(){return ir.regexpCode}});Object.defineProperty(oe,"Name",{enumerable:!0,get:function(){return ir.Name}});var di=pc();Object.defineProperty(oe,"Scope",{enumerable:!0,get:function(){return di.Scope}});Object.defineProperty(oe,"ValueScope",{enumerable:!0,get:function(){return di.ValueScope}});Object.defineProperty(oe,"ValueScopeName",{enumerable:!0,get:function(){return di.ValueScopeName}});Object.defineProperty(oe,"varKinds",{enumerable:!0,get:function(){return di.varKinds}});oe.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 Ft=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},hc=class extends Ft{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?kt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=ln(this.rhs,t,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},ai=class extends Ft{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof de.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=ln(this.rhs,t,r),this}get names(){let t=this.lhs instanceof de.Name?{}:{...this.lhs.names};return ci(t,this.rhs)}},mc=class extends ai{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},fc=class extends Ft{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},gc=class extends Ft{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},yc=class extends Ft{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},bc=class extends Ft{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=ln(this.code,t,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},so=class extends Ft{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(t,r)||(LR(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Rr(t,r.names),{})}},Ht=class extends so{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},wc=class extends so{},an=class extends Ht{};an.kind="else";var xr=class e extends Ht{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new an(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(sg(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=ln(this.condition,t,r),this}get names(){let t=super.names;return ci(t,this.condition),this.else&&Rr(t,this.else.names),t}};xr.kind="if";var Tr=class extends Ht{};Tr.kind="for";var vc=class extends Tr{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=ln(this.iteration,t,r),this}get names(){return Rr(super.names,this.iteration.names)}},_c=class extends Tr{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?kt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=ci(super.names,this.from);return ci(t,this.to)}},li=class extends Tr{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=ln(this.iterable,t,r),this}get names(){return Rr(super.names,this.iterable.names)}},io=class extends Ht{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};io.kind="func";var ao=class extends so{render(t){return"return "+super.render(t)}};ao.kind="return";var Sc=class extends Ht{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Rr(t,this.catch.names),this.finally&&Rr(t,this.finally.names),t}},lo=class extends Ht{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};lo.kind="catch";var co=class extends Ht{render(t){return"finally"+super.render(t)}};co.kind="finally";var kc=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2437
|
-
`:""},this._extScope=t,this._scope=new kt.Scope({parent:t}),this._nodes=[new wc]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new hc(t,s,n)),s}const(t,r,n){return this._def(kt.varKinds.const,t,r,n)}let(t,r,n){return this._def(kt.varKinds.let,t,r,n)}var(t,r,n){return this._def(kt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new ai(t,r,n))}add(t,r){return this._leafNode(new mc(t,oe.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==de.nil&&this._leafNode(new bc(t)),this}object(...t){let r=["{"];for(let[n,o]of t)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(t,r,n){if(this._blockNode(new xr(t)),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(t){return this._elseNode(new xr(t))}else(){return this._elseNode(new an)}endIf(){return this._endBlockNode(xr,an)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new vc(t),r)}forRange(t,r,n,o,s=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let i=this._scope.toName(t);return this._for(new _c(s,i,r,n),()=>o(i))}forOf(t,r,n,o=kt.varKinds.const){let s=this._scope.toName(t);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 li("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,de._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new li("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Tr)}label(t){return this._leafNode(new fc(t))}break(t){return this._leafNode(new gc(t))}return(t){let r=new ao;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ao)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Sc;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new lo(s),r(s)}return n&&(this._currNode=o.finally=new co,this.code(n)),this._endBlockNode(lo,co)}throw(t){return this._leafNode(new yc(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){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||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=de.nil,n,o){return this._blockNode(new io(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(io)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof xr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};oe.CodeGen=kc;function Rr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function ci(e,t){return t instanceof de._CodeOrName?Rr(e,t.names):e}function ln(e,t,r){if(e instanceof de.Name)return n(e);if(!o(e))return e;return new de._Code(e._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||t[s.str]!==1?s:(delete t[s.str],i)}function o(s){return s instanceof de._Code&&s._items.some(i=>i instanceof de.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function LR(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function sg(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,de._)`!${xc(e)}`}oe.not=sg;var jR=ig(oe.operators.AND);function DR(...e){return e.reduce(jR)}oe.and=DR;var UR=ig(oe.operators.OR);function MR(...e){return e.reduce(UR)}oe.or=MR;function ig(e){return(t,r)=>t===de.nil?r:r===de.nil?t:(0,de._)`${xc(t)} ${e} ${xc(r)}`}function xc(e){return e instanceof de.Name?e:(0,de._)`(${e})`}});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(),qR=oo();function zR(e){let t={};for(let r of e)t[r]=!0;return t}se.toHash=zR;function BR(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(cg(e,t),!dg(t,e.self.RULES.all))}se.alwaysValidSchema=BR;function cg(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let s in t)o[s]||hg(e,`unknown keyword: "${s}"`)}se.checkUnknownRules=cg;function dg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}se.schemaHasRules=dg;function FR(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}se.schemaHasRulesButRef=FR;function HR({topSchemaRef:e,schemaPath:t},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._)`${e}${t}${(0,we.getProperty)(n)}`}se.schemaRefOrVal=HR;function VR(e){return ug(decodeURIComponent(e))}se.unescapeFragment=VR;function KR(e){return encodeURIComponent(Rc(e))}se.escapeFragment=KR;function Rc(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=Rc;function ug(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=ug;function WR(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}se.eachItem=WR;function ag({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?e(o,s,i):t(o,s,i),i):s instanceof we.Name?(t(o,i,s),s):r(s,i);return a===we.Name&&!(l instanceof we.Name)?n(o,l):l}}se.mergeEvaluated={props:ag({mergeNames:(e,t,r)=>e.if((0,we._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,we._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,we._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,we._)`${r} || {}`),$c(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:pg}),items:ag({mergeNames:(e,t,r)=>e.if((0,we._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,we._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,we._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,we._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function pg(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,we._)`{}`);return t!==void 0&&$c(e,r,t),r}se.evaluatedPropsToName=pg;function $c(e,t,r){Object.keys(r).forEach(n=>e.assign((0,we._)`${t}${(0,we.getProperty)(n)}`,!0))}se.setEvaluated=$c;var lg={};function GR(e,t){return e.scopeValue("func",{ref:t,code:lg[t.code]||(lg[t.code]=new qR._Code(t.code))})}se.useFunc=GR;var Tc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Tc||(se.Type=Tc={}));function JR(e,t,r){if(e instanceof we.Name){let n=t===Tc.Num;return r?n?(0,we._)`"[" + ${e} + "]"`:(0,we._)`"['" + ${e} + "']"`:n?(0,we._)`"/" + ${e}`:(0,we._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(e).toString():"/"+Rc(e)}se.getErrorPath=JR;function hg(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}se.checkStrictMode=hg});var Vt=q(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});var ze=re(),YR={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")};Ec.default=YR});var uo=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(),ui=pe(),We=Vt();Be.keywordError={message:({keyword:e})=>(0,he.str)`must pass "${e}" keyword validation`};Be.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,he.str)`"${e}" keyword must be ${t} ($data)`:(0,he.str)`"${e}" keyword is invalid ($data)`};function XR(e,t=Be.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,l=gg(e,t,r);n??(i||a)?mg(s,l):fg(o,(0,he._)`[${l}]`)}Be.reportError=XR;function ZR(e,t=Be.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=gg(e,t,r);mg(o,a),s||i||fg(n,We.default.vErrors)}Be.reportExtraError=ZR;function QR(e,t){e.assign(We.default.errors,t),e.if((0,he._)`${We.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,he._)`${We.default.vErrors}.length`,t),()=>e.assign(We.default.vErrors,null)))}Be.resetErrorsCount=QR;function e$({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,We.default.errors,a=>{e.const(i,(0,he._)`${We.default.vErrors}[${a}]`),e.if((0,he._)`${i}.instancePath === undefined`,()=>e.assign((0,he._)`${i}.instancePath`,(0,he.strConcat)(We.default.instancePath,s.errorPath))),e.assign((0,he._)`${i}.schemaPath`,(0,he.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,he._)`${i}.schema`,r),e.assign((0,he._)`${i}.data`,n))})}Be.extendErrors=e$;function mg(e,t){let r=e.const("err",t);e.if((0,he._)`${We.default.vErrors} === null`,()=>e.assign(We.default.vErrors,(0,he._)`[${r}]`),(0,he._)`${We.default.vErrors}.push(${r})`),e.code((0,he._)`${We.default.errors}++`)}function fg(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,he._)`new ${e.ValidationError}(${t})`):(r.assign((0,he._)`${n}.errors`,t),r.return(!1))}var $r={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 gg(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,he._)`{}`:t$(e,t,r)}function t$(e,t,r={}){let{gen:n,it:o}=e,s=[r$(o,r),n$(e,r)];return o$(e,t,s),n.object(...s)}function r$({errorPath:e},{instancePath:t}){let r=t?(0,he.str)`${e}${(0,ui.getErrorPath)(t,ui.Type.Str)}`:e;return[We.default.instancePath,(0,he.strConcat)(We.default.instancePath,r)]}function n$({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,he.str)`${t}/${e}`;return r&&(o=(0,he.str)`${o}${(0,ui.getErrorPath)(r,ui.Type.Str)}`),[$r.schemaPath,o]}function o$(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:g}=a;n.push([$r.keyword,o],[$r.params,typeof t=="function"?t(e):t||(0,he._)`{}`]),l.messages&&n.push([$r.message,typeof r=="function"?r(e):r]),l.verbose&&n.push([$r.schema,i],[$r.parentSchema,(0,he._)`${p}${g}`],[We.default.data,s]),u&&n.push([$r.propertyName,u])}});var bg=q(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.boolOrEmptySchema=cn.topBoolOrEmptySchema=void 0;var s$=uo(),i$=re(),a$=Vt(),l$={message:"boolean schema is false"};function c$(e){let{gen:t,schema:r,validateName:n}=e;r===!1?yg(e,!1):typeof r=="object"&&r.$async===!0?t.return(a$.default.data):(t.assign((0,i$._)`${n}.errors`,null),t.return(!0))}cn.topBoolOrEmptySchema=c$;function d$(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),yg(e)):r.var(t,!0)}cn.boolOrEmptySchema=d$;function yg(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,s$.reportError)(o,l$,void 0,t)}});var Pc=q(dn=>{"use strict";Object.defineProperty(dn,"__esModule",{value:!0});dn.getRules=dn.isJSONType=void 0;var u$=["string","number","integer","boolean","null","object","array"],p$=new Set(u$);function h$(e){return typeof e=="string"&&p$.has(e)}dn.isJSONType=h$;function m$(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}dn.getRules=m$});var Ac=q(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.shouldUseRule=ar.shouldUseGroup=ar.schemaHasRulesForType=void 0;function f$({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&wg(e,n)}ar.schemaHasRulesForType=f$;function wg(e,t){return t.rules.some(r=>vg(e,r))}ar.shouldUseGroup=wg;function vg(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}ar.shouldUseRule=vg});var po=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 g$=Pc(),y$=Ac(),b$=uo(),te=re(),_g=pe(),un;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(un||(Fe.DataType=un={}));function w$(e){let t=Sg(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Fe.getSchemaTypes=w$;function Sg(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(g$.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Fe.getJSONTypes=Sg;function v$(e,t){let{gen:r,data:n,opts:o}=e,s=_$(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,y$.schemaHasRulesForType)(e,t[0]));if(i){let a=Ic(t,n,o.strictNumbers,un.Wrong);r.if(a,()=>{s.length?S$(e,t,s):Oc(e)})}return i}Fe.coerceAndCheckDataType=v$;var kg=new Set(["string","number","integer","boolean","null"]);function _$(e,t){return t?e.filter(r=>kg.has(r)||t==="array"&&r==="array"):[]}function S$(e,t,r){let{gen:n,data:o,opts:s}=e,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(Ic(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,te._)`${a} !== undefined`);for(let u of r)(kg.has(u)||u==="array"&&s.coerceTypes==="array")&&l(u);n.else(),Oc(e),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(o,a),k$(e,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
|
|
2454
|
+
]`;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 ${t.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return o}var Ml,_t,wR,Qs=D(()=>{sr();_t={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:()=>(Ml===void 0&&(Ml=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ml),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-_]*$/};wR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});import{ZodFirstPartyTypeKind as eo}from"zod/v3";function ei(e,t){if(t.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),t.target==="openApi3"&&e.keyType?._def.typeName===eo.ZodEnum)return{type:"object",required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,o)=>({...n,[o]:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,"properties",o]})??xe(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]})??t.allowedAdditionalProperties};if(t.target==="openApi3")return r;if(e.keyType?._def.typeName===eo.ZodString&&e.keyType._def.checks?.length){let{type:n,...o}=Zs(e.keyType._def,t);return{...r,propertyNames:o}}else{if(e.keyType?._def.typeName===eo.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===eo.ZodBranded&&e.keyType._def.type._def.typeName===eo.ZodString&&e.keyType._def.type._def.checks?.length){let{type:n,...o}=Ys(e.keyType._def,t);return{...r,propertyNames:o}}}return r}var ti=D(()=>{Pe();Qs();Xs();pt()});function Nf(e,t){if(t.mapStrategy==="record")return ei(e,t);let r=Z(e.keyType._def,{...t,currentPath:[...t.currentPath,"items","items","0"]})||xe(t),n=Z(e.valueType._def,{...t,currentPath:[...t.currentPath,"items","items","1"]})||xe(t);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var zl=D(()=>{Pe();ti();pt()});function Lf(e){let t=e.values,n=Object.keys(e.values).filter(s=>typeof t[t[s]]!="number").map(s=>t[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 Bl=D(()=>{});function jf(e){return e.target==="openAi"?void 0:{not:xe({...e,currentPath:[...e.currentPath,"not"]})}}var Fl=D(()=>{pt()});function Df(e){return e.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Hl=D(()=>{});function Mf(e,t){if(t.target==="openApi3")return Uf(e,t);let r=e.options instanceof Map?Array.from(e.options.values()):e.options;if(r.every(n=>n._def.typeName in to&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=to[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 Uf(e,t)}var to,Uf,ri=D(()=>{Pe();to={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};Uf=(e,t)=>{let r=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((n,o)=>Z(n._def,{...t,currentPath:[...t.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!t.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function qf(e,t){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target==="openApi3"?{type:to[e.innerType._def.typeName],nullable:!0}:{type:[to[e.innerType._def.typeName],"null"]};if(t.target==="openApi3"){let n=Z(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Vl=D(()=>{Pe();ri()});function zf(e,t){let r={type:"number"};if(!e.checks)return r;for(let n of e.checks)switch(n.kind){case"int":r.type="integer",$l(r,"type",n.message,t);break;case"min":t.target==="jsonSchema7"?n.inclusive?ce(r,"minimum",n.value,n.message,t):ce(r,"exclusiveMinimum",n.value,n.message,t):(n.inclusive||(r.exclusiveMinimum=!0),ce(r,"minimum",n.value,n.message,t));break;case"max":t.target==="jsonSchema7"?n.inclusive?ce(r,"maximum",n.value,n.message,t):ce(r,"exclusiveMaximum",n.value,n.message,t):(n.inclusive||(r.exclusiveMaximum=!0),ce(r,"maximum",n.value,n.message,t));break;case"multipleOf":ce(r,"multipleOf",n.value,n.message,t);break}return r}var Kl=D(()=>{sr()});function Bf(e,t){let r=t.target==="openAi",n={type:"object",properties:{}},o=[],s=e.shape();for(let a in s){let l=s[a];if(l===void 0||l._def===void 0)continue;let u=SR(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let p=Z(l._def,{...t,currentPath:[...t.currentPath,"properties",a],propertyPath:[...t.currentPath,"properties",a]});p!==void 0&&(n.properties[a]=p,u||o.push(a))}o.length&&(n.required=o);let i=_R(e,t);return i!==void 0&&(n.additionalProperties=i),n}function _R(e,t){if(e.catchall._def.typeName!=="ZodNever")return Z(e.catchall._def,{...t,currentPath:[...t.currentPath,"additionalProperties"]});switch(e.unknownKeys){case"passthrough":return t.allowedAdditionalProperties;case"strict":return t.rejectedAdditionalProperties;case"strip":return t.removeAdditionalStrategy==="strict"?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function SR(e){try{return e.isOptional()}catch{return!0}}var Wl=D(()=>{Pe()});var Ff,Gl=D(()=>{Pe();pt();Ff=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Z(e.innerType._def,t);let r=Z(e.innerType._def,{...t,currentPath:[...t.currentPath,"anyOf","1"]});return r?{anyOf:[{not:xe(t)},r]}:xe(t)}});var Hf,Jl=D(()=>{Pe();Hf=(e,t)=>{if(t.pipeStrategy==="input")return Z(e.in._def,t);if(t.pipeStrategy==="output")return Z(e.out._def,t);let r=Z(e.in._def,{...t,currentPath:[...t.currentPath,"allOf","0"]}),n=Z(e.out._def,{...t,currentPath:[...t.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function Vf(e,t){return Z(e.type._def,t)}var Yl=D(()=>{Pe()});function Kf(e,t){let n={type:"array",uniqueItems:!0,items:Z(e.valueType._def,{...t,currentPath:[...t.currentPath,"items"]})};return e.minSize&&ce(n,"minItems",e.minSize.value,e.minSize.message,t),e.maxSize&&ce(n,"maxItems",e.maxSize.value,e.maxSize.message,t),n}var Xl=D(()=>{sr();Pe()});function Wf(e,t){return e.rest?{type:"array",minItems:e.items.length,items:e.items.map((r,n)=>Z(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Z(e.rest._def,{...t,currentPath:[...t.currentPath,"additionalItems"]})}:{type:"array",minItems:e.items.length,maxItems:e.items.length,items:e.items.map((r,n)=>Z(r._def,{...t,currentPath:[...t.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Zl=D(()=>{Pe()});function Gf(e){return{not:xe(e)}}var Ql=D(()=>{pt()});function Jf(e){return xe(e)}var ec=D(()=>{pt()});var Yf,tc=D(()=>{Pe();Yf=(e,t)=>Z(e.innerType._def,t)});import{ZodFirstPartyTypeKind as le}from"zod/v3";var Xf,rc=D(()=>{pt();El();Pl();Al();Xs();Cl();Ol();Nl();Ll();jl();Dl();Ul();zl();Bl();Fl();Hl();Vl();Kl();Wl();Gl();Jl();Yl();ti();Xl();Qs();Zl();Ql();ri();ec();tc();Xf=(e,t,r)=>{switch(t){case le.ZodString:return Zs(e,r);case le.ZodNumber:return zf(e,r);case le.ZodObject:return Bf(e,r);case le.ZodBigInt:return Tf(e,r);case le.ZodBoolean:return Rf();case le.ZodDate:return Il(e,r);case le.ZodUndefined:return Gf(r);case le.ZodNull:return Df(r);case le.ZodArray:return xf(e,r);case le.ZodUnion:case le.ZodDiscriminatedUnion:return Mf(e,r);case le.ZodIntersection:return Cf(e,r);case le.ZodTuple:return Wf(e,r);case le.ZodRecord:return ei(e,r);case le.ZodLiteral:return If(e,r);case le.ZodEnum:return Af(e);case le.ZodNativeEnum:return Lf(e);case le.ZodNullable:return qf(e,r);case le.ZodOptional:return Ff(e,r);case le.ZodMap:return Nf(e,r);case le.ZodSet:return Kf(e,r);case le.ZodLazy:return()=>e.getter()._def;case le.ZodPromise:return Vf(e,r);case le.ZodNaN:case le.ZodNever:return jf(r);case le.ZodEffects:return Pf(e,r);case le.ZodAny:return xe(r);case le.ZodUnknown:return Jf(r);case le.ZodDefault:return Ef(e,r);case le.ZodBranded:return Ys(e,r);case le.ZodReadonly:return Yf(e,r);case le.ZodCatch:return $f(e,r);case le.ZodPipeline:return Hf(e,r);case le.ZodFunction:case le.ZodVoid:case le.ZodSymbol:return;default:return(n=>{})(t)}}});function Z(e,t,r=!1){let n=t.seen.get(e);if(t.override){let a=t.override?.(e,t,n,r);if(a!==_f)return a}if(n&&!r){let a=kR(n,t);if(a!==void 0)return a}let o={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,o);let s=Xf(e,e.typeName,t),i=typeof s=="function"?Z(s(),t):s;if(i&&xR(e,t,i),t.postProcess){let a=t.postProcess(i,e,t);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var kR,xR,Pe=D(()=>{Ws();rc();Js();pt();kR=(e,t)=>{switch(t.$refStrategy){case"root":return{$ref:e.path.join("/")};case"relative":return{$ref:Gs(t.currentPath,e.path)};case"none":case"seen":return e.path.length<t.currentPath.length&&e.path.every((r,n)=>t.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${t.currentPath.join("/")}! Defaulting to any`),xe(t)):t.$refStrategy==="seen"?xe(t):void 0}},xR=(e,t,r)=>(e.description&&(r.description=e.description,t.markdownDescription&&(r.markdownDescription=e.description)),r)});var Zf=D(()=>{});var nc,oc=D(()=>{Pe();Rl();pt();nc=(e,t)=>{let r=kf(t),n=typeof t=="object"&&t.definitions?Object.entries(t.definitions).reduce((l,[u,p])=>({...l,[u]:Z(p._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??xe(r)}),{}):void 0,o=typeof t=="string"?t:t?.nameStrategy==="title"?void 0:t?.name,s=Z(e._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??xe(r),i=typeof t=="object"&&t.name!==void 0&&t.nameStrategy==="title"?t.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 Qf=D(()=>{Ws();Rl();sr();Js();Pe();Zf();pt();El();Pl();Al();Xs();Cl();Ol();Nl();Ll();jl();Dl();Ul();zl();Bl();Fl();Hl();Vl();Kl();Wl();Gl();Jl();Yl();tc();ti();Xl();Qs();Zl();Ql();ri();ec();rc();oc();oc()});import*as eg from"zod/v4-mini";function TR(e){return!e||e==="jsonSchema7"||e==="draft-7"?"draft-7":e==="jsonSchema2019-09"||e==="draft-2020-12"?"draft-2020-12":"draft-7"}function sc(e,t){return It(e)?eg.toJSONSchema(e,{target:TR(t?.target),io:t?.pipeStrategy??"input"}):nc(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??"input"})}function ic(e){let r=rr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zr(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function ac(e,t){let r=tr(e,t);if(!r.success)throw r.error;return r.data}var lc=D(()=>{Fn();Qf()});function tg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function rg(e,t){let r={...e};for(let n in t){let o=n,s=t[o];if(s===void 0)continue;let i=r[o];tg(i)&&tg(s)?r[o]={...i,...s}:r[o]=s}return r}var RR,ni,ng=D(()=>{Fn();on();wf();lc();RR=6e4,ni=class{constructor(t){this._options=t,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(As,r=>{this._oncancel(r)}),this.setNotificationHandler(Is,r=>{this._onprogress(r)}),this.setRequestHandler(Cs,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Os,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(V.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ls,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(!await this._taskStore.getTask(s,n.sessionId))throw new B(V.InvalidParams,`Task not found: ${s}`);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,x=new B(g.error.code,g.error.message,g.error.data);p(x)}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(V.InvalidParams,`Task not found: ${s}`);if(!or(i.status))return await this._waitForTaskUpdate(s,n.signal,n.sessionId),await o();if(or(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s,n.sessionId),{...a,_meta:{...a._meta,[nr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(js,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(V.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Us,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new B(V.InvalidParams,`Task not found: ${r.params.taskId}`);if(or(o.status))throw new B(V.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,n.sessionId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new B(V.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof B?o:new B(V.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(t){if(!t.params.requestId)return;this._requestHandlerAbortControllers.get(t.params.requestId)?.abort(t.params.reason)}_setupTimeout(t,r,n,o,s=!1){this._timeoutInfo.set(t,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(t){let r=this._timeoutInfo.get(t);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(t),B.fromError(V.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(t){let r=this._timeoutInfo.get(t);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(t))}async connect(t){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=t;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),Vn(s)||lf(s)?this._onresponse(s):pl(s)?this._onrequest(s,i):af(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let t=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(V.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of t.values())n(r)}_onerror(t){this.onerror?.(t)}_onnotification(t){let r=this._notificationHandlers.get(t.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(t)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(t,r){let n=this._requestHandlers.get(t.method)??this.fallbackRequestHandler,o=this._transport,s=t.params?._meta?.[nr]?.taskId,i=o?.sessionId,a=this._taskStore,l=!0,u;if(s&&a&&this._taskMessageQueue&&i!==void 0&&(l=!1,u=(async()=>{if(!await a.getTask(s,i))throw new B(V.InvalidParams,`Task not found: ${s}`);l=!0})()),n===void 0){let k={jsonrpc:"2.0",id:t.id,error:{code:V.MethodNotFound,message:"Method not found"}};if(s&&u){let T={type:"error",message:k,timestamp:Date.now()};u.then(()=>this._enqueueTaskMessage(s,T,i),()=>o?.send(k)).catch($=>this._onerror(new Error(`Failed to send an error response: ${$}`)))}else s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:k,timestamp:Date.now()},o?.sessionId).catch(T=>this._onerror(new Error(`Failed to enqueue error response: ${T}`))):o?.send(k).catch(T=>this._onerror(new Error(`Failed to send an error response: ${T}`)));return}let p=new AbortController;this._requestHandlerAbortControllers.set(t.id,p);let g=nf(t.params)?t.params.task:void 0,x=this._taskStore?this.requestTaskStore(t,o?.sessionId):void 0,y={signal:p.signal,sessionId:o?.sessionId,_meta:t.params?._meta,sendNotification:async k=>{if(p.signal.aborted)return;let T={relatedRequestId:t.id};s&&(T.relatedTask={taskId:s}),await this.notification(k,T)},sendRequest:async(k,T,$)=>{if(p.signal.aborted)throw new B(V.ConnectionClosed,"Request was cancelled");let P={...$,relatedRequestId:t.id};s&&!P.relatedTask&&(P.relatedTask={taskId:s});let C=P.relatedTask?.taskId??s;return C&&x&&await x.updateTaskStatus(C,"input_required"),await this.request(k,T,P)},authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:s,taskStore:x,taskRequestedTtl:g?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};(u??Promise.resolve()).then(()=>{if(u&&p.signal.aborted)throw new B(V.ConnectionClosed,"Request was cancelled");g&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,y)).then(async k=>{if(p.signal.aborted)return;let T={result:k,jsonrpc:"2.0",id:t.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:T,timestamp:Date.now()},o?.sessionId):await o?.send(T)},async k=>{if(p.signal.aborted)return;let T={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(k.code)?k.code:V.InternalError,message:k.message??"Internal error",...k.data!==void 0&&{data:k.data}}};s&&this._taskMessageQueue&&l?await this._enqueueTaskMessage(s,{type:"error",message:T,timestamp:Date.now()},o?.sessionId):await o?.send(T)}).catch(k=>this._onerror(new Error(`Failed to send response: ${k}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===p&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.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(t)}`));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(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Vn(t))n(t);else{let i=new B(t.error.code,t.error.message,t.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(t)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Vn(t)&&t.result&&typeof t.result=="object"){let i=t.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),Vn(t))o(t);else{let i=B.fromError(t.error.code,t.error.message,t.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(t,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(t,r,n)}}catch(i){yield{type:"error",error:i instanceof B?i:new B(V.InternalError,String(i))}}return}let s;try{let i=await this.request(t,en,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new B(V.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},or(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(V.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new B(V.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(V.InternalError,String(i))}}}request(t,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:l}=n??{};return new Promise((u,p)=>{let g=C=>{p(C)};if(!this._transport){g(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),a&&this.assertTaskCapability(t.method)}catch(C){g(C);return}n?.signal?.throwIfAborted();let x=this._requestMessageId++,y={...t,jsonrpc:"2.0",id:x};n?.onprogress&&(this._progressHandlers.set(x,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta||{},progressToken:x}}),a&&(y.params={...y.params,task:a}),l&&(y.params={...y.params,_meta:{...y.params?._meta||{},[nr]:l}});let k=C=>{this._responseHandlers.delete(x),this._progressHandlers.delete(x),this._cleanupTimeout(x),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:x,reason:String(C)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(H=>this._onerror(new Error(`Failed to send cancellation: ${H}`)));let j=C instanceof B?C:new B(V.RequestTimeout,String(C));p(j)};this._responseHandlers.set(x,C=>{if(!n?.signal?.aborted){if(C instanceof Error)return p(C);try{let j=tr(r,C.result);j.success?u(j.data):p(j.error)}catch(j){p(j)}}}),n?.signal?.addEventListener("abort",()=>{k(n?.signal?.reason)});let T=n?.timeout??RR,$=()=>k(B.fromError(V.RequestTimeout,"Request timed out",{timeout:T}));this._setupTimeout(x,T,n?.maxTotalTimeout,$,n?.resetTimeoutOnProgress??!1);let P=l?.taskId;if(P){let C=j=>{let H=this._responseHandlers.get(x);H?H(j):this._onerror(new Error(`Response handler missing for side-channeled request ${x}`))};this._requestResolvers.set(x,C),this._enqueueTaskMessage(P,{type:"request",message:y,timestamp:Date.now()}).catch(j=>{this._cleanupTimeout(x),p(j)})}else this._transport.send(y,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(C=>{this._cleanupTimeout(x),p(C)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},Ns,r)}async getTaskResult(t,r,n){return this.request({method:"tasks/result",params:t},r,n)}async listTasks(t,r){return this.request({method:"tasks/list",params:t},Ds,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},uf,r)}async notification(t,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(t.method);let n=r?.relatedTask?.taskId;if(n){let a={...t,jsonrpc:"2.0",params:{...t.params,_meta:{...t.params?._meta||{},[nr]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(t.method),!this._transport)return;let a={...t,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[nr]:r.relatedTask}}}),this._transport?.send(a,r).catch(l=>this._onerror(l))});return}let i={...t,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[nr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(t,r){let n=ic(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=ac(t,o);return Promise.resolve(r(i,s))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=ic(t);this._notificationHandlers.set(n,o=>{let s=ac(t,o);return Promise.resolve(r(s))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,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(t,r,n??this._transport?.sessionId,o)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let o of n)if(o.type==="request"&&pl(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new B(V.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${t} cleanup`))}}}async _waitForTaskUpdate(t,r,n){let o=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(t,n);s?.pollInterval&&(o=s.pollInterval)}catch{}return new Promise((s,i)=>{if(r.aborted){i(new B(V.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,o);r.addEventListener("abort",()=>{clearTimeout(a),i(new B(V.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(t,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!t)throw new Error("No request provided");return await n.createTask(o,t.id,{method:t.method,params:t.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new B(V.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=Yn.parse({method:"notifications/tasks/status",params:a});await this.notification(l),or(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(V.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(or(a.status))throw new B(V.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=Yn.parse({method:"notifications/tasks/status",params:l});await this.notification(u),or(l.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var oo=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 ro=class{};me._CodeOrName=ro;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var kr=class extends ro{constructor(t){if(super(),!me.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};me.Name=kr;var ht=class extends ro{constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof kr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=ht;me.nil=new ht("");function og(e,...t){let r=[e[0]],n=0;for(;n<t.length;)dc(r,t[n]),r.push(e[++n]);return new ht(r)}me._=og;var cc=new ht("+");function sg(e,...t){let r=[no(e[0])],n=0;for(;n<t.length;)r.push(cc),dc(r,t[n]),r.push(cc,no(e[++n]));return $R(r),new ht(r)}me.str=sg;function dc(e,t){t instanceof ht?e.push(...t._items):t instanceof kr?e.push(t):e.push(AR(t))}me.addCodeArg=dc;function $R(e){let t=1;for(;t<e.length-1;){if(e[t]===cc){let r=ER(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}function ER(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof kr||e[e.length-1]!=='"'?void 0:typeof t!="string"?`${e.slice(0,-1)}${t}"`:t[0]==='"'?e.slice(0,-1)+t.slice(1):void 0;if(typeof t=="string"&&t[0]==='"'&&!(e instanceof kr))return`"${e}${t.slice(1)}`}function PR(e,t){return t.emptyStr()?e:e.emptyStr()?t:sg`${e}${t}`}me.strConcat=PR;function AR(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:no(Array.isArray(e)?e.join(","):e)}function CR(e){return new ht(no(e))}me.stringify=CR;function no(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=no;function IR(e){return typeof e=="string"&&me.IDENTIFIER.test(e)?new ht(`.${e}`):og`[${e}]`}me.getProperty=IR;function OR(e){if(typeof e=="string"&&me.IDENTIFIER.test(e))return new ht(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}me.getEsmExportName=OR;function NR(e){return new ht(e.toString())}me.regexpCode=NR});var hc=q(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ValueScope=Qe.ValueScopeName=Qe.Scope=Qe.varKinds=Qe.UsedValueState=void 0;var Ze=oo(),uc=class extends Error{constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},oi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(oi||(Qe.UsedValueState=oi={}));Qe.varKinds={const:new Ze.Name("const"),let:new Ze.Name("let"),var:new Ze.Name("var")};var si=class{constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Ze.Name?t:this.name(t)}name(t){return new Ze.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};Qe.Scope=si;var ii=class extends Ze.Name{constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Ze._)`.${new Ze.Name(r)}[${n}]`}};Qe.ValueScopeName=ii;var LR=(0,Ze._)`\n`,pc=class extends si{constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?LR:Ze.nil}}get(){return this._scope}name(t){return new ii(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(t),{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(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Ze._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(t,r,n={},o){let s=Ze.nil;for(let i in t){let a=t[i];if(!a)continue;let l=n[i]=n[i]||new Map;a.forEach(u=>{if(l.has(u))return;l.set(u,oi.Started);let p=r(u);if(p){let g=this.opts.es5?Qe.varKinds.var:Qe.varKinds.const;s=(0,Ze._)`${s}${g} ${u} = ${p};${this.opts._n}`}else if(p=o?.(u))s=(0,Ze._)`${s}${p}${this.opts._n}`;else throw new uc(u);l.set(u,oi.Completed)})}return s}};Qe.ValueScope=pc});var re=q(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.or=oe.and=oe.not=oe.CodeGen=oe.operators=oe.varKinds=oe.ValueScopeName=oe.ValueScope=oe.Scope=oe.Name=oe.regexpCode=oe.stringify=oe.getProperty=oe.nil=oe.strConcat=oe.str=oe._=void 0;var de=oo(),kt=hc(),ir=oo();Object.defineProperty(oe,"_",{enumerable:!0,get:function(){return ir._}});Object.defineProperty(oe,"str",{enumerable:!0,get:function(){return ir.str}});Object.defineProperty(oe,"strConcat",{enumerable:!0,get:function(){return ir.strConcat}});Object.defineProperty(oe,"nil",{enumerable:!0,get:function(){return ir.nil}});Object.defineProperty(oe,"getProperty",{enumerable:!0,get:function(){return ir.getProperty}});Object.defineProperty(oe,"stringify",{enumerable:!0,get:function(){return ir.stringify}});Object.defineProperty(oe,"regexpCode",{enumerable:!0,get:function(){return ir.regexpCode}});Object.defineProperty(oe,"Name",{enumerable:!0,get:function(){return ir.Name}});var di=hc();Object.defineProperty(oe,"Scope",{enumerable:!0,get:function(){return di.Scope}});Object.defineProperty(oe,"ValueScope",{enumerable:!0,get:function(){return di.ValueScope}});Object.defineProperty(oe,"ValueScopeName",{enumerable:!0,get:function(){return di.ValueScopeName}});Object.defineProperty(oe,"varKinds",{enumerable:!0,get:function(){return di.varKinds}});oe.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 Ft=class{optimizeNodes(){return this}optimizeNames(t,r){return this}},mc=class extends Ft{constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?kt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(t,r){if(t[this.name.str])return this.rhs&&(this.rhs=an(this.rhs,t,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},ai=class extends Ft{constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof de.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=an(this.rhs,t,r),this}get names(){let t=this.lhs instanceof de.Name?{}:{...this.lhs.names};return ci(t,this.rhs)}},fc=class extends ai{constructor(t,r,n,o){super(t,n,o),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},gc=class extends Ft{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},yc=class extends Ft{constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},bc=class extends Ft{constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},wc=class extends Ft{constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=an(this.code,t,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},so=class extends Ft{constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(t,r)||(jR(t,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Rr(t,r.names),{})}},Ht=class extends so{render(t){return"{"+t._n+super.render(t)+"}"+t._n}},vc=class extends so{},sn=class extends Ht{};sn.kind="else";var xr=class e extends Ht{constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new sn(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(ig(t),r instanceof e?[r]:r.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(t,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(t,r),!!(super.optimizeNames(t,r)||this.else))return this.condition=an(this.condition,t,r),this}get names(){let t=super.names;return ci(t,this.condition),this.else&&Rr(t,this.else.names),t}};xr.kind="if";var Tr=class extends Ht{};Tr.kind="for";var _c=class extends Tr{constructor(t){super(),this.iteration=t}render(t){return`for(${this.iteration})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iteration=an(this.iteration,t,r),this}get names(){return Rr(super.names,this.iteration.names)}},Sc=class extends Tr{constructor(t,r,n,o){super(),this.varKind=t,this.name=r,this.from=n,this.to=o}render(t){let r=t.es5?kt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(t)}get names(){let t=ci(super.names,this.from);return ci(t,this.to)}},li=class extends Tr{constructor(t,r,n,o){super(),this.loop=t,this.varKind=r,this.name=n,this.iterable=o}render(t){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(t)}optimizeNames(t,r){if(super.optimizeNames(t,r))return this.iterable=an(this.iterable,t,r),this}get names(){return Rr(super.names,this.iterable.names)}},io=class extends Ht{constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};io.kind="func";var ao=class extends so{render(t){return"return "+super.render(t)}};ao.kind="return";var kc=class extends Ht{render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,o;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(o=this.finally)===null||o===void 0||o.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Rr(t,this.catch.names),this.finally&&Rr(t,this.finally.names),t}},lo=class extends Ht{constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};lo.kind="catch";var co=class extends Ht{render(t){return"finally"+super.render(t)}};co.kind="finally";var xc=class{constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
2455
|
+
`:""},this._extScope=t,this._scope=new kt.Scope({parent:t}),this._nodes=[new vc]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new mc(t,s,n)),s}const(t,r,n){return this._def(kt.varKinds.const,t,r,n)}let(t,r,n){return this._def(kt.varKinds.let,t,r,n)}var(t,r,n){return this._def(kt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new ai(t,r,n))}add(t,r){return this._leafNode(new fc(t,oe.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==de.nil&&this._leafNode(new wc(t)),this}object(...t){let r=["{"];for(let[n,o]of t)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(t,r,n){if(this._blockNode(new xr(t)),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(t){return this._elseNode(new xr(t))}else(){return this._elseNode(new sn)}endIf(){return this._endBlockNode(xr,sn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new _c(t),r)}forRange(t,r,n,o,s=this.opts.es5?kt.varKinds.var:kt.varKinds.let){let i=this._scope.toName(t);return this._for(new Sc(s,i,r,n),()=>o(i))}forOf(t,r,n,o=kt.varKinds.const){let s=this._scope.toName(t);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 li("of",o,s,r),()=>n(s))}forIn(t,r,n,o=this.opts.es5?kt.varKinds.var:kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,de._)`Object.keys(${r})`,n);let s=this._scope.toName(t);return this._for(new li("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Tr)}label(t){return this._leafNode(new gc(t))}break(t){return this._leafNode(new yc(t))}return(t){let r=new ao;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ao)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new kc;if(this._blockNode(o),this.code(t),r){let s=this.name("e");this._currNode=o.catch=new lo(s),r(s)}return n&&(this._currNode=o.finally=new co,this.code(n)),this._endBlockNode(lo,co)}throw(t){return this._leafNode(new bc(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){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||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=de.nil,n,o){return this._blockNode(new io(t,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(io)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof xr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};oe.CodeGen=xc;function Rr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}function ci(e,t){return t instanceof de._CodeOrName?Rr(e,t.names):e}function an(e,t,r){if(e instanceof de.Name)return n(e);if(!o(e))return e;return new de._Code(e._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||t[s.str]!==1?s:(delete t[s.str],i)}function o(s){return s instanceof de._Code&&s._items.some(i=>i instanceof de.Name&&t[i.str]===1&&r[i.str]!==void 0)}}function jR(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}function ig(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,de._)`!${Tc(e)}`}oe.not=ig;var DR=ag(oe.operators.AND);function UR(...e){return e.reduce(DR)}oe.and=UR;var MR=ag(oe.operators.OR);function qR(...e){return e.reduce(MR)}oe.or=qR;function ag(e){return(t,r)=>t===de.nil?r:r===de.nil?t:(0,de._)`${Tc(t)} ${e} ${Tc(r)}`}function Tc(e){return e instanceof de.Name?e:(0,de._)`(${e})`}});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(),zR=oo();function BR(e){let t={};for(let r of e)t[r]=!0;return t}se.toHash=BR;function FR(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(dg(e,t),!ug(t,e.self.RULES.all))}se.alwaysValidSchema=FR;function dg(e,t=e.schema){let{opts:r,self:n}=e;if(!r.strictSchema||typeof t=="boolean")return;let o=n.RULES.keywords;for(let s in t)o[s]||mg(e,`unknown keyword: "${s}"`)}se.checkUnknownRules=dg;function ug(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}se.schemaHasRules=ug;function HR(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}se.schemaHasRulesButRef=HR;function VR({topSchemaRef:e,schemaPath:t},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._)`${e}${t}${(0,we.getProperty)(n)}`}se.schemaRefOrVal=VR;function KR(e){return pg(decodeURIComponent(e))}se.unescapeFragment=KR;function WR(e){return encodeURIComponent($c(e))}se.escapeFragment=WR;function $c(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=$c;function pg(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=pg;function GR(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}se.eachItem=GR;function lg({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let l=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?e(o,s,i):t(o,s,i),i):s instanceof we.Name?(t(o,i,s),s):r(s,i);return a===we.Name&&!(l instanceof we.Name)?n(o,l):l}}se.mergeEvaluated={props:lg({mergeNames:(e,t,r)=>e.if((0,we._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,we._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,we._)`${r} || {}`).code((0,we._)`Object.assign(${r}, ${t})`))}),mergeToName:(e,t,r)=>e.if((0,we._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,we._)`${r} || {}`),Ec(e,r,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:hg}),items:lg({mergeNames:(e,t,r)=>e.if((0,we._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,we._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),mergeToName:(e,t,r)=>e.if((0,we._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,we._)`${r} > ${t} ? ${r} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function hg(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,we._)`{}`);return t!==void 0&&Ec(e,r,t),r}se.evaluatedPropsToName=hg;function Ec(e,t,r){Object.keys(r).forEach(n=>e.assign((0,we._)`${t}${(0,we.getProperty)(n)}`,!0))}se.setEvaluated=Ec;var cg={};function JR(e,t){return e.scopeValue("func",{ref:t,code:cg[t.code]||(cg[t.code]=new zR._Code(t.code))})}se.useFunc=JR;var Rc;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(Rc||(se.Type=Rc={}));function YR(e,t,r){if(e instanceof we.Name){let n=t===Rc.Num;return r?n?(0,we._)`"[" + ${e} + "]"`:(0,we._)`"['" + ${e} + "']"`:n?(0,we._)`"/" + ${e}`:(0,we._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,we.getProperty)(e).toString():"/"+$c(e)}se.getErrorPath=YR;function mg(e,t,r=e.opts.strictSchema){if(r){if(t=`strict mode: ${t}`,r===!0)throw new Error(t);e.self.logger.warn(t)}}se.checkStrictMode=mg});var Vt=q(Pc=>{"use strict";Object.defineProperty(Pc,"__esModule",{value:!0});var ze=re(),XR={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")};Pc.default=XR});var uo=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(),ui=pe(),We=Vt();Be.keywordError={message:({keyword:e})=>(0,he.str)`must pass "${e}" keyword validation`};Be.keyword$DataError={message:({keyword:e,schemaType:t})=>t?(0,he.str)`"${e}" keyword must be ${t} ($data)`:(0,he.str)`"${e}" keyword is invalid ($data)`};function ZR(e,t=Be.keywordError,r,n){let{it:o}=e,{gen:s,compositeRule:i,allErrors:a}=o,l=yg(e,t,r);n??(i||a)?fg(s,l):gg(o,(0,he._)`[${l}]`)}Be.reportError=ZR;function QR(e,t=Be.keywordError,r){let{it:n}=e,{gen:o,compositeRule:s,allErrors:i}=n,a=yg(e,t,r);fg(o,a),s||i||gg(n,We.default.vErrors)}Be.reportExtraError=QR;function e$(e,t){e.assign(We.default.errors,t),e.if((0,he._)`${We.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,he._)`${We.default.vErrors}.length`,t),()=>e.assign(We.default.vErrors,null)))}Be.resetErrorsCount=e$;function t$({gen:e,keyword:t,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=e.name("err");e.forRange("i",o,We.default.errors,a=>{e.const(i,(0,he._)`${We.default.vErrors}[${a}]`),e.if((0,he._)`${i}.instancePath === undefined`,()=>e.assign((0,he._)`${i}.instancePath`,(0,he.strConcat)(We.default.instancePath,s.errorPath))),e.assign((0,he._)`${i}.schemaPath`,(0,he.str)`${s.errSchemaPath}/${t}`),s.opts.verbose&&(e.assign((0,he._)`${i}.schema`,r),e.assign((0,he._)`${i}.data`,n))})}Be.extendErrors=t$;function fg(e,t){let r=e.const("err",t);e.if((0,he._)`${We.default.vErrors} === null`,()=>e.assign(We.default.vErrors,(0,he._)`[${r}]`),(0,he._)`${We.default.vErrors}.push(${r})`),e.code((0,he._)`${We.default.errors}++`)}function gg(e,t){let{gen:r,validateName:n,schemaEnv:o}=e;o.$async?r.throw((0,he._)`new ${e.ValidationError}(${t})`):(r.assign((0,he._)`${n}.errors`,t),r.return(!1))}var $r={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 yg(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,he._)`{}`:r$(e,t,r)}function r$(e,t,r={}){let{gen:n,it:o}=e,s=[n$(o,r),o$(e,r)];return s$(e,t,s),n.object(...s)}function n$({errorPath:e},{instancePath:t}){let r=t?(0,he.str)`${e}${(0,ui.getErrorPath)(t,ui.Type.Str)}`:e;return[We.default.instancePath,(0,he.strConcat)(We.default.instancePath,r)]}function o$({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let o=n?t:(0,he.str)`${t}/${e}`;return r&&(o=(0,he.str)`${o}${(0,ui.getErrorPath)(r,ui.Type.Str)}`),[$r.schemaPath,o]}function s$(e,{params:t,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=e,{opts:l,propertyName:u,topSchemaRef:p,schemaPath:g}=a;n.push([$r.keyword,o],[$r.params,typeof t=="function"?t(e):t||(0,he._)`{}`]),l.messages&&n.push([$r.message,typeof r=="function"?r(e):r]),l.verbose&&n.push([$r.schema,i],[$r.parentSchema,(0,he._)`${p}${g}`],[We.default.data,s]),u&&n.push([$r.propertyName,u])}});var wg=q(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.boolOrEmptySchema=ln.topBoolOrEmptySchema=void 0;var i$=uo(),a$=re(),l$=Vt(),c$={message:"boolean schema is false"};function d$(e){let{gen:t,schema:r,validateName:n}=e;r===!1?bg(e,!1):typeof r=="object"&&r.$async===!0?t.return(l$.default.data):(t.assign((0,a$._)`${n}.errors`,null),t.return(!0))}ln.topBoolOrEmptySchema=d$;function u$(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),bg(e)):r.var(t,!0)}ln.boolOrEmptySchema=u$;function bg(e,t){let{gen:r,data:n}=e,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,i$.reportError)(o,c$,void 0,t)}});var Ac=q(cn=>{"use strict";Object.defineProperty(cn,"__esModule",{value:!0});cn.getRules=cn.isJSONType=void 0;var p$=["string","number","integer","boolean","null","object","array"],h$=new Set(p$);function m$(e){return typeof e=="string"&&h$.has(e)}cn.isJSONType=m$;function f$(){let e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}cn.getRules=f$});var Cc=q(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.shouldUseRule=ar.shouldUseGroup=ar.schemaHasRulesForType=void 0;function g$({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&vg(e,n)}ar.schemaHasRulesForType=g$;function vg(e,t){return t.rules.some(r=>_g(e,r))}ar.shouldUseGroup=vg;function _g(e,t){var r;return e[t.keyword]!==void 0||((r=t.definition.implements)===null||r===void 0?void 0:r.some(n=>e[n]!==void 0))}ar.shouldUseRule=_g});var po=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 y$=Ac(),b$=Cc(),w$=uo(),te=re(),Sg=pe(),dn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(dn||(Fe.DataType=dn={}));function v$(e){let t=kg(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}Fe.getSchemaTypes=v$;function kg(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(y$.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}Fe.getJSONTypes=kg;function _$(e,t){let{gen:r,data:n,opts:o}=e,s=S$(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,b$.schemaHasRulesForType)(e,t[0]));if(i){let a=Oc(t,n,o.strictNumbers,dn.Wrong);r.if(a,()=>{s.length?k$(e,t,s):Nc(e)})}return i}Fe.coerceAndCheckDataType=_$;var xg=new Set(["string","number","integer","boolean","null"]);function S$(e,t){return t?e.filter(r=>xg.has(r)||t==="array"&&r==="array"):[]}function k$(e,t,r){let{gen:n,data:o,opts:s}=e,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(Oc(t,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,te._)`${a} !== undefined`);for(let u of r)(xg.has(u)||u==="array"&&s.coerceTypes==="array")&&l(u);n.else(),Nc(e),n.endIf(),n.if((0,te._)`${a} !== undefined`,()=>{n.assign(o,a),x$(e,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
|
|
2438
2456
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,te._)`+${o}`);return;case"integer":n.elseIf((0,te._)`${i} === "boolean" || ${o} === null
|
|
2439
2457
|
|| (${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"
|
|
2440
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function k$({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,te._)`${t} !== undefined`,()=>e.assign((0,te._)`${t}[${r}]`,n))}function Cc(e,t,r,n=un.Correct){let o=n===un.Correct?te.operators.EQ:te.operators.NEQ,s;switch(e){case"null":return(0,te._)`${t} ${o} null`;case"array":s=(0,te._)`Array.isArray(${t})`;break;case"object":s=(0,te._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,te._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${t} ${o} ${e}`}return n===un.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${t} == "number"`,a,r?(0,te._)`isFinite(${t})`:te.nil)}}Fe.checkDataType=Cc;function Ic(e,t,r,n){if(e.length===1)return Cc(e[0],t,r,n);let o,s=(0,_g.toHash)(e);if(s.array&&s.object){let i=(0,te._)`typeof ${t} != "object"`;o=s.null?i:(0,te._)`!${t} || ${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,Cc(i,t,r,n));return o}Fe.checkDataTypes=Ic;var x$={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,te._)`{type: ${e}}`:(0,te._)`{type: ${t}}`};function Oc(e){let t=T$(e);(0,b$.reportError)(t,x$)}Fe.reportTypeError=Oc;function T$(e){let{gen:t,data:r,schema:n}=e,o=(0,_g.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Tg=q(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.assignDefaults=void 0;var pn=re(),R$=pe();function $$(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)xg(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>xg(e,s,o.default))}pi.assignDefaults=$$;function xg(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,pn._)`${s}${(0,pn.getProperty)(t)}`;if(o){(0,R$.checkStrictMode)(e,`default is ignored for: ${a}`);return}let l=(0,pn._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,pn._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,pn._)`${a} = ${(0,pn.stringify)(r)}`)}});var mt=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(),Nc=pe(),lr=Vt(),E$=pe();function P$(e,t){let{gen:r,data:n,it:o}=e;r.if(jc(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,_e._)`${t}`},!0),e.error()})}ye.checkReportMissingProp=P$;function A$({gen:e,data:t,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(jc(e,t,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}ye.checkMissingProp=A$;function C$(e,t){e.setParams({missingProperty:t},!0),e.error()}ye.reportMissingProp=C$;function Rg(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}ye.hasPropFunc=Rg;function Lc(e,t,r){return(0,_e._)`${Rg(e)}.call(${t}, ${r})`}ye.isOwnProperty=Lc;function I$(e,t,r,n){let o=(0,_e._)`${t}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${Lc(e,t,r)}`:o}ye.propertyInData=I$;function jc(e,t,r,n){let o=(0,_e._)`${t}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(Lc(e,t,r))):o}ye.noPropertyInData=jc;function $g(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}ye.allSchemaProperties=$g;function O$(e,t){return $g(t).filter(r=>!(0,Nc.alwaysValidSchema)(e,t[r]))}ye.schemaProperties=O$;function N$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,u){let p=u?(0,_e._)`${e}, ${t}, ${n}${o}`:t,g=[[lr.default.instancePath,(0,_e.strConcat)(lr.default.instancePath,s)],[lr.default.parentData,i.parentData],[lr.default.parentDataProperty,i.parentDataProperty],[lr.default.rootData,lr.default.rootData]];i.opts.dynamicRef&&g.push([lr.default.dynamicAnchors,lr.default.dynamicAnchors]);let x=(0,_e._)`${p}, ${r.object(...g)}`;return l!==_e.nil?(0,_e._)`${a}.call(${l}, ${x})`:(0,_e._)`${a}(${x})`}ye.callValidateCode=N$;var L$=(0,_e._)`new RegExp`;function j$({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,_e._)`${o.code==="new RegExp"?L$:(0,E$.useFunc)(e,o)}(${r}, ${n})`})}ye.usePattern=j$;function D$(e){let{gen:t,data:r,keyword:n,it:o}=e,s=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let l=t.const("len",(0,_e._)`${r}.length`);t.forRange("i",0,l,u=>{e.subschema({keyword:n,dataProp:u,dataPropType:Nc.Type.Num},s),t.if((0,_e.not)(s),a)})}}ye.validateArray=D$;function U$(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Nc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((l,u)=>{let p=e.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);t.assign(i,(0,_e._)`${i} || ${a}`),e.mergeValidEvaluated(p,a)||t.if((0,_e.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}ye.validateUnion=U$});var Ag=q(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateKeywordUsage=Ot.validSchemaType=Ot.funcKeywordCode=Ot.macroKeywordCode=void 0;var Ge=re(),Er=Vt(),M$=mt(),q$=uo();function z$(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),l=Pg(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:Ge.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Ot.macroKeywordCode=z$;function B$(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=e;H$(l,t);let u=!a&&t.compile?t.compile.call(l.self,s,i,l):t.validate,p=Pg(n,o,u),g=n.let("valid");e.block$data(g,x),e.ok((r=t.valid)!==null&&r!==void 0?r:g);function x(){if(t.errors===!1)R(),t.modifying&&Eg(e),$(()=>e.error());else{let P=t.async?y():k();t.modifying&&Eg(e),$(()=>F$(e,P))}}function y(){let P=n.let("ruleErrs",null);return n.try(()=>R((0,Ge._)`await `),C=>n.assign(g,!1).if((0,Ge._)`${C} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ge._)`${C}.errors`),()=>n.throw(C))),P}function k(){let P=(0,Ge._)`${p}.errors`;return n.assign(P,null),R(Ge.nil),P}function R(P=t.async?(0,Ge._)`await `:Ge.nil){let C=l.opts.passContext?Er.default.this:Er.default.self,j=!("compile"in t&&!a||t.schema===!1);n.assign(g,(0,Ge._)`${P}${(0,M$.callValidateCode)(e,p,C,j)}`,t.modifying)}function $(P){var C;n.if((0,Ge.not)((C=t.valid)!==null&&C!==void 0?C:g),P)}}Ot.funcKeywordCode=B$;function Eg(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ge._)`${n.parentData}[${n.parentDataProperty}]`))}function F$(e,t){let{gen:r}=e;r.if((0,Ge._)`Array.isArray(${t})`,()=>{r.assign(Er.default.vErrors,(0,Ge._)`${Er.default.vErrors} === null ? ${t} : ${Er.default.vErrors}.concat(${t})`).assign(Er.default.errors,(0,Ge._)`${Er.default.vErrors}.length`),(0,q$.extendErrors)(e)},()=>e.error())}function H$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Pg(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ge.stringify)(r)})}function V$(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Ot.validSchemaType=V$;function K$({schema:e,opts:t,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(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Ot.validateKeywordUsage=K$});var Ig=q(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.extendSubschemaMode=cr.extendSubschemaData=cr.getSubschema=void 0;var Nt=re(),Cg=pe();function W$(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,Nt._)`${e.schemaPath}${(0,Nt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Nt._)`${e.schemaPath}${(0,Nt.getProperty)(t)}${(0,Nt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Cg.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')}cr.getSubschema=W$;function G$(e,t,{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}=t;if(r!==void 0){let{errorPath:u,dataPathArr:p,opts:g}=t,x=a.let("data",(0,Nt._)`${t.data}${(0,Nt.getProperty)(r)}`,!0);l(x),e.errorPath=(0,Nt.str)`${u}${(0,Cg.getErrorPath)(r,n,g.jsPropertySyntax)}`,e.parentDataProperty=(0,Nt._)`${r}`,e.dataPathArr=[...p,e.parentDataProperty]}if(o!==void 0){let u=o instanceof Nt.Name?o:a.let("data",o,!0);l(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function l(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}cr.extendSubschemaData=G$;function J$(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}cr.extendSubschemaMode=J$});var Dc=q((BU,Og)=>{"use strict";Og.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),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(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}});var Lg=q((FU,Ng)=>{"use strict";var dr=Ng.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};hi(t,n,o,e,"",e)};dr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};dr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};dr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};dr.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 hi(e,t,r,n,o,s,i,a,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,l,u);for(var p in n){var g=n[p];if(Array.isArray(g)){if(p in dr.arrayKeywords)for(var x=0;x<g.length;x++)hi(e,t,r,g[x],o+"/"+p+"/"+x,s,o,p,n,x)}else if(p in dr.propsKeywords){if(g&&typeof g=="object")for(var y in g)hi(e,t,r,g[y],o+"/"+p+"/"+Y$(y),s,o,p,n,y)}else(p in dr.keywords||e.allKeys&&!(p in dr.skipKeywords))&&hi(e,t,r,g,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,u)}}function Y$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ho=q(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var X$=pe(),Z$=Dc(),Q$=Lg(),eE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function tE(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Uc(e):t?jg(e)<=t:!1}et.inlineRef=tE;var rE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Uc(e){for(let t in e){if(rE.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Uc)||typeof r=="object"&&Uc(r))return!0}return!1}function jg(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!eE.has(r)&&(typeof e[r]=="object"&&(0,X$.eachItem)(e[r],n=>t+=jg(n)),t===1/0))return 1/0}return t}function Dg(e,t="",r){r!==!1&&(t=hn(t));let n=e.parse(t);return Ug(e,n)}et.getFullPath=Dg;function Ug(e,t){return e.serialize(t).split("#")[0]+"#"}et._getFullPath=Ug;var nE=/#\/?$/;function hn(e){return e?e.replace(nE,""):""}et.normalizeId=hn;function oE(e,t,r){return r=hn(r),e.resolve(t,r)}et.resolveUrl=oE;var sE=/^[a-z_][-a-z0-9._]*$/i;function iE(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=hn(e[r]||t),s={"":o},i=Dg(n,o,!1),a={},l=new Set;return Q$(e,{allKeys:!0},(g,x,y,k)=>{if(k===void 0)return;let R=i+x,$=s[k];typeof g[r]=="string"&&($=P.call(this,g[r])),C.call(this,g.$anchor),C.call(this,g.$dynamicAnchor),s[x]=$;function P(j){let H=this.opts.uriResolver.resolve;if(j=hn($?H($,j):j),l.has(j))throw p(j);l.add(j);let G=this.refs[j];return typeof G=="string"&&(G=this.refs[G]),typeof G=="object"?u(g,G.schema,j):j!==hn(R)&&(j[0]==="#"?(u(g,a[j],j),a[j]=g):this.refs[j]=R),j}function C(j){if(typeof j=="string"){if(!sE.test(j))throw new Error(`invalid anchor "${j}"`);P.call(this,`#${j}`)}}}),a;function u(g,x,y){if(x!==void 0&&!Z$(g,x))throw p(y)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}et.getSchemaRefs=iE});var go=q(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.getData=ur.KeywordCxt=ur.validateFunctionCode=void 0;var Fg=bg(),Mg=po(),qc=Ac(),mi=po(),aE=Tg(),fo=Ag(),Mc=Ig(),K=re(),ee=Vt(),lE=ho(),Kt=pe(),mo=uo();function cE(e){if(Kg(e)&&(Wg(e),Vg(e))){pE(e);return}Hg(e,()=>(0,Fg.topBoolOrEmptySchema)(e))}ur.validateFunctionCode=cE;function Hg({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,K._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{e.code((0,K._)`"use strict"; ${qg(r,o)}`),uE(e,o),e.code(s)}):e.func(t,(0,K._)`${ee.default.data}, ${dE(o)}`,n.$async,()=>e.code(qg(r,o)).code(s))}function dE(e){return(0,K._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${e.dynamicRef?(0,K._)`, ${ee.default.dynamicAnchors}={}`:K.nil}}={}`}function uE(e,t){e.if(ee.default.valCxt,()=>{e.var(ee.default.instancePath,(0,K._)`${ee.default.valCxt}.${ee.default.instancePath}`),e.var(ee.default.parentData,(0,K._)`${ee.default.valCxt}.${ee.default.parentData}`),e.var(ee.default.parentDataProperty,(0,K._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),e.var(ee.default.rootData,(0,K._)`${ee.default.valCxt}.${ee.default.rootData}`),t.dynamicRef&&e.var(ee.default.dynamicAnchors,(0,K._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{e.var(ee.default.instancePath,(0,K._)`""`),e.var(ee.default.parentData,(0,K._)`undefined`),e.var(ee.default.parentDataProperty,(0,K._)`undefined`),e.var(ee.default.rootData,ee.default.data),t.dynamicRef&&e.var(ee.default.dynamicAnchors,(0,K._)`{}`)})}function pE(e){let{schema:t,opts:r,gen:n}=e;Hg(e,()=>{r.$comment&&t.$comment&&Jg(e),yE(e),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&hE(e),Gg(e),vE(e)})}function hE(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,K._)`${r}.evaluated`),t.if((0,K._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,K._)`${e.evaluated}.props`,(0,K._)`undefined`)),t.if((0,K._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,K._)`${e.evaluated}.items`,(0,K._)`undefined`))}function qg(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,K._)`/*# sourceURL=${r} */`:K.nil}function mE(e,t){if(Kg(e)&&(Wg(e),Vg(e))){fE(e,t);return}(0,Fg.boolOrEmptySchema)(e,t)}function Vg({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Kg(e){return typeof e.schema!="boolean"}function fE(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Jg(e),bE(e),wE(e);let s=n.const("_errs",ee.default.errors);Gg(e,s),n.var(t,(0,K._)`${s} === ${ee.default.errors}`)}function Wg(e){(0,Kt.checkUnknownRules)(e),gE(e)}function Gg(e,t){if(e.opts.jtd)return zg(e,[],!1,t);let r=(0,Mg.getSchemaTypes)(e.schema),n=(0,Mg.coerceAndCheckDataType)(e,r);zg(e,r,!n,t)}function gE(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Kt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function yE(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Kt.checkStrictMode)(e,"default is ignored in the schema root")}function bE(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,lE.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function wE(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Jg({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,K._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,K.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,K._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function vE(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,K._)`${ee.default.errors} === 0`,()=>t.return(ee.default.data),()=>t.throw((0,K._)`new ${o}(${ee.default.vErrors})`)):(t.assign((0,K._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&_E(e),t.return((0,K._)`${ee.default.errors} === 0`))}function _E({gen:e,evaluated:t,props:r,items:n}){r instanceof K.Name&&e.assign((0,K._)`${t}.props`,r),n instanceof K.Name&&e.assign((0,K._)`${t}.items`,n)}function zg(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:u}=e,{RULES:p}=u;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,Kt.schemaHasRulesButRef)(s,p))){o.block(()=>Xg(e,"$ref",p.all.$ref.definition));return}l.jtd||SE(e,t),o.block(()=>{for(let x of p.rules)g(x);g(p.post)});function g(x){(0,qc.shouldUseGroup)(s,x)&&(x.type?(o.if((0,mi.checkDataType)(x.type,i,l.strictNumbers)),Bg(e,x),t.length===1&&t[0]===x.type&&r&&(o.else(),(0,mi.reportTypeError)(e)),o.endIf()):Bg(e,x),a||o.if((0,K._)`${ee.default.errors} === ${n||0}`))}}function Bg(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,aE.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,qc.shouldUseRule)(n,s)&&Xg(e,s.keyword,s.definition,t.type)})}function SE(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(kE(e,t),e.opts.allowUnionTypes||xE(e,t),TE(e,e.dataTypes))}function kE(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Yg(e.dataTypes,r)||zc(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),$E(e,t)}}function xE(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&zc(e,"use allowUnionTypes to allow union type keyword")}function TE(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,qc.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>RE(t,i))&&zc(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function RE(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Yg(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function $E(e,t){let r=[];for(let n of e.dataTypes)Yg(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function zc(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Kt.checkStrictMode)(e,t,e.opts.strictTypes)}var fi=class{constructor(t,r,n){if((0,fo.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Kt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Zg(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,fo.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=t.gen.const("_errs",ee.default.errors))}result(t,r,n){this.failResult((0,K.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,K.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,K._)`${r} !== undefined && (${(0,K.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?mo.reportExtraError:mo.reportError)(this,this.def.error,r)}$dataError(){(0,mo.reportError)(this,this.def.$dataError||mo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,mo.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=K.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=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)),t!==K.nil&&n.assign(t,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==K.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,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,mi.checkDataTypes)(l,r,s.opts.strictNumbers,mi.DataType.Wrong)}`}return K.nil}function a(){if(o.validateSchema){let l=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,K._)`!${l}(${r})`}return K.nil}}subschema(t,r){let n=(0,Mc.getSubschema)(this.it,t);(0,Mc.extendSubschemaData)(n,this.it,t),(0,Mc.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return mE(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Kt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Kt.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,K.Name)),!0}};ur.KeywordCxt=fi;function Xg(e,t,r,n){let o=new fi(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,fo.funcKeywordCode)(o,r):"macro"in r?(0,fo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,fo.funcKeywordCode)(o,r)}var EE=/^\/(?:[^~]|~0|~1)*$/,PE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Zg(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return ee.default.rootData;if(e[0]==="/"){if(!EE.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=ee.default.rootData}else{let u=PE.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);let p=+u[1];if(o=u[2],o==="#"){if(p>=t)throw new Error(l("property/index",p));return n[t-p]}if(p>t)throw new Error(l("data",p));if(s=r[t-p],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,K._)`${s}${(0,K.getProperty)((0,Kt.unescapeJsonPointer)(u))}`,i=(0,K._)`${i} && ${s}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${t}`}}ur.getData=Zg});var gi=q(Fc=>{"use strict";Object.defineProperty(Fc,"__esModule",{value:!0});var Bc=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Fc.default=Bc});var yo=q(Kc=>{"use strict";Object.defineProperty(Kc,"__esModule",{value:!0});var Hc=ho(),Vc=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Hc.resolveUrl)(t,r,n),this.missingSchema=(0,Hc.normalizeId)((0,Hc.getFullPath)(t,this.missingRef))}};Kc.default=Vc});var bi=q(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.resolveSchema=ft.getCompilingSchema=ft.resolveRef=ft.compileSchema=ft.SchemaEnv=void 0;var xt=re(),AE=gi(),Pr=Vt(),Tt=ho(),Qg=pe(),CE=go(),mn=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,Tt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};ft.SchemaEnv=mn;function Gc(e){let t=ey.call(this,e);if(t)return t;let r=(0,Tt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new xt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:AE.default,code:(0,xt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");e.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:Pr.default.data,parentData:Pr.default.parentData,parentDataProperty:Pr.default.parentDataProperty,dataNames:[Pr.default.data],dataPathArr:[xt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,xt.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:xt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,xt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(e),(0,CE.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(Pr.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,e));let y=new Function(`${Pr.default.self}`,`${Pr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=e.schema,y.schemaEnv=e,e.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:g,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:R}=u;y.evaluated={props:k instanceof xt.Name?void 0:k,items:R instanceof xt.Name?void 0:R,dynamicProps:k instanceof xt.Name,dynamicItems:R instanceof xt.Name},y.source&&(y.source.evaluated=(0,xt.stringify)(y.evaluated))}return e.validate=y,e}catch(g){throw delete e.validate,delete e.validateName,p&&this.logger.error("Error compiling schema, function code:",p),g}finally{this._compilations.delete(e)}}ft.compileSchema=Gc;function IE(e,t,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=LE.call(this,e,r);if(s===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new mn({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=OE.call(this,s)}ft.resolveRef=IE;function OE(e){return(0,Tt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Gc.call(this,e)}function ey(e){for(let t of this._compilations)if(NE(t,e))return t}ft.getCompilingSchema=ey;function NE(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function LE(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||yi.call(this,e,t)}function yi(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),o=(0,Tt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Wc.call(this,r,e);let s=(0,Tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=yi.call(this,e,i);return typeof a?.schema!="object"?void 0:Wc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Gc.call(this,i),s===(0,Tt.normalizeId)(t)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(o=(0,Tt.resolveUrl)(this.opts.uriResolver,o,u)),new mn({schema:a,schemaId:l,root:e,baseId:o})}return Wc.call(this,r,i)}}ft.resolveSchema=yi;var jE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Wc(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,Qg.unescapeFragment)(a)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!jE.has(a)&&u&&(t=(0,Tt.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Qg.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Tt.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=yi.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new mn({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var ty=q((JU,DE)=>{DE.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 ed=q((YU,cy)=>{"use strict";var UE=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Yc=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),ME=RegExp.prototype.test.bind(/^\d*$/u),Ar=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Xc=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ny=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Zc=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),qE=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),tt=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)tt[t]="%"+e[t>>4]+e[t&15]}function He(e){return e<2048?tt[192|e>>6]+tt[128|e&63]:e<65536?tt[224|e>>12]+tt[128|e>>6&63]+tt[128|e&63]:tt[240|e>>18]+tt[128|e>>12&63]+tt[128|e>>6&63]+tt[128|e&63]}function zE(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var BE=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),FE=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),HE=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),VE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function KE(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!HE(e[t])){if(e[t]==="%"&&t+2<e.length&&Ar(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function ry(e){let t=-1,r=0,n=-1,o=0;for(let a=0;a<e.length;a++)e[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,t=n)):(n=-1,o=0);if(r<2)return e.join(":");let s=e.slice(0,t).join(":"),i=e.slice(t+r).join(":");return s+"::"+i}function WE(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let r=t===-1?e.split(":"):e.slice(0,t).split(":"),n=t===-1?[]:e.slice(t+2).split(":");t!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let l=o[a];if(l==="")return;if(l.indexOf(".")!==-1){if(a!==o.length-1||t!==-1&&n.length===0||!Yc(l))return;s+=2;continue}if(!BE(l))return;o[a]=parseInt(l,16).toString(16),s++}if(t===-1)return s!==8?void 0:ry(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return ry(i)}function Jc(e){let t=e[0]==="["&&e[e.length-1]==="]";if((e[0]==="["||e[e.length-1]==="]")&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&FE(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(GE(n,":")<2)return{host:e,isIPV6:!1,error:t};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!KE(o))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=WE(n);return i===void 0?{host:e,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function GE(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function oy(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function JE(e){if(e===""||e[0]==="/")return oy(e);let t=e.split("/"),r=t.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=t[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var YE={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},XE=/[@/?#:]/g,ZE=/[@/?#]/g;function sy(e,t){let r=t?ZE:XE;return r.lastIndex=0,e.replace(r,n=>YE[n])}function iy(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Ar(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Xc(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function QE(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let o=e.slice(r+1,r+3);if(Ar(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Xc(i)?t+=i:t+="%"+s,r+=2;continue}}if(ny(n))t+=n;else{let o=e.charCodeAt(r);if(o<128)t+=ly(o)?n:tt[o];else if(o<55296||o>57343)t+=He(o);else if(o<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343?(t+=He(65536+(o-55296<<10)+(s-56320)),r++):t+=He(65533)}else t+=He(65533)}}return t}function e0(e,t=!1){let r="",n=t&&e[0]!=="/";for(let o=0;o<e.length;o++){let s=e[o];if(s==="%"&&o+2<e.length){let i=e.slice(o+1,o+3);if(Ar(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),ny(s)&&(s!==":"||!n))r+=s;else{let i=e.charCodeAt(o);if(i<128)r+=tt[i];else if(i<55296||i>57343)r+=He(i);else if(i<=56319&&o+1<e.length){let a=e.charCodeAt(o+1);a>=56320&&a<=57343?(r+=He(65536+(i-55296<<10)+(a-56320)),o++):r+=He(65533)}else r+=He(65533)}}return r}function Qc(e,t){let r="";for(let n=0;n<e.length;n++){let o=e[n];if(o==="%"&&n+2<e.length){let s=e.slice(n+1,n+3);if(Ar(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(t(o))r+=o;else{let s=e.charCodeAt(n);if(s<128)r+=tt[s];else if(s<55296||s>57343)r+=He(s);else if(s<=56319&&n+1<e.length){let i=e.charCodeAt(n+1);i>=56320&&i<=57343?(r+=He(65536+(s-55296<<10)+(i-56320)),n++):r+=He(65533)}else r+=He(65533)}}return r}function ay(e){return Qc(e,qE)}function t0(e){return Qc(e,Zc)}function r0(e){return Qc(e,Zc)}function ly(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function n0(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let o=e.slice(r+1,r+3);if(Ar(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Xc(i)?t+=i:t+="%"+s,r+=2;continue}}if(Zc(n))t+=n;else{let o=e.charCodeAt(r);if(o<128)t+=ly(o)?n:tt[o];else if(o<55296||o>57343)t+=He(o);else if(o<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343?(t+=He(65536+(o-55296<<10)+(s-56320)),r++):t+=He(65533)}else t+=He(65533)}}return t}function o0(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Ar(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function s0(e){let t=[];if(e.userinfo!==void 0&&(t.push(ay(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!Yc(r)){let n=Jc(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=iy(r,!0),n=Jc(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=sy(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!ME(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}cy.exports={nonSimpleDomain:VE,recomposeAuthority:s0,reescapeHostDelimiters:sy,normalizePercentEncoding:iy,normalizePathEncoding:QE,serializePathEncoding:e0,normalizeQueryFragmentEncoding:n0,encodeUserinfo:ay,encodeQuery:t0,encodeFragment:r0,escapePreservingEscapes:o0,removeDotSegments:oy,removeDotSegmentsRelative:JE,isIPv4:Yc,isUUID:UE,normalizeIPv6:Jc,stringArrayToHexStripped:zE}});var my=q((XU,hy)=>{"use strict";var{isUUID:i0}=ed(),a0=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,l0=["http","https","ws","wss","urn","urn:uuid"];function c0(e){return l0.indexOf(e)!==-1}function td(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function dy(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function uy(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function d0(e){return e.secure=td(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function u0(e){if((e.port===(td(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf("?"),r=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=r&&r!=="/"?r:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function p0(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(a0);if(r&&r[0]===e.path){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,s=rd(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function h0(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,s=rd(o);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function m0(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!i0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function f0(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var py={scheme:"http",domainHost:!0,parse:dy,serialize:uy},g0={scheme:"https",domainHost:py.domainHost,parse:dy,serialize:uy},wi={scheme:"ws",domainHost:!0,parse:d0,serialize:u0},y0={scheme:"wss",domainHost:wi.domainHost,parse:wi.parse,serialize:wi.serialize},b0={scheme:"urn",parse:p0,serialize:h0,skipNormalize:!0},w0={scheme:"urn:uuid",parse:m0,serialize:f0,skipNormalize:!0},vi={http:py,https:g0,ws:wi,wss:y0,urn:b0,"urn:uuid":w0};Object.setPrototypeOf(vi,null);function rd(e){return e&&(vi[e]||vi[e.toLowerCase()])||void 0}hy.exports={wsIsSecure:td,SCHEMES:vi,isValidSchemeName:c0,getSchemeHandler:rd}});var Py=q((ZU,Ti)=>{"use strict";var{normalizeIPv6:wy,removeDotSegments:wo,removeDotSegmentsRelative:vy,recomposeAuthority:v0,normalizePercentEncoding:nd,normalizePathEncoding:_0,serializePathEncoding:fy,normalizeQueryFragmentEncoding:gy,encodeQuery:S0,encodeFragment:k0,reescapeHostDelimiters:x0,isIPv4:_y,nonSimpleDomain:T0}=ed(),{SCHEMES:Sy,getSchemeHandler:od}=my(),ky=/^[A-Za-z][A-Za-z0-9+.-]*$/u,xy="URI scheme is malformed.",_i="URI host is malformed.",R0=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function yy(e){let t=String(e);if(!ky.test(t))throw new TypeError(xy);return t}function $0(e,t){return typeof e=="string"?e=j0(e,t):typeof e=="object"&&(e=ki(Cr(e,t),t)),e}function E0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:l,malformedScheme:u}=Si(e,n),{parsed:p,malformedAuthorityOrPort:g,malformedPercentEncoding:x,malformedSchemeSpecific:y,malformedHost:k,malformedScheme:R}=Si(t,n);if(s||g||i||x||a||y||l||k||u||R)throw new Error(o.error||p.error||"URI is malformed.");let $=Ty(o,p,n,!0),P=od(r&&r.scheme||$.scheme),C=$.host,j=C!==void 0&&C!==""&&(_y(C)||wy(C).isIPV6);if($y($,r||{},P,j))throw new Error(_i);Ry($,r||{},P,j);let H=C&&C.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(C);if($.error&&!H)throw new Error($.error);return n.skipEscape=!0,Cr($,n)}function Ty(e,t,r,n){let o={};if(n||(e=ki(Cr(e,r),r),t=ki(Cr(t,r),r)),r=r||{},!r.tolerant&&t.scheme)o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=wo(t.path||""),o.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=wo(t.path||""),o.query=t.query;else{if(!t.path)o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query;else{if(t.path[0]==="/")o.path=wo(t.path);else{let s=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;s&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=e.scheme===void 0&&!s&&o.path[0]!=="/"?vy(o.path):wo(o.path)}o.query=t.query}o.userinfo=e.userinfo,o.host=e.host,o.port=e.port}o.scheme=e.scheme}return o.fragment=t.fragment,o}function P0(e,t,r){let n=by(e,r),o=by(t,r);return n!==void 0&&o!==void 0&&n===o}function Cr(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[];r.scheme&&(r.scheme=yy(r.scheme));let s=od(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=(r.scheme===void 0||n.reference==="suffix")&&!i,l=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=nd(r.path):r.path=fy(r.path,l)),n.reference!=="suffix"&&r.scheme&&(r.scheme=yy(r.scheme),o.push(r.scheme,":"));let u=v0(r);if(u!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(u),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let p=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(p=a&&p[0]!=="/"?vy(p):wo(p)),a&&(p=fy(p,!0)),u===void 0&&p[0]==="/"&&p[1]==="/"&&(p="/%2F"+p.slice(2)),o.push(p)}return r.query!==void 0&&o.push("?",S0(r.query)),r.fragment!==void 0&&o.push("#",k0(r.fragment)),o.join("")}var A0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,C0=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,I0=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function O0(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function bo(e){if(e===void 0)return!1;let t=e.indexOf("%");for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function xi(e){return e[0]==="["&&e[e.length-1]==="]"}function N0(e){let t=e[4];return bo(e[3])||t!==void 0&&!xi(t)&&bo(t)||bo(e[6])||bo(e[7])||bo(e[8])}function Ry(e,t,r,n){if($y(e,t,r,n))return e.error=e.error||_i,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!xi(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&T0(e.host)){let o;try{o=new URL("http://"+e.host)}catch(s){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!L0(o))return e.error=e.error||_i,!0;e.host=o.hostname}return!1}function $y(e,t,r,n){return!!(e.host&&n===!1&&!xi(e.host)&&(t.domainHost||r&&r.domainHost)&&R0.test(e.host))}function L0(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Si(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,l=!1,u=!1,p=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let g=e.match(C0);g!==null&&g[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let x=e.match(I0);if(x!==null){let k=x[1],R=k.replace(/[\t\n\r]/g,"");R.length>=2&&(R.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):k.length!==R.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let y=e.match(A0);if(y){n.scheme=y[1],n.userinfo=y[3],n.host=y[4],n.port=parseInt(y[5],10),n.path=y[6]||"",n.query=y[7],n.fragment=y[8],n.scheme!==void 0&&(ky.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||xy,u=!0)),s=N0(y),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=y[5]);let k=O0(n,y);if(k!==void 0&&(n.error=n.error||k,o=!0),n.host)if(_y(n.host)===!1){let P=xi(n.host),C=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,j=wy(n.host);p=j.isIPV6||j.isIPVFuture===!0,l=C&&(!P||j.error===!0),n.host=p?j.host:j.host.toLowerCase(),l&&(n.error=n.error||_i,o=!0)}else p=!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 R=od(r.scheme||n.scheme);if(l||(a=Ry(n,r,R,p)),e.indexOf("%")!==-1&&n.host!==void 0&&!l){let $=p?n.host:nd(n.host,!0);p||($=nd($.toLowerCase())),n.host=p||r.scheme!=="null"?x0($,p):$}(!R||R&&!R.skipNormalize)&&(n.path&&(n.path=_0(n.path)),n.query&&(n.query=gy(n.query)),n.fragment&&(n.fragment=gy(n.fragment))),R&&R.parse&&(R.parse(n,r),R===Sy.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function ki(e,t){return Si(e,t).parsed}function j0(e,t){return Ey(e,t).normalized}function Ey(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Si(e,t);return{normalized:n||o||s||i||a?e:Cr(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function by(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:Cr(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:l}=Ey(r,t);return o||s||i||a||l?void 0:n}var sd={SCHEMES:Sy,normalize:$0,resolve:E0,resolveComponent:Ty,equal:P0,serialize:Cr,parse:ki};Ti.exports=sd;Ti.exports.default=sd;Ti.exports.fastUri=sd});var Cy=q(id=>{"use strict";Object.defineProperty(id,"__esModule",{value:!0});var Ay=Py();Ay.code='require("ajv/dist/runtime/uri").default';id.default=Ay});var My=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 D0=go();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:function(){return D0.KeywordCxt}});var fn=re();Object.defineProperty(Ue,"_",{enumerable:!0,get:function(){return fn._}});Object.defineProperty(Ue,"str",{enumerable:!0,get:function(){return fn.str}});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:function(){return fn.stringify}});Object.defineProperty(Ue,"nil",{enumerable:!0,get:function(){return fn.nil}});Object.defineProperty(Ue,"Name",{enumerable:!0,get:function(){return fn.Name}});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:function(){return fn.CodeGen}});var U0=gi(),jy=yo(),M0=Pc(),vo=bi(),q0=re(),_o=ho(),Ri=po(),ld=pe(),Iy=ty(),z0=Cy(),Dy=(e,t)=>new RegExp(e,t);Dy.code="new RegExp";var B0=["removeAdditional","useDefaults","coerceTypes"],F0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),H0={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."},V0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Oy=200;function K0(e){var t,r,n,o,s,i,a,l,u,p,g,x,y,k,R,$,P,C,j,H,G,Re,qe,Et,Gt;let Pt=e.strict,Jt=(t=e.code)===null||t===void 0?void 0:t.optimize,Lo=Jt===!0||Jt===void 0?1:Jt||0,fr=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Dy,Ut=(o=e.uriResolver)!==null&&o!==void 0?o:z0.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:Pt)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=e.strictNumbers)!==null&&a!==void 0?a:Pt)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=e.strictTypes)!==null&&u!==void 0?u:Pt)!==null&&p!==void 0?p:"log",strictTuples:(x=(g=e.strictTuples)!==null&&g!==void 0?g:Pt)!==null&&x!==void 0?x:"log",strictRequired:(k=(y=e.strictRequired)!==null&&y!==void 0?y:Pt)!==null&&k!==void 0?k:!1,code:e.code?{...e.code,optimize:Lo,regExp:fr}:{optimize:Lo,regExp:fr},loopRequired:(R=e.loopRequired)!==null&&R!==void 0?R:Oy,loopEnum:($=e.loopEnum)!==null&&$!==void 0?$:Oy,meta:(P=e.meta)!==null&&P!==void 0?P:!0,messages:(C=e.messages)!==null&&C!==void 0?C:!0,inlineRefs:(j=e.inlineRefs)!==null&&j!==void 0?j:!0,schemaId:(H=e.schemaId)!==null&&H!==void 0?H:"$id",addUsedSchema:(G=e.addUsedSchema)!==null&&G!==void 0?G:!0,validateSchema:(Re=e.validateSchema)!==null&&Re!==void 0?Re:!0,validateFormats:(qe=e.validateFormats)!==null&&qe!==void 0?qe:!0,unicodeRegExp:(Et=e.unicodeRegExp)!==null&&Et!==void 0?Et:!0,int32range:(Gt=e.int32range)!==null&&Gt!==void 0?Gt:!0,uriResolver:Ut}}var So=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...K0(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new q0.ValueScope({scope:{},prefixes:F0,es5:r,lines:n}),this.logger=Z0(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,M0.getRules)(),Ny.call(this,H0,t,"NOT SUPPORTED"),Ny.call(this,V0,t,"DEPRECATED","warn"),this._metaOpts=Y0.call(this),t.formats&&G0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&J0.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),W0.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Iy;n==="id"&&(o={...Iy},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,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,t,r);async function o(p,g){await s.call(this,p.$schema);let x=this._addSchema(p,g);return x.validate||i.call(this,x)}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 jy.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(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,n,o);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,_o.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$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,t);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(t){let r;for(;typeof(r=Ly.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new vo.SchemaEnv({schema:{},schemaId:n});if(r=vo.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=Ly.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,_o.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,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(eP.call(this,n,r),!r)return(0,ld.eachItem)(n,s=>ad.call(this,s)),this;rP.call(this,r);let o={...r,type:(0,Ri.getJSONTypes)(r.type),schemaType:(0,Ri.getJSONTypes)(r.schemaType)};return(0,ld.eachItem)(n,o.type.length===0?s=>ad.call(this,s,o):s=>o.type.forEach(i=>ad.call(this,s,o,i))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===t);o>=0&&n.rules.splice(o,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let s=o.split("/").slice(1),i=t;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]=Uy(p))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(t);if(l!==void 0)return l;n=(0,_o.normalizeId)(i||n);let u=_o.getSchemaRefs.call(this,t,n);return l=new vo.SchemaEnv({schema:t,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(t,!0),l}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):vo.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{vo.compileSchema.call(this,t)}finally{this.opts=r}}};So.ValidationError=U0.default;So.MissingRefError=jy.default;Ue.default=So;function Ny(e,t,r,n="error"){for(let o in e){let s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function Ly(e){return e=(0,_o.normalizeId)(e),this.schemas[e]||this.refs[e]}function W0(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function G0(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function J0(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function Y0(){let e={...this.opts};for(let t of B0)delete e[t];return e}var X0={log(){},warn(){},error(){}};function Z0(e){if(e===!1)return X0;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var Q0=/^[a-z_$][a-z0-9_$:-]*$/i;function eP(e,t){let{RULES:r}=this;if((0,ld.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Q0.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function ad(e,t,r){var n;let o=t?.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[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Ri.getJSONTypes)(t.type),schemaType:(0,Ri.getJSONTypes)(t.schemaType)}};t.before?tP.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function tP(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function rP(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Uy(t)),e.validateSchema=this.compile(t,!0))}var nP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Uy(e){return{anyOf:[e,nP]}}});var qy=q(cd=>{"use strict";Object.defineProperty(cd,"__esModule",{value:!0});var oP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};cd.default=oP});var Hy=q(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.callRef=Ir.getValidate=void 0;var sP=yo(),zy=mt(),rt=re(),gn=Vt(),By=bi(),$i=pe(),iP={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return g();let p=By.resolveRef.call(l,u,o,r);if(p===void 0)throw new sP.default(n.opts.uriResolver,o,r);if(p instanceof By.SchemaEnv)return x(p);return y(p);function g(){if(s===u)return Ei(e,i,s,s.$async);let k=t.scopeValue("root",{ref:u});return Ei(e,(0,rt._)`${k}.validate`,u,u.$async)}function x(k){let R=Fy(e,k);Ei(e,R,k,k.$async)}function y(k){let R=t.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,rt.stringify)(k)}:{ref:k}),$=t.name("valid"),P=e.subschema({schema:k,dataTypes:[],schemaPath:rt.nil,topSchemaRef:R,errSchemaPath:r},$);e.mergeEvaluated(P),e.ok($)}}};function Fy(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,rt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Ir.getValidate=Fy;function Ei(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:l}=s,u=l.passContext?gn.default.this:rt.nil;n?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=o.let("valid");o.try(()=>{o.code((0,rt._)`await ${(0,zy.callValidateCode)(e,t,u)}`),y(t),i||o.assign(k,!0)},R=>{o.if((0,rt._)`!(${R} instanceof ${s.ValidationError})`,()=>o.throw(R)),x(R),i||o.assign(k,!1)}),e.ok(k)}function g(){e.result((0,zy.callValidateCode)(e,t,u),()=>y(t),()=>x(t))}function x(k){let R=(0,rt._)`${k}.errors`;o.assign(gn.default.vErrors,(0,rt._)`${gn.default.vErrors} === null ? ${R} : ${gn.default.vErrors}.concat(${R})`),o.assign(gn.default.errors,(0,rt._)`${gn.default.vErrors}.length`)}function y(k){var R;if(!s.opts.unevaluated)return;let $=(R=r?.validate)===null||R===void 0?void 0:R.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=$i.mergeEvaluated.props(o,$.props,s.props));else{let P=o.var("props",(0,rt._)`${k}.evaluated.props`);s.props=$i.mergeEvaluated.props(o,P,s.props,rt.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=$i.mergeEvaluated.items(o,$.items,s.items));else{let P=o.var("items",(0,rt._)`${k}.evaluated.items`);s.items=$i.mergeEvaluated.items(o,P,s.items,rt.Name)}}}Ir.callRef=Ei;Ir.default=iP});var Vy=q(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var aP=qy(),lP=Hy(),cP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",aP.default,lP.default];dd.default=cP});var Ky=q(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var Pi=re(),pr=Pi.operators,Ai={maximum:{okStr:"<=",ok:pr.LTE,fail:pr.GT},minimum:{okStr:">=",ok:pr.GTE,fail:pr.LT},exclusiveMaximum:{okStr:"<",ok:pr.LT,fail:pr.GTE},exclusiveMinimum:{okStr:">",ok:pr.GT,fail:pr.LTE}},dP={message:({keyword:e,schemaCode:t})=>(0,Pi.str)`must be ${Ai[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Pi._)`{comparison: ${Ai[e].okStr}, limit: ${t}}`},uP={keyword:Object.keys(Ai),type:"number",schemaType:"number",$data:!0,error:dP,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Pi._)`${r} ${Ai[t].fail} ${n} || isNaN(${r})`)}};ud.default=uP});var Wy=q(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var ko=re(),pP={message:({schemaCode:e})=>(0,ko.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,ko._)`{multipleOf: ${e}}`},hP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:pP,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,ko._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ko._)`${i} !== parseInt(${i})`;e.fail$data((0,ko._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};pd.default=hP});var Jy=q(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});function Gy(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}hd.default=Gy;Gy.code='require("ajv/dist/runtime/ucs2length").default'});var Yy=q(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});var Or=re(),mP=pe(),fP=Jy(),gP={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Or.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Or._)`{limit: ${e}}`},yP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:gP,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?Or.operators.GT:Or.operators.LT,i=o.opts.unicode===!1?(0,Or._)`${r}.length`:(0,Or._)`${(0,mP.useFunc)(e.gen,fP.default)}(${r})`;e.fail$data((0,Or._)`${i} ${s} ${n}`)}};md.default=yP});var Xy=q(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var bP=mt(),wP=pe(),yn=re(),vP={message:({schemaCode:e})=>(0,yn.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,yn._)`{pattern: ${e}}`},_P={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:vP,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,yn._)`new RegExp`:(0,wP.useFunc)(t,l),p=t.let("valid");t.try(()=>t.assign(p,(0,yn._)`${u}(${s}, ${a}).test(${r})`),()=>t.assign(p,!1)),e.fail$data((0,yn._)`!${p}`)}else{let l=(0,bP.usePattern)(e,o);e.fail$data((0,yn._)`!${l}.test(${r})`)}}};fd.default=_P});var Zy=q(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var xo=re(),SP={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,xo.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,xo._)`{limit: ${e}}`},kP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:SP,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?xo.operators.GT:xo.operators.LT;e.fail$data((0,xo._)`Object.keys(${r}).length ${o} ${n}`)}};gd.default=kP});var Qy=q(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var To=mt(),Ro=re(),xP=pe(),TP={message:({params:{missingProperty:e}})=>(0,Ro.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Ro._)`{missingProperty: ${e}}`},RP={keyword:"required",type:"object",schemaType:"array",$data:!0,error:TP,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let y=e.parentSchema.properties,{definedProperties:k}=e.it;for(let R of r)if(y?.[R]===void 0&&!k.has(R)){let $=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${R}" is not defined at "${$}" (strictRequired)`;(0,xP.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||s)e.block$data(Ro.nil,g);else for(let y of r)(0,To.checkReportMissingProp)(e,y)}function p(){let y=t.let("missing");if(l||s){let k=t.let("valid",!0);e.block$data(k,()=>x(y,k)),e.ok(k)}else t.if((0,To.checkMissingProp)(e,r,y)),(0,To.reportMissingProp)(e,y),t.else()}function g(){t.forOf("prop",n,y=>{e.setParams({missingProperty:y}),t.if((0,To.noPropertyInData)(t,o,y,a.ownProperties),()=>e.error())})}function x(y,k){e.setParams({missingProperty:y}),t.forOf(y,n,()=>{t.assign(k,(0,To.propertyInData)(t,o,y,a.ownProperties)),t.if((0,Ro.not)(k),()=>{e.error(),t.break()})},Ro.nil)}}};yd.default=RP});var eb=q(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var $o=re(),$P={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,$o.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,$o._)`{limit: ${e}}`},EP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:$P,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?$o.operators.GT:$o.operators.LT;e.fail$data((0,$o._)`${r}.length ${o} ${n}`)}};bd.default=EP});var Ci=q(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var tb=Dc();tb.code='require("ajv/dist/runtime/equal").default';wd.default=tb});var rb=q(_d=>{"use strict";Object.defineProperty(_d,"__esModule",{value:!0});var vd=po(),Me=re(),PP=pe(),AP=Ci(),CP={message:({params:{i:e,j:t}})=>(0,Me.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Me._)`{i: ${e}, j: ${t}}`},IP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:CP,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!n&&!o)return;let l=t.let("valid"),u=s.items?(0,vd.getSchemaTypes)(s.items):[];e.block$data(l,p,(0,Me._)`${i} === false`),e.ok(l);function p(){let k=t.let("i",(0,Me._)`${r}.length`),R=t.let("j");e.setParams({i:k,j:R}),t.assign(l,!0),t.if((0,Me._)`${k} > 1`,()=>(g()?x:y)(k,R))}function g(){return u.length>0&&!u.some(k=>k==="object"||k==="array")}function x(k,R){let $=t.name("item"),P=(0,vd.checkDataTypes)(u,$,a.opts.strictNumbers,vd.DataType.Wrong),C=t.const("indices",(0,Me._)`{}`);t.for((0,Me._)`;${k}--;`,()=>{t.let($,(0,Me._)`${r}[${k}]`),t.if(P,(0,Me._)`continue`),u.length>1&&t.if((0,Me._)`typeof ${$} == "string"`,(0,Me._)`${$} += "_"`),t.if((0,Me._)`typeof ${C}[${$}] == "number"`,()=>{t.assign(R,(0,Me._)`${C}[${$}]`),e.error(),t.assign(l,!1).break()}).code((0,Me._)`${C}[${$}] = ${k}`)})}function y(k,R){let $=(0,PP.useFunc)(t,AP.default),P=t.name("outer");t.label(P).for((0,Me._)`;${k}--;`,()=>t.for((0,Me._)`${R} = ${k}; ${R}--;`,()=>t.if((0,Me._)`${$}(${r}[${k}], ${r}[${R}])`,()=>{e.error(),t.assign(l,!1).break(P)})))}}};_d.default=IP});var nb=q(kd=>{"use strict";Object.defineProperty(kd,"__esModule",{value:!0});var Sd=re(),OP=pe(),NP=Ci(),LP={message:"must be equal to constant",params:({schemaCode:e})=>(0,Sd._)`{allowedValue: ${e}}`},jP={keyword:"const",$data:!0,error:LP,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,Sd._)`!${(0,OP.useFunc)(t,NP.default)}(${r}, ${o})`):e.fail((0,Sd._)`${s} !== ${r}`)}};kd.default=jP});var ob=q(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var Eo=re(),DP=pe(),UP=Ci(),MP={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Eo._)`{allowedValues: ${e}}`},qP={keyword:"enum",schemaType:"array",$data:!0,error:MP,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e;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,DP.useFunc)(t,UP.default)),p;if(a||n)p=t.let("valid"),e.block$data(p,g);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=t.const("vSchema",s);p=(0,Eo.or)(...o.map((k,R)=>x(y,R)))}e.pass(p);function g(){t.assign(p,!1),t.forOf("v",s,y=>t.if((0,Eo._)`${u()}(${r}, ${y})`,()=>t.assign(p,!0).break()))}function x(y,k){let R=o[k];return typeof R=="object"&&R!==null?(0,Eo._)`${u()}(${r}, ${y}[${k}])`:(0,Eo._)`${r} === ${R}`}}};xd.default=qP});var sb=q(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var zP=Ky(),BP=Wy(),FP=Yy(),HP=Xy(),VP=Zy(),KP=Qy(),WP=eb(),GP=rb(),JP=nb(),YP=ob(),XP=[zP.default,BP.default,FP.default,HP.default,VP.default,KP.default,WP.default,GP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},JP.default,YP.default];Td.default=XP});var $d=q(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.validateAdditionalItems=void 0;var Nr=re(),Rd=pe(),ZP={message:({params:{len:e}})=>(0,Nr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Nr._)`{limit: ${e}}`},QP={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:ZP,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Rd.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ib(e,n)}};function ib(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,Nr._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Nr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,Rd.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Nr._)`${a} <= ${t.length}`);r.if((0,Nr.not)(u),()=>l(u)),e.ok(u)}function l(u){r.forRange("i",t.length,a,p=>{e.subschema({keyword:s,dataProp:p,dataPropType:Rd.Type.Num},u),i.allErrors||r.if((0,Nr.not)(u),()=>r.break())})}}Po.validateAdditionalItems=ib;Po.default=QP});var Ed=q(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.validateTuple=void 0;var ab=re(),Ii=pe(),eA=mt(),tA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return lb(e,"additionalItems",t);r.items=!0,!(0,Ii.alwaysValidSchema)(r,t)&&e.ok((0,eA.validateArray)(e))}};function lb(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ii.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),u=n.const("len",(0,ab._)`${s}.length`);r.forEach((g,x)=>{(0,Ii.alwaysValidSchema)(a,g)||(n.if((0,ab._)`${u} > ${x}`,()=>e.subschema({keyword:i,schemaProp:x,dataProp:x},l)),e.ok(l))});function p(g){let{opts:x,errSchemaPath:y}=a,k=r.length,R=k===g.minItems&&(k===g.maxItems||g[t]===!1);if(x.strictTuples&&!R){let $=`"${i}" is ${k}-tuple, but minItems or maxItems/${t} are not specified or different at path "${y}"`;(0,Ii.checkStrictMode)(a,$,x.strictTuples)}}}Ao.validateTuple=lb;Ao.default=tA});var cb=q(Pd=>{"use strict";Object.defineProperty(Pd,"__esModule",{value:!0});var rA=Ed(),nA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,rA.validateTuple)(e,"items")};Pd.default=nA});var ub=q(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var db=re(),oA=pe(),sA=mt(),iA=$d(),aA={message:({params:{len:e}})=>(0,db.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,db._)`{limit: ${e}}`},lA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:aA,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,oA.alwaysValidSchema)(n,t)&&(o?(0,iA.validateAdditionalItems)(e,o):e.ok((0,sA.validateArray)(e)))}};Ad.default=lA});var pb=q(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var gt=re(),Oi=pe(),cA={message:({params:{min:e,max:t}})=>t===void 0?(0,gt.str)`must contain at least ${e} valid item(s)`:(0,gt.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,gt._)`{minContains: ${e}}`:(0,gt._)`{minContains: ${e}, maxContains: ${t}}`},dA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:cA,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:l,maxContains:u}=n;s.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=t.const("len",(0,gt._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Oi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Oi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Oi.alwaysValidSchema)(s,r)){let R=(0,gt._)`${p} >= ${i}`;a!==void 0&&(R=(0,gt._)`${R} && ${p} <= ${a}`),e.pass(R);return}s.items=!0;let g=t.name("valid");a===void 0&&i===1?y(g,()=>t.if(g,()=>t.break())):i===0?(t.let(g,!0),a!==void 0&&t.if((0,gt._)`${o}.length > 0`,x)):(t.let(g,!1),x()),e.result(g,()=>e.reset());function x(){let R=t.name("_valid"),$=t.let("count",0);y(R,()=>t.if(R,()=>k($)))}function y(R,$){t.forRange("i",0,p,P=>{e.subschema({keyword:"contains",dataProp:P,dataPropType:Oi.Type.Num,compositeRule:!0},R),$()})}function k(R){t.code((0,gt._)`${R}++`),a===void 0?t.if((0,gt._)`${R} >= ${i}`,()=>t.assign(g,!0).break()):(t.if((0,gt._)`${R} > ${a}`,()=>t.assign(g,!1).break()),i===1?t.assign(g,!0):t.if((0,gt._)`${R} >= ${i}`,()=>t.assign(g,!0)))}}};Cd.default=dA});var fb=q(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.validateSchemaDeps=Lt.validatePropertyDeps=Lt.error=void 0;var Id=re(),uA=pe(),Co=mt();Lt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Id.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Id._)`{property: ${e},
|
|
2458
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function x$({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,te._)`${t} !== undefined`,()=>e.assign((0,te._)`${t}[${r}]`,n))}function Ic(e,t,r,n=dn.Correct){let o=n===dn.Correct?te.operators.EQ:te.operators.NEQ,s;switch(e){case"null":return(0,te._)`${t} ${o} null`;case"array":s=(0,te._)`Array.isArray(${t})`;break;case"object":s=(0,te._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,te._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${t} ${o} ${e}`}return n===dn.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${t} == "number"`,a,r?(0,te._)`isFinite(${t})`:te.nil)}}Fe.checkDataType=Ic;function Oc(e,t,r,n){if(e.length===1)return Ic(e[0],t,r,n);let o,s=(0,Sg.toHash)(e);if(s.array&&s.object){let i=(0,te._)`typeof ${t} != "object"`;o=s.null?i:(0,te._)`!${t} || ${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,Ic(i,t,r,n));return o}Fe.checkDataTypes=Oc;var T$={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,te._)`{type: ${e}}`:(0,te._)`{type: ${t}}`};function Nc(e){let t=R$(e);(0,w$.reportError)(t,T$)}Fe.reportTypeError=Nc;function R$(e){let{gen:t,data:r,schema:n}=e,o=(0,Sg.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:e}}});var Rg=q(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.assignDefaults=void 0;var un=re(),$$=pe();function E$(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let o in r)Tg(e,o,r[o].default);else t==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Tg(e,s,o.default))}pi.assignDefaults=E$;function Tg(e,t,r){let{gen:n,compositeRule:o,data:s,opts:i}=e;if(r===void 0)return;let a=(0,un._)`${s}${(0,un.getProperty)(t)}`;if(o){(0,$$.checkStrictMode)(e,`default is ignored for: ${a}`);return}let l=(0,un._)`${a} === undefined`;i.useDefaults==="empty"&&(l=(0,un._)`${l} || ${a} === null || ${a} === ""`),n.if(l,(0,un._)`${a} = ${(0,un.stringify)(r)}`)}});var mt=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(),Lc=pe(),lr=Vt(),P$=pe();function A$(e,t){let{gen:r,data:n,it:o}=e;r.if(Dc(r,n,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,_e._)`${t}`},!0),e.error()})}ye.checkReportMissingProp=A$;function C$({gen:e,data:t,it:{opts:r}},n,o){return(0,_e.or)(...n.map(s=>(0,_e.and)(Dc(e,t,s,r.ownProperties),(0,_e._)`${o} = ${s}`)))}ye.checkMissingProp=C$;function I$(e,t){e.setParams({missingProperty:t},!0),e.error()}ye.reportMissingProp=I$;function $g(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,_e._)`Object.prototype.hasOwnProperty`})}ye.hasPropFunc=$g;function jc(e,t,r){return(0,_e._)`${$g(e)}.call(${t}, ${r})`}ye.isOwnProperty=jc;function O$(e,t,r,n){let o=(0,_e._)`${t}${(0,_e.getProperty)(r)} !== undefined`;return n?(0,_e._)`${o} && ${jc(e,t,r)}`:o}ye.propertyInData=O$;function Dc(e,t,r,n){let o=(0,_e._)`${t}${(0,_e.getProperty)(r)} === undefined`;return n?(0,_e.or)(o,(0,_e.not)(jc(e,t,r))):o}ye.noPropertyInData=Dc;function Eg(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}ye.allSchemaProperties=Eg;function N$(e,t){return Eg(t).filter(r=>!(0,Lc.alwaysValidSchema)(e,t[r]))}ye.schemaProperties=N$;function L$({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,l,u){let p=u?(0,_e._)`${e}, ${t}, ${n}${o}`:t,g=[[lr.default.instancePath,(0,_e.strConcat)(lr.default.instancePath,s)],[lr.default.parentData,i.parentData],[lr.default.parentDataProperty,i.parentDataProperty],[lr.default.rootData,lr.default.rootData]];i.opts.dynamicRef&&g.push([lr.default.dynamicAnchors,lr.default.dynamicAnchors]);let x=(0,_e._)`${p}, ${r.object(...g)}`;return l!==_e.nil?(0,_e._)`${a}.call(${l}, ${x})`:(0,_e._)`${a}(${x})`}ye.callValidateCode=L$;var j$=(0,_e._)`new RegExp`;function D$({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(r,n);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,_e._)`${o.code==="new RegExp"?j$:(0,P$.useFunc)(e,o)}(${r}, ${n})`})}ye.usePattern=D$;function U$(e){let{gen:t,data:r,keyword:n,it:o}=e,s=t.name("valid");if(o.allErrors){let a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){let l=t.const("len",(0,_e._)`${r}.length`);t.forRange("i",0,l,u=>{e.subschema({keyword:n,dataProp:u,dataPropType:Lc.Type.Num},s),t.if((0,_e.not)(s),a)})}}ye.validateArray=U$;function M$(e){let{gen:t,schema:r,keyword:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(l=>(0,Lc.alwaysValidSchema)(o,l))&&!o.opts.unevaluated)return;let i=t.let("valid",!1),a=t.name("_valid");t.block(()=>r.forEach((l,u)=>{let p=e.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);t.assign(i,(0,_e._)`${i} || ${a}`),e.mergeValidEvaluated(p,a)||t.if((0,_e.not)(i))})),e.result(i,()=>e.reset(),()=>e.error(!0))}ye.validateUnion=M$});var Cg=q(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.validateKeywordUsage=Ot.validSchemaType=Ot.funcKeywordCode=Ot.macroKeywordCode=void 0;var Ge=re(),Er=Vt(),q$=mt(),z$=uo();function B$(e,t){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),l=Ag(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");e.subschema({schema:a,schemaPath:Ge.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:l,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Ot.macroKeywordCode=B$;function F$(e,t){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:l}=e;V$(l,t);let u=!a&&t.compile?t.compile.call(l.self,s,i,l):t.validate,p=Ag(n,o,u),g=n.let("valid");e.block$data(g,x),e.ok((r=t.valid)!==null&&r!==void 0?r:g);function x(){if(t.errors===!1)T(),t.modifying&&Pg(e),$(()=>e.error());else{let P=t.async?y():k();t.modifying&&Pg(e),$(()=>H$(e,P))}}function y(){let P=n.let("ruleErrs",null);return n.try(()=>T((0,Ge._)`await `),C=>n.assign(g,!1).if((0,Ge._)`${C} instanceof ${l.ValidationError}`,()=>n.assign(P,(0,Ge._)`${C}.errors`),()=>n.throw(C))),P}function k(){let P=(0,Ge._)`${p}.errors`;return n.assign(P,null),T(Ge.nil),P}function T(P=t.async?(0,Ge._)`await `:Ge.nil){let C=l.opts.passContext?Er.default.this:Er.default.self,j=!("compile"in t&&!a||t.schema===!1);n.assign(g,(0,Ge._)`${P}${(0,q$.callValidateCode)(e,p,C,j)}`,t.modifying)}function $(P){var C;n.if((0,Ge.not)((C=t.valid)!==null&&C!==void 0?C:g),P)}}Ot.funcKeywordCode=F$;function Pg(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Ge._)`${n.parentData}[${n.parentDataProperty}]`))}function H$(e,t){let{gen:r}=e;r.if((0,Ge._)`Array.isArray(${t})`,()=>{r.assign(Er.default.vErrors,(0,Ge._)`${Er.default.vErrors} === null ? ${t} : ${Er.default.vErrors}.concat(${t})`).assign(Er.default.errors,(0,Ge._)`${Er.default.vErrors}.length`),(0,z$.extendErrors)(e)},()=>e.error())}function V$({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Ag(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ge.stringify)(r)})}function K$(e,t,r=!1){return!t.length||t.some(n=>n==="array"?Array.isArray(e):n==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==n||r&&typeof e>"u")}Ot.validSchemaType=K$;function W$({schema:e,opts:t,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(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){let l=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")r.logger.error(l);else throw new Error(l)}}Ot.validateKeywordUsage=W$});var Og=q(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.extendSubschemaMode=cr.extendSubschemaData=cr.getSubschema=void 0;var Nt=re(),Ig=pe();function G$(e,{keyword:t,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let a=e.schema[t];return r===void 0?{schema:a,schemaPath:(0,Nt._)`${e.schemaPath}${(0,Nt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[r],schemaPath:(0,Nt._)`${e.schemaPath}${(0,Nt.getProperty)(t)}${(0,Nt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Ig.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')}cr.getSubschema=G$;function J$(e,t,{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}=t;if(r!==void 0){let{errorPath:u,dataPathArr:p,opts:g}=t,x=a.let("data",(0,Nt._)`${t.data}${(0,Nt.getProperty)(r)}`,!0);l(x),e.errorPath=(0,Nt.str)`${u}${(0,Ig.getErrorPath)(r,n,g.jsPropertySyntax)}`,e.parentDataProperty=(0,Nt._)`${r}`,e.dataPathArr=[...p,e.parentDataProperty]}if(o!==void 0){let u=o instanceof Nt.Name?o:a.let("data",o,!0);l(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function l(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}cr.extendSubschemaData=J$;function Y$(e,{jtdDiscriminator:t,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(e.compositeRule=n),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=r}cr.extendSubschemaMode=Y$});var Uc=q((FU,Ng)=>{"use strict";Ng.exports=function e(t,r){if(t===r)return!0;if(t&&r&&typeof t=="object"&&typeof r=="object"){if(t.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(t)){if(n=t.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!e(t[o],r[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===r.source&&t.flags===r.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===r.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===r.toString();if(s=Object.keys(t),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(!e(t[i],r[i]))return!1}return!0}return t!==t&&r!==r}});var jg=q((HU,Lg)=>{"use strict";var dr=Lg.exports=function(e,t,r){typeof t=="function"&&(r=t,t={}),r=t.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};hi(t,n,o,e,"",e)};dr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};dr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};dr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};dr.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 hi(e,t,r,n,o,s,i,a,l,u){if(n&&typeof n=="object"&&!Array.isArray(n)){t(n,o,s,i,a,l,u);for(var p in n){var g=n[p];if(Array.isArray(g)){if(p in dr.arrayKeywords)for(var x=0;x<g.length;x++)hi(e,t,r,g[x],o+"/"+p+"/"+x,s,o,p,n,x)}else if(p in dr.propsKeywords){if(g&&typeof g=="object")for(var y in g)hi(e,t,r,g[y],o+"/"+p+"/"+X$(y),s,o,p,n,y)}else(p in dr.keywords||e.allKeys&&!(p in dr.skipKeywords))&&hi(e,t,r,g,o+"/"+p,s,o,p,n)}r(n,o,s,i,a,l,u)}}function X$(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}});var ho=q(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var Z$=pe(),Q$=Uc(),eE=jg(),tE=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function rE(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Mc(e):t?Dg(e)<=t:!1}et.inlineRef=rE;var nE=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Mc(e){for(let t in e){if(nE.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Mc)||typeof r=="object"&&Mc(r))return!0}return!1}function Dg(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!tE.has(r)&&(typeof e[r]=="object"&&(0,Z$.eachItem)(e[r],n=>t+=Dg(n)),t===1/0))return 1/0}return t}function Ug(e,t="",r){r!==!1&&(t=pn(t));let n=e.parse(t);return Mg(e,n)}et.getFullPath=Ug;function Mg(e,t){return e.serialize(t).split("#")[0]+"#"}et._getFullPath=Mg;var oE=/#\/?$/;function pn(e){return e?e.replace(oE,""):""}et.normalizeId=pn;function sE(e,t,r){return r=pn(r),e.resolve(t,r)}et.resolveUrl=sE;var iE=/^[a-z_][-a-z0-9._]*$/i;function aE(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=pn(e[r]||t),s={"":o},i=Ug(n,o,!1),a={},l=new Set;return eE(e,{allKeys:!0},(g,x,y,k)=>{if(k===void 0)return;let T=i+x,$=s[k];typeof g[r]=="string"&&($=P.call(this,g[r])),C.call(this,g.$anchor),C.call(this,g.$dynamicAnchor),s[x]=$;function P(j){let H=this.opts.uriResolver.resolve;if(j=pn($?H($,j):j),l.has(j))throw p(j);l.add(j);let G=this.refs[j];return typeof G=="string"&&(G=this.refs[G]),typeof G=="object"?u(g,G.schema,j):j!==pn(T)&&(j[0]==="#"?(u(g,a[j],j),a[j]=g):this.refs[j]=T),j}function C(j){if(typeof j=="string"){if(!iE.test(j))throw new Error(`invalid anchor "${j}"`);P.call(this,`#${j}`)}}}),a;function u(g,x,y){if(x!==void 0&&!Q$(g,x))throw p(y)}function p(g){return new Error(`reference "${g}" resolves to more than one schema`)}}et.getSchemaRefs=aE});var go=q(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.getData=ur.KeywordCxt=ur.validateFunctionCode=void 0;var Hg=wg(),qg=po(),zc=Cc(),mi=po(),lE=Rg(),fo=Cg(),qc=Og(),K=re(),ee=Vt(),cE=ho(),Kt=pe(),mo=uo();function dE(e){if(Wg(e)&&(Gg(e),Kg(e))){hE(e);return}Vg(e,()=>(0,Hg.topBoolOrEmptySchema)(e))}ur.validateFunctionCode=dE;function Vg({gen:e,validateName:t,schema:r,schemaEnv:n,opts:o},s){o.code.es5?e.func(t,(0,K._)`${ee.default.data}, ${ee.default.valCxt}`,n.$async,()=>{e.code((0,K._)`"use strict"; ${zg(r,o)}`),pE(e,o),e.code(s)}):e.func(t,(0,K._)`${ee.default.data}, ${uE(o)}`,n.$async,()=>e.code(zg(r,o)).code(s))}function uE(e){return(0,K._)`{${ee.default.instancePath}="", ${ee.default.parentData}, ${ee.default.parentDataProperty}, ${ee.default.rootData}=${ee.default.data}${e.dynamicRef?(0,K._)`, ${ee.default.dynamicAnchors}={}`:K.nil}}={}`}function pE(e,t){e.if(ee.default.valCxt,()=>{e.var(ee.default.instancePath,(0,K._)`${ee.default.valCxt}.${ee.default.instancePath}`),e.var(ee.default.parentData,(0,K._)`${ee.default.valCxt}.${ee.default.parentData}`),e.var(ee.default.parentDataProperty,(0,K._)`${ee.default.valCxt}.${ee.default.parentDataProperty}`),e.var(ee.default.rootData,(0,K._)`${ee.default.valCxt}.${ee.default.rootData}`),t.dynamicRef&&e.var(ee.default.dynamicAnchors,(0,K._)`${ee.default.valCxt}.${ee.default.dynamicAnchors}`)},()=>{e.var(ee.default.instancePath,(0,K._)`""`),e.var(ee.default.parentData,(0,K._)`undefined`),e.var(ee.default.parentDataProperty,(0,K._)`undefined`),e.var(ee.default.rootData,ee.default.data),t.dynamicRef&&e.var(ee.default.dynamicAnchors,(0,K._)`{}`)})}function hE(e){let{schema:t,opts:r,gen:n}=e;Vg(e,()=>{r.$comment&&t.$comment&&Yg(e),bE(e),n.let(ee.default.vErrors,null),n.let(ee.default.errors,0),r.unevaluated&&mE(e),Jg(e),_E(e)})}function mE(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,K._)`${r}.evaluated`),t.if((0,K._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,K._)`${e.evaluated}.props`,(0,K._)`undefined`)),t.if((0,K._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,K._)`${e.evaluated}.items`,(0,K._)`undefined`))}function zg(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,K._)`/*# sourceURL=${r} */`:K.nil}function fE(e,t){if(Wg(e)&&(Gg(e),Kg(e))){gE(e,t);return}(0,Hg.boolOrEmptySchema)(e,t)}function Kg({schema:e,self:t}){if(typeof e=="boolean")return!e;for(let r in e)if(t.RULES.all[r])return!0;return!1}function Wg(e){return typeof e.schema!="boolean"}function gE(e,t){let{schema:r,gen:n,opts:o}=e;o.$comment&&r.$comment&&Yg(e),wE(e),vE(e);let s=n.const("_errs",ee.default.errors);Jg(e,s),n.var(t,(0,K._)`${s} === ${ee.default.errors}`)}function Gg(e){(0,Kt.checkUnknownRules)(e),yE(e)}function Jg(e,t){if(e.opts.jtd)return Bg(e,[],!1,t);let r=(0,qg.getSchemaTypes)(e.schema),n=(0,qg.coerceAndCheckDataType)(e,r);Bg(e,r,!n,t)}function yE(e){let{schema:t,errSchemaPath:r,opts:n,self:o}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Kt.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function bE(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Kt.checkStrictMode)(e,"default is ignored in the schema root")}function wE(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,cE.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function vE(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function Yg({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)e.code((0,K._)`${ee.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,K.str)`${n}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,K._)`${ee.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function _E(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=e;r.$async?t.if((0,K._)`${ee.default.errors} === 0`,()=>t.return(ee.default.data),()=>t.throw((0,K._)`new ${o}(${ee.default.vErrors})`)):(t.assign((0,K._)`${n}.errors`,ee.default.vErrors),s.unevaluated&&SE(e),t.return((0,K._)`${ee.default.errors} === 0`))}function SE({gen:e,evaluated:t,props:r,items:n}){r instanceof K.Name&&e.assign((0,K._)`${t}.props`,r),n instanceof K.Name&&e.assign((0,K._)`${t}.items`,n)}function Bg(e,t,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:l,self:u}=e,{RULES:p}=u;if(s.$ref&&(l.ignoreKeywordsWithRef||!(0,Kt.schemaHasRulesButRef)(s,p))){o.block(()=>Zg(e,"$ref",p.all.$ref.definition));return}l.jtd||kE(e,t),o.block(()=>{for(let x of p.rules)g(x);g(p.post)});function g(x){(0,zc.shouldUseGroup)(s,x)&&(x.type?(o.if((0,mi.checkDataType)(x.type,i,l.strictNumbers)),Fg(e,x),t.length===1&&t[0]===x.type&&r&&(o.else(),(0,mi.reportTypeError)(e)),o.endIf()):Fg(e,x),a||o.if((0,K._)`${ee.default.errors} === ${n||0}`))}}function Fg(e,t){let{gen:r,schema:n,opts:{useDefaults:o}}=e;o&&(0,lE.assignDefaults)(e,t.type),r.block(()=>{for(let s of t.rules)(0,zc.shouldUseRule)(n,s)&&Zg(e,s.keyword,s.definition,t.type)})}function kE(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(xE(e,t),e.opts.allowUnionTypes||TE(e,t),RE(e,e.dataTypes))}function xE(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{Xg(e.dataTypes,r)||Bc(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),EE(e,t)}}function TE(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Bc(e,"use allowUnionTypes to allow union type keyword")}function RE(e,t){let r=e.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,zc.shouldUseRule)(e.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>$E(t,i))&&Bc(e,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function $E(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function Xg(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function EE(e,t){let r=[];for(let n of e.dataTypes)Xg(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}function Bc(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Kt.checkStrictMode)(e,t,e.opts.strictTypes)}var fi=class{constructor(t,r,n){if((0,fo.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Kt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",Qg(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,fo.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=t.gen.const("_errs",ee.default.errors))}result(t,r,n){this.failResult((0,K.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,K.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,K._)`${r} !== undefined && (${(0,K.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?mo.reportExtraError:mo.reportError)(this,this.def.error,r)}$dataError(){(0,mo.reportError)(this,this.def.$dataError||mo.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,mo.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=K.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=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)),t!==K.nil&&n.assign(t,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==K.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,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,mi.checkDataTypes)(l,r,s.opts.strictNumbers,mi.DataType.Wrong)}`}return K.nil}function a(){if(o.validateSchema){let l=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,K._)`!${l}(${r})`}return K.nil}}subschema(t,r){let n=(0,qc.getSubschema)(this.it,t);(0,qc.extendSubschemaData)(n,this.it,t),(0,qc.extendSubschemaMode)(n,t);let o={...this.it,...n,items:void 0,props:void 0};return fE(o,r),o}mergeEvaluated(t,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Kt.mergeEvaluated.props(o,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Kt.mergeEvaluated.items(o,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(t,K.Name)),!0}};ur.KeywordCxt=fi;function Zg(e,t,r,n){let o=new fi(e,r,t);"code"in r?r.code(o,n):o.$data&&r.validate?(0,fo.funcKeywordCode)(o,r):"macro"in r?(0,fo.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,fo.funcKeywordCode)(o,r)}var PE=/^\/(?:[^~]|~0|~1)*$/,AE=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Qg(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let o,s;if(e==="")return ee.default.rootData;if(e[0]==="/"){if(!PE.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=ee.default.rootData}else{let u=AE.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);let p=+u[1];if(o=u[2],o==="#"){if(p>=t)throw new Error(l("property/index",p));return n[t-p]}if(p>t)throw new Error(l("data",p));if(s=r[t-p],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,K._)`${s}${(0,K.getProperty)((0,Kt.unescapeJsonPointer)(u))}`,i=(0,K._)`${i} && ${s}`);return i;function l(u,p){return`Cannot access ${u} ${p} levels up, current level is ${t}`}}ur.getData=Qg});var gi=q(Hc=>{"use strict";Object.defineProperty(Hc,"__esModule",{value:!0});var Fc=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Hc.default=Fc});var yo=q(Wc=>{"use strict";Object.defineProperty(Wc,"__esModule",{value:!0});var Vc=ho(),Kc=class extends Error{constructor(t,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Vc.resolveUrl)(t,r,n),this.missingSchema=(0,Vc.normalizeId)((0,Vc.getFullPath)(t,this.missingRef))}};Wc.default=Kc});var bi=q(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.resolveSchema=ft.getCompilingSchema=ft.resolveRef=ft.compileSchema=ft.SchemaEnv=void 0;var xt=re(),CE=gi(),Pr=Vt(),Tt=ho(),ey=pe(),IE=go(),hn=class{constructor(t){var r;this.refs={},this.dynamicAnchors={};let n;typeof t.schema=="object"&&(n=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(r=t.baseId)!==null&&r!==void 0?r:(0,Tt.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};ft.SchemaEnv=hn;function Jc(e){let t=ty.call(this,e);if(t)return t;let r=(0,Tt.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new xt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;e.$async&&(a=i.scopeValue("Error",{ref:CE.default,code:(0,xt._)`require("ajv/dist/runtime/validation_error").default`}));let l=i.scopeName("validate");e.validateName=l;let u={gen:i,allErrors:this.opts.allErrors,data:Pr.default.data,parentData:Pr.default.parentData,parentDataProperty:Pr.default.parentDataProperty,dataNames:[Pr.default.data],dataPathArr:[xt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,xt.stringify)(e.schema)}:{ref:e.schema}),validateName:l,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:xt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,xt._)`""`,opts:this.opts,self:this},p;try{this._compilations.add(e),(0,IE.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let g=i.toString();p=`${i.scopeRefs(Pr.default.scope)}return ${g}`,this.opts.code.process&&(p=this.opts.code.process(p,e));let y=new Function(`${Pr.default.self}`,`${Pr.default.scope}`,p)(this,this.scope.get());if(this.scope.value(l,{ref:y}),y.errors=null,y.schema=e.schema,y.schemaEnv=e,e.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:l,validateCode:g,scopeValues:i._values}),this.opts.unevaluated){let{props:k,items:T}=u;y.evaluated={props:k instanceof xt.Name?void 0:k,items:T instanceof xt.Name?void 0:T,dynamicProps:k instanceof xt.Name,dynamicItems:T instanceof xt.Name},y.source&&(y.source.evaluated=(0,xt.stringify)(y.evaluated))}return e.validate=y,e}catch(g){throw delete e.validate,delete e.validateName,p&&this.logger.error("Error compiling schema, function code:",p),g}finally{this._compilations.delete(e)}}ft.compileSchema=Jc;function OE(e,t,r){var n;r=(0,Tt.resolveUrl)(this.opts.uriResolver,t,r);let o=e.refs[r];if(o)return o;let s=jE.call(this,e,r);if(s===void 0){let i=(n=e.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new hn({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[r]=NE.call(this,s)}ft.resolveRef=OE;function NE(e){return(0,Tt.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Jc.call(this,e)}function ty(e){for(let t of this._compilations)if(LE(t,e))return t}ft.getCompilingSchema=ty;function LE(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function jE(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||yi.call(this,e,t)}function yi(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Tt._getFullPath)(this.opts.uriResolver,r),o=(0,Tt.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===o)return Gc.call(this,r,e);let s=(0,Tt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=yi.call(this,e,i);return typeof a?.schema!="object"?void 0:Gc.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Jc.call(this,i),s===(0,Tt.normalizeId)(t)){let{schema:a}=i,{schemaId:l}=this.opts,u=a[l];return u&&(o=(0,Tt.resolveUrl)(this.opts.uriResolver,o,u)),new hn({schema:a,schemaId:l,root:e,baseId:o})}return Gc.call(this,r,i)}}ft.resolveSchema=yi;var DE=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Gc(e,{baseId:t,schema:r,root:n}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let l=r[(0,ey.unescapeFragment)(a)];if(l===void 0)return;r=l;let u=typeof r=="object"&&r[this.opts.schemaId];!DE.has(a)&&u&&(t=(0,Tt.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,ey.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Tt.resolveUrl)(this.opts.uriResolver,t,r.$ref);s=yi.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new hn({schema:r,schemaId:i,root:n,baseId:t}),s.schema!==s.root.schema)return s}});var ry=q((YU,UE)=>{UE.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 td=q((XU,dy)=>{"use strict";var ME=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Xc=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),qE=RegExp.prototype.test.bind(/^\d*$/u),Ar=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Zc=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),oy=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Qc=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),zE=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),tt=new Array(256);{let e="0123456789ABCDEF";for(let t=0;t<256;t++)tt[t]="%"+e[t>>4]+e[t&15]}function He(e){return e<2048?tt[192|e>>6]+tt[128|e&63]:e<65536?tt[224|e>>12]+tt[128|e>>6&63]+tt[128|e&63]:tt[240|e>>18]+tt[128|e>>12&63]+tt[128|e>>6&63]+tt[128|e&63]}function BE(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}var FE=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),HE=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),VE=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),KE=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function WE(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!VE(e[t])){if(e[t]==="%"&&t+2<e.length&&Ar(e.slice(t+1,t+3))){t+=2;continue}return!1}return!0}function ny(e){let t=-1,r=0,n=-1,o=0;for(let a=0;a<e.length;a++)e[a]==="0"?(n===-1&&(n=a),o++,o>r&&(r=o,t=n)):(n=-1,o=0);if(r<2)return e.join(":");let s=e.slice(0,t).join(":"),i=e.slice(t+r).join(":");return s+"::"+i}function GE(e){let t=e.indexOf("::");if(t!==-1&&e.indexOf("::",t+1)!==-1)return;let r=t===-1?e.split(":"):e.slice(0,t).split(":"),n=t===-1?[]:e.slice(t+2).split(":");t!==-1&&(r.length===1&&r[0]===""&&(r.length=0),n.length===1&&n[0]===""&&(n.length=0));let o=r.concat(n),s=0;for(let a=0;a<o.length;a++){let l=o[a];if(l==="")return;if(l.indexOf(".")!==-1){if(a!==o.length-1||t!==-1&&n.length===0||!Xc(l))return;s+=2;continue}if(!FE(l))return;o[a]=parseInt(l,16).toString(16),s++}if(t===-1)return s!==8?void 0:ny(o);if(s>=8)return;let i=o.slice(0,r.length);for(let a=s;a<8;a++)i.push("0");for(let a=r.length;a<o.length;a++)i.push(o[a]);return ny(i)}function Yc(e){let t=e[0]==="["&&e[e.length-1]==="]";if((e[0]==="["||e[e.length-1]==="]")&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&HE(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(JE(n,":")<2)return{host:e,isIPV6:!1,error:t};let o="",s=n.indexOf("%");if(s!==-1){let a=n.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=n.slice(s+a),!WE(o))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,s)}let i=GE(n);return i===void 0?{host:e,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function JE(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}function sy(e){let t=e,r=[],n=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){r.push("/");break}else{r.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){r.push("/");break}}else if(o===3&&t==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),r.length!==0&&r.pop();continue}}if((n=t.indexOf("/",1))===-1){r.push(t);break}else r.push(t.slice(0,n)),t=t.slice(n)}return r.join("")}function YE(e){if(e===""||e[0]==="/")return sy(e);let t=e.split("/"),r=t.length-1,n=[],o=!1;for(let s=0;s<=r;s++){let i=t[s];i==="."||i===".."?(i===".."&&(n.length!==0&&n[n.length-1]!==".."?n.pop():n.push("..")),o=s===r):n.push(i)}return o&&n[n.length-1]!==".."&&n.push(""),(n.length===0||n[0]===""||n[0].includes(":"))&&n.unshift("."),n.join("/")}var XE={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},ZE=/[@/?#:]/g,QE=/[@/?#]/g;function iy(e,t){let r=t?QE:ZE;return r.lastIndex=0,e.replace(r,n=>XE[n])}function ay(e,t=!1){if(e.indexOf("%")===-1)return e;let r="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){let o=e.slice(n+1,n+3);if(Ar(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Zc(i)?r+=i:r+="%"+s,n+=2;continue}}r+=e[n]}return r}function e0(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let o=e.slice(r+1,r+3);if(Ar(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Zc(i)?t+=i:t+="%"+s,r+=2;continue}}if(oy(n))t+=n;else{let o=e.charCodeAt(r);if(o<128)t+=cy(o)?n:tt[o];else if(o<55296||o>57343)t+=He(o);else if(o<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343?(t+=He(65536+(o-55296<<10)+(s-56320)),r++):t+=He(65533)}else t+=He(65533)}}return t}function t0(e,t=!1){let r="",n=t&&e[0]!=="/";for(let o=0;o<e.length;o++){let s=e[o];if(s==="%"&&o+2<e.length){let i=e.slice(o+1,o+3);if(Ar(i)){r+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(n=!1),oy(s)&&(s!==":"||!n))r+=s;else{let i=e.charCodeAt(o);if(i<128)r+=tt[i];else if(i<55296||i>57343)r+=He(i);else if(i<=56319&&o+1<e.length){let a=e.charCodeAt(o+1);a>=56320&&a<=57343?(r+=He(65536+(i-55296<<10)+(a-56320)),o++):r+=He(65533)}else r+=He(65533)}}return r}function ed(e,t){let r="";for(let n=0;n<e.length;n++){let o=e[n];if(o==="%"&&n+2<e.length){let s=e.slice(n+1,n+3);if(Ar(s)){r+="%"+s.toUpperCase(),n+=2;continue}}if(t(o))r+=o;else{let s=e.charCodeAt(n);if(s<128)r+=tt[s];else if(s<55296||s>57343)r+=He(s);else if(s<=56319&&n+1<e.length){let i=e.charCodeAt(n+1);i>=56320&&i<=57343?(r+=He(65536+(s-55296<<10)+(i-56320)),n++):r+=He(65533)}else r+=He(65533)}}return r}function ly(e){return ed(e,zE)}function r0(e){return ed(e,Qc)}function n0(e){return ed(e,Qc)}function cy(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function o0(e){let t="";for(let r=0;r<e.length;r++){let n=e[r];if(n==="%"&&r+2<e.length){let o=e.slice(r+1,r+3);if(Ar(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Zc(i)?t+=i:t+="%"+s,r+=2;continue}}if(Qc(n))t+=n;else{let o=e.charCodeAt(r);if(o<128)t+=cy(o)?n:tt[o];else if(o<55296||o>57343)t+=He(o);else if(o<=56319&&r+1<e.length){let s=e.charCodeAt(r+1);s>=56320&&s<=57343?(t+=He(65536+(o-55296<<10)+(s-56320)),r++):t+=He(65533)}else t+=He(65533)}}return t}function s0(e){let t="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){let n=e.slice(r+1,r+3);if(Ar(n)){t+="%"+n.toUpperCase(),r+=2;continue}}t+=escape(e[r])}return t}function i0(e){let t=[];if(e.userinfo!==void 0&&(t.push(ly(e.userinfo)),t.push("@")),e.host!==void 0){let r=e.host;if(!Xc(r)){let n=Yc(r);n.isIPV6!==!0&&n.isIPVFuture!==!0&&(r=ay(r,!0),n=Yc(r)),n.isIPV6===!0||n.isIPVFuture===!0?r=`[${n.escapedHost}]`:r=iy(r,!1)}t.push(r)}if(typeof e.port=="number"||typeof e.port=="string"){let r=String(e.port);if(!qE(r))throw new TypeError("URI port is malformed.");t.push(":"),t.push(r)}return t.length?t.join(""):void 0}dy.exports={nonSimpleDomain:KE,recomposeAuthority:i0,reescapeHostDelimiters:iy,normalizePercentEncoding:ay,normalizePathEncoding:e0,serializePathEncoding:t0,normalizeQueryFragmentEncoding:o0,encodeUserinfo:ly,encodeQuery:r0,encodeFragment:n0,escapePreservingEscapes:s0,removeDotSegments:sy,removeDotSegmentsRelative:YE,isIPv4:Xc,isUUID:ME,normalizeIPv6:Yc,stringArrayToHexStripped:BE}});var fy=q((ZU,my)=>{"use strict";var{isUUID:a0}=td(),l0=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,c0=["http","https","ws","wss","urn","urn:uuid"];function d0(e){return c0.indexOf(e)!==-1}function rd(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function uy(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function py(e){let t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function u0(e){return e.secure=rd(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function p0(e){if((e.port===(rd(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let t=e.resourceName.indexOf("?"),r=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=r&&r!=="/"?r:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),e.resourceName=void 0}return e.fragment=void 0,e}function h0(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(l0);if(r&&r[0]===e.path){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let o=`${n}:${t.nid||e.nid}`,s=nd(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function m0(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),o=`${r}:${t.nid||n}`,s=nd(o);s&&(e=s.serialize(e,t));let i=e,a=e.nss;return i.path=`${n||t.nid}:${a}`,t.skipEscape=!0,i}function f0(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!a0(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function g0(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}var hy={scheme:"http",domainHost:!0,parse:uy,serialize:py},y0={scheme:"https",domainHost:hy.domainHost,parse:uy,serialize:py},wi={scheme:"ws",domainHost:!0,parse:u0,serialize:p0},b0={scheme:"wss",domainHost:wi.domainHost,parse:wi.parse,serialize:wi.serialize},w0={scheme:"urn",parse:h0,serialize:m0,skipNormalize:!0},v0={scheme:"urn:uuid",parse:f0,serialize:g0,skipNormalize:!0},vi={http:hy,https:y0,ws:wi,wss:b0,urn:w0,"urn:uuid":v0};Object.setPrototypeOf(vi,null);function nd(e){return e&&(vi[e]||vi[e.toLowerCase()])||void 0}my.exports={wsIsSecure:rd,SCHEMES:vi,isValidSchemeName:d0,getSchemeHandler:nd}});var Ay=q((QU,Ti)=>{"use strict";var{normalizeIPv6:vy,removeDotSegments:wo,removeDotSegmentsRelative:_y,recomposeAuthority:_0,normalizePercentEncoding:od,normalizePathEncoding:S0,serializePathEncoding:gy,normalizeQueryFragmentEncoding:yy,encodeQuery:k0,encodeFragment:x0,reescapeHostDelimiters:T0,isIPv4:Sy,nonSimpleDomain:R0}=td(),{SCHEMES:ky,getSchemeHandler:sd}=fy(),xy=/^[A-Za-z][A-Za-z0-9+.-]*$/u,Ty="URI scheme is malformed.",_i="URI host is malformed.",$0=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function by(e){let t=String(e);if(!xy.test(t))throw new TypeError(Ty);return t}function E0(e,t){return typeof e=="string"?e=D0(e,t):typeof e=="object"&&(e=ki(Cr(e,t),t)),e}function P0(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:l,malformedScheme:u}=Si(e,n),{parsed:p,malformedAuthorityOrPort:g,malformedPercentEncoding:x,malformedSchemeSpecific:y,malformedHost:k,malformedScheme:T}=Si(t,n);if(s||g||i||x||a||y||l||k||u||T)throw new Error(o.error||p.error||"URI is malformed.");let $=Ry(o,p,n,!0),P=sd(r&&r.scheme||$.scheme),C=$.host,j=C!==void 0&&C!==""&&(Sy(C)||vy(C).isIPV6);if(Ey($,r||{},P,j))throw new Error(_i);$y($,r||{},P,j);let H=C&&C.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(C);if($.error&&!H)throw new Error($.error);return n.skipEscape=!0,Cr($,n)}function Ry(e,t,r,n){let o={};if(n||(e=ki(Cr(e,r),r),t=ki(Cr(t,r),r)),r=r||{},!r.tolerant&&t.scheme)o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=wo(t.path||""),o.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=wo(t.path||""),o.query=t.query;else{if(!t.path)o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query;else{if(t.path[0]==="/")o.path=wo(t.path);else{let s=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;s&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=e.scheme===void 0&&!s&&o.path[0]!=="/"?_y(o.path):wo(o.path)}o.query=t.query}o.userinfo=e.userinfo,o.host=e.host,o.port=e.port}o.scheme=e.scheme}return o.fragment=t.fragment,o}function A0(e,t,r){let n=wy(e,r),o=wy(t,r);return n!==void 0&&o!==void 0&&n===o}function Cr(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),o=[];r.scheme&&(r.scheme=by(r.scheme));let s=sd(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n);let i=r.userinfo!==void 0||r.host!==void 0||r.port!==void 0,a=(r.scheme===void 0||n.reference==="suffix")&&!i,l=!n.skipEscape&&a;r.path!==void 0&&(n.skipEscape?r.path=od(r.path):r.path=gy(r.path,l)),n.reference!=="suffix"&&r.scheme&&(r.scheme=by(r.scheme),o.push(r.scheme,":"));let u=_0(r);if(u!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(u),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let p=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(p=a&&p[0]!=="/"?_y(p):wo(p)),a&&(p=gy(p,!0)),u===void 0&&p[0]==="/"&&p[1]==="/"&&(p="/%2F"+p.slice(2)),o.push(p)}return r.query!==void 0&&o.push("?",k0(r.query)),r.fragment!==void 0&&o.push("#",x0(r.fragment)),o.join("")}var C0=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,I0=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,O0=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function N0(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function bo(e){if(e===void 0)return!1;let t=e.indexOf("%");for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf("%",t+3)}return!1}function xi(e){return e[0]==="["&&e[e.length-1]==="]"}function L0(e){let t=e[4];return bo(e[3])||t!==void 0&&!xi(t)&&bo(t)||bo(e[6])||bo(e[7])||bo(e[8])}function $y(e,t,r,n){if(Ey(e,t,r,n))return e.error=e.error||_i,!0;if(!t.unicodeSupport&&(!r||!r.unicodeSupport)&&e.host&&!xi(e.host)&&(t.domainHost||r&&r.domainHost)&&n===!1&&R0(e.host)){let o;try{o=new URL("http://"+e.host)}catch(s){return e.error=e.error||"Host's domain name can not be converted to ASCII: "+s,!0}if(!j0(o))return e.error=e.error||_i,!0;e.host=o.hostname}return!1}function Ey(e,t,r,n){return!!(e.host&&n===!1&&!xi(e.host)&&(t.domainHost||r&&r.domainHost)&&$0.test(e.host))}function j0(e){return e.username===""&&e.password===""&&e.port===""&&e.pathname==="/"&&e.search===""&&e.hash===""&&e.hostname!==""}function Si(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,l=!1,u=!1,p=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let g=e.match(I0);g!==null&&g[1].indexOf("\\")!==-1&&(n.error="URI authority must not contain a literal backslash.",o=!0);let x=e.match(O0);if(x!==null){let k=x[1],T=k.replace(/[\t\n\r]/g,"");T.length>=2&&(T.slice(0,2)!=="//"?(n.error=n.error||"URI authority must not contain a literal backslash.",o=!0):k.length!==T.length&&(n.error=n.error||"URI authority introducer must not contain whitespace.",o=!0))}let y=e.match(C0);if(y){n.scheme=y[1],n.userinfo=y[3],n.host=y[4],n.port=parseInt(y[5],10),n.path=y[6]||"",n.query=y[7],n.fragment=y[8],n.scheme!==void 0&&(xy.test(n.scheme)?n.scheme=n.scheme.toLowerCase():(n.error=n.error||Ty,u=!0)),s=L0(y),s&&(n.error=n.error||"URI contains malformed percent-encoding."),isNaN(n.port)&&(n.port=y[5]);let k=N0(n,y);if(k!==void 0&&(n.error=n.error||k,o=!0),n.host)if(Sy(n.host)===!1){let P=xi(n.host),C=n.host.indexOf("[")!==-1||n.host.indexOf("]")!==-1,j=vy(n.host);p=j.isIPV6||j.isIPVFuture===!0,l=C&&(!P||j.error===!0),n.host=p?j.host:j.host.toLowerCase(),l&&(n.error=n.error||_i,o=!0)}else p=!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 T=sd(r.scheme||n.scheme);if(l||(a=$y(n,r,T,p)),e.indexOf("%")!==-1&&n.host!==void 0&&!l){let $=p?n.host:od(n.host,!0);p||($=od($.toLowerCase())),n.host=p||r.scheme!=="null"?T0($,p):$}(!T||T&&!T.skipNormalize)&&(n.path&&(n.path=S0(n.path)),n.query&&(n.query=yy(n.query)),n.fragment&&(n.fragment=yy(n.fragment))),T&&T.parse&&(T.parse(n,r),T===ky.urn&&n.nid===void 0&&(i=!0))}else n.error=n.error||"URI can not be parsed.";return{parsed:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function ki(e,t){return Si(e,t).parsed}function D0(e,t){return Py(e,t).normalized}function Py(e,t){let{parsed:r,malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Si(e,t);return{normalized:n||o||s||i||a?e:Cr(r,t),malformedAuthorityOrPort:n,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function wy(e,t){if(typeof e!="string"&&typeof e!="object")return;let r;try{r=typeof e=="string"?e:Cr(e,t)}catch{return}let{normalized:n,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:l}=Py(r,t);return o||s||i||a||l?void 0:n}var id={SCHEMES:ky,normalize:E0,resolve:P0,resolveComponent:Ry,equal:A0,serialize:Cr,parse:ki};Ti.exports=id;Ti.exports.default=id;Ti.exports.fastUri=id});var Iy=q(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});var Cy=Ay();Cy.code='require("ajv/dist/runtime/uri").default';ad.default=Cy});var qy=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 U0=go();Object.defineProperty(Ue,"KeywordCxt",{enumerable:!0,get:function(){return U0.KeywordCxt}});var mn=re();Object.defineProperty(Ue,"_",{enumerable:!0,get:function(){return mn._}});Object.defineProperty(Ue,"str",{enumerable:!0,get:function(){return mn.str}});Object.defineProperty(Ue,"stringify",{enumerable:!0,get:function(){return mn.stringify}});Object.defineProperty(Ue,"nil",{enumerable:!0,get:function(){return mn.nil}});Object.defineProperty(Ue,"Name",{enumerable:!0,get:function(){return mn.Name}});Object.defineProperty(Ue,"CodeGen",{enumerable:!0,get:function(){return mn.CodeGen}});var M0=gi(),Dy=yo(),q0=Ac(),vo=bi(),z0=re(),_o=ho(),Ri=po(),cd=pe(),Oy=ry(),B0=Iy(),Uy=(e,t)=>new RegExp(e,t);Uy.code="new RegExp";var F0=["removeAdditional","useDefaults","coerceTypes"],H0=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),V0={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."},K0={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Ny=200;function W0(e){var t,r,n,o,s,i,a,l,u,p,g,x,y,k,T,$,P,C,j,H,G,Re,qe,Et,Gt;let Pt=e.strict,Jt=(t=e.code)===null||t===void 0?void 0:t.optimize,Lo=Jt===!0||Jt===void 0?1:Jt||0,fr=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Uy,Ut=(o=e.uriResolver)!==null&&o!==void 0?o:B0.default;return{strictSchema:(i=(s=e.strictSchema)!==null&&s!==void 0?s:Pt)!==null&&i!==void 0?i:!0,strictNumbers:(l=(a=e.strictNumbers)!==null&&a!==void 0?a:Pt)!==null&&l!==void 0?l:!0,strictTypes:(p=(u=e.strictTypes)!==null&&u!==void 0?u:Pt)!==null&&p!==void 0?p:"log",strictTuples:(x=(g=e.strictTuples)!==null&&g!==void 0?g:Pt)!==null&&x!==void 0?x:"log",strictRequired:(k=(y=e.strictRequired)!==null&&y!==void 0?y:Pt)!==null&&k!==void 0?k:!1,code:e.code?{...e.code,optimize:Lo,regExp:fr}:{optimize:Lo,regExp:fr},loopRequired:(T=e.loopRequired)!==null&&T!==void 0?T:Ny,loopEnum:($=e.loopEnum)!==null&&$!==void 0?$:Ny,meta:(P=e.meta)!==null&&P!==void 0?P:!0,messages:(C=e.messages)!==null&&C!==void 0?C:!0,inlineRefs:(j=e.inlineRefs)!==null&&j!==void 0?j:!0,schemaId:(H=e.schemaId)!==null&&H!==void 0?H:"$id",addUsedSchema:(G=e.addUsedSchema)!==null&&G!==void 0?G:!0,validateSchema:(Re=e.validateSchema)!==null&&Re!==void 0?Re:!0,validateFormats:(qe=e.validateFormats)!==null&&qe!==void 0?qe:!0,unicodeRegExp:(Et=e.unicodeRegExp)!==null&&Et!==void 0?Et:!0,int32range:(Gt=e.int32range)!==null&&Gt!==void 0?Gt:!0,uriResolver:Ut}}var So=class{constructor(t={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,t=this.opts={...t,...W0(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new z0.ValueScope({scope:{},prefixes:H0,es5:r,lines:n}),this.logger=Q0(t.logger);let o=t.validateFormats;t.validateFormats=!1,this.RULES=(0,q0.getRules)(),Ly.call(this,V0,t,"NOT SUPPORTED"),Ly.call(this,K0,t,"DEPRECATED","warn"),this._metaOpts=X0.call(this),t.formats&&J0.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&Y0.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),G0.call(this),t.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,o=Oy;n==="id"&&(o={...Oy},o.id=o.$id,delete o.$id),r&&t&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:t,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof t=="object"?t[r]||t:void 0}validate(t,r){let n;if(typeof t=="string"){if(n=this.getSchema(t),!n)throw new Error(`no schema with key or ref "${t}"`)}else n=this.compile(t);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(t,r){let n=this._addSchema(t,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(t,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,t,r);async function o(p,g){await s.call(this,p.$schema);let x=this._addSchema(p,g);return x.validate||i.call(this,x)}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 Dy.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(t,r,n,o=this.opts.validateSchema){if(Array.isArray(t)){for(let i of t)this.addSchema(i,void 0,n,o);return this}let s;if(typeof t=="object"){let{schemaId:i}=this.opts;if(s=t[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,_o.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(t,n,r,o,!0),this}addMetaSchema(t,r,n=this.opts.validateSchema){return this.addSchema(t,r,!0,n),this}validateSchema(t,r){if(typeof t=="boolean")return!0;let n;if(n=t.$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,t);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(t){let r;for(;typeof(r=jy.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,o=new vo.SchemaEnv({schema:{},schemaId:n});if(r=vo.resolveSchema.call(this,o,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=jy.call(this,t);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[t],delete this.refs[t],this}case"object":{let r=t;this._cache.delete(r);let n=t[this.opts.schemaId];return n&&(n=(0,_o.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(t){for(let r of t)this.addKeyword(r);return this}addKeyword(t,r){let n;if(typeof t=="string")n=t,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof t=="object"&&r===void 0){if(r=t,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(tP.call(this,n,r),!r)return(0,cd.eachItem)(n,s=>ld.call(this,s)),this;nP.call(this,r);let o={...r,type:(0,Ri.getJSONTypes)(r.type),schemaType:(0,Ri.getJSONTypes)(r.schemaType)};return(0,cd.eachItem)(n,o.type.length===0?s=>ld.call(this,s,o):s=>o.type.forEach(i=>ld.call(this,s,o,i))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===t);o>=0&&n.rules.splice(o,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let o of r){let s=o.split("/").slice(1),i=t;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]=My(p))}}return t}_removeAllSchemas(t,r){for(let n in t){let o=t[n];(!r||r.test(n))&&(typeof o=="string"?delete t[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete t[n]))}}_addSchema(t,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof t=="object")i=t[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof t!="boolean")throw new Error("schema must be object or boolean")}let l=this._cache.get(t);if(l!==void 0)return l;n=(0,_o.normalizeId)(i||n);let u=_o.getSchemaRefs.call(this,t,n);return l=new vo.SchemaEnv({schema:t,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(t,!0),l}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):vo.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{vo.compileSchema.call(this,t)}finally{this.opts=r}}};So.ValidationError=M0.default;So.MissingRefError=Dy.default;Ue.default=So;function Ly(e,t,r,n="error"){for(let o in e){let s=o;s in t&&this.logger[n](`${r}: option ${o}. ${e[s]}`)}}function jy(e){return e=(0,_o.normalizeId)(e),this.schemas[e]||this.refs[e]}function G0(){let e=this.opts.schemas;if(e)if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}function J0(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function Y0(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let t in e){let r=e[t];r.keyword||(r.keyword=t),this.addKeyword(r)}}function X0(){let e={...this.opts};for(let t of F0)delete e[t];return e}var Z0={log(){},warn(){},error(){}};function Q0(e){if(e===!1)return Z0;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw new Error("logger must implement log, warn and error methods")}var eP=/^[a-z_$][a-z0-9_$:-]*$/i;function tP(e,t){let{RULES:r}=this;if((0,cd.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!eP.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!t&&t.$data&&!("code"in t||"validate"in t))throw new Error('$data keyword must have "code" or "validate" function')}function ld(e,t,r){var n;let o=t?.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[e]=!0,!t)return;let a={keyword:e,definition:{...t,type:(0,Ri.getJSONTypes)(t.type),schemaType:(0,Ri.getJSONTypes)(t.schemaType)}};t.before?rP.call(this,i,a,t.before):i.rules.push(a),s.all[e]=a,(n=t.implements)===null||n===void 0||n.forEach(l=>this.addKeyword(l))}function rP(e,t,r){let n=e.rules.findIndex(o=>o.keyword===r);n>=0?e.rules.splice(n,0,t):(e.rules.push(t),this.logger.warn(`rule ${r} is not defined`))}function nP(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=My(t)),e.validateSchema=this.compile(t,!0))}var oP={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function My(e){return{anyOf:[e,oP]}}});var zy=q(dd=>{"use strict";Object.defineProperty(dd,"__esModule",{value:!0});var sP={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};dd.default=sP});var Vy=q(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.callRef=Ir.getValidate=void 0;var iP=yo(),By=mt(),rt=re(),fn=Vt(),Fy=bi(),$i=pe(),aP={keyword:"$ref",schemaType:"string",code(e){let{gen:t,schema:r,it:n}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:l}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return g();let p=Fy.resolveRef.call(l,u,o,r);if(p===void 0)throw new iP.default(n.opts.uriResolver,o,r);if(p instanceof Fy.SchemaEnv)return x(p);return y(p);function g(){if(s===u)return Ei(e,i,s,s.$async);let k=t.scopeValue("root",{ref:u});return Ei(e,(0,rt._)`${k}.validate`,u,u.$async)}function x(k){let T=Hy(e,k);Ei(e,T,k,k.$async)}function y(k){let T=t.scopeValue("schema",a.code.source===!0?{ref:k,code:(0,rt.stringify)(k)}:{ref:k}),$=t.name("valid"),P=e.subschema({schema:k,dataTypes:[],schemaPath:rt.nil,topSchemaRef:T,errSchemaPath:r},$);e.mergeEvaluated(P),e.ok($)}}};function Hy(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,rt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}Ir.getValidate=Hy;function Ei(e,t,r,n){let{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:l}=s,u=l.passContext?fn.default.this:rt.nil;n?p():g();function p(){if(!a.$async)throw new Error("async schema referenced by sync schema");let k=o.let("valid");o.try(()=>{o.code((0,rt._)`await ${(0,By.callValidateCode)(e,t,u)}`),y(t),i||o.assign(k,!0)},T=>{o.if((0,rt._)`!(${T} instanceof ${s.ValidationError})`,()=>o.throw(T)),x(T),i||o.assign(k,!1)}),e.ok(k)}function g(){e.result((0,By.callValidateCode)(e,t,u),()=>y(t),()=>x(t))}function x(k){let T=(0,rt._)`${k}.errors`;o.assign(fn.default.vErrors,(0,rt._)`${fn.default.vErrors} === null ? ${T} : ${fn.default.vErrors}.concat(${T})`),o.assign(fn.default.errors,(0,rt._)`${fn.default.vErrors}.length`)}function y(k){var T;if(!s.opts.unevaluated)return;let $=(T=r?.validate)===null||T===void 0?void 0:T.evaluated;if(s.props!==!0)if($&&!$.dynamicProps)$.props!==void 0&&(s.props=$i.mergeEvaluated.props(o,$.props,s.props));else{let P=o.var("props",(0,rt._)`${k}.evaluated.props`);s.props=$i.mergeEvaluated.props(o,P,s.props,rt.Name)}if(s.items!==!0)if($&&!$.dynamicItems)$.items!==void 0&&(s.items=$i.mergeEvaluated.items(o,$.items,s.items));else{let P=o.var("items",(0,rt._)`${k}.evaluated.items`);s.items=$i.mergeEvaluated.items(o,P,s.items,rt.Name)}}}Ir.callRef=Ei;Ir.default=aP});var Ky=q(ud=>{"use strict";Object.defineProperty(ud,"__esModule",{value:!0});var lP=zy(),cP=Vy(),dP=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",lP.default,cP.default];ud.default=dP});var Wy=q(pd=>{"use strict";Object.defineProperty(pd,"__esModule",{value:!0});var Pi=re(),pr=Pi.operators,Ai={maximum:{okStr:"<=",ok:pr.LTE,fail:pr.GT},minimum:{okStr:">=",ok:pr.GTE,fail:pr.LT},exclusiveMaximum:{okStr:"<",ok:pr.LT,fail:pr.GTE},exclusiveMinimum:{okStr:">",ok:pr.GT,fail:pr.LTE}},uP={message:({keyword:e,schemaCode:t})=>(0,Pi.str)`must be ${Ai[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Pi._)`{comparison: ${Ai[e].okStr}, limit: ${t}}`},pP={keyword:Object.keys(Ai),type:"number",schemaType:"number",$data:!0,error:uP,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,Pi._)`${r} ${Ai[t].fail} ${n} || isNaN(${r})`)}};pd.default=pP});var Gy=q(hd=>{"use strict";Object.defineProperty(hd,"__esModule",{value:!0});var ko=re(),hP={message:({schemaCode:e})=>(0,ko.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,ko._)`{multipleOf: ${e}}`},mP={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:hP,code(e){let{gen:t,data:r,schemaCode:n,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,ko._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ko._)`${i} !== parseInt(${i})`;e.fail$data((0,ko._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};hd.default=mP});var Yy=q(md=>{"use strict";Object.defineProperty(md,"__esModule",{value:!0});function Jy(e){let t=e.length,r=0,n=0,o;for(;n<t;)r++,o=e.charCodeAt(n++),o>=55296&&o<=56319&&n<t&&(o=e.charCodeAt(n),(o&64512)===56320&&n++);return r}md.default=Jy;Jy.code='require("ajv/dist/runtime/ucs2length").default'});var Xy=q(fd=>{"use strict";Object.defineProperty(fd,"__esModule",{value:!0});var Or=re(),fP=pe(),gP=Yy(),yP={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,Or.str)`must NOT have ${r} than ${t} characters`},params:({schemaCode:e})=>(0,Or._)`{limit: ${e}}`},bP={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:yP,code(e){let{keyword:t,data:r,schemaCode:n,it:o}=e,s=t==="maxLength"?Or.operators.GT:Or.operators.LT,i=o.opts.unicode===!1?(0,Or._)`${r}.length`:(0,Or._)`${(0,fP.useFunc)(e.gen,gP.default)}(${r})`;e.fail$data((0,Or._)`${i} ${s} ${n}`)}};fd.default=bP});var Zy=q(gd=>{"use strict";Object.defineProperty(gd,"__esModule",{value:!0});var wP=mt(),vP=pe(),gn=re(),_P={message:({schemaCode:e})=>(0,gn.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,gn._)`{pattern: ${e}}`},SP={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_P,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:l}=i.opts.code,u=l.code==="new RegExp"?(0,gn._)`new RegExp`:(0,vP.useFunc)(t,l),p=t.let("valid");t.try(()=>t.assign(p,(0,gn._)`${u}(${s}, ${a}).test(${r})`),()=>t.assign(p,!1)),e.fail$data((0,gn._)`!${p}`)}else{let l=(0,wP.usePattern)(e,o);e.fail$data((0,gn._)`!${l}.test(${r})`)}}};gd.default=SP});var Qy=q(yd=>{"use strict";Object.defineProperty(yd,"__esModule",{value:!0});var xo=re(),kP={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,xo.str)`must NOT have ${r} than ${t} properties`},params:({schemaCode:e})=>(0,xo._)`{limit: ${e}}`},xP={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:kP,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxProperties"?xo.operators.GT:xo.operators.LT;e.fail$data((0,xo._)`Object.keys(${r}).length ${o} ${n}`)}};yd.default=xP});var eb=q(bd=>{"use strict";Object.defineProperty(bd,"__esModule",{value:!0});var To=mt(),Ro=re(),TP=pe(),RP={message:({params:{missingProperty:e}})=>(0,Ro.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,Ro._)`{missingProperty: ${e}}`},$P={keyword:"required",type:"object",schemaType:"array",$data:!0,error:RP,code(e){let{gen:t,schema:r,schemaCode:n,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&r.length===0)return;let l=r.length>=a.loopRequired;if(i.allErrors?u():p(),a.strictRequired){let y=e.parentSchema.properties,{definedProperties:k}=e.it;for(let T of r)if(y?.[T]===void 0&&!k.has(T)){let $=i.schemaEnv.baseId+i.errSchemaPath,P=`required property "${T}" is not defined at "${$}" (strictRequired)`;(0,TP.checkStrictMode)(i,P,i.opts.strictRequired)}}function u(){if(l||s)e.block$data(Ro.nil,g);else for(let y of r)(0,To.checkReportMissingProp)(e,y)}function p(){let y=t.let("missing");if(l||s){let k=t.let("valid",!0);e.block$data(k,()=>x(y,k)),e.ok(k)}else t.if((0,To.checkMissingProp)(e,r,y)),(0,To.reportMissingProp)(e,y),t.else()}function g(){t.forOf("prop",n,y=>{e.setParams({missingProperty:y}),t.if((0,To.noPropertyInData)(t,o,y,a.ownProperties),()=>e.error())})}function x(y,k){e.setParams({missingProperty:y}),t.forOf(y,n,()=>{t.assign(k,(0,To.propertyInData)(t,o,y,a.ownProperties)),t.if((0,Ro.not)(k),()=>{e.error(),t.break()})},Ro.nil)}}};bd.default=$P});var tb=q(wd=>{"use strict";Object.defineProperty(wd,"__esModule",{value:!0});var $o=re(),EP={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,$o.str)`must NOT have ${r} than ${t} items`},params:({schemaCode:e})=>(0,$o._)`{limit: ${e}}`},PP={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:EP,code(e){let{keyword:t,data:r,schemaCode:n}=e,o=t==="maxItems"?$o.operators.GT:$o.operators.LT;e.fail$data((0,$o._)`${r}.length ${o} ${n}`)}};wd.default=PP});var Ci=q(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});var rb=Uc();rb.code='require("ajv/dist/runtime/equal").default';vd.default=rb});var nb=q(Sd=>{"use strict";Object.defineProperty(Sd,"__esModule",{value:!0});var _d=po(),Me=re(),AP=pe(),CP=Ci(),IP={message:({params:{i:e,j:t}})=>(0,Me.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,Me._)`{i: ${e}, j: ${t}}`},OP={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:IP,code(e){let{gen:t,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!n&&!o)return;let l=t.let("valid"),u=s.items?(0,_d.getSchemaTypes)(s.items):[];e.block$data(l,p,(0,Me._)`${i} === false`),e.ok(l);function p(){let k=t.let("i",(0,Me._)`${r}.length`),T=t.let("j");e.setParams({i:k,j:T}),t.assign(l,!0),t.if((0,Me._)`${k} > 1`,()=>(g()?x:y)(k,T))}function g(){return u.length>0&&!u.some(k=>k==="object"||k==="array")}function x(k,T){let $=t.name("item"),P=(0,_d.checkDataTypes)(u,$,a.opts.strictNumbers,_d.DataType.Wrong),C=t.const("indices",(0,Me._)`{}`);t.for((0,Me._)`;${k}--;`,()=>{t.let($,(0,Me._)`${r}[${k}]`),t.if(P,(0,Me._)`continue`),u.length>1&&t.if((0,Me._)`typeof ${$} == "string"`,(0,Me._)`${$} += "_"`),t.if((0,Me._)`typeof ${C}[${$}] == "number"`,()=>{t.assign(T,(0,Me._)`${C}[${$}]`),e.error(),t.assign(l,!1).break()}).code((0,Me._)`${C}[${$}] = ${k}`)})}function y(k,T){let $=(0,AP.useFunc)(t,CP.default),P=t.name("outer");t.label(P).for((0,Me._)`;${k}--;`,()=>t.for((0,Me._)`${T} = ${k}; ${T}--;`,()=>t.if((0,Me._)`${$}(${r}[${k}], ${r}[${T}])`,()=>{e.error(),t.assign(l,!1).break(P)})))}}};Sd.default=OP});var ob=q(xd=>{"use strict";Object.defineProperty(xd,"__esModule",{value:!0});var kd=re(),NP=pe(),LP=Ci(),jP={message:"must be equal to constant",params:({schemaCode:e})=>(0,kd._)`{allowedValue: ${e}}`},DP={keyword:"const",$data:!0,error:jP,code(e){let{gen:t,data:r,$data:n,schemaCode:o,schema:s}=e;n||s&&typeof s=="object"?e.fail$data((0,kd._)`!${(0,NP.useFunc)(t,LP.default)}(${r}, ${o})`):e.fail((0,kd._)`${s} !== ${r}`)}};xd.default=DP});var sb=q(Td=>{"use strict";Object.defineProperty(Td,"__esModule",{value:!0});var Eo=re(),UP=pe(),MP=Ci(),qP={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,Eo._)`{allowedValues: ${e}}`},zP={keyword:"enum",schemaType:"array",$data:!0,error:qP,code(e){let{gen:t,data:r,$data:n,schema:o,schemaCode:s,it:i}=e;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,UP.useFunc)(t,MP.default)),p;if(a||n)p=t.let("valid"),e.block$data(p,g);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let y=t.const("vSchema",s);p=(0,Eo.or)(...o.map((k,T)=>x(y,T)))}e.pass(p);function g(){t.assign(p,!1),t.forOf("v",s,y=>t.if((0,Eo._)`${u()}(${r}, ${y})`,()=>t.assign(p,!0).break()))}function x(y,k){let T=o[k];return typeof T=="object"&&T!==null?(0,Eo._)`${u()}(${r}, ${y}[${k}])`:(0,Eo._)`${r} === ${T}`}}};Td.default=zP});var ib=q(Rd=>{"use strict";Object.defineProperty(Rd,"__esModule",{value:!0});var BP=Wy(),FP=Gy(),HP=Xy(),VP=Zy(),KP=Qy(),WP=eb(),GP=tb(),JP=nb(),YP=ob(),XP=sb(),ZP=[BP.default,FP.default,HP.default,VP.default,KP.default,WP.default,GP.default,JP.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},YP.default,XP.default];Rd.default=ZP});var Ed=q(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.validateAdditionalItems=void 0;var Nr=re(),$d=pe(),QP={message:({params:{len:e}})=>(0,Nr.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,Nr._)`{limit: ${e}}`},eA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:QP,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,$d.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}ab(e,n)}};function ab(e,t){let{gen:r,schema:n,data:o,keyword:s,it:i}=e;i.items=!0;let a=r.const("len",(0,Nr._)`${o}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,Nr._)`${a} <= ${t.length}`);else if(typeof n=="object"&&!(0,$d.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Nr._)`${a} <= ${t.length}`);r.if((0,Nr.not)(u),()=>l(u)),e.ok(u)}function l(u){r.forRange("i",t.length,a,p=>{e.subschema({keyword:s,dataProp:p,dataPropType:$d.Type.Num},u),i.allErrors||r.if((0,Nr.not)(u),()=>r.break())})}}Po.validateAdditionalItems=ab;Po.default=eA});var Pd=q(Ao=>{"use strict";Object.defineProperty(Ao,"__esModule",{value:!0});Ao.validateTuple=void 0;var lb=re(),Ii=pe(),tA=mt(),rA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return cb(e,"additionalItems",t);r.items=!0,!(0,Ii.alwaysValidSchema)(r,t)&&e.ok((0,tA.validateArray)(e))}};function cb(e,t,r=e.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=e;p(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ii.mergeEvaluated.items(n,r.length,a.items));let l=n.name("valid"),u=n.const("len",(0,lb._)`${s}.length`);r.forEach((g,x)=>{(0,Ii.alwaysValidSchema)(a,g)||(n.if((0,lb._)`${u} > ${x}`,()=>e.subschema({keyword:i,schemaProp:x,dataProp:x},l)),e.ok(l))});function p(g){let{opts:x,errSchemaPath:y}=a,k=r.length,T=k===g.minItems&&(k===g.maxItems||g[t]===!1);if(x.strictTuples&&!T){let $=`"${i}" is ${k}-tuple, but minItems or maxItems/${t} are not specified or different at path "${y}"`;(0,Ii.checkStrictMode)(a,$,x.strictTuples)}}}Ao.validateTuple=cb;Ao.default=rA});var db=q(Ad=>{"use strict";Object.defineProperty(Ad,"__esModule",{value:!0});var nA=Pd(),oA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,nA.validateTuple)(e,"items")};Ad.default=oA});var pb=q(Cd=>{"use strict";Object.defineProperty(Cd,"__esModule",{value:!0});var ub=re(),sA=pe(),iA=mt(),aA=Ed(),lA={message:({params:{len:e}})=>(0,ub.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ub._)`{limit: ${e}}`},cA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:lA,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:o}=r;n.items=!0,!(0,sA.alwaysValidSchema)(n,t)&&(o?(0,aA.validateAdditionalItems)(e,o):e.ok((0,iA.validateArray)(e)))}};Cd.default=cA});var hb=q(Id=>{"use strict";Object.defineProperty(Id,"__esModule",{value:!0});var gt=re(),Oi=pe(),dA={message:({params:{min:e,max:t}})=>t===void 0?(0,gt.str)`must contain at least ${e} valid item(s)`:(0,gt.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,gt._)`{minContains: ${e}}`:(0,gt._)`{minContains: ${e}, maxContains: ${t}}`},uA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:dA,code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e,i,a,{minContains:l,maxContains:u}=n;s.opts.next?(i=l===void 0?1:l,a=u):i=1;let p=t.const("len",(0,gt._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Oi.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Oi.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Oi.alwaysValidSchema)(s,r)){let T=(0,gt._)`${p} >= ${i}`;a!==void 0&&(T=(0,gt._)`${T} && ${p} <= ${a}`),e.pass(T);return}s.items=!0;let g=t.name("valid");a===void 0&&i===1?y(g,()=>t.if(g,()=>t.break())):i===0?(t.let(g,!0),a!==void 0&&t.if((0,gt._)`${o}.length > 0`,x)):(t.let(g,!1),x()),e.result(g,()=>e.reset());function x(){let T=t.name("_valid"),$=t.let("count",0);y(T,()=>t.if(T,()=>k($)))}function y(T,$){t.forRange("i",0,p,P=>{e.subschema({keyword:"contains",dataProp:P,dataPropType:Oi.Type.Num,compositeRule:!0},T),$()})}function k(T){t.code((0,gt._)`${T}++`),a===void 0?t.if((0,gt._)`${T} >= ${i}`,()=>t.assign(g,!0).break()):(t.if((0,gt._)`${T} > ${a}`,()=>t.assign(g,!1).break()),i===1?t.assign(g,!0):t.if((0,gt._)`${T} >= ${i}`,()=>t.assign(g,!0)))}}};Id.default=uA});var gb=q(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.validateSchemaDeps=Lt.validatePropertyDeps=Lt.error=void 0;var Od=re(),pA=pe(),Co=mt();Lt.error={message:({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Od.str)`must have ${n} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Od._)`{property: ${e},
|
|
2441
2459
|
missingProperty: ${n},
|
|
2442
2460
|
depsCount: ${t},
|
|
2443
|
-
deps: ${r}}`};var pA={keyword:"dependencies",type:"object",schemaType:"object",error:Lt.error,code(e){let[t,r]=hA(e);hb(e,t),mb(e,r)}};function hA({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function hb(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let l=(0,Co.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let u of a)(0,Co.checkReportMissingProp)(e,u)}):(r.if((0,Id._)`${l} && (${(0,Co.checkMissingProp)(e,a,s)})`),(0,Co.reportMissingProp)(e,s),r.else())}}Lt.validatePropertyDeps=hb;function mb(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,uA.alwaysValidSchema)(s,t[a])||(r.if((0,Co.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=e.subschema({keyword:o,schemaProp:a},i);e.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),e.ok(i))}Lt.validateSchemaDeps=mb;Lt.default=pA});var yb=q(Od=>{"use strict";Object.defineProperty(Od,"__esModule",{value:!0});var gb=re(),mA=pe(),fA={message:"property name must be valid",params:({params:e})=>(0,gb._)`{propertyName: ${e.propertyName}}`},gA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:fA,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,mA.alwaysValidSchema)(o,r))return;let s=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,gb.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Od.default=gA});var Ld=q(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var Ni=mt(),Rt=re(),yA=Vt(),Li=pe(),bA={message:"must NOT have additional properties",params:({params:e})=>(0,Rt._)`{additionalProperty: ${e.additionalProperty}}`},wA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:bA,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Li.alwaysValidSchema)(i,r))return;let u=(0,Ni.allSchemaProperties)(n.properties),p=(0,Ni.allSchemaProperties)(n.patternProperties);g(),e.ok((0,Rt._)`${s} === ${yA.default.errors}`);function g(){t.forIn("key",o,$=>{!u.length&&!p.length?k($):t.if(x($),()=>k($))})}function x($){let P;if(u.length>8){let C=(0,Li.schemaRefOrVal)(i,n.properties,"properties");P=(0,Ni.isOwnProperty)(t,C,$)}else u.length?P=(0,Rt.or)(...u.map(C=>(0,Rt._)`${$} === ${C}`)):P=Rt.nil;return p.length&&(P=(0,Rt.or)(P,...p.map(C=>(0,Rt._)`${(0,Ni.usePattern)(e,C)}.test(${$})`))),(0,Rt.not)(P)}function y($){t.code((0,Rt._)`delete ${o}[${$}]`)}function k($){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){y($);return}if(r===!1){e.setParams({additionalProperty:$}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Li.alwaysValidSchema)(i,r)){let P=t.name("valid");l.removeAdditional==="failing"?(R($,P,!1),t.if((0,Rt.not)(P),()=>{e.reset(),y($)})):(R($,P),a||t.if((0,Rt.not)(P),()=>t.break()))}}function R($,P,C){let j={keyword:"additionalProperties",dataProp:$,dataPropType:Li.Type.Str};C===!1&&Object.assign(j,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(j,P)}}};Nd.default=wA});var vb=q(Dd=>{"use strict";Object.defineProperty(Dd,"__esModule",{value:!0});var vA=go(),bb=mt(),jd=pe(),wb=Ld(),_A={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&wb.default.code(new vA.KeywordCxt(s,wb.default,"additionalProperties"));let i=(0,bb.allSchemaProperties)(r);for(let g of i)s.definedProperties.add(g);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=jd.mergeEvaluated.props(t,(0,jd.toHash)(i),s.props));let a=i.filter(g=>!(0,jd.alwaysValidSchema)(s,r[g]));if(a.length===0)return;let l=t.name("valid");for(let g of a)u(g)?p(g):(t.if((0,bb.propertyInData)(t,o,g,s.opts.ownProperties)),p(g),s.allErrors||t.else().var(l,!0),t.endIf()),e.it.definedProperties.add(g),e.ok(l);function u(g){return s.opts.useDefaults&&!s.compositeRule&&r[g].default!==void 0}function p(g){e.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};Dd.default=_A});var xb=q(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var _b=mt(),ji=re(),Sb=pe(),kb=pe(),SA={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,_b.allSchemaProperties)(r),l=a.filter(R=>(0,Sb.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=t.name("valid");s.props!==!0&&!(s.props instanceof ji.Name)&&(s.props=(0,kb.evaluatedPropsToName)(t,s.props));let{props:g}=s;x();function x(){for(let R of a)u&&y(R),s.allErrors?k(R):(t.var(p,!0),k(R),t.if(p))}function y(R){for(let $ in u)new RegExp(R).test($)&&(0,Sb.checkStrictMode)(s,`property ${$} matches pattern ${R} (use allowMatchingProperties)`)}function k(R){t.forIn("key",n,$=>{t.if((0,ji._)`${(0,_b.usePattern)(e,R)}.test(${$})`,()=>{let P=l.includes(R);P||e.subschema({keyword:"patternProperties",schemaProp:R,dataProp:$,dataPropType:kb.Type.Str},p),s.opts.unevaluated&&g!==!0?t.assign((0,ji._)`${g}[${$}]`,!0):!P&&!s.allErrors&&t.if((0,ji.not)(p),()=>t.break())})})}}};Ud.default=SA});var Tb=q(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var kA=pe(),xA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,kA.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Md.default=xA});var Rb=q(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var TA=mt(),RA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:TA.validateUnion,error:{message:"must match a schema in anyOf"}};qd.default=RA});var $b=q(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var Di=re(),$A=pe(),EA={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Di._)`{passingSchemas: ${e.passing}}`},PA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:EA,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=t.let("valid",!1),a=t.let("passing",null),l=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((p,g)=>{let x;(0,$A.alwaysValidSchema)(o,p)?t.var(l,!0):x=e.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&t.if((0,Di._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Di._)`[${a}, ${g}]`).else(),t.if(l,()=>{t.assign(i,!0),t.assign(a,g),x&&e.mergeEvaluated(x,Di.Name)})})}}};zd.default=PA});var Eb=q(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var AA=pe(),CA={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=t.name("valid");r.forEach((s,i)=>{if((0,AA.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Bd.default=CA});var Cb=q(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Ui=re(),Ab=pe(),IA={message:({params:e})=>(0,Ui.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ui._)`{failingKeyword: ${e.ifClause}}`},OA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:IA,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Ab.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Pb(n,"then"),s=Pb(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(l(),e.reset(),o&&s){let p=t.let("ifClause");e.setParams({ifClause:p}),t.if(a,u("then",p),u("else",p))}else o?t.if(a,u("then")):t.if((0,Ui.not)(a),u("else"));e.pass(i,()=>e.error(!0));function l(){let p=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(p)}function u(p,g){return()=>{let x=e.subschema({keyword:p},a);t.assign(i,a),e.mergeValidEvaluated(x,i),g?t.assign(g,(0,Ui._)`${p}`):e.setParams({ifClause:p})}}}};function Pb(e,t){let r=e.schema[t];return r!==void 0&&!(0,Ab.alwaysValidSchema)(e,r)}Fd.default=OA});var Ib=q(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var NA=pe(),LA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,NA.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Hd.default=LA});var Ob=q(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var jA=$d(),DA=cb(),UA=Ed(),MA=ub(),qA=pb(),zA=fb(),BA=yb(),FA=Ld(),HA=vb(),VA=xb(),KA=Tb(),WA=Rb(),GA=$b(),JA=Eb(),YA=Cb(),XA=Ib();function ZA(e=!1){let t=[KA.default,WA.default,GA.default,JA.default,YA.default,XA.default,BA.default,FA.default,zA.default,HA.default,VA.default];return e?t.push(DA.default,MA.default):t.push(jA.default,UA.default),t.push(qA.default),t}Vd.default=ZA});var Nb=q(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var Te=re(),QA={message:({schemaCode:e})=>(0,Te.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Te._)`{format: ${e}}`},eC={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:QA,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:l,errSchemaPath:u,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;o?x():y();function x(){let k=r.scopeValue("formats",{ref:g.formats,code:l.code.formats}),R=r.const("fDef",(0,Te._)`${k}[${i}]`),$=r.let("fType"),P=r.let("format");r.if((0,Te._)`typeof ${R} == "object" && !(${R} instanceof RegExp)`,()=>r.assign($,(0,Te._)`${R}.type || "string"`).assign(P,(0,Te._)`${R}.validate`),()=>r.assign($,(0,Te._)`"string"`).assign(P,R)),e.fail$data((0,Te.or)(C(),j()));function C(){return l.strictSchema===!1?Te.nil:(0,Te._)`${i} && !${P}`}function j(){let H=p.$async?(0,Te._)`(${R}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,Te._)`${P}(${n})`,G=(0,Te._)`(typeof ${P} == "function" ? ${H} : ${P}.test(${n}))`;return(0,Te._)`${P} && ${P} !== true && ${$} === ${t} && !${G}`}}function y(){let k=g.formats[s];if(!k){C();return}if(k===!0)return;let[R,$,P]=j(k);R===t&&e.pass(H());function C(){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 j(G){let Re=G instanceof RegExp?(0,Te.regexpCode)(G):l.code.formats?(0,Te._)`${l.code.formats}${(0,Te.getProperty)(s)}`:void 0,qe=r.scopeValue("formats",{key:s,ref:G,code:Re});return typeof G=="object"&&!(G instanceof RegExp)?[G.type||"string",G.validate,(0,Te._)`${qe}.validate`]:["string",G,qe]}function H(){if(typeof k=="object"&&!(k instanceof RegExp)&&k.async){if(!p.$async)throw new Error("async format in sync schema");return(0,Te._)`await ${P}(${n})`}return typeof $=="function"?(0,Te._)`${P}(${n})`:(0,Te._)`${P}.test(${n})`}}}};Kd.default=eC});var Lb=q(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var tC=Nb(),rC=[tC.default];Wd.default=rC});var jb=q(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.contentVocabulary=bn.metadataVocabulary=void 0;bn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];bn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Ub=q(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var nC=Vy(),oC=sb(),sC=Ob(),iC=Lb(),Db=jb(),aC=[nC.default,oC.default,(0,sC.default)(),iC.default,Db.metadataVocabulary,Db.contentVocabulary];Gd.default=aC});var qb=q(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.DiscrError=void 0;var Mb;(function(e){e.Tag="tag",e.Mapping="mapping"})(Mb||(Mi.DiscrError=Mb={}))});var Bb=q(Yd=>{"use strict";Object.defineProperty(Yd,"__esModule",{value:!0});var wn=re(),Jd=qb(),zb=bi(),lC=yo(),cC=pe(),dC={message:({params:{discrError:e,tagName:t}})=>e===Jd.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,wn._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},uC={keyword:"discriminator",type:"object",schemaType:"object",error:dC,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{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=t.let("valid",!1),u=t.const("tag",(0,wn._)`${r}${(0,wn.getProperty)(a)}`);t.if((0,wn._)`typeof ${u} == "string"`,()=>p(),()=>e.error(!1,{discrError:Jd.DiscrError.Tag,tag:u,tagName:a})),e.ok(l);function p(){let y=x();t.if(!1);for(let k in y)t.elseIf((0,wn._)`${u} === ${k}`),t.assign(l,g(y[k]));t.else(),e.error(!1,{discrError:Jd.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function g(y){let k=t.name("valid"),R=e.subschema({keyword:"oneOf",schemaProp:y},k);return e.mergeEvaluated(R,wn.Name),k}function x(){var y;let k={},R=P(o),$=!0;for(let H=0;H<i.length;H++){let G=i[H];if(G?.$ref&&!(0,cC.schemaHasRulesButRef)(G,s.self.RULES)){let qe=G.$ref;if(G=zb.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,qe),G instanceof zb.SchemaEnv&&(G=G.schema),G===void 0)throw new lC.default(s.opts.uriResolver,s.baseId,qe)}let Re=(y=G?.properties)===null||y===void 0?void 0:y[a];if(typeof Re!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(R||P(G)),C(Re,H)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:H}){return Array.isArray(H)&&H.includes(a)}function C(H,G){if(H.const)j(H.const,G);else if(H.enum)for(let Re of H.enum)j(Re,G);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function j(H,G){if(typeof H!="string"||H in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[H]=G}}}};Yd.default=uC});var Fb=q((qM,pC)=>{pC.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 Zd=q((Se,Xd)=>{"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 hC=My(),mC=Ub(),fC=Bb(),Hb=Fb(),gC=["/properties"],qi="http://json-schema.org/draft-07/schema",vn=class extends hC.default{_addVocabularies(){super._addVocabularies(),mC.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(fC.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Hb,gC):Hb;this.addMetaSchema(t,qi,!1),this.refs["http://json-schema.org/schema"]=qi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(qi)?qi:void 0)}};Se.Ajv=vn;Xd.exports=Se=vn;Xd.exports.Ajv=vn;Object.defineProperty(Se,"__esModule",{value:!0});Se.default=vn;var yC=go();Object.defineProperty(Se,"KeywordCxt",{enumerable:!0,get:function(){return yC.KeywordCxt}});var _n=re();Object.defineProperty(Se,"_",{enumerable:!0,get:function(){return _n._}});Object.defineProperty(Se,"str",{enumerable:!0,get:function(){return _n.str}});Object.defineProperty(Se,"stringify",{enumerable:!0,get:function(){return _n.stringify}});Object.defineProperty(Se,"nil",{enumerable:!0,get:function(){return _n.nil}});Object.defineProperty(Se,"Name",{enumerable:!0,get:function(){return _n.Name}});Object.defineProperty(Se,"CodeGen",{enumerable:!0,get:function(){return _n.CodeGen}});var bC=gi();Object.defineProperty(Se,"ValidationError",{enumerable:!0,get:function(){return bC.default}});var wC=yo();Object.defineProperty(Se,"MissingRefError",{enumerable:!0,get:function(){return wC.default}})});var Zb=q(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.formatNames=Dt.fastFormats=Dt.fullFormats=void 0;function jt(e,t){return{validate:e,compare:t}}Dt.fullFormats={date:jt(Gb,ru),time:jt(eu(!0),nu),"date-time":jt(Vb(!0),Yb),"iso-time":jt(eu(),Jb),"iso-date-time":jt(Vb(),Xb),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:TC,"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:IC,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:RC,int32:{type:"number",validate:PC},int64:{type:"number",validate:AC},float:{type:"number",validate:Wb},double:{type:"number",validate:Wb},password:!0,binary:!0};Dt.fastFormats={...Dt.fullFormats,date:jt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,ru),time:jt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,nu),"date-time":jt(/^\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,Yb),"iso-time":jt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Jb),"iso-date-time":jt(/^\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,Xb),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};Dt.formatNames=Object.keys(Dt.fullFormats);function vC(e){return e%4===0&&(e%100!==0||e%400===0)}var _C=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,SC=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Gb(e){let t=_C.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&vC(r)?29:SC[n])}function ru(e,t){if(e&&t)return e>t?1:e<t?-1:0}var Qd=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function eu(e){return function(r){let n=Qd.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||e&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let g=s-p*l,x=o-u*l-(g<0?1:0);return(x===23||x===-1)&&(g===59||g===-1)&&i<61}}function nu(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function Jb(e,t){if(!(e&&t))return;let r=Qd.exec(e),n=Qd.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}var tu=/t|\s/i;function Vb(e){let t=eu(e);return function(n){let o=n.split(tu);return o.length===2&&Gb(o[0])&&t(o[1])}}function Yb(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Xb(e,t){if(!(e&&t))return;let[r,n]=e.split(tu),[o,s]=t.split(tu),i=ru(r,o);if(i!==void 0)return i||nu(n,s)}var kC=/\/|:/,xC=/^(?:[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 TC(e){return kC.test(e)&&xC.test(e)}var Kb=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function RC(e){return Kb.lastIndex=0,Kb.test(e)}var $C=-(2**31),EC=2**31-1;function PC(e){return Number.isInteger(e)&&e<=EC&&e>=$C}function AC(e){return Number.isInteger(e)}function Wb(){return!0}var CC=/[^\\]\\Z/;function IC(e){if(CC.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var Qb=q(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.formatLimitDefinition=void 0;var OC=Zd(),$t=re(),hr=$t.operators,zi={formatMaximum:{okStr:"<=",ok:hr.LTE,fail:hr.GT},formatMinimum:{okStr:">=",ok:hr.GTE,fail:hr.LT},formatExclusiveMaximum:{okStr:"<",ok:hr.LT,fail:hr.GTE},formatExclusiveMinimum:{okStr:">",ok:hr.GT,fail:hr.LTE}},NC={message:({keyword:e,schemaCode:t})=>(0,$t.str)`should be ${zi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,$t._)`{comparison: ${zi[e].okStr}, limit: ${t}}`};Sn.formatLimitDefinition={keyword:Object.keys(zi),type:"string",schemaType:"string",$data:!0,error:NC,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:s}=e,{opts:i,self:a}=s;if(!i.validateFormats)return;let l=new OC.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let x=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=t.const("fmt",(0,$t._)`${x}[${l.schemaCode}]`);e.fail$data((0,$t.or)((0,$t._)`typeof ${y} != "object"`,(0,$t._)`${y} instanceof RegExp`,(0,$t._)`typeof ${y}.compare != "function"`,g(y)))}function p(){let x=l.schema,y=a.formats[x];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${x}" does not define "compare" function`);let k=t.scopeValue("formats",{key:x,ref:y,code:i.code.formats?(0,$t._)`${i.code.formats}${(0,$t.getProperty)(x)}`:void 0});e.fail$data(g(k))}function g(x){return(0,$t._)`${x}.compare(${r}, ${n}) ${zi[o].fail} 0`}},dependencies:["format"]};var LC=e=>(e.addKeyword(Sn.formatLimitDefinition),e);Sn.default=LC});var nw=q((Io,rw)=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var kn=Zb(),jC=Qb(),ou=re(),ew=new ou.Name("fullFormats"),DC=new ou.Name("fastFormats"),su=(e,t={keywords:!0})=>{if(Array.isArray(t))return tw(e,t,kn.fullFormats,ew),e;let[r,n]=t.mode==="fast"?[kn.fastFormats,DC]:[kn.fullFormats,ew],o=t.formats||kn.formatNames;return tw(e,o,r,n),t.keywords&&(0,jC.default)(e),e};su.get=(e,t="full")=>{let n=(t==="fast"?kn.fastFormats:kn.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function tw(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,ou._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}rw.exports=Io=su;Object.defineProperty(Io,"__esModule",{value:!0});Io.default=su});function UC(){let e=new ow.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sw.default)(e),e}var ow,sw,Bi,iw=D(()=>{ow=Su(Zd(),1),sw=Su(nw(),1);Bi=class{constructor(t){this._ajv=t??UC()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Fi,aw=D(()=>{sn();Fi=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(p=>p.type==="tool_result"),a=t.messages.length>1?t.messages[t.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(x=>x.type==="tool_use").map(x=>x.id)),g=new Set(s.filter(x=>x.type==="tool_result").map(x=>x.toolUseId));if(p.size!==g.size||![...p].every(x=>g.has(x)))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:t},Qn,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.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"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:s},on,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}}});function lw(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function cw(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var dw=D(()=>{});var Hi,uw=D(()=>{rg();sn();iw();Fn();aw();dw();Hi=class extends ni{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Zn.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 Bi,this.setRequestHandler(ml,n=>this._oninitialize(n)),this.setNotificationHandler(fl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Sl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Zn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Fi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=tg(this._capabilities,t)}setRequestHandler(t,r){let o=rr(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Qr(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=tr(nn,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new F(V.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:g}=p.data,x=await Promise.resolve(r(l,u));if(g.task){let k=tr(tn,x);if(!k.success){let R=k.error instanceof Error?k.error.message:String(k.error);throw new F(V.InvalidParams,`Invalid task creation result: ${R}`)}return k.data}let y=tr(Vs,x);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new F(V.InvalidParams,`Invalid tools/call result: ${k}`)}return y.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);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 ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);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 ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);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 ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){cw(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&lw(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:Qm.includes(r)?r:cl,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ps)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=t.messages.length>1?t.messages[t.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 t.tools?this.request({method:"sampling/createMessage",params:t},kl,r):this.request({method:"sampling/createMessage",params:t},Qn,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},on,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},s=await this.request({method:"elicitation/create",params:o},on,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(V.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof F?i:new F(V.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(t,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:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},xl,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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 iu(e){return!!e&&typeof e=="object"&&hw in e}function mw(e){return e[hw]?.complete}var hw,pw,fw=D(()=>{hw=Symbol.for("mcp.completable");(function(e){e.Completable="McpCompletable"})(pw||(pw={}))});var gw=D(()=>{});function qC(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!MC.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return t.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:t}}return{isValid:!0,warnings:t}}function zC(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)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 au(e){let t=qC(e);return zC(e,t.warnings),t.isValid}var MC,yw=D(()=>{MC=/^[A-Za-z0-9._-]{1,128}$/});var Vi,bw=D(()=>{Vi=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});import{ZodOptional as BC}from"zod";function FC(e,t){let r=0,n=[e];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>t)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>t)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function HC(e){if(!(e===void 0||e===1/0)){if(typeof e!="number"||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}function _w(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function Sw(e){return"_def"in e||"_zod"in e||_w(e)}function lu(e){return typeof e!="object"||e===null||Sw(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(_w)}function ww(e){if(e){if(lu(e))return Sr(e);if(!Sw(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function KC(e){let t=rr(e);return t?Object.entries(t).map(([r,n])=>{let o=Xm(n),s=Zm(n);return{name:r,description:o,required:!s}}):[]}function mr(e){let r=rr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Qr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function vw(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Ki,VC,Oo,kw=D(()=>{uw();Fn();ac();sn();fw();gw();yw();bw();Ki=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Hi(t,r),this._maxToolInputElements=HC(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new Vi(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Hs)),this.server.assertCanSetRequestHandler(mr(nn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Hs,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=Zr(r.inputSchema);return o?oc(o,{strictUnions:!0,pipeStrategy:"input"}):VC})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Zr(r.outputSchema);o&&(n.outputSchema=oc(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(nn,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new F(V.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new F(V.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new F(V.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new F(V.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof F&&n.code===V.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(this._maxToolInputElements!==void 0&&FC(r,this._maxToolInputElements)>this._maxToolInputElements)throw new F(V.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!t.inputSchema)return;let s=Zr(t.inputSchema)??t.inputSchema,i=await xs(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",l=Ts(a);throw new F(V.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new F(V.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Zr(t.outputSchema),s=await xs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ts(i);throw new F(V.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(t.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),s=t.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(x=>setTimeout(x,p));let g=await n.taskStore.getTask(l);if(!g)throw new F(V.InternalError,`Task ${l} not found during polling`);u=g}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(mr(Ks)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ks,async t=>{switch(t.params.ref.type){case"ref/prompt":return gf(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return yf(t),this.handleResourceCompletion(t,t.params.ref);default:throw new F(V.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new F(V.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new F(V.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Oo;let s=rr(n.argsSchema)?.[t.params.argument.name];if(!iu(s))return Oo;let i=mw(s);if(!i)return Oo;let a=await i(t.params.argument.value,t.params.context);return vw(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Oo;throw new F(V.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Oo;let s=await o(t.params.argument.value,t.params.context);return vw(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Ms)),this.server.assertCanSetRequestHandler(mr(qs)),this.server.assertCanSetRequestHandler(mr(zs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ms,async(t,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(qs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(zs,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new F(V.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(V.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Bs)),this.server.assertCanSetRequestHandler(mr(Fs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Bs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?KC(r.argsSchema):void 0}))})),this.server.setRequestHandler(Fs,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new F(V.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new F(V.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=Zr(n.argsSchema),s=await xs(o,t.params.arguments??{});if(!s.success){let l="error"in s?s.error:"Unknown error",u=Ts(l);throw new F(V.InvalidParams,`Invalid arguments for prompt ${t.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(t,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(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,n,o,s){let i={name:t,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(t,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!==t&&(delete this._registeredResourceTemplates[t],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[t]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(t,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Sr(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!==t&&(delete this._registeredPrompts[t],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=Sr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=i,o&&Object.values(o).some(l=>{let u=l instanceof BC?l._def?.innerType:l;return iu(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(t,r,n,o,s,i,a,l,u){au(t);let p={title:r,description:n,inputSchema:ww(o),outputSchema:ww(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!==t&&(typeof g.name=="string"&&au(g.name),delete this._registeredTools[t],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=Sr(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=Sr(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[t]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(lu(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!lu(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 ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:l,_meta:u}=r;return this._createRegisteredTool(t,o,s,i,a,l,{taskSupport:"forbidden"},u,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} 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(t,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(t,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},VC={type:"object",properties:{}};Oo={completion:{values:[],hasMore:!1}}});function GC(e){return lf.parse(JSON.parse(e))}function xw(e){return JSON.stringify(e)+`
|
|
2444
|
-
`}var
|
|
2445
|
-
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),
|
|
2461
|
+
deps: ${r}}`};var hA={keyword:"dependencies",type:"object",schemaType:"object",error:Lt.error,code(e){let[t,r]=mA(e);mb(e,t),fb(e,r)}};function mA({schema:e}){let t={},r={};for(let n in e){if(n==="__proto__")continue;let o=Array.isArray(e[n])?t:r;o[n]=e[n]}return[t,r]}function mb(e,t=e.schema){let{gen:r,data:n,it:o}=e;if(Object.keys(t).length===0)return;let s=r.let("missing");for(let i in t){let a=t[i];if(a.length===0)continue;let l=(0,Co.propertyInData)(r,n,i,o.opts.ownProperties);e.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(l,()=>{for(let u of a)(0,Co.checkReportMissingProp)(e,u)}):(r.if((0,Od._)`${l} && (${(0,Co.checkMissingProp)(e,a,s)})`),(0,Co.reportMissingProp)(e,s),r.else())}}Lt.validatePropertyDeps=mb;function fb(e,t=e.schema){let{gen:r,data:n,keyword:o,it:s}=e,i=r.name("valid");for(let a in t)(0,pA.alwaysValidSchema)(s,t[a])||(r.if((0,Co.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let l=e.subschema({keyword:o,schemaProp:a},i);e.mergeValidEvaluated(l,i)},()=>r.var(i,!0)),e.ok(i))}Lt.validateSchemaDeps=fb;Lt.default=hA});var bb=q(Nd=>{"use strict";Object.defineProperty(Nd,"__esModule",{value:!0});var yb=re(),fA=pe(),gA={message:"property name must be valid",params:({params:e})=>(0,yb._)`{propertyName: ${e.propertyName}}`},yA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:gA,code(e){let{gen:t,schema:r,data:n,it:o}=e;if((0,fA.alwaysValidSchema)(o,r))return;let s=t.name("valid");t.forIn("key",n,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,yb.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Nd.default=yA});var jd=q(Ld=>{"use strict";Object.defineProperty(Ld,"__esModule",{value:!0});var Ni=mt(),Rt=re(),bA=Vt(),Li=pe(),wA={message:"must NOT have additional properties",params:({params:e})=>(0,Rt._)`{additionalProperty: ${e.additionalProperty}}`},vA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:wA,code(e){let{gen:t,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:l}=i;if(i.props=!0,l.removeAdditional!=="all"&&(0,Li.alwaysValidSchema)(i,r))return;let u=(0,Ni.allSchemaProperties)(n.properties),p=(0,Ni.allSchemaProperties)(n.patternProperties);g(),e.ok((0,Rt._)`${s} === ${bA.default.errors}`);function g(){t.forIn("key",o,$=>{!u.length&&!p.length?k($):t.if(x($),()=>k($))})}function x($){let P;if(u.length>8){let C=(0,Li.schemaRefOrVal)(i,n.properties,"properties");P=(0,Ni.isOwnProperty)(t,C,$)}else u.length?P=(0,Rt.or)(...u.map(C=>(0,Rt._)`${$} === ${C}`)):P=Rt.nil;return p.length&&(P=(0,Rt.or)(P,...p.map(C=>(0,Rt._)`${(0,Ni.usePattern)(e,C)}.test(${$})`))),(0,Rt.not)(P)}function y($){t.code((0,Rt._)`delete ${o}[${$}]`)}function k($){if(l.removeAdditional==="all"||l.removeAdditional&&r===!1){y($);return}if(r===!1){e.setParams({additionalProperty:$}),e.error(),a||t.break();return}if(typeof r=="object"&&!(0,Li.alwaysValidSchema)(i,r)){let P=t.name("valid");l.removeAdditional==="failing"?(T($,P,!1),t.if((0,Rt.not)(P),()=>{e.reset(),y($)})):(T($,P),a||t.if((0,Rt.not)(P),()=>t.break()))}}function T($,P,C){let j={keyword:"additionalProperties",dataProp:$,dataPropType:Li.Type.Str};C===!1&&Object.assign(j,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(j,P)}}};Ld.default=vA});var _b=q(Ud=>{"use strict";Object.defineProperty(Ud,"__esModule",{value:!0});var _A=go(),wb=mt(),Dd=pe(),vb=jd(),SA={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:o,it:s}=e;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&vb.default.code(new _A.KeywordCxt(s,vb.default,"additionalProperties"));let i=(0,wb.allSchemaProperties)(r);for(let g of i)s.definedProperties.add(g);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Dd.mergeEvaluated.props(t,(0,Dd.toHash)(i),s.props));let a=i.filter(g=>!(0,Dd.alwaysValidSchema)(s,r[g]));if(a.length===0)return;let l=t.name("valid");for(let g of a)u(g)?p(g):(t.if((0,wb.propertyInData)(t,o,g,s.opts.ownProperties)),p(g),s.allErrors||t.else().var(l,!0),t.endIf()),e.it.definedProperties.add(g),e.ok(l);function u(g){return s.opts.useDefaults&&!s.compositeRule&&r[g].default!==void 0}function p(g){e.subschema({keyword:"properties",schemaProp:g,dataProp:g},l)}}};Ud.default=SA});var Tb=q(Md=>{"use strict";Object.defineProperty(Md,"__esModule",{value:!0});var Sb=mt(),ji=re(),kb=pe(),xb=pe(),kA={keyword:"patternProperties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,data:n,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,Sb.allSchemaProperties)(r),l=a.filter(T=>(0,kb.alwaysValidSchema)(s,r[T]));if(a.length===0||l.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,p=t.name("valid");s.props!==!0&&!(s.props instanceof ji.Name)&&(s.props=(0,xb.evaluatedPropsToName)(t,s.props));let{props:g}=s;x();function x(){for(let T of a)u&&y(T),s.allErrors?k(T):(t.var(p,!0),k(T),t.if(p))}function y(T){for(let $ in u)new RegExp(T).test($)&&(0,kb.checkStrictMode)(s,`property ${$} matches pattern ${T} (use allowMatchingProperties)`)}function k(T){t.forIn("key",n,$=>{t.if((0,ji._)`${(0,Sb.usePattern)(e,T)}.test(${$})`,()=>{let P=l.includes(T);P||e.subschema({keyword:"patternProperties",schemaProp:T,dataProp:$,dataPropType:xb.Type.Str},p),s.opts.unevaluated&&g!==!0?t.assign((0,ji._)`${g}[${$}]`,!0):!P&&!s.allErrors&&t.if((0,ji.not)(p),()=>t.break())})})}}};Md.default=kA});var Rb=q(qd=>{"use strict";Object.defineProperty(qd,"__esModule",{value:!0});var xA=pe(),TA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,xA.alwaysValidSchema)(n,r)){e.fail();return}let o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};qd.default=TA});var $b=q(zd=>{"use strict";Object.defineProperty(zd,"__esModule",{value:!0});var RA=mt(),$A={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:RA.validateUnion,error:{message:"must match a schema in anyOf"}};zd.default=$A});var Eb=q(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});var Di=re(),EA=pe(),PA={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,Di._)`{passingSchemas: ${e.passing}}`},AA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:PA,code(e){let{gen:t,schema:r,parentSchema:n,it:o}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=t.let("valid",!1),a=t.let("passing",null),l=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((p,g)=>{let x;(0,EA.alwaysValidSchema)(o,p)?t.var(l,!0):x=e.subschema({keyword:"oneOf",schemaProp:g,compositeRule:!0},l),g>0&&t.if((0,Di._)`${l} && ${i}`).assign(i,!1).assign(a,(0,Di._)`[${a}, ${g}]`).else(),t.if(l,()=>{t.assign(i,!0),t.assign(a,g),x&&e.mergeEvaluated(x,Di.Name)})})}}};Bd.default=AA});var Pb=q(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var CA=pe(),IA={keyword:"allOf",schemaType:"array",code(e){let{gen:t,schema:r,it:n}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=t.name("valid");r.forEach((s,i)=>{if((0,CA.alwaysValidSchema)(n,s))return;let a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};Fd.default=IA});var Ib=q(Hd=>{"use strict";Object.defineProperty(Hd,"__esModule",{value:!0});var Ui=re(),Cb=pe(),OA={message:({params:e})=>(0,Ui.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Ui._)`{failingKeyword: ${e.ifClause}}`},NA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:OA,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,Cb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Ab(n,"then"),s=Ab(n,"else");if(!o&&!s)return;let i=t.let("valid",!0),a=t.name("_valid");if(l(),e.reset(),o&&s){let p=t.let("ifClause");e.setParams({ifClause:p}),t.if(a,u("then",p),u("else",p))}else o?t.if(a,u("then")):t.if((0,Ui.not)(a),u("else"));e.pass(i,()=>e.error(!0));function l(){let p=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(p)}function u(p,g){return()=>{let x=e.subschema({keyword:p},a);t.assign(i,a),e.mergeValidEvaluated(x,i),g?t.assign(g,(0,Ui._)`${p}`):e.setParams({ifClause:p})}}}};function Ab(e,t){let r=e.schema[t];return r!==void 0&&!(0,Cb.alwaysValidSchema)(e,r)}Hd.default=NA});var Ob=q(Vd=>{"use strict";Object.defineProperty(Vd,"__esModule",{value:!0});var LA=pe(),jA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,LA.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Vd.default=jA});var Nb=q(Kd=>{"use strict";Object.defineProperty(Kd,"__esModule",{value:!0});var DA=Ed(),UA=db(),MA=Pd(),qA=pb(),zA=hb(),BA=gb(),FA=bb(),HA=jd(),VA=_b(),KA=Tb(),WA=Rb(),GA=$b(),JA=Eb(),YA=Pb(),XA=Ib(),ZA=Ob();function QA(e=!1){let t=[WA.default,GA.default,JA.default,YA.default,XA.default,ZA.default,FA.default,HA.default,BA.default,VA.default,KA.default];return e?t.push(UA.default,qA.default):t.push(DA.default,MA.default),t.push(zA.default),t}Kd.default=QA});var Lb=q(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});var Te=re(),eC={message:({schemaCode:e})=>(0,Te.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,Te._)`{format: ${e}}`},tC={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:eC,code(e,t){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:l,errSchemaPath:u,schemaEnv:p,self:g}=a;if(!l.validateFormats)return;o?x():y();function x(){let k=r.scopeValue("formats",{ref:g.formats,code:l.code.formats}),T=r.const("fDef",(0,Te._)`${k}[${i}]`),$=r.let("fType"),P=r.let("format");r.if((0,Te._)`typeof ${T} == "object" && !(${T} instanceof RegExp)`,()=>r.assign($,(0,Te._)`${T}.type || "string"`).assign(P,(0,Te._)`${T}.validate`),()=>r.assign($,(0,Te._)`"string"`).assign(P,T)),e.fail$data((0,Te.or)(C(),j()));function C(){return l.strictSchema===!1?Te.nil:(0,Te._)`${i} && !${P}`}function j(){let H=p.$async?(0,Te._)`(${T}.async ? await ${P}(${n}) : ${P}(${n}))`:(0,Te._)`${P}(${n})`,G=(0,Te._)`(typeof ${P} == "function" ? ${H} : ${P}.test(${n}))`;return(0,Te._)`${P} && ${P} !== true && ${$} === ${t} && !${G}`}}function y(){let k=g.formats[s];if(!k){C();return}if(k===!0)return;let[T,$,P]=j(k);T===t&&e.pass(H());function C(){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 j(G){let Re=G instanceof RegExp?(0,Te.regexpCode)(G):l.code.formats?(0,Te._)`${l.code.formats}${(0,Te.getProperty)(s)}`:void 0,qe=r.scopeValue("formats",{key:s,ref:G,code:Re});return typeof G=="object"&&!(G instanceof RegExp)?[G.type||"string",G.validate,(0,Te._)`${qe}.validate`]:["string",G,qe]}function H(){if(typeof k=="object"&&!(k instanceof RegExp)&&k.async){if(!p.$async)throw new Error("async format in sync schema");return(0,Te._)`await ${P}(${n})`}return typeof $=="function"?(0,Te._)`${P}(${n})`:(0,Te._)`${P}.test(${n})`}}}};Wd.default=tC});var jb=q(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});var rC=Lb(),nC=[rC.default];Gd.default=nC});var Db=q(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.contentVocabulary=yn.metadataVocabulary=void 0;yn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];yn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Mb=q(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var oC=Ky(),sC=ib(),iC=Nb(),aC=jb(),Ub=Db(),lC=[oC.default,sC.default,(0,iC.default)(),aC.default,Ub.metadataVocabulary,Ub.contentVocabulary];Jd.default=lC});var zb=q(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.DiscrError=void 0;var qb;(function(e){e.Tag="tag",e.Mapping="mapping"})(qb||(Mi.DiscrError=qb={}))});var Fb=q(Xd=>{"use strict";Object.defineProperty(Xd,"__esModule",{value:!0});var bn=re(),Yd=zb(),Bb=bi(),cC=yo(),dC=pe(),uC={message:({params:{discrError:e,tagName:t}})=>e===Yd.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:r}})=>(0,bn._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`},pC={keyword:"discriminator",type:"object",schemaType:"object",error:uC,code(e){let{gen:t,data:r,schema:n,parentSchema:o,it:s}=e,{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=t.let("valid",!1),u=t.const("tag",(0,bn._)`${r}${(0,bn.getProperty)(a)}`);t.if((0,bn._)`typeof ${u} == "string"`,()=>p(),()=>e.error(!1,{discrError:Yd.DiscrError.Tag,tag:u,tagName:a})),e.ok(l);function p(){let y=x();t.if(!1);for(let k in y)t.elseIf((0,bn._)`${u} === ${k}`),t.assign(l,g(y[k]));t.else(),e.error(!1,{discrError:Yd.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function g(y){let k=t.name("valid"),T=e.subschema({keyword:"oneOf",schemaProp:y},k);return e.mergeEvaluated(T,bn.Name),k}function x(){var y;let k={},T=P(o),$=!0;for(let H=0;H<i.length;H++){let G=i[H];if(G?.$ref&&!(0,dC.schemaHasRulesButRef)(G,s.self.RULES)){let qe=G.$ref;if(G=Bb.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,qe),G instanceof Bb.SchemaEnv&&(G=G.schema),G===void 0)throw new cC.default(s.opts.uriResolver,s.baseId,qe)}let Re=(y=G?.properties)===null||y===void 0?void 0:y[a];if(typeof Re!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);$=$&&(T||P(G)),C(Re,H)}if(!$)throw new Error(`discriminator: "${a}" must be required`);return k;function P({required:H}){return Array.isArray(H)&&H.includes(a)}function C(H,G){if(H.const)j(H.const,G);else if(H.enum)for(let Re of H.enum)j(Re,G);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function j(H,G){if(typeof H!="string"||H in k)throw new Error(`discriminator: "${a}" values must be unique strings`);k[H]=G}}}};Xd.default=pC});var Hb=q((zM,hC)=>{hC.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 Qd=q((Se,Zd)=>{"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 mC=qy(),fC=Mb(),gC=Fb(),Vb=Hb(),yC=["/properties"],qi="http://json-schema.org/draft-07/schema",wn=class extends mC.default{_addVocabularies(){super._addVocabularies(),fC.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(gC.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(Vb,yC):Vb;this.addMetaSchema(t,qi,!1),this.refs["http://json-schema.org/schema"]=qi}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(qi)?qi:void 0)}};Se.Ajv=wn;Zd.exports=Se=wn;Zd.exports.Ajv=wn;Object.defineProperty(Se,"__esModule",{value:!0});Se.default=wn;var bC=go();Object.defineProperty(Se,"KeywordCxt",{enumerable:!0,get:function(){return bC.KeywordCxt}});var vn=re();Object.defineProperty(Se,"_",{enumerable:!0,get:function(){return vn._}});Object.defineProperty(Se,"str",{enumerable:!0,get:function(){return vn.str}});Object.defineProperty(Se,"stringify",{enumerable:!0,get:function(){return vn.stringify}});Object.defineProperty(Se,"nil",{enumerable:!0,get:function(){return vn.nil}});Object.defineProperty(Se,"Name",{enumerable:!0,get:function(){return vn.Name}});Object.defineProperty(Se,"CodeGen",{enumerable:!0,get:function(){return vn.CodeGen}});var wC=gi();Object.defineProperty(Se,"ValidationError",{enumerable:!0,get:function(){return wC.default}});var vC=yo();Object.defineProperty(Se,"MissingRefError",{enumerable:!0,get:function(){return vC.default}})});var Qb=q(Dt=>{"use strict";Object.defineProperty(Dt,"__esModule",{value:!0});Dt.formatNames=Dt.fastFormats=Dt.fullFormats=void 0;function jt(e,t){return{validate:e,compare:t}}Dt.fullFormats={date:jt(Jb,nu),time:jt(tu(!0),ou),"date-time":jt(Kb(!0),Xb),"iso-time":jt(tu(),Yb),"iso-date-time":jt(Kb(),Zb),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:RC,"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:OC,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:$C,int32:{type:"number",validate:AC},int64:{type:"number",validate:CC},float:{type:"number",validate:Gb},double:{type:"number",validate:Gb},password:!0,binary:!0};Dt.fastFormats={...Dt.fullFormats,date:jt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,nu),time:jt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ou),"date-time":jt(/^\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,Xb),"iso-time":jt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Yb),"iso-date-time":jt(/^\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,Zb),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};Dt.formatNames=Object.keys(Dt.fullFormats);function _C(e){return e%4===0&&(e%100!==0||e%400===0)}var SC=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,kC=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Jb(e){let t=SC.exec(e);if(!t)return!1;let r=+t[1],n=+t[2],o=+t[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&_C(r)?29:kC[n])}function nu(e,t){if(e&&t)return e>t?1:e<t?-1:0}var eu=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function tu(e){return function(r){let n=eu.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||e&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let g=s-p*l,x=o-u*l-(g<0?1:0);return(x===23||x===-1)&&(g===59||g===-1)&&i<61}}function ou(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}function Yb(e,t){if(!(e&&t))return;let r=eu.exec(e),n=eu.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}var ru=/t|\s/i;function Kb(e){let t=tu(e);return function(n){let o=n.split(ru);return o.length===2&&Jb(o[0])&&t(o[1])}}function Xb(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}function Zb(e,t){if(!(e&&t))return;let[r,n]=e.split(ru),[o,s]=t.split(ru),i=nu(r,o);if(i!==void 0)return i||ou(n,s)}var xC=/\/|:/,TC=/^(?:[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 RC(e){return xC.test(e)&&TC.test(e)}var Wb=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function $C(e){return Wb.lastIndex=0,Wb.test(e)}var EC=-(2**31),PC=2**31-1;function AC(e){return Number.isInteger(e)&&e<=PC&&e>=EC}function CC(e){return Number.isInteger(e)}function Gb(){return!0}var IC=/[^\\]\\Z/;function OC(e){if(IC.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}});var ew=q(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.formatLimitDefinition=void 0;var NC=Qd(),$t=re(),hr=$t.operators,zi={formatMaximum:{okStr:"<=",ok:hr.LTE,fail:hr.GT},formatMinimum:{okStr:">=",ok:hr.GTE,fail:hr.LT},formatExclusiveMaximum:{okStr:"<",ok:hr.LT,fail:hr.GTE},formatExclusiveMinimum:{okStr:">",ok:hr.GT,fail:hr.LTE}},LC={message:({keyword:e,schemaCode:t})=>(0,$t.str)`should be ${zi[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,$t._)`{comparison: ${zi[e].okStr}, limit: ${t}}`};_n.formatLimitDefinition={keyword:Object.keys(zi),type:"string",schemaType:"string",$data:!0,error:LC,code(e){let{gen:t,data:r,schemaCode:n,keyword:o,it:s}=e,{opts:i,self:a}=s;if(!i.validateFormats)return;let l=new NC.KeywordCxt(s,a.RULES.all.format.definition,"format");l.$data?u():p();function u(){let x=t.scopeValue("formats",{ref:a.formats,code:i.code.formats}),y=t.const("fmt",(0,$t._)`${x}[${l.schemaCode}]`);e.fail$data((0,$t.or)((0,$t._)`typeof ${y} != "object"`,(0,$t._)`${y} instanceof RegExp`,(0,$t._)`typeof ${y}.compare != "function"`,g(y)))}function p(){let x=l.schema,y=a.formats[x];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${o}": format "${x}" does not define "compare" function`);let k=t.scopeValue("formats",{key:x,ref:y,code:i.code.formats?(0,$t._)`${i.code.formats}${(0,$t.getProperty)(x)}`:void 0});e.fail$data(g(k))}function g(x){return(0,$t._)`${x}.compare(${r}, ${n}) ${zi[o].fail} 0`}},dependencies:["format"]};var jC=e=>(e.addKeyword(_n.formatLimitDefinition),e);_n.default=jC});var ow=q((Io,nw)=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0});var Sn=Qb(),DC=ew(),su=re(),tw=new su.Name("fullFormats"),UC=new su.Name("fastFormats"),iu=(e,t={keywords:!0})=>{if(Array.isArray(t))return rw(e,t,Sn.fullFormats,tw),e;let[r,n]=t.mode==="fast"?[Sn.fastFormats,UC]:[Sn.fullFormats,tw],o=t.formats||Sn.formatNames;return rw(e,o,r,n),t.keywords&&(0,DC.default)(e),e};iu.get=(e,t="full")=>{let n=(t==="fast"?Sn.fastFormats:Sn.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function rw(e,t,r,n){var o,s;(o=(s=e.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,su._)`require("ajv-formats/dist/formats").${n}`);for(let i of t)e.addFormat(i,r[i])}nw.exports=Io=iu;Object.defineProperty(Io,"__esModule",{value:!0});Io.default=iu});function MC(){let e=new sw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,iw.default)(e),e}var sw,iw,Bi,aw=D(()=>{sw=ku(Qd(),1),iw=ku(ow(),1);Bi=class{constructor(t){this._ajv=t??MC()}getValidator(t){let r="$id"in t&&typeof t.$id=="string"?this._ajv.getSchema(t.$id)??this._ajv.compile(t):this._ajv.compile(t);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var Fi,lw=D(()=>{on();Fi=class{constructor(t){this._server=t}requestStream(t,r,n){return this._server.requestStream(t,r,n)}createMessageStream(t,r){let n=this._server.getClientCapabilities();if((t.tools||t.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let o=t.messages[t.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(p=>p.type==="tool_result"),a=t.messages.length>1?t.messages[t.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(x=>x.type==="tool_use").map(x=>x.id)),g=new Set(s.filter(x=>x.type==="tool_result").map(x=>x.toolUseId));if(p.size!==g.size||![...p].every(x=>g.has(x)))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:t},Qn,r)}elicitInputStream(t,r){let n=this._server.getClientCapabilities(),o=t.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"&&t.mode===void 0?{...t,mode:"form"}:t;return this.requestStream({method:"elicitation/create",params:s},nn,r)}async getTask(t,r){return this._server.getTask({taskId:t},r)}async getTaskResult(t,r,n){return this._server.getTaskResult({taskId:t},r,n)}async listTasks(t,r){return this._server.listTasks(t?{cursor:t}:void 0,r)}async cancelTask(t,r){return this._server.cancelTask({taskId:t},r)}}});function cw(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"tools/call":if(!e.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${t})`);break;default:break}}function dw(e,t,r){if(!e)throw new Error(`${r} does not support task creation (required for ${t})`);switch(t){case"sampling/createMessage":if(!e.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${t})`);break;case"elicitation/create":if(!e.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${t})`);break;default:break}}var uw=D(()=>{});var Hi,pw=D(()=>{ng();on();aw();Fn();lw();uw();Hi=class extends ni{constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Zn.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 Bi,this.setRequestHandler(fl,n=>this._oninitialize(n)),this.setNotificationHandler(gl,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(kl,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Zn.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Fi(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=rg(this._capabilities,t)}setRequestHandler(t,r){let o=rr(t)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Zr(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=tr(rn,l);if(!p.success){let k=p.error instanceof Error?p.error.message:String(p.error);throw new B(V.InvalidParams,`Invalid tools/call request: ${k}`)}let{params:g}=p.data,x=await Promise.resolve(r(l,u));if(g.task){let k=tr(en,x);if(!k.success){let T=k.error instanceof Error?k.error.message:String(k.error);throw new B(V.InvalidParams,`Invalid task creation result: ${T}`)}return k.data}let y=tr(Vs,x);if(!y.success){let k=y.error instanceof Error?y.error.message:String(y.error);throw new B(V.InvalidParams,`Invalid tools/call result: ${k}`)}return y.data};return super.setRequestHandler(t,a)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);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 ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);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 ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);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 ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){dw(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&cw(this._capabilities.tasks?.requests,t,"Server")}async _oninitialize(t){let r=t.params.protocolVersion;return this._clientCapabilities=t.params.capabilities,this._clientVersion=t.params.clientInfo,{protocolVersion:ef.includes(r)?r:dl,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Ps)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=t.messages.length>1?t.messages[t.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 t.tools?this.request({method:"sampling/createMessage",params:t},xl,r):this.request({method:"sampling/createMessage",params:t},Qn,r)}async elicitInput(t,r){switch(t.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=t;return this.request({method:"elicitation/create",params:o},nn,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=t.mode==="form"?t:{...t,mode:"form"},s=await this.request({method:"elicitation/create",params:o},nn,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(V.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof B?i:new B(V.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(t,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:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},Tl,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}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 au(e){return!!e&&typeof e=="object"&&mw in e}function fw(e){return e[mw]?.complete}var mw,hw,gw=D(()=>{mw=Symbol.for("mcp.completable");(function(e){e.Completable="McpCompletable"})(hw||(hw={}))});var yw=D(()=>{});function zC(e){let t=[];if(e.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(" ")&&t.push("Tool name contains spaces, which may cause parsing issues"),e.includes(",")&&t.push("Tool name contains commas, which may cause parsing issues"),(e.startsWith("-")||e.endsWith("-"))&&t.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(e.startsWith(".")||e.endsWith("."))&&t.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!qC.test(e)){let r=e.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return t.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:t}}return{isValid:!0,warnings:t}}function BC(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let r of t)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 lu(e){let t=zC(e);return BC(e,t.warnings),t.isValid}var qC,bw=D(()=>{qC=/^[A-Za-z0-9._-]{1,128}$/});var Vi,ww=D(()=>{Vi=class{constructor(t){this._mcpServer=t}registerToolTask(t,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${t}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(t,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});import{ZodOptional as FC}from"zod";function HC(e,t){let r=0,n=[e];for(;n.length>0;){let o=n.pop();if(!(o===null||typeof o!="object"))if(Array.isArray(o))for(let s of o){if(++r>t)return r;s!==null&&typeof s=="object"&&n.push(s)}else for(let s in o){if(!Object.prototype.hasOwnProperty.call(o,s))continue;if(++r>t)return r;let i=o[s];i!==null&&typeof i=="object"&&n.push(i)}}return r}function VC(e){if(!(e===void 0||e===1/0)){if(typeof e!="number"||Number.isNaN(e)||e<1)throw new RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}function Sw(e){return e!==null&&typeof e=="object"&&"parse"in e&&typeof e.parse=="function"&&"safeParse"in e&&typeof e.safeParse=="function"}function kw(e){return"_def"in e||"_zod"in e||Sw(e)}function cu(e){return typeof e!="object"||e===null||kw(e)?!1:Object.keys(e).length===0?!0:Object.values(e).some(Sw)}function vw(e){if(e){if(cu(e))return Sr(e);if(!kw(e))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return e}}function WC(e){let t=rr(e);return t?Object.entries(t).map(([r,n])=>{let o=Zm(n),s=Qm(n);return{name:r,description:o,required:!s}}):[]}function mr(e){let r=rr(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zr(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function _w(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}var Ki,KC,Oo,xw=D(()=>{pw();Fn();lc();on();gw();yw();bw();ww();Ki=class{constructor(t,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Hi(t,r),this._maxToolInputElements=VC(r?.maxToolInputElements),r?.capabilities?.tools&&this.setToolRequestHandlers(),r?.capabilities?.resources&&this.setResourceRequestHandlers(),r?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||(this._experimental={tasks:new Vi(this)}),this._experimental}async connect(t){return await this.server.connect(t)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Hs)),this.server.assertCanSetRequestHandler(mr(rn)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Hs,()=>({tools:Object.entries(this._registeredTools).filter(([,t])=>t.enabled).map(([t,r])=>{let n={name:t,title:r.title,description:r.description,inputSchema:(()=>{let o=Xr(r.inputSchema);return o?sc(o,{strictUnions:!0,pipeStrategy:"input"}):KC})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Xr(r.outputSchema);o&&(n.outputSchema=sc(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(rn,async(t,r)=>{try{let n=this._registeredTools[t.params.name];if(!n)throw new B(V.InvalidParams,`Tool ${t.params.name} not found`);if(!n.enabled)throw new B(V.InvalidParams,`Tool ${t.params.name} disabled`);let o=!!t.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new B(V.InternalError,`Tool ${t.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new B(V.MethodNotFound,`Tool ${t.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,t,r);let a=await this.validateToolInput(n,t.params.arguments,t.params.name),l=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,l,t.params.name),l}catch(n){if(n instanceof B&&n.code===V.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(t){return{content:[{type:"text",text:t}],isError:!0}}async validateToolInput(t,r,n){if(this._maxToolInputElements!==void 0&&HC(r,this._maxToolInputElements)>this._maxToolInputElements)throw new B(V.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!t.inputSchema)return;let s=Xr(t.inputSchema)??t.inputSchema,i=await xs(s,r??{});if(!i.success){let a="error"in i?i.error:"Unknown error",l=Ts(a);throw new B(V.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${l}`)}return i.data}async validateToolOutput(t,r,n){if(!t.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new B(V.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Xr(t.outputSchema),s=await xs(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ts(i);throw new B(V.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(t,r,n){let o=t.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(t.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(t.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(t,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(t,r.params.arguments,r.params.name),s=t.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(x=>setTimeout(x,p));let g=await n.taskStore.getTask(l);if(!g)throw new B(V.InternalError,`Task ${l} not found during polling`);u=g}return await n.taskStore.getTaskResult(l)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(mr(Ks)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ks,async t=>{switch(t.params.ref.type){case"ref/prompt":return yf(t),this.handlePromptCompletion(t,t.params.ref);case"ref/resource":return bf(t),this.handleResourceCompletion(t,t.params.ref);default:throw new B(V.InvalidParams,`Invalid completion reference: ${t.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(t,r){let n=this._registeredPrompts[r.name];if(!n)throw new B(V.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new B(V.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Oo;let s=rr(n.argsSchema)?.[t.params.argument.name];if(!au(s))return Oo;let i=fw(s);if(!i)return Oo;let a=await i(t.params.argument.value,t.params.context);return _w(a)}async handleResourceCompletion(t,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Oo;throw new B(V.InvalidParams,`Resource template ${t.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(t.params.argument.name);if(!o)return Oo;let s=await o(t.params.argument.value,t.params.context);return _w(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Ms)),this.server.assertCanSetRequestHandler(mr(qs)),this.server.assertCanSetRequestHandler(mr(zs)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Ms,async(t,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(qs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(zs,async(t,r)=>{let n=new URL(t.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new B(V.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(V.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Bs)),this.server.assertCanSetRequestHandler(mr(Fs)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Bs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,t])=>t.enabled).map(([t,r])=>({name:t,title:r.title,description:r.description,arguments:r.argsSchema?WC(r.argsSchema):void 0}))})),this.server.setRequestHandler(Fs,async(t,r)=>{let n=this._registeredPrompts[t.params.name];if(!n)throw new B(V.InvalidParams,`Prompt ${t.params.name} not found`);if(!n.enabled)throw new B(V.InvalidParams,`Prompt ${t.params.name} disabled`);if(n.argsSchema){let o=Xr(n.argsSchema),s=await xs(o,t.params.arguments??{});if(!s.success){let l="error"in s?s.error:"Unknown error",u=Ts(l);throw new B(V.InvalidParams,`Invalid arguments for prompt ${t.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(t,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(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let i=this._createRegisteredResourceTemplate(t,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(t,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[t])throw new Error(`Resource template ${t} is already registered`);let s=this._createRegisteredResourceTemplate(t,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(t,r,n,o,s){let i={name:t,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(t,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!==t&&(delete this._registeredResourceTemplates[t],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[t]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(t,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Sr(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!==t&&(delete this._registeredPrompts[t],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=Sr(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[t]=i,o&&Object.values(o).some(l=>{let u=l instanceof FC?l._def?.innerType:l;return au(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(t,r,n,o,s,i,a,l,u){lu(t);let p={title:r,description:n,inputSchema:vw(o),outputSchema:vw(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!==t&&(typeof g.name=="string"&&lu(g.name),delete this._registeredTools[t],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=Sr(g.paramsSchema)),typeof g.outputSchema<"u"&&(p.outputSchema=Sr(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[t]=p,this.setToolRequestHandlers(),this.sendToolListChanged(),p}tool(t,...r){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let l=r[0];if(cu(l))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!cu(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 ${t} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(t,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(t,r,n){if(this._registeredTools[t])throw new Error(`Tool ${t} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:l,_meta:u}=r;return this._createRegisteredTool(t,o,s,i,a,l,{taskSupport:"forbidden"},u,n)}prompt(t,...r){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} 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(t,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(t,r,n){if(this._registeredPrompts[t])throw new Error(`Prompt ${t} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(t,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(t,r){return this.server.sendLoggingMessage(t,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},KC={type:"object",properties:{}};Oo={completion:{values:[],hasMore:!1}}});function JC(e){return cf.parse(JSON.parse(e))}function Tw(e){return JSON.stringify(e)+`
|
|
2462
|
+
`}var GC,Wi,Rw=D(()=>{on();GC=10*1024*1024,Wi=class{constructor(t){this._maxBufferSize=t?.maxBufferSize??GC}append(t){if((this._buffer?.length??0)+t.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,t]):t}readMessage(){if(!this._buffer)return null;let t=this._buffer.indexOf(`
|
|
2463
|
+
`);if(t===-1)return null;let r=this._buffer.toString("utf8",0,t).replace(/\r$/,"");return this._buffer=this._buffer.subarray(t+1),JC(r)}clear(){this._buffer=void 0}}});import $w from"node:process";var Gi,Ew=D(()=>{Rw();Gi=class{constructor(t=$w.stdin,r=$w.stdout,n){this._stdin=t,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 Wi({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 t=this._readBuffer.readMessage();if(t===null)break;this.onmessage?.(t)}catch(t){this.onerror?.(t)}}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(t){return new Promise(r=>{let n=Tw(t);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Pw,Aw=D(()=>{Pw=[]});var Mw={};Su(Mw,{AUTHORING_MCP_SERVER_NAME:()=>Nw,AUTHORING_MCP_SERVER_VERSION:()=>Lw,AUTHORING_RESOURCES:()=>rI,AUTHORING_TOOLS:()=>tI,AUTHORING_TOOLS_PUBLIC:()=>Uw,buildAuthoringMcpServer:()=>Dw,resolveSamplesDir:()=>jw,runAuthoringMcpServer:()=>nI});import{promises as YC}from"node:fs";import{isAbsolute as XC,resolve as Ji,sep as ZC}from"node:path";import{z as U}from"zod";function Ow(){return Iw??=import("../mcp/grounding.js").then(t=>t,()=>null),Iw}function jw(e,t){if(t===void 0)return Ji(process.cwd(),e??"samples");let r=Ji(t);if(e===void 0)return r;if(XC(e))return null;let n=Ji(r,e);return n===r||n.startsWith(r+ZC)?n:null}function ke(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}]}}async function eI(e,t={}){let r=t.fetchImpl??fetch;try{let n=await r(`${e.baseUrl.replace(/\/+$/,"")}/v1/extensions`,{headers:{Authorization:`Bearer ${e.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 Dw(e={}){async function t(){if(e.resolveTenant)return e.resolveTenant();let y=await yt(e.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=e.grounding??{},n=await Ow(),o=null;if(n)try{let y=await t();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 eI(o,r):null,p=new Ki({name:Nw,version:Lw},n?{instructions:n.renderAuthoringInstructions({baseUrl:e.displayBaseUrl??o?.baseUrl??e.baseUrl??"this instance",sources:s,recipeIntents:l,promptNames:a.map(y=>y.id),deployedExtensions:u,docsToken:r.docsToken??n.docsPublicToken()})}:void 0);if(n&&o){let y=o;for(let k of a)p.registerPrompt(k.id,{title:k.name,description:k.description},async()=>{let T=await n.getMcpPromptSkill(y,k.id,r);if(!T)throw new Error(`unknown prompt: ${k.id}`);return{description:T.description,messages:[{role:"user",content:{type:"text",text:(T.prompts??[]).join(`
|
|
2446
2464
|
|
|
2447
|
-
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await t(),R=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog fetch failed: ${R.status}`);return ke(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: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:y,source:k})=>{let{baseUrl:R,token:$}=await t(),P=k?`?source=${encodeURIComponent(k)}`:"",C=await fetch(`${R}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(C.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`record anatomy fetch failed: ${C.status}`);return ke(await C.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes: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:y,source:k})=>{let{baseUrl:R,token:$}=await t(),P=new URLSearchParams({types:y.join(",")});k&&P.set("source",k);let C=await fetch(`${R}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(C.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`common columns fetch failed: ${C.status}`);return ke(await C.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await t(),R=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!R.ok)throw new Error(`catalog census failed: ${R.status}`);return ke(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:U.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:U.enum(Aw).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:y,kind:k,limit:R})=>{let{baseUrl:$,token:P}=await t(),C=new URLSearchParams({q:y});k&&C.set("kind",k),R!==void 0&&C.set("limit",String(R));let j=await fetch(`${$}/v1/catalog/objects?${C}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!j.ok)throw new Error(`catalog object search failed: ${j.status}`);return ke(await j.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(Aw),externalId:U.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:k})=>{let{baseUrl:R,token:$}=await t(),P=await fetch(`${R}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${k} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return 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:y,limit:k})=>{let{baseUrl:R,token:$}=await t(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let C=await fetch(`${R}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!C.ok)throw new Error(`kb search failed: ${C.status}`);return ke(await C.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:U.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:k,token:R}=await t(),$=await fetch(`${k}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return ke(await $.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:y,limit:k})=>{let{baseUrl:R,token:$}=await t(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let C=await fetch(`${R}/v1/catalog/docs/search?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!C.ok)throw new Error(`turbobase docs search failed: ${C.status}`);return ke(await C.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:y})=>{let{baseUrl:k,token:R}=await t(),$=await fetch(`${k}/v1/catalog/docs/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${R}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`turbobase doc fetch failed: ${$.status}`);return ke(await $.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:y})=>{let{baseUrl:k,token:R}=await t();return{content:[{type:"text",text:await br({baseUrl:k,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: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 y=>{let k=Ct("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return ke({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source: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(Ur).optional().describe("Conduit lifecycle event (default after_canonicalize_inbound)."),id:U.string().optional()}},async y=>{let k=Ct("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return ke({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType: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 y=>{let k=Ct("process",{recordType:y.recordType,then:y.then,onFailure:y.onFailure,id:y.id});return ke({path:k.relativePath,content:k.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent: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 y=>{let{baseUrl:k,token:R}=await t(),$=new z({baseUrl:k,token:R});return ke(await $.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:U.string().describe("The extension TS source."),samplesDir:U.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:k})=>{let R=Lw(k,e.samplesRoot);if(R===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:ZC})}],isError:!0};let $;try{$=await An(R)}catch(j){if(e.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw j}let P=await ns(y,$.map(j=>j.fixture)),C=P.filter(j=>!j.pass).length;return ke({total:P.length,passed:P.length-C,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id: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 y=>{let{baseUrl:k,token:R}=await t(),P=await new z({baseUrl:k,token:R}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.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:y,limit:k})=>{let{baseUrl:R,token:$}=await t(),P=new z({baseUrl:R,token:$});return ke({id:y,logs:await P.logs(y,k)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await t(),R=new z({baseUrl:y,token:k});return ke(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: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:y,name:k,description:R})=>{let{baseUrl:$,token:P}=await t(),C=new z({baseUrl:$,token:P});return ke(await C.appsCreate({slug:y,name:k,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:U.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:k,token:R}=await t(),$=new z({baseUrl:k,token:R});return ke(await $.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: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:y,files:k,note:R})=>{let{baseUrl:$,token:P}=await t(),C=new z({baseUrl:$,token:P});return ke(await C.appsPush(y,k,{note:R}))});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()}),x=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:y,token:k}=await t(),R=new z({baseUrl:y,token:k});return ke(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:U.array(x),claimedBy:U.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await t(),P=new z({baseUrl:R,token:$});return ke(await P.tablesPlan({tables:y,claimedBy:k}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:U.array(x),claimedBy:U.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:R,token:$}=await t(),P=new z({baseUrl:R,token:$});return ke(await P.tablesApply({tables:y,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:k,token:R}=await t(),P=await(await fetch(`${k}/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:k,token:R}=await t(),$=await br({baseUrl:k,token:R});return{contents:[{uri:y.href,mimeType:"text/plain",text:$}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let k=Ji(process.cwd(),"samples"),R=[];try{R=(await JC.readdir(k)).filter(P=>P.endsWith(".json"))}catch{R=[]}let $=await An(k);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:R,samples:$.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async y=>{let k=await Iw(),R=[];if(k){let{baseUrl:$,token:P}=await t();R=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:P},r)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:R})}]}}),p}async function rI(e={}){let t=await jw(e),r=new Gi;await t.connect(r)}var Aw,Cw,Ow,Nw,ZC,Dw,eI,tI,Mw=D(()=>{kw();$w();pa();$n();bt();ka();cs();Pw();Aw=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Ow="turbobase-authoring",Nw="0.1.0";ZC="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.";Dw=["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"],eI=[...Dw,...Ew],tI=["catalog:///","types://all","samples:///","recipes:///"]});pa();$n();bt();ka();import{spawn as mu}from"node:child_process";import{promises as ie}from"node:fs";import{homedir as nI}from"node:os";import{basename as Bw,dirname as Wt,join as nt,relative as Xi,resolve as ne,sep as hu}from"node:path";import{Command as oI}from"commander";rs();import{promises as pp}from"node:fs";var n_=/^[a-z][a-z0-9_]+$/;function ap(e,t){if(typeof e!="string"||!n_.test(e))throw new Error(`${t} ${JSON.stringify(e)} 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 e}var o_="customrecord",s_="customlist";function i_(e){return e.startsWith("customrecord_")?e.slice(13):e}function a_(e){return e.startsWith("customlist_")?e.slice(11):e}function l_(e){return ap(e,"custom_record scriptId"),`cr_${i_(e)}`}function c_(e){return ap(e,"custom_list scriptId"),`cl_${a_(e)}`}function lp(e){return e.startsWith(o_)?l_(e):e.startsWith(s_)?c_(e):null}var d_={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:"segment_value",typeColumn:"canonical_segment",typeValue:"location",capabilityTable:"location"},department:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"department",capabilityTable:"department"},classification:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class",capabilityTable:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_entry"},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"},creditCardCharge:{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"charge"},creditCardRefund:{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"refund"},request:{table:"request"}};function cp(e,t){let r=t?p_[`${t}:${e}`]:void 0;if(r)return r;let n=d_[e];if(n)return n;let o=lp(e);return o?{table:o}:void 0}var u_={accountingPeriod:"accounting_period",printer:"printer"};var p_={...Object.fromEntries(Object.entries(u_).map(([e,t])=>[`standalone:${e}`,{table:t}])),"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:user":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"salesforce:queue":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"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"},"xero:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"quickbooks:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"billdotcom:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"workday:organization":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"department"},"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"},"github:project":{table:"board",typeColumn:"kind",typeValue:"project"},"zendesk:ticket_comment":{table:"activity",typeColumn:"activity_type",typeValue:"ticket_comment"},"intercom:conversation_part":{table:"activity",typeColumn:"activity_type",typeValue:"message"},"notion:notion_comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"jira:board":{table:"board",typeColumn:"kind",typeValue:"board"},"jira:project":{table:"board",typeColumn:"kind",typeValue:"project"},"asana:asanaProject":{table:"board",typeColumn:"kind",typeValue:"project"},"asana:asanaSection":{table:"board_field"},"workday:worker":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"notion:notion_document":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"ramp:card_transaction":{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"charge"},"azure_blob:file":{table:"source_file"},"whatsapp:contact":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"whatsapp:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"whatsapp:message":{table:"activity",typeColumn:"activity_type",typeValue:"message"},"whatsapp:phoneNumber":{table:"whatsapp_phone_number"},"whatsapp:messageTemplate":{table:"whatsapp_message_template"},"slack:file":{table:"source_file"}};function dp(e,t){let r=cp(e,t);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function up(e,t,r){if(t===e)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=dp(e,n),i=dp(t,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var hp=4;function xa(e){if(!/\bdefineConduit\s*[<(]/.test(e))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let t=zr(e,"id"),r=zr(e,"on"),n=zr(e,"source"),o=zr(e,"recordType"),s=[];for(let u of e.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let p=zr(u[1]??"","source"),g=zr(u[1]??"","recordType");p&&g&&s.push({source:p,recordType:g})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(e),l=/^[ \t]*reads\s*:\s*\[\s*\{/m.test(e);if(!t||!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:t,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):hp,declaresReads:l}}function zr(e,t){let r=new RegExp(`${t}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return r?r[2]:void 0}function h_(e){return{recordType:e.recordType,event:e.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:e.fromSource,payload:e.payload??{},tenantConfig:e.tenantConfig??{},metadata:{externalId:e.externalId,lines:e.lines??[]},bindings:e.bindings??[],atlasLinks:e.atlasLinks??{}}}function m_(e,t){let r=e.queryRows;if(!(!r||!Object.prototype.hasOwnProperty.call(r,t)))return r[t]}async function mp(e,t,r="fixture",n={}){let o=t.name??r,s=[],i;try{i=xa(e)}catch(g){return{fixtureName:o,conduit:g_(),guards:s,whenPassed:!1,atlasResolutions:[],queryReads:[],wouldWriteBindings:[],targets:[],logs:[],error:g instanceof Error?g.message:String(g)}}let a=h_(t),l=Object.entries(t.atlasLinks??{}).map(([g,x])=>({key:g,resolved:x})),u=[],p=i.declaresReads?async g=>{let x=m_(t,g);return u.push({query:g,served:x!==void 0,rowCount:x?.length??0}),x??[]}:void 0;try{for(let[j,H]of Object.entries(t.queryRows??{}))if(!Array.isArray(H))throw new Error(`fixture queryRows['${j}'] 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 ts(e,{resolveDir:n.resolveDir}),y=!!(await Pn(g,a,{member:"when",timeoutMs:es,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 k=t.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${k} 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=[],$=[],P=[];for(let j=0;j<i.targets.length;j+=1){let H=i.targets[j],G=await Pn(g,{...a,materialized:P.map(Jt=>({...Jt}))},{member:"transform",stepIndex:j,timeoutMs:es,query:p});R.push(...G.effects.logs);let Re=G.effects.result;if(!Re||typeof Re!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${j+1})`:""} returned no result (expected { patch, createdFrom? })`);let qe=Re,Et=up(i.fromRecordType,H.recordType,{fromSource:i.fromSource,toSource:H.source}),{wouldWriteBindings:Gt,masterAction:Pt}=f_(i,H,Et,t);$.push({to:H,transformResult:qe,applyBranch:Et,wouldWriteBindings:Gt,masterAction:Pt}),P.push({source:H.source,recordType:H.recordType,masterTable:`<${H.recordType} master, dry-run>`,masterRowId:`<dry-run target ${j+1}>`,externalId:null})}let C=$[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:y,atlasResolutions:l,queryReads:u,transformResult:C.transformResult,applyBranch:C.applyBranch,wouldWriteBindings:C.wouldWriteBindings,masterAction:C.masterAction,targets:$,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 f_(e,t,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${e.fromRecordType} master (firing source '${e.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:e.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.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 ${t.recordType} master (source_system='${t.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.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 g_(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:hp,declaresReads:!1}}async function fp(e){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 gp(e){let t=await pp.readFile(e,"utf8");return JSON.parse(t)}function yp(e){return pp.readFile(e,"utf8")}function bp(e,t){let r=e.conduit,n=`replay ${e.fixtureName}: ERROR \u2014 ${e.error}`,o=e.targets.length>1;if(!t){if(e.error)return n;if(!e.whenPassed)return`replay ${e.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(o){let l=e.targets.reduce((u,p)=>u+p.wouldWriteBindings.length,0);return`replay ${e.fixtureName} [${r.id}]: OK \u2014 ${e.targets.length} targets in sequence (${l} binding(s) would be written)`}return`replay ${e.fixtureName} [${r.id}]: OK \u2014 ${e.applyBranch} (${e.wouldWriteBindings.length} binding(s) would be written)`}if(e.error&&!r.id)return n;let s=[];s.push(`\u2501\u2501 replay ${e.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):"),e.guards.length===0&&s.push(" (none ran \u2014 the replay stopped before dispatch)");for(let l of e.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):"),e.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let l of e.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(e.queryReads.length===0)s.push(" (declared, but this replay made no read)");else for(let l of e.queryReads)s.push(` ${l.query} \u2192 ${l.served?"served":"not served by the fixture"}, ${l.rowCount} row(s)`);if(e.error)return s.push(""),s.push(`ERROR \u2014 ${e.error}`),s.join(`
|
|
2465
|
+
`)}}]}})}p.registerTool("catalog_get",{title:"Get the instance catalog",description:"Fetch the instance's record-type catalog (/v1/catalog/records).",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await t(),T=await fetch(`${y}/v1/catalog/records`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog fetch failed: ${T.status}`);return ke(await T.json())}),p.registerTool("record_anatomy",{title:"Record anatomy + display contract",description:"Fetch ONE record type in depth (/v1/catalog/records/:type): anatomy markdown (field meanings, sublists, gotchas, relations), authored recipe display contracts (columns/labels/formats), semantic column metadata and the record's plain-English description. Read this BEFORE building UI over a record \u2014 column names alone routinely mislead (e.g. tran_id is the human-facing document number, entity_id has a display twin entity_name). Also reports `unpopulatedColumns`: columns that EXIST but carry no value in any sampled row on this instance (currency_name is the classic \u2014 currency_id holds the data). Rendering one of those produces a blank column while faithfully following the display contract, so check it before choosing what to show. And reports `lines`: the record's LINE tables with their columns, including line-level custom fields (custcol_*). Check the lines before concluding a link is absent \u2014 a transaction routinely carries a reference on its LINES while the header field is NULL, and reading only the header reports a real link as missing.",inputSchema:{recordType: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:y,source:k})=>{let{baseUrl:T,token:$}=await t(),P=k?`?source=${encodeURIComponent(k)}`:"",C=await fetch(`${T}/v1/catalog/records/${encodeURIComponent(y)}${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(C.status===404)throw new Error(`unknown record type "${y}" \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`record anatomy fetch failed: ${C.status}`);return ke(await C.json())}),p.registerTool("common_columns",{title:"Columns common to several record types",description:"Given SEVERAL record types, return the columns present on ALL of them (safe to select in one shared query shape) and the columns present on only some, with exactly which types lack each. Use this BEFORE writing a query that spans record types \u2014 transaction tables are NOT uniform (memo, total, created_from_id and even pg_row_id are missing from some), and PostgREST rejects an unknown column with 42703 and fails the ENTIRE request, so one wrong name loses the whole table rather than one field. Record types the caller cannot read come back in unknownRecordTypes \u2014 if that is non-empty the intersection covers fewer types than you asked for.",inputSchema:{recordTypes: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:y,source:k})=>{let{baseUrl:T,token:$}=await t(),P=new URLSearchParams({types:y.join(",")});k&&P.set("source",k);let C=await fetch(`${T}/v1/catalog/columns?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(C.status===404)throw new Error(`none of those record types resolved: ${y.join(", ")} \u2014 list them with catalog_get.`);if(!C.ok)throw new Error(`common columns fetch failed: ${C.status}`);return ke(await C.json())}),p.registerTool("catalog_census",{title:"Count the customer's customizations",description:'Count the whole customization catalog: every object by kind AND by whether it can be changed (editable / partner_owned / turbobase_managed / unknown), plus which classes were never collected and why. Call this BEFORE search_catalog when the question is "how much is there" / "what is this account made of" / "how much of this is even ours to change". Takes no arguments.',inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await t(),T=await fetch(`${y}/v1/catalog/census`,{headers:{Authorization:`Bearer ${k}`,Accept:"application/json"}});if(!T.ok)throw new Error(`catalog census failed: ${T.status}`);return ke(await T.json())}),p.registerTool("search_catalog",{title:"Search the customization catalog",description:'Survey the customer\'s customization catalog by free text \u2014 scripts, custom records, fields, lists, workflows, roles, saved searches, and installed bundles. Matches ids, names AND the generated plain-English explanations, so ask what you actually want ("which object handles rebates?"), not just an exact id. Returns compact {kind, externalId, name, summary, modifiability} hits plus the TRUE match total, so you can see when the page truncated; pass a hit to explain_object for the full definition + prose. A `partner_owned` object CANNOT be edited by this account however well you understand it \u2014 check that before planning a change. Search this before building over a custom record: its definition and explanation are the spec.',inputSchema:{query:U.string().describe('Free text, e.g. "inbound shipment" or "customscript_recalc".'),kind:U.enum(Cw).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:y,kind:k,limit:T})=>{let{baseUrl:$,token:P}=await t(),C=new URLSearchParams({q:y});k&&C.set("kind",k),T!==void 0&&C.set("limit",String(T));let j=await fetch(`${$}/v1/catalog/objects?${C}`,{headers:{Authorization:`Bearer ${P}`,Accept:"application/json"}});if(!j.ok)throw new Error(`catalog object search failed: ${j.status}`);return ke(await j.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(Cw),externalId:U.string().describe('The source scriptid, e.g. "customrecord_inbound_shipment".')}},async({kind:y,externalId:k})=>{let{baseUrl:T,token:$}=await t(),P=await fetch(`${T}/v1/catalog/objects/${encodeURIComponent(y)}/${encodeURIComponent(k)}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(P.status===404)throw new Error(`unknown object ${y}:${k} \u2014 find it with search_catalog.`);if(!P.ok)throw new Error(`catalog object fetch failed: ${P.status}`);return 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:y,limit:k})=>{let{baseUrl:T,token:$}=await t(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let C=await fetch(`${T}/v1/kb/search?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!C.ok)throw new Error(`kb search failed: ${C.status}`);return ke(await C.json())}),p.registerTool("read_document",{title:"Read a knowledge-base document",description:"Read one published knowledge-base document in full by its slug (from a search_documentation hit). Returns {found, slug, title, body_markdown}. Published release only \u2014 unpublished / admin-only drafts are never returned.",inputSchema:{slug:U.string().describe("The document slug, e.g. one returned by search_documentation.")}},async({slug:y})=>{let{baseUrl:k,token:T}=await t(),$=await fetch(`${k}/v1/kb/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`kb document fetch failed: ${$.status}`);return ke(await $.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:y,limit:k})=>{let{baseUrl:T,token:$}=await t(),P=new URLSearchParams({q:y});k!==void 0&&P.set("limit",String(k));let C=await fetch(`${T}/v1/catalog/docs/search?${P}`,{headers:{Authorization:`Bearer ${$}`,Accept:"application/json"}});if(!C.ok)throw new Error(`turbobase docs search failed: ${C.status}`);return ke(await C.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:y})=>{let{baseUrl:k,token:T}=await t(),$=await fetch(`${k}/v1/catalog/docs/document/${encodeURIComponent(y)}`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}});if(!$.ok&&$.status!==404)throw new Error(`turbobase doc fetch failed: ${$.status}`);return ke(await $.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:y})=>{let{baseUrl:k,token:T}=await t();return{content:[{type:"text",text:await br({baseUrl:k,token:T,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: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 y=>{let k=Ct("hook",{recordType:y.recordType,event:y.event,template:y.template,field:y.field,regex:y.regex,source:y.source,id:y.id});return ke({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_conduit",{title:"Scaffold a conduit",description:"Generate a conduit file body that bridges a canonical record from one source into another (does not write to disk; returns path + content).",inputSchema:{source: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(Dr).optional().describe("Conduit lifecycle event (default after_canonicalize_inbound)."),id:U.string().optional()}},async y=>{let k=Ct("conduit",{recordType:y.recordType,source:y.source,to:y.to,toRecordType:y.toRecordType,event:y.event,id:y.id});return ke({path:k.relativePath,content:k.content})}),p.registerTool("scaffold_process",{title:"Scaffold a process",description:"Generate a process file body \u2014 an ordered sequence of record writes an app invokes and the platform runs on the server (does not write to disk; returns path + content).",inputSchema:{recordType: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 y=>{let k=Ct("process",{recordType:y.recordType,then:y.then,onFailure:y.onFailure,id:y.id});return ke({path:k.relativePath,content:k.content})}),p.registerTool("author_conduit",{title:"Draft and check a conduit",description:'Ask the instance to WRITE a conduit from a plain-English intent and check it before staging it for review \u2014 the cross-source counterpart to the hook the healing agent drafts. Returns {status, intentId, id?, reason?}: "written" staged a proposal, "rejected_by_validation" says why it could not (including a target system this instance can only read from). Nothing is deployed \u2014 an administrator applies the staged bridge from the Conduits tab. Prefer scaffold_conduit when you intend to write the transform yourself.',inputSchema:{intent: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 y=>{let{baseUrl:k,token:T}=await t(),$=new z({baseUrl:k,token:T});return ke(await $.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:U.string().describe("The extension TS source."),samplesDir:U.string().optional().describe('Samples directory (default "samples").')}},async({source:y,samplesDir:k})=>{let T=jw(k,e.samplesRoot);if(T===null)return{content:[{type:"text",text:JSON.stringify({error:"samples_dir_refused",message:QC})}],isError:!0};let $;try{$=await An(T)}catch(j){if(e.samplesRoot!==void 0)return{content:[{type:"text",text:JSON.stringify({error:"samples_unreadable",message:"the samples directory could not be read"})}],isError:!0};throw j}let P=await ns(y,$.map(j=>j.fixture)),C=P.filter(j=>!j.pass).length;return ke({total:P.length,passed:P.length-C,results:P})}),p.registerTool("deploy",{title:"Deploy an extension",description:"Deploy an extension source to the instance (POST /v1/extensions).",inputSchema:{id: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 y=>{let{baseUrl:k,token:T}=await t(),P=await new z({baseUrl:k,token:T}).deploy({id:y.id,recordType:y.recordType,event:y.event,source:y.source,sourceCode:y.sourceCode,extensionKind:y.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:y,limit:k})=>{let{baseUrl:T,token:$}=await t(),P=new z({baseUrl:T,token:$});return ke({id:y,logs:await P.logs(y,k)})}),p.registerTool("apps_list",{title:"List hosted apps",description:"Every hosted app on this instance with its slug, whether it's deployed, and its latest source revision. `sourceRev: null` means the app has no source of record yet (deployed dist only) \u2014 pull will 404 until something is pushed. GET /v1/apps.",inputSchema:{}},async()=>{let{baseUrl:y,token:k}=await t(),T=new z({baseUrl:y,token:k});return ke(await T.appsList())}),p.registerTool("apps_create",{title:"Create a hosted app",description:"Create a bare hosted-app row so source can be pushed and a build shipped to it \u2014 the author-led path that needs no proposal. Creates the registration only; it serves nothing until a build is shipped. POST /v1/apps.",inputSchema:{slug: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:y,name:k,description:T})=>{let{baseUrl:$,token:P}=await t(),C=new z({baseUrl:$,token:P});return ke(await C.appsCreate({slug:y,name:k,description:T}))}),p.registerTool("apps_pull",{title:"Pull a hosted app's source",description:"Fetch the app's latest source tree as {path \u2192 contents} READ-ONLY \u2014 write it to disk, refine it, then apps_push it back. Returns 404 when the app has no source revision yet. NEVER deploys. GET /v1/apps/:id/pull.",inputSchema:{app:U.string().describe("App slug or id.")}},async({app:y})=>{let{baseUrl:k,token:T}=await t(),$=new z({baseUrl:k,token:T});return ke(await $.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: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:y,files:k,note:T})=>{let{baseUrl:$,token:P}=await t(),C=new z({baseUrl:$,token:P});return ke(await C.appsPush(y,k,{note:T}))});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()}),x=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:y,token:k}=await t(),T=new z({baseUrl:y,token:k});return ke(await T.tablesList())}),p.registerTool("tables_plan",{title:"Preview a table declaration",description:"What these table declarations WOULD do, without doing it. Several apps may claim one table and the instance merges their declarations, so this reports the merged shape and \u2014 the reason to call it \u2014 fails with a conflict report when another claimant already declares one of your field names at a different type. Writes NOTHING. POST /v1/tables/plan.",inputSchema:{tables:U.array(x),claimedBy:U.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:T,token:$}=await t(),P=new z({baseUrl:T,token:$});return ke(await P.tablesPlan({tables:y,claimedBy:k}))}),p.registerTool("tables_apply",{title:"Create or evolve custom tables",description:"Record these table declarations and reconcile them into real Postgres tables \u2014 RLS, realtime, and the write path included. Additive: an existing table gains the fields you declare and keeps the ones other claimants declared. Never drops a column, so removing a field from your declaration releases your claim on it rather than deleting data. Prefer declaring tables in the app manifest (public/turbobase.json) so the deploy applies them; use this when authoring outside an app. POST /v1/tables/apply.",inputSchema:{tables:U.array(x),claimedBy:U.string().optional().describe("`cli` or `app:<slug>`. `console` is reserved for the in-product builder.")}},async({tables:y,claimedBy:k})=>{let{baseUrl:T,token:$}=await t(),P=new z({baseUrl:T,token:$});return ke(await P.tablesApply({tables:y,claimedBy:k}))}),p.registerResource("catalog","catalog:///",{title:"Instance catalog",description:"The instance record-type catalog.",mimeType:"application/json"},async y=>{let{baseUrl:k,token:T}=await t(),P=await(await fetch(`${k}/v1/catalog/records`,{headers:{Authorization:`Bearer ${T}`,Accept:"application/json"}})).text();return{contents:[{uri:y.href,mimeType:"application/json",text:P}]}}),p.registerResource("types","types://all",{title:"Generated types",description:"The instance types.ts source.",mimeType:"text/plain"},async y=>{let{baseUrl:k,token:T}=await t(),$=await br({baseUrl:k,token:T});return{contents:[{uri:y.href,mimeType:"text/plain",text:$}]}}),p.registerResource("samples","samples:///",{title:"Sample fixtures",description:"The local samples/ dry-run fixtures.",mimeType:"application/json"},async y=>{let k=Ji(process.cwd(),"samples"),T=[];try{T=(await YC.readdir(k)).filter(P=>P.endsWith(".json"))}catch{T=[]}let $=await An(k);return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({files:T,samples:$.map(P=>P.fixture)},null,2)}]}}),p.registerResource("recipes","recipes:///",{title:"Intent recipes",description:"Intent recipes (columns / stats / actions per record type + intent), filtered to the instance's installed sources.",mimeType:"application/json"},async y=>{let k=await Ow(),T=[];if(k){let{baseUrl:$,token:P}=await t();T=await k.listRecipesForSurface({surface:"mcp-authoring",baseUrl:$,token:P},r)}return{contents:[{uri:y.href,mimeType:"application/json",text:JSON.stringify({recipes:T})}]}}),p}async function nI(e={}){let t=await Dw(e),r=new Gi;await t.connect(r)}var Cw,Iw,Nw,Lw,QC,Uw,tI,rI,qw=D(()=>{xw();Ew();ha();$n();bt();xa();cs();Aw();Cw=["script","field","record","list","workflow","role","saved_search","bundle","form","dataset"];Nw="turbobase-authoring",Lw="0.1.0";QC="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.";Uw=["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"],tI=[...Uw,...Pw],rI=["catalog:///","types://all","samples:///","recipes:///"]});ha();$n();bt();xa();import{spawn as fu}from"node:child_process";import{promises as ie}from"node:fs";import{homedir as oI}from"node:os";import{basename as Fw,dirname as Wt,join as nt,relative as Xi,resolve as ne,sep as mu}from"node:path";import{Command as sI}from"commander";rs();import{promises as hp}from"node:fs";var o_=/^[a-z][a-z0-9_]+$/;function lp(e,t){if(typeof e!="string"||!o_.test(e))throw new Error(`${t} ${JSON.stringify(e)} 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 e}var s_="customrecord",i_="customlist";function a_(e){return e.startsWith("customrecord_")?e.slice(13):e}function l_(e){return e.startsWith("customlist_")?e.slice(11):e}function c_(e){return lp(e,"custom_record scriptId"),`cr_${a_(e)}`}function d_(e){return lp(e,"custom_list scriptId"),`cl_${l_(e)}`}function cp(e){return e.startsWith(s_)?c_(e):e.startsWith(i_)?d_(e):null}var u_={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:"segment_value",typeColumn:"canonical_segment",typeValue:"location",capabilityTable:"location"},department:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"department",capabilityTable:"department"},classification:{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class",capabilityTable:"classification"},vendorBill:{table:"vendor_bill"},vendorPayment:{table:"vendor_payment"},purchaseOrder:{table:"purchase_order"},journalEntry:{table:"journal_entry"},timeBill:{table:"time_entry"},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"},creditCardCharge:{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"charge"},creditCardRefund:{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"refund"},request:{table:"request"}};function dp(e,t){let r=t?h_[`${t}:${e}`]:void 0;if(r)return r;let n=u_[e];if(n)return n;let o=cp(e);return o?{table:o}:void 0}var p_={accountingPeriod:"accounting_period",printer:"printer"};var h_={...Object.fromEntries(Object.entries(p_).map(([e,t])=>[`standalone:${e}`,{table:t}])),"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:user":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"salesforce:queue":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"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"},"xero:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"quickbooks:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"billdotcom:class":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"class"},"workday:organization":{table:"segment_value",typeColumn:"canonical_segment",typeValue:"department"},"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"},"github:project":{table:"board",typeColumn:"kind",typeValue:"project"},"zendesk:ticket_comment":{table:"activity",typeColumn:"activity_type",typeValue:"ticket_comment"},"intercom:conversation_part":{table:"activity",typeColumn:"activity_type",typeValue:"message"},"notion:notion_comment":{table:"activity",typeColumn:"activity_type",typeValue:"comment"},"jira:board":{table:"board",typeColumn:"kind",typeValue:"board"},"jira:project":{table:"board",typeColumn:"kind",typeValue:"project"},"asana:asanaProject":{table:"board",typeColumn:"kind",typeValue:"project"},"asana:asanaSection":{table:"board_field"},"workday:worker":{table:"entity",typeColumn:"entity_type",typeValue:"employee"},"notion:notion_document":{table:"memory_document",typeColumn:"kind",typeValue:"doc"},"ramp:card_transaction":{table:"credit_card_charge",typeColumn:"record_kind",typeValue:"charge"},"azure_blob:file":{table:"source_file"},"whatsapp:contact":{table:"entity",typeColumn:"entity_type",typeValue:"contact"},"whatsapp:conversation":{table:"work_item",typeColumn:"item_type",typeValue:"conversation"},"whatsapp:message":{table:"activity",typeColumn:"activity_type",typeValue:"message"},"whatsapp:phoneNumber":{table:"whatsapp_phone_number"},"whatsapp:messageTemplate":{table:"whatsapp_message_template"},"slack:file":{table:"source_file"}};function up(e,t){let r=dp(e,t);return r?`${r.table}|${r.typeColumn??"-"}|${r.typeValue??"-"}`:void 0}function pp(e,t,r){if(t===e)return"same-type-merge";let n=r?.fromSource,o=r?.toSource;if(n&&o&&n!==o){let s=up(e,n),i=up(t,o);if(s!==void 0&&s===i)return"same-type-merge"}return"different-type-mint"}var mp=4;function Ta(e){if(!/\bdefineConduit\s*[<(]/.test(e))throw new Error("not a conduit file \u2014 replay drives a defineConduit({...}) module");let t=qr(e,"id"),r=qr(e,"on"),n=qr(e,"source"),o=qr(e,"recordType"),s=[];for(let u of e.matchAll(/\bto\s*:\s*\{([^}]*)\}/g)){let p=qr(u[1]??"","source"),g=qr(u[1]??"","recordType");p&&g&&s.push({source:p,recordType:g})}let i=s[0],a=/cycleBudget\s*:\s*(\d+)/.exec(e),l=/^[ \t]*reads\s*:\s*\[\s*\{/m.test(e);if(!t||!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:t,on:r,fromSource:n,fromRecordType:o,toSource:i.source,toRecordType:i.recordType,targets:s,cycleBudget:a?Number(a[1]):mp,declaresReads:l}}function qr(e,t){let r=new RegExp(`${t}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return r?r[2]:void 0}function m_(e){return{recordType:e.recordType,event:e.event??"after_canonicalize_inbound",direction:"inbound",origin:"system",source:e.fromSource,payload:e.payload??{},tenantConfig:e.tenantConfig??{},metadata:{externalId:e.externalId,lines:e.lines??[]},bindings:e.bindings??[],atlasLinks:e.atlasLinks??{}}}function f_(e,t){let r=e.queryRows;if(!(!r||!Object.prototype.hasOwnProperty.call(r,t)))return r[t]}async function fp(e,t,r="fixture",n={}){let o=t.name??r,s=[],i;try{i=Ta(e)}catch(g){return{fixtureName:o,conduit:y_(),guards:s,whenPassed:!1,atlasResolutions:[],queryReads:[],wouldWriteBindings:[],targets:[],logs:[],error:g instanceof Error?g.message:String(g)}}let a=m_(t),l=Object.entries(t.atlasLinks??{}).map(([g,x])=>({key:g,resolved:x})),u=[],p=i.declaresReads?async g=>{let x=f_(t,g);return u.push({query:g,served:x!==void 0,rowCount:x?.length??0}),x??[]}:void 0;try{for(let[j,H]of Object.entries(t.queryRows??{}))if(!Array.isArray(H))throw new Error(`fixture queryRows['${j}'] 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 ts(e,{resolveDir:n.resolveDir}),y=!!(await Pn(g,a,{member:"when",timeoutMs:es,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 k=t.hop??0;if(s.push({name:"cycle-budget",status:"skipped-offline",detail:`hop=${k} 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 T=[],$=[],P=[];for(let j=0;j<i.targets.length;j+=1){let H=i.targets[j],G=await Pn(g,{...a,materialized:P.map(Jt=>({...Jt}))},{member:"transform",stepIndex:j,timeoutMs:es,query:p});T.push(...G.effects.logs);let Re=G.effects.result;if(!Re||typeof Re!="object")throw new Error(`conduit ${i.id} transform${i.targets.length>1?` (target ${j+1})`:""} returned no result (expected { patch, createdFrom? })`);let qe=Re,Et=pp(i.fromRecordType,H.recordType,{fromSource:i.fromSource,toSource:H.source}),{wouldWriteBindings:Gt,masterAction:Pt}=g_(i,H,Et,t);$.push({to:H,transformResult:qe,applyBranch:Et,wouldWriteBindings:Gt,masterAction:Pt}),P.push({source:H.source,recordType:H.recordType,masterTable:`<${H.recordType} master, dry-run>`,masterRowId:`<dry-run target ${j+1}>`,externalId:null})}let C=$[0];return{fixtureName:o,conduit:i,guards:s,whenPassed:y,atlasResolutions:l,queryReads:u,transformResult:C.transformResult,applyBranch:C.applyBranch,wouldWriteBindings:C.wouldWriteBindings,masterAction:C.masterAction,targets:$,logs:T}}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 g_(e,t,r,n){return r==="same-type-merge"?{masterAction:`would MERGE the patch onto the existing ${e.fromRecordType} master (firing source '${e.fromSource}', external_id='${n.externalId}') and flip originating_system='hybrid'`,wouldWriteBindings:[{source:e.fromSource,externalId:n.externalId,role:"origin",why:"firing source \u2014 its identity already on-row; backfilled into txn_source_link"},{source:t.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 ${t.recordType} master (source_system='${t.source}', originating_system='hybrid', external_id=null) + stamp created_from lineage`,wouldWriteBindings:[{source:t.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 y_(){return{id:"",fromSource:"",fromRecordType:"",toSource:"",toRecordType:"",targets:[],cycleBudget:mp,declaresReads:!1}}async function gp(e){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 yp(e){let t=await hp.readFile(e,"utf8");return JSON.parse(t)}function bp(e){return hp.readFile(e,"utf8")}function wp(e,t){let r=e.conduit,n=`replay ${e.fixtureName}: ERROR \u2014 ${e.error}`,o=e.targets.length>1;if(!t){if(e.error)return n;if(!e.whenPassed)return`replay ${e.fixtureName} [${r.id}]: WHEN-FAILED (conduit short-circuited)`;if(o){let l=e.targets.reduce((u,p)=>u+p.wouldWriteBindings.length,0);return`replay ${e.fixtureName} [${r.id}]: OK \u2014 ${e.targets.length} targets in sequence (${l} binding(s) would be written)`}return`replay ${e.fixtureName} [${r.id}]: OK \u2014 ${e.applyBranch} (${e.wouldWriteBindings.length} binding(s) would be written)`}if(e.error&&!r.id)return n;let s=[];s.push(`\u2501\u2501 replay ${e.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):"),e.guards.length===0&&s.push(" (none ran \u2014 the replay stopped before dispatch)");for(let l of e.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):"),e.atlasResolutions.length===0)s.push(" (none declared \u2014 every ctx.atlas.resolve(...) resolves to null in fixture mode)");else for(let l of e.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(e.queryReads.length===0)s.push(" (declared, but this replay made no read)");else for(let l of e.queryReads)s.push(` ${l.query} \u2192 ${l.served?"served":"not served by the fixture"}, ${l.rowCount} row(s)`);if(e.error)return s.push(""),s.push(`ERROR \u2014 ${e.error}`),s.join(`
|
|
2448
2466
|
`);if(!e.whenPassed)return s.push(""),s.push("transform: SKIPPED (from.when gate did not fire)."),s.join(`
|
|
2449
|
-
`);let a=e.targets.length>0?e.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:e.transformResult??{patch:{}},applyBranch:e.applyBranch??"different-type-mint",wouldWriteBindings:e.wouldWriteBindings,masterAction:e.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(
|
|
2450
|
-
`)}function
|
|
2467
|
+
`);let a=e.targets.length>0?e.targets:[{to:{source:r.toSource,recordType:r.toRecordType},transformResult:e.transformResult??{patch:{}},applyBranch:e.applyBranch??"different-type-mint",wouldWriteBindings:e.wouldWriteBindings,masterAction:e.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(b_(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}`)}),e.logs.length>0){s.push(""),s.push("conduit logs:");for(let l of e.logs)s.push(` [${l.level}] ${l.message}${l.meta?` ${JSON.stringify(l.meta)}`:""}`)}return s.join(`
|
|
2468
|
+
`)}function b_(e,t){return e.split(`
|
|
2451
2469
|
`).map(r=>t+r).join(`
|
|
2452
|
-
`)}var
|
|
2453
|
-
`,s);s=a<0?e.length:a;continue}if(i==="/"&&e[s+1]==="*"){let a=e.indexOf("*/",s+2);s=a<0?e.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(e.slice(s));if(!a)continue;let l=/^(['"`])([^'"`]+)\1/.exec(e.slice(s+a[0].length));return l?{literal:l[2],index:s}:{}}}return{}}function
|
|
2470
|
+
`)}var w_="2026-01-01",vp="2026-01-01T00:00:00.000Z";function v_(e,t){let r=e.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"?w_:r.startsWith("timestamp")?vp:r.startsWith("time")?"00:00:00":r==="json"||r==="jsonb"?t&&/^cf_[a-z]{2}_/.test(t)?1074:t==="raw"||t==="attrs"?{id:"1074",lastModifiedDate:vp}:{}:r==="uuid"?"00000000-0000-0000-0000-000000000000":r==="array"||r.endsWith("[]")?[]:t?`sample ${t}`:"sample text"}function __(e){let t={};for(let r of e.columns)t[r.name]=v_(r.pgType,r.name);return t}function S_(e,t={}){let r=t.event??"before_save";return{name:`${e.recordType} ${r} (generated)`,context:{recordType:e.recordType,event:r,source:e.source,payload:__(e)},expect:t.expect??"pass"}}function _p(e,t={}){return e.map(r=>({recordType:r.recordType,fixture:S_(r,t)}))}import{promises as Sp}from"node:fs";import{join as kp,relative as k_,sep as x_}from"node:path";var T_=67324752,R_=33639248,$_=101010256,E_=(()=>{let e=new Uint32Array(256);for(let t=0;t<256;t++){let r=t;for(let n=0;n<8;n++)r=r&1?3988292384^r>>>1:r>>>1;e[t]=r>>>0}return e})();function P_(e){let t=4294967295;for(let r=0;r<e.length;r++)t=E_[(t^e[r])&255]^t>>>8;return(t^4294967295)>>>0}async function A_(e){let t=[];async function r(n){let o=await Sp.readdir(n,{withFileTypes:!0});for(let s of o){let i=kp(n,s.name);s.isDirectory()?await r(i):s.isFile()&&t.push(k_(e,i).split(x_).join("/"))}}return await r(e),t.sort(),t}async function xp(e){let t=await A_(e),r=[],n=[],o=0;for(let a of t){let l=Buffer.from(a,"utf8"),u=await Sp.readFile(kp(e,a)),p=P_(u),g=Buffer.alloc(30+l.length);g.writeUInt32LE(T_,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 x=Buffer.alloc(46+l.length);x.writeUInt32LE(R_,0),x.writeUInt16LE(20,4),x.writeUInt16LE(20,6),x.writeUInt16LE(0,10),x.writeUInt32LE(p,16),x.writeUInt32LE(u.length,20),x.writeUInt32LE(u.length,24),x.writeUInt16LE(l.length,28),x.writeUInt32LE(o,42),l.copy(x,46),n.push(x),o+=g.length+u.length}let s=Buffer.concat(n),i=Buffer.alloc(22);return i.writeUInt32LE($_,0),i.writeUInt16LE(t.length,8),i.writeUInt16LE(t.length,10),i.writeUInt32LE(s.length,12),i.writeUInt32LE(o,16),{buffer:Buffer.concat([...r,s,i]),fileCount:t.length}}wa();function C_(e){return/\bdefineConduit\s*[<(]/.test(e)?"conduit":/\bdefineProcess\s*[<(]/.test(e)?"process":"hook"}function os(e,t){let r=new RegExp(`${t}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return r?r[2]:void 0}var I_=new Set(["after_save","after_delete"]);function Tp(e){let t=/(?:^|[\s{,(;])on\s*:\s*(['"`])([^'"`]+)\1/.exec(e);return t?t[2]:void 0}function O_(e){let t=N_(e,"from"),n=Rp(e,"to").map(o=>({source:os(o,"source"),recordType:os(o,"recordType")}));return{fromSource:t?os(t,"source"):void 0,fromRecordType:t?os(t,"recordType"):void 0,toSource:n[0]?.source,toRecordType:n[0]?.recordType,targets:n}}function N_(e,t){return Rp(e,t)[0]??null}function Rp(e,t){let r=[],n=new RegExp(`\\b${t}\\s*:\\s*\\{`,"g"),o;for(;(o=n.exec(e))!==null;){let s=0,i=o.index+o[0].length-1;for(let a=i;a<e.length;a+=1){let l=e[a];if(l==="{")s+=1;else if(l==="}"&&(s-=1,s===0)){r.push(e.slice(i+1,a)),n.lastIndex=a+1;break}}}return r}function L_(e){let t=/idempotencyKey\s*:/.exec(e);if(!t)return null;let r=t.index+t[0].length,n=0,o=null,s=r;for(;s<e.length;s+=1){let l=e[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=e.slice(r,s),a=i.indexOf("=>");return a>=0?i.slice(a+2):i}function j_(e,t){let r=new RegExp(`${t}\\s*:\\s*(-?\\d+)`).exec(e);return r?Number(r[1]):void 0}function D_(e){return/\bcreatedFrom\b/.test(e)}function U_(e){let t=/\bdefine(?:Hook|Conduit|Process)\s*(?:<[^>]*>)?\s*\(\s*\{/.exec(e);if(!t)return null;let r=0,n=null,o=!1;for(let s=t.index+t[0].length-1;s<e.length;s+=1){let i=e[s];if(n){i==="\\"?s+=1:i===n&&(n=null);continue}if(i==="/"&&e[s+1]==="/"){let a=e.indexOf(`
|
|
2471
|
+
`,s);s=a<0?e.length:a;continue}if(i==="/"&&e[s+1]==="*"){let a=e.indexOf("*/",s+2);s=a<0?e.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(e.slice(s));if(!a)continue;let l=/^(['"`])([^'"`]+)\1/.exec(e.slice(s+a[0].length));return l?{literal:l[2],index:s}:{}}}return{}}function M_(e){let t=/id\s*:\s*(['"`])([^'"`]+)\1/.exec(e),r=U_(e);if(!t||!r||r.index===t.index)return null;let n=t[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 $p(e){let t=C_(e),r=[],n=M_(e);if(n&&r.push(n),t!=="conduit")return{kind:t,warnings:r};let{fromSource:o,fromRecordType:s,toRecordType:i,targets:a}=O_(e);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=L_(e);if(l!==null){let g=/\bexternalId\b/.test(l),x=/\bfromSource\b/.test(l),y=/\bchange\b/.test(l);!g&&!x?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}``."}):I_.has(Tp(e)??"")&&!y&&r.push({rule:"lifetime-idempotency-key",message:`this conduit fires on '${Tp(e)}' and its idempotencyKey carries nothing about the save \u2014 on a save trigger ctx.externalId is the same string for the whole of a record's life, so every later save dedupes into the first one and the conduit fires ONCE per record and never again.`,fix:"Omit `idempotencyKey` entirely \u2014 the engine derives a per-save token for this trigger \u2014 or include something about the change, e.g. `idempotencyKey: (ctx) => `${ctx.externalId}:${(ctx.change?.fields ?? []).join(`,`)}``."})}let u=a.find(g=>g.recordType&&s&&g.recordType!==s)?.recordType??(s!==i?i:void 0);s&&u&&!D_(e)&&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=j_(e,"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:t,warnings:r}}function Ep(e,t,r={}){let n=r.warn??(a=>a),o=r.ok??(a=>a),s=r.dim??(a=>a),i=[];if(i.push(`lint: ${e} (${t.kind})`),t.warnings.length===0)return i.push(` ${o("ok")} \u2014 no warnings.`),i.join(`
|
|
2454
2472
|
`);for(let a of t.warnings)i.push(` ${n("WARN")} ${s(`[${a.rule}]`)} ${a.message}`),i.push(` ${s("\u2192 fix:")} ${a.fix}`);return i.push(`
|
|
2455
2473
|
lint: ${n(`${t.warnings.length} warning(s).`)}`),i.join(`
|
|
2456
|
-
`)}function
|
|
2474
|
+
`)}function Pp(e){return e.cases.filter(t=>t.status==="failed").length}function In(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function q_(e){let t=Pp(e),r=[];r.push('<?xml version="1.0" encoding="UTF-8"?>'),r.push(`<testsuite name="${In(e.name)}" tests="${e.cases.length}" failures="${t}">`);for(let n of e.cases){let o=` <testcase name="${In(n.name)}"`;if(n.status==="passed"){r.push(`${o} />`);continue}r.push(`${o}>`);let s=n.detail??"failed",i=n.type?` type="${In(n.type)}"`:"";r.push(` <failure${i} message="${In(s)}">${In(s)}</failure>`),r.push(" </testcase>")}return r.push("</testsuite>"),`${r.join(`
|
|
2457
2475
|
`)}
|
|
2458
|
-
`}function
|
|
2459
|
-
`}function ss(e,t){return t==="junit"?
|
|
2476
|
+
`}function z_(e){let t={suite:e.name,tests:e.cases.length,failures:Pp(e),cases:e.cases};return`${JSON.stringify(t,null,2)}
|
|
2477
|
+
`}function ss(e,t){return t==="junit"?q_(e):z_(e)}var Je={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:e=>`\x1B[${e}A`},zr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],it={tl:"\u256D",tr:"\u256E",bl:"\u2570",br:"\u256F",ml:"\u251C",mr:"\u2524",h:"\u2500",v:"\u2502"},Ap=/\x1b\[[0-9;]*m/g;function qt(e){return e.replace(Ap,"").length}function Ra(e,t){return t<=0?1:Math.max(1,Math.ceil(qt(e)/t))}function B_(){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 $a=B_();function Oe(){return $a}function Ea(e){$a=e}function Ne(){return process.stdin.isTTY===!0&&process.stdout.isTTY===!0}function at(e,t){return $a?`${e}${t}${Je.reset}`:t}var m={bold:e=>at(Je.bold,e),dim:e=>at(Je.dim,e),red:e=>at(Je.red,e),green:e=>at(Je.green,e),yellow:e=>at(Je.yellow,e),blue:e=>at(Je.blue,e),magenta:e=>at(Je.magenta,e),cyan:e=>at(Je.cyan,e),grey:e=>at(Je.grey,e)};var ve={success:e=>`${m.green("\u2713")} ${e}`,error:e=>`${m.red("\u2716")} ${e}`,warn:e=>`${m.yellow("\u26A0")} ${e}`,info:e=>`${m.dim("\xB7")} ${e}`,step:e=>`${m.cyan("\u25B8")} ${e}`},Xt={add:e=>m.green(`+ ${e}`),change:e=>m.yellow(`~ ${e}`),destroy:e=>m.red(`- ${e}`)},F_=new Set(["ok","active","completed","complete","success","passed","pass","live","done","healthy","created","deployed","applied","up-to-date"]),H_=new Set(["failed","fail","error","divergent","blocked","rejected","down","missing","unreachable"]),V_=new Set(["pending","queued","running","in_progress","building","muted","skipped","warn","warning","draft","rolled_back"]);function Br(e){let t=e.toLowerCase();return F_.has(t)?m.green(e):H_.has(t)?m.red(e):V_.has(t)?m.yellow(e):e}function Zt(e,t=[]){let r=Math.max(qt(e),...t.map(qt),0),n=r+2,o=m.cyan(it.v),s=a=>` ${a}${" ".repeat(r-qt(a))} `,i=[m.cyan(`${it.tl}${it.h.repeat(n)}${it.tr}`),`${o}${m.bold(s(e))}${o}`];if(t.length){i.push(`${m.cyan(it.ml)}${m.dim(it.h.repeat(n))}${m.cyan(it.mr)}`);for(let a of t)i.push(`${o}${s(a)}${o}`)}return i.push(m.cyan(`${it.bl}${it.h.repeat(n)}${it.br}`)),i.join(`
|
|
2460
2478
|
`)}function lt(e,t={}){let r=t.indent??" ",n=t.gap??" ",o=t.head?[t.head,...e]:e,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=>qt(p[u]??"")));let a=u=>{let p=u.map((g,x)=>{let y=g??"";return x===u.length-1?y:y+" ".repeat(Math.max(0,i[x]-qt(y)))});return r+p.join(n)},l=[];t.head&&(l.push(a(t.head.map(u=>m.bold(u)))),l.push(a(t.head.map((u,p)=>m.dim("\u2500".repeat(i[p]??qt(u)))))));for(let u of e)l.push(a(u));return l.join(`
|
|
2461
|
-
`)}function
|
|
2479
|
+
`)}function Pa(e="the CLI for your Turbobase instance"){let t=[" \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()?t.map(n=>at(Je.cyan,n)).join(`
|
|
2462
2480
|
`):t.join(`
|
|
2463
2481
|
`)}
|
|
2464
|
-
${m.dim(` ${e}`)}`}var ct=e=>{process.stderr.write(e)};function is(){return Oe()&&process.stderr.isTTY===!0}function
|
|
2482
|
+
${m.dim(` ${e}`)}`}var ct=e=>{process.stderr.write(e)};function is(){return Oe()&&process.stderr.isTTY===!0}function Cp(e,t=15){let r=Math.max(0,Math.min(100,e??0)),n=Math.round(r/100*t);return`${"\u2588".repeat(n)}${m.dim("\u2591".repeat(t-n))}`}async function X(e,t){let r=is(),n=0,o;r&&(ct(Ee.hideCursor),o=setInterval(()=>{ct(`${Ee.col0}${Ee.clearLine}${m.magenta(zr[n++%zr.length])} ${e}`)},80));let s=()=>{o&&clearInterval(o),r&&ct(`${Ee.col0}${Ee.clearLine}${Ee.showCursor}`)};try{let i=await t();return s(),r&&ct(`${ve.success(e)}
|
|
2465
2483
|
`),i}catch(i){throw s(),r&&ct(`${ve.error(e)}
|
|
2466
|
-
`),i}}function
|
|
2467
|
-
`),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),ct(Ee.showCursor);let u=l.stage!=="failed",p=`${e} ${m.dim("\u25B8")} ${
|
|
2468
|
-
`)},stop(){clearInterval(a),i(),ct(Ee.showCursor)}}}function
|
|
2484
|
+
`),i}}function Aa(e){let t=0,r={stage:"queued"},n=!1,o=()=>{let l=m.magenta(zr[t%zr.length]),u=m.cyan(r.stage),p=r.runStatus?` ${m.dim(`(${r.runStatus})`)}`:"",g=`${String(Math.round(r.percent??0)).padStart(3)}%`;return`${l} ${e} ${m.dim("\u25B8")} ${u}${p} ${Cp(r.percent)} ${g}`},s=()=>{ct(`${Ee.col0}${Ee.clearLine}${o()}`),n=!0},i=()=>{n&&ct(`${Ee.col0}${Ee.clearLine}`),n=!1};ct(Ee.hideCursor);let a=setInterval(()=>{t+=1,s()},80);return{log(l){i(),ct(`${l}
|
|
2485
|
+
`),s()},status(l){r=l,s()},done(l){clearInterval(a),i(),ct(Ee.showCursor);let u=l.stage!=="failed",p=`${e} ${m.dim("\u25B8")} ${K_(l.stage)}${l.runStatus?` (${l.runStatus})`:""}`;ct(`${u?ve.success(p):ve.error(p)}
|
|
2486
|
+
`)},stop(){clearInterval(a),i(),ct(Ee.showCursor)}}}function K_(e){return e==="completed"?m.green(e):e==="failed"?m.red(e):m.cyan(e)}function Le(e,t,r={}){return new Promise((n,o)=>{let s=t.findIndex(T=>!T.disabled);if(s===-1){o(new Error("no selectable options"));return}let i=r.defaultIndex!==void 0&&!t[r.defaultIndex]?.disabled?r.defaultIndex:s,a=T=>{process.stderr.write(T)},l=process.stdin,u=l.isRaw;l.setRawMode?.(!0),l.resume(),a(`${m.bold(m.cyan("?"))} ${m.bold(e)}
|
|
2469
2487
|
`),a(`${m.dim(" (\u2191/\u2193 to move, enter to select, ctrl+c to abort)")}
|
|
2470
|
-
`),a(Ee.hideCursor);let p=0,g=()=>{let
|
|
2471
|
-
`),$+=
|
|
2488
|
+
`),a(Ee.hideCursor);let p=0,g=()=>{let T=process.stderr.columns??process.stdout.columns??80;p>0&&(a(Ee.cursorUp(p)),a(Ee.clearToEnd));let $=0;for(let P=0;P<t.length;P+=1){let C=t[P],j=P===i,H=j?m.cyan("\u25B6"):" ",G=C.disabled?m.grey(C.label):j?m.bold(m.cyan(C.label)):C.label,Re=C.description?` ${m.dim(C.description)}`:"",qe=` ${H} ${G}${Re}`;a(`\r${qe}
|
|
2489
|
+
`),$+=Ra(qe,T)}p=$},x=()=>{l.removeListener("data",k),l.setRawMode?.(u??!1),l.pause(),a(Ee.showCursor)},y=T=>{let $=i;for(let P=0;P<t.length;P+=1)if($=($+T+t.length)%t.length,!t[$].disabled){i=$;return}},k=T=>{let $=T.toString("utf8");if($===""||$==="q"){x(),a(`
|
|
2472
2490
|
`),o(new Error("aborted"));return}if($==="\r"||$===`
|
|
2473
|
-
`){let C=t[i];if(C.disabled)return;x(),n(C.value);return}if($==="\x1B[A"||$==="k"){y(-1),g();return}if($==="\x1B[B"||$==="j"){y(1),g();return}let P=Number($);Number.isFinite(P)&&P>=1&&P<=t.length&&!t[P-1].disabled&&(i=P-1,g())};l.on("data",k),g()})}function as(e,t){return`${
|
|
2474
|
-
`)}),o=r.sleep??
|
|
2475
|
-
`)});if(t.retry){let o=await e.retryBinding(t.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 e.bindings({status:t.status,limit:t.limit});if(n.length===0)return r(t.status?`binding: no bindings with write_status='${t.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(
|
|
2476
|
-
binding: ${n.length} binding(s)${t.status?` (write_status='${t.status}')`:""}.`),{mode:"list",count:n.length}}function
|
|
2477
|
-
`)}),n=t.sleep??
|
|
2478
|
-
`)},
|
|
2479
|
-
${t.length} run(s).`)}function ls(e,t=On){let r=e.run?.runId??e.runId??"(unknown run)",n=e.run?.processId??e.processId??"",o=e.run?.state??e.state??"",s=e.run?.reason??e.reason??null,i=e.run?.outstanding??e.outstanding??null;t(`${r} ${o}${n?` ${n}`:""}`),s&&t(` ${s}`),i!==null&&i>0&&t(` ${i} still outstanding`);let a=e.steps??[];if(a.length===0){t(" no steps recorded yet.");return}for(let l of a){let u=l.externalId??l.pgRowId??"\u2014",p=l.refusal?.message?` ${l.refusal.message}`:"";t(` ${String(l.sequence).padStart(3)} ${l.stepId.padEnd(16)} ${l.disposition.padEnd(12)} ${l.recordType}/${u}${p}`)}}async function
|
|
2491
|
+
`){let C=t[i];if(C.disabled)return;x(),n(C.value);return}if($==="\x1B[A"||$==="k"){y(-1),g();return}if($==="\x1B[B"||$==="j"){y(1),g();return}let P=Number($);Number.isFinite(P)&&P>=1&&P<=t.length&&!t[P-1].disabled&&(i=P-1,g())};l.on("data",k),g()})}function as(e,t){return`${Br(e)}${" ".repeat(Math.max(0,t-e.length))}`}var Op=e=>new Promise(t=>setTimeout(t,e));function Ip(e){let t=e.toRecordType?`${e.toSource}/${e.toRecordType}`:e.toSource,r=e.reason?` reason="${e.reason}"`:"",n=e.fromExternalId?` ext=${e.fromExternalId}`:"",o=e.toMasterTable&&e.toMasterRowId?` master=${e.toMasterTable}/${e.toMasterRowId}`:"",s=e.toExternalId?` to_ext=${e.toExternalId}`:"";return`[${e.updatedAt}] ${as(e.state,9)} ${e.conduitId} \u2192 ${t}${n} hop=${e.hop}${o}${s}${r}`}async function Np(e,t,r={}){let n=r.sink??(p=>{process.stdout.write(`${p}
|
|
2492
|
+
`)}),o=r.sleep??Op,s=r.intervalMs??2e3,i=await e.conduitEvents(t,{limit:r.limit??100});if(i.length===0&&!r.follow)return n(`logs: no conduit_event rows for ${t}.`),0;let a=0,l="";for(let p of[...i].reverse())n(Ip(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 e.conduitEvents(t,{since:l||void 0,limit:200});for(let x of[...g].reverse())n(Ip(x)),a+=1,x.updatedAt>l&&(l=x.updatedAt)}return a}function W_(e){let t=e.externalId??"\u2014",r=e.createdByConduit?` via=${e.createdByConduit}`:"",n=e.lastError?` last_error="${e.lastError}"`:"";return`${e.id} ${as(e.writeStatus,9)} ${e.sourceSystem}/${t} role=${e.role} master=${e.masterTable}/${e.masterRowId}${r}${n}`}async function Lp(e,t={}){let r=t.sink??(o=>{process.stdout.write(`${o}
|
|
2493
|
+
`)});if(t.retry){let o=await e.retryBinding(t.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 e.bindings({status:t.status,limit:t.limit});if(n.length===0)return r(t.status?`binding: no bindings with write_status='${t.status}'.`:"binding: no bindings."),{mode:"list",count:0};for(let o of n)r(W_(o));return r(`
|
|
2494
|
+
binding: ${n.length} binding(s)${t.status?` (write_status='${t.status}')`:""}.`),{mode:"list",count:n.length}}function G_(e){let t=Object.entries(e.detail??{}).map(([i,a])=>`${i}=${typeof a=="string"?JSON.stringify(a):String(a)}`).join(" "),r=[e.sourceSystem,e.recordType,e.subjectId].filter(Boolean).join("/"),n=e.occurrences>1?` x${e.occurrences}`:"",o=e.redaction?.length?` redacted=[${e.redaction.join(",")}]`:"",s=e.correlationId?` corr=${e.correlationId}`:"";return`[${e.ts}] ${as(e.severity,5)} ${as(e.outcome,8)} ${e.code}${n}${r?` ${r}`:""}${s}${t?` ${t}`:""}${o}`}async function jp(e,t={}){let r=t.sink??(P=>{process.stdout.write(`${P}
|
|
2495
|
+
`)}),n=t.sleep??Op,o=t.intervalMs??2e3,{follow:s,maxPolls:i,json:a,sink:l,sleep:u,intervalMs:p,...g}=t,x=P=>{r(a?JSON.stringify(P):G_(P))},y=await e.platformEvents({...g,limit:g.limit??100});if(y.length===0&&!s)return r("logs: no events matched."),0;let k=0,T="";for(let P of[...y].reverse())x(P),k+=1,P.ts>T&&(T=P.ts);if(!s)return k;let $=i??Number.POSITIVE_INFINITY;for(let P=0;P<$;P+=1){await n(o);let C=await e.platformEvents({...g,...T?{after:T,since:void 0}:{},limit:200});for(let j of[...C].reverse())x(j),k+=1,j.ts>T&&(T=j.ts)}return k}var Dp=new Set(["committed","failed","rolled_back","cancelled"]),On=e=>{process.stdout.write(`${e}
|
|
2496
|
+
`)},J_=e=>new Promise(t=>setTimeout(t,e));function Y_(e){return e==null?"\u2014":e<1e3?`${e}ms`:e<6e4?`${(e/1e3).toFixed(1)}s`:`${Math.floor(e/6e4)}m${Math.round(e%6e4/1e3)}s`}function Up(e){let t=e.startedAt??"not started",r=e.outcome&&e.outcome!==e.state?` ${e.outcome}`:"",n=e.scheduleId?" (scheduled)":"";return` ${e.runId} ${e.state.padEnd(11)} ${t} ${Y_(e.durationMs)}${n}${r}`}function X_(e){if(e.trigger.kind!=="scheduled")return"manual";let t=e.trigger.timezone?` ${e.trigger.timezone}`:"",r=e.trigger.status&&e.trigger.status!=="active"?` (${e.trigger.status})`:"";return`scheduled ${e.trigger.cron??"?"}${t}${r}`}function Mp(e,t=On){if(e.length===0){t("No processes are deployed on this instance."),t("Author one with `turbobase ext new process` and ship it with `turbobase ext deploy`.");return}for(let r of e){if(t(`${r.id}${r.enabled?"":" [off]"}`),t(` trigger: ${X_(r)}`),r.runs.length===0)t(" never run");else for(let n of r.runs)t(Up(n));t("")}t(`${e.length} process(es).`)}function qp(e,t,r=On){if(r(e),t.length===0){r(" no runs yet.");return}for(let n of t)r(Up(n));r(`
|
|
2497
|
+
${t.length} run(s).`)}function ls(e,t=On){let r=e.run?.runId??e.runId??"(unknown run)",n=e.run?.processId??e.processId??"",o=e.run?.state??e.state??"",s=e.run?.reason??e.reason??null,i=e.run?.outstanding??e.outstanding??null;t(`${r} ${o}${n?` ${n}`:""}`),s&&t(` ${s}`),i!==null&&i>0&&t(` ${i} still outstanding`);let a=e.steps??[];if(a.length===0){t(" no steps recorded yet.");return}for(let l of a){let u=l.externalId??l.pgRowId??"\u2014",p=l.refusal?.message?` ${l.refusal.message}`:"";t(` ${String(l.sequence).padStart(3)} ${l.stepId.padEnd(16)} ${l.disposition.padEnd(12)} ${l.recordType}/${u}${p}`)}}async function zp(e,t,r={}){let n=r.sink??On,o=r.sleep??J_,s=r.intervalMs??2e3,i=r.maxPolls??Number.POSITIVE_INFINITY,a=new Set,l=p=>{let g=[];ls(p,x=>g.push(x));for(let x of g)a.has(x)||(a.add(x),n(x));return p.run?.state??p.state??""},u=l(await e.processRun(t));if(!r.follow)return u;for(let p=0;p<i;p+=1){if(Dp.has(u))return u;await o(s),u=l(await e.processRun(t))}return Dp.has(u)?u:null}function Bp(e,t){let r;try{r=JSON.parse(e)}catch(n){return{ok:!1,message:`${t} must be valid JSON: ${n instanceof Error?n.message:String(n)}`}}return typeof r!="object"||r===null||Array.isArray(r)?{ok:!1,message:`${t} must be a JSON object (the process input), e.g. '{"customerId":"42"}'.`}:{ok:!0,input:r}}function Fp(e,t,r,n=On){let o=e.runId??"(unknown run)",s=`${r} logs --process-run ${o} --follow`;if(e.error==="sync_budget_exceeded"){n(`${o} still running ${e.processId??t}`),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(e.steps!==void 0){ls(e,n);return}n(`${o} ${e.state??"queued"} ${e.processId??t}`),n(` Watch it: ${s}`)}cs();rs();function Vp(e,t={}){if(e.learningIngestError)return{level:"warn",message:`warning: learning ingest was not queued (${e.learningIngestError}). The version is live, but the findings in INSTANCE-LEARNINGS.md / TURBOBASE-FEEDBACK.md were NOT read. Re-deploy to retry.`};if(e.learningIngestTaskId){let r=typeof t.recordedSourceRev=="number"?t.recordedSourceRev:null,n=r??e.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&&t.localDocsModifiedAt&&e.learningSourceAt&&t.localDocsModifiedAt.getTime()>Date.parse(e.learningSourceAt)?{level:"warn",message:`warning: learning ingest queued (task ${e.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 ${e.learningIngestTaskId}) \u2014 reading source rev ${n}.`}:{level:"info",message:`learning ingest queued (task ${e.learningIngestTaskId}).`}}return null}var Gp=9,Nn=" ".repeat(2+Gp);function Fr(e,t=r=>r){return t(e)+" ".repeat(Math.max(1,Gp-e.length))}function rS(e,t,r){return e===1?t:r}function Jp(e){return e?m.dim(` (${e} holder${e===1?"":"s"} re-stamped)`):""}function Yp(e){return e.length>0?`[${e.join(", ")}]`:"unrestricted"}function nS(e){if(!e)return[];let t=[],r=e.addedGrants??[],n=e.removedGrants??[];if(r.length>0||n.length>0){let s=[...r.map(i=>`+${i}`),...n.map(i=>`\u2212${i}`)];t.push(`content ${s.join(" ")}`)}let o=e.setRestrictions??{};for(let s of Object.keys(o).sort())t.push(`${s} \u2192 ${Yp(o[s]??[])}`);return t}function Kp(e){let t=[],r=e.scopeChanges?.adoptedGrants??[];r.length>0&&t.push({stream:"out",text:m.dim(`${Nn}adopted (already on the role \u2014 the admin's, never retired by this app): ${r.join(", ")}`)});let n=e.scopeChanges?.adoptedRestrictions??{};for(let s of Object.keys(n).sort())t.push({stream:"out",text:m.dim(`${Nn}adopted ${s} ${Yp(n[s]??[])} (already on the role \u2014 the admin's, never cleared or widened by this app)`)});let o=[...e.keptRemovedCapabilities??[],...e.scopeChanges?.keptRemovedGrants??[]];o.length>0&&t.push({stream:"out",text:m.dim(`${Nn}kept (admin removed): ${o.join(", ")}`)});for(let s of e.scopeChanges?.keptAdminRestrictions??[])t.push({stream:"out",text:m.dim(`${Nn}kept admin value for ${s}`)});for(let s of e.warnings??[])t.push({stream:"out",text:m.yellow(`${Nn}! ${s}`)});return t}function Xp(e){return(e.warnings?.length??0)>0||(e.keptRemovedCapabilities?.length??0)>0||(e.scopeChanges?.keptRemovedGrants?.length??0)>0||(e.scopeChanges?.keptAdminRestrictions?.length??0)>0}function Wp(e){return Xp(e)||(e.scopeChanges?.adoptedGrants?.length??0)>0||Object.keys(e.scopeChanges?.adoptedRestrictions??{}).length>0}function oS(e,t,r){let n=r==="applied",o=nS(e.scopeChanges),s=n?Jp(e.holdersRestamped):"",i=l=>{let u=[...l,...o];return u.length>0?` ${m.dim(u.join(" "))}`:""};if(e.action==="error")return[{stream:"err",text:` ${Fr("ERROR",m.bold)}${t} \u2014 ${e.message??"cannot be created"}`},...Kp(e)];let a;if(e.action==="create"){let l=e.addCapabilities?.length??0;a=` ${Fr(n?"created":"create")}${t}${i([`${l} ${rS(l,"capability","capabilities")}`])}${s}`}else if(e.action==="add_capabilities"){let l=(e.addCapabilities??[]).map(u=>`+${u}`).join(", ");a=` ${Fr(n?"updated":"add")}${t}${i([l])}${s}`}else e.action==="update_scopes"?a=` ${Fr(n?"updated":"update")}${t}${o.length>0?i([]):` ${m.dim("scopes changed")}`}${s}`:e.action==="noop"?a=` ${Fr("ok",m.dim)}${t} ${m.dim("already up to date")}`:a=` ${Fr(n?"changed":"change")}${t}${i([])} ${m.dim("(upgrade the CLI to see details)")}${s}`;return[{stream:"out",text:a},...Kp(e)]}function sS(e,t){let r=[];for(let n of e){if(!n.removedGrants||n.removedGrants.length===0)continue;let o=n.removedGrants.map(i=>`\u2212${i}`).join(" "),s=t==="applied"?"retired":"retire";r.push({stream:"out",text:` ${s} grants on ${n.name}: ${m.dim(o)}${t==="applied"?Jp(n.holdersRestamped):""}`})}return r}function Zp(e){let{mode:t}=e,r=e.verdicts??[],n=t==="plan"?r:r.filter(u=>u.action!=="noop"||Wp(u)),o=sS(e.retired??[],t);if(n.length===0&&o.length===0)return[];let s=[{stream:"out",text:""},{stream:"out",text:m.bold(t==="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(...oS(u,u.name.padEnd(i),t));s.push(...o);let a=n.some(u=>iS.has(u.action)),l=n.every(u=>u.action==="noop");if(a){let u=t==="plan"?" roles are created at deploy \u2014 a declared role has no holders until an admin assigns it in Admin \u2192 Users.":t==="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=>Wp(u))){let u=t==="applied"?"no role changed":t==="preview"?"no role would change on promote":"no role would change",p=n.some(g=>Xp(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 iS=new Set(["create","add_capabilities","update_scopes"]);function Ca(e){let{app:t,roles:r}=e;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 t===null?n(o,"pass --app <slug> so the plan can name them."):Array.isArray(e.retired)?e.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 t===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 Qp(e){let t=e.roles;return Array.isArray(t)?{verdicts:t,retired:e.rolesRetired??[]}:t&&typeof t=="object"?{verdicts:t.verdicts??[],retired:t.retired??e.rolesRetired??[]}:{verdicts:[],retired:e.rolesRetired??[]}}var Ia=".github/workflows/turbobase-release-deploy.yml",aS=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2480
2498
|
# Turbobase release deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR repo)
|
|
2481
2499
|
#
|
|
2482
2500
|
# Epic #775 "GitHub is just a link": Turbobase hosts nothing and clones nothing.
|
|
@@ -2578,7 +2596,7 @@ jobs:
|
|
|
2578
2596
|
--ref "\${{ github.sha }}" \\
|
|
2579
2597
|
--project . \\
|
|
2580
2598
|
--follow
|
|
2581
|
-
`,
|
|
2599
|
+
`,lS=".github/workflows/turbobase-app-deploy.yml",cS=`# \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
2582
2600
|
# Turbobase app deploy \u2014 REUSABLE TEMPLATE (drop this into YOUR app repo)
|
|
2583
2601
|
#
|
|
2584
2602
|
# What ships from this repo, and when:
|
|
@@ -2798,14 +2816,14 @@ jobs:
|
|
|
2798
2816
|
else
|
|
2799
2817
|
echo "no preview labelled \\"$PR_LABEL\\" \u2014 nothing to discard."
|
|
2800
2818
|
fi
|
|
2801
|
-
`;function
|
|
2819
|
+
`;function eh(){return[{path:Ia,content:aS}]}function th(){return[{path:lS,content:cS}]}cs();var dS=[".mcp.json"];function sh(e,t=dS){let r=i=>i.replace(/^\//,""),n=new Set(e.split(`
|
|
2802
2820
|
`).map(i=>i.trim()).filter(i=>i!==""&&!i.startsWith("#")).map(r)),o=t.filter(i=>!n.has(r(i)));return o.length===0?null:`${e===""||e.endsWith(`
|
|
2803
2821
|
`)?e:`${e}
|
|
2804
2822
|
`}
|
|
2805
2823
|
# Added by the Turbobase scaffold.
|
|
2806
2824
|
${o.join(`
|
|
2807
2825
|
`)}
|
|
2808
|
-
`}var
|
|
2826
|
+
`}var uS=`# Turbobase Extensions \u2014 extension project
|
|
2809
2827
|
|
|
2810
2828
|
This directory authors **Turbobase extensions** (hooks today; conduits later)
|
|
2811
2829
|
against a live instance. The \`turbobase\` CLI is the engine; Claude Code drives it
|
|
@@ -2874,8 +2892,8 @@ order is the signal, and it is the part the product team reads first.
|
|
|
2874
2892
|
|
|
2875
2893
|
Do this WITHOUT being asked \u2014 treat it as part of finishing a task, like
|
|
2876
2894
|
updating a test. It is checked into the repo so the whole team sees it.
|
|
2877
|
-
`,
|
|
2878
|
-
`;function
|
|
2895
|
+
`,pS=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)+`
|
|
2896
|
+
`;function hS(e){return`---
|
|
2879
2897
|
name: generate-types
|
|
2880
2898
|
description: Regenerate ${e} from the signed-in instance's catalog. Use before authoring or whenever the schema may have changed.
|
|
2881
2899
|
---
|
|
@@ -2886,7 +2904,7 @@ write \`${e}\`. Import the generated record interfaces for typed rows.
|
|
|
2886
2904
|
|
|
2887
2905
|
The OpenAPI half is cookie-session-gated, so a headless run with a stored token
|
|
2888
2906
|
degrades to record shapes only and says so \u2014 that is expected, not a failure.
|
|
2889
|
-
`}var
|
|
2907
|
+
`}var mS=`---
|
|
2890
2908
|
name: mock-test
|
|
2891
2909
|
description: Dry-run a hook against samples/ fixtures using the production sandbox. Use after editing a hook, before deploy.
|
|
2892
2910
|
---
|
|
@@ -2895,7 +2913,7 @@ Run \`turbobase ext test hooks/<file>.ts\`. It bundles the hook through the same
|
|
|
2895
2913
|
self-contained-fence esbuild + isolated-vm the live runtime uses, then runs it
|
|
2896
2914
|
against every \`samples/*.json\` fixture and reports pass/reject per sample. Add a
|
|
2897
2915
|
fixture for each branch (a passing record and a rejecting record).
|
|
2898
|
-
`,
|
|
2916
|
+
`,fS=`---
|
|
2899
2917
|
name: deploy
|
|
2900
2918
|
description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
2901
2919
|
---
|
|
@@ -2903,7 +2921,7 @@ description: Deploy a hook to your instance. Use only after mock-test is green.
|
|
|
2903
2921
|
Run \`turbobase ext deploy hooks/<file>.ts\`. It POSTs the hook source to
|
|
2904
2922
|
/v1/extensions with the stored admin PAT; the hook lands **active**. Re-deploying
|
|
2905
2923
|
the same id overwrites it (idempotent). Tail with \`turbobase ext logs <id>\`.
|
|
2906
|
-
`;function
|
|
2924
|
+
`;function gS(e){return`# ${e} \u2014 Turbobase app
|
|
2907
2925
|
|
|
2908
2926
|
This directory is a **hosted Turbobase app**: a Vite + React + TS SPA served
|
|
2909
2927
|
same-origin by the instance at \`/a/${e}\`. The \`turbobase\` CLI ships it; you
|
|
@@ -3279,7 +3297,7 @@ a test. \`turbobase apps deploy\` reads both files and queues what it finds for
|
|
|
3279
3297
|
review, so what you write reaches the knowledge base and the product team instead
|
|
3280
3298
|
of evaporating at the end of the session. Keep the section headings exactly as
|
|
3281
3299
|
they are \u2014 the ingest finds entries by heading, not by filename.
|
|
3282
|
-
`}var
|
|
3300
|
+
`}var Hr="customer",wr="email",yS="^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",bS=`// EXAMPLE \u2014 a business rule that holds for EVERY writer, not just this app.
|
|
3283
3301
|
//
|
|
3284
3302
|
// It runs inside \`POST /v1/data\`, which is the only way an app can write at all:
|
|
3285
3303
|
// the \`authenticated\` role holds no INSERT/UPDATE/DELETE on the mirror, so a
|
|
@@ -3298,8 +3316,8 @@ they are \u2014 the ingest finds entries by heading, not by filename.
|
|
|
3298
3316
|
// Pure and credentials-free: no secrets, no network, no Node builtins, one
|
|
3299
3317
|
// concern per file, nothing factored into a shared module (the sandbox fences
|
|
3300
3318
|
// every import except the SDK).
|
|
3301
|
-
`;function
|
|
3302
|
-
`;return[{path:e.relativePath,content:`${
|
|
3319
|
+
`;function wS(){let e=Ct("hook",{recordType:Hr,event:"before_save",template:"enforce-format",field:wr,regex:yS,id:`app:${Hr}:${wr}-format`,description:`Reject a ${Hr} write whose ${wr} is not an address.`}),t=(r,n,o)=>JSON.stringify({name:o,context:{recordType:Hr,event:"before_save",payload:r},expect:n},null,2)+`
|
|
3320
|
+
`;return[{path:e.relativePath,content:`${bS}${e.content}`},{path:`samples/${Hr}.${wr}-ok.json`,content:t({company_name:"Acme Supply",[wr]:"ada@example.com"},"pass","a well-formed address passes")},{path:`samples/${Hr}.${wr}-malformed.json`,content:t({company_name:"Acme Supply",[wr]:"ada-at-example"},"reject","a malformed address is rejected")}]}var vS="---\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",_S=`---
|
|
3303
3321
|
name: ship-app
|
|
3304
3322
|
description: Push the app's source to the instance and deploy it live. Use once the app has been previewed and works.
|
|
3305
3323
|
---
|
|
@@ -3342,12 +3360,12 @@ Text files only \u2014 \`push\` skips \`node_modules/\`, \`dist/\`, \`build/\`,
|
|
|
3342
3360
|
non-text, so images and fonts belong in the build pipeline or object storage, not
|
|
3343
3361
|
the source tree. \`INSTANCE-LEARNINGS.md\` and \`TURBOBASE-FEEDBACK.md\` sit at the
|
|
3344
3362
|
project root and DO travel \u2014 deploy reads them.
|
|
3345
|
-
`,
|
|
3363
|
+
`,Oa="<!-- platform-maintained: rewritten every session by `turbobase project skills` from the installed CLI. Do not edit \u2014 your own lessons go in INSTANCE-LEARNINGS.md. -->";function rh(e){let t=e.indexOf(`
|
|
3346
3364
|
---
|
|
3347
3365
|
`,4);if(!e.startsWith(`---
|
|
3348
3366
|
`)||t<0)throw new Error("a platform skill must open with frontmatter");let r=t+5;return`${e.slice(0,r)}
|
|
3349
|
-
${
|
|
3350
|
-
${e.slice(r)}`}var
|
|
3367
|
+
${Oa}
|
|
3368
|
+
${e.slice(r)}`}var SS=`---
|
|
3351
3369
|
name: business-rule-to-hook
|
|
3352
3370
|
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.
|
|
3353
3371
|
---
|
|
@@ -3415,7 +3433,7 @@ subsidiary as headquarters"), also record it in \`INSTANCE-LEARNINGS.md\` under
|
|
|
3415
3433
|
standing rules for every agent on the instance \u2014 see the record-learning skill.
|
|
3416
3434
|
A rule enforced in code and nowhere written down gets re-litigated by the next
|
|
3417
3435
|
person.
|
|
3418
|
-
`,
|
|
3436
|
+
`,kS="---\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. `rolled_back`\n means removed here and ACCEPTED for sending \u2014 never tell a reader it is gone\n upstream from the state alone. A rollback also deletes a record whose create\n has not reached the source yet (a step that did not await, or whose wait ran\n out), so a run that merely stopped on a wait is RESUMED (item 9) and rolled\n back only when the work is to be undone.\n9. **A chain that stops is RESUMED, never invoked again.** An `awaitSource`\n step waits five minutes; past that the run ends `committed` with\n `outstanding > 0`. Invoking again starts at step one and CREATES AGAIN \u2014 a\n chain's step keys are per run (an `eachRow` process is different: its keys\n are per row, so that one IS invoked again). Carry the same run on with\n `resumeProcessRun(runId)` (`POST /v1/processes/runs/<runId>/resume`, or\n `turbobase processes resume <runId>`): it picks up at the step it stopped\n on and writes nothing twice. Only a run `committed` with work outstanding \u2014\n anything else answers `409` naming the state.\n10. **Invoking takes no idempotency key.** After a 502/504 the run may exist;\n retry only a 429 and `503 enqueue_failed`, and otherwise read the\n process's runs before starting another.\n11. **A create the source applied but could not link back** ends its step\n `SOURCE_APPLIED_UNLINKED`, with the source's id on the step: the row is\n kept by every rollback. Link it (item 7). On an older instance it read\n `SOURCE_REFUSED` and a rollback deleted the row \u2014 check `ADOPT.md`.\n12. **An update address may be `async`.** Read the row's current\n `sync_version` with `ctx.query` inside `expectedSyncVersion` itself.\n13. **Only a delete step takes `onRefused: 'continue'`.** A refused create or\n update ends the run. A refusal for a location, class, department or segment\n outside the user's scope is a bare `WRITE_REFUSED` / `forbidden`, naming\n no field.\n14. **A preview cannot run a new or changed process.** Processes are installed\n on merge, so a preview answers `404 process_not_found` (or runs the\n installed version). Say so on screen. `turbobase ext test` runs hooks and\n cannot run a process \u2014 `ext lint`, then invoke it and read the run.\n",Na=[{path:".claude/skills/business-rule-to-hook/SKILL.md",content:rh(SS)},{path:".claude/skills/write-a-process/SKILL.md",content:rh(kS)}];function xS(e){return`---
|
|
3419
3437
|
name: record-learning
|
|
3420
3438
|
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.
|
|
3421
3439
|
---
|
|
@@ -3470,7 +3488,7 @@ earlier claim" and still publish.
|
|
|
3470
3488
|
|
|
3471
3489
|
Do not reword the three headings. The deploy-side ingest recognises entries by
|
|
3472
3490
|
heading, not by filename, so a renamed section is a finding nobody receives.
|
|
3473
|
-
`}function
|
|
3491
|
+
`}function TS(e){return`# What this instance's source system actually does
|
|
3474
3492
|
|
|
3475
3493
|
Findings from ${e?`building the ${e.slug} app against the live mirror`:"authoring extensions against the live instance"}.
|
|
3476
3494
|
Written for the knowledge base, and **everything here is verified against real
|
|
@@ -3601,7 +3619,7 @@ finding has not been handed to the knowledge base yet.
|
|
|
3601
3619
|
and then \`turbobase skills release\`. \`turbobase skills list\` shows what is
|
|
3602
3620
|
already live, which is worth reading before adding another rule. -->
|
|
3603
3621
|
|
|
3604
|
-
`}function
|
|
3622
|
+
`}function RS(e){return`# Feedback for the Turbobase team \u2014 what ${e?`building the ${e.slug} app`:"authoring extensions here"} actually hit
|
|
3605
3623
|
|
|
3606
3624
|
Everything below cost time or produced a wrong result. Not speculation, and not
|
|
3607
3625
|
a wishlist. This file is about the PLATFORM \u2014 scaffold, catalog, CLI, MCP, API.
|
|
@@ -3681,7 +3699,7 @@ Expected / happened / cost / fix.
|
|
|
3681
3699
|
and what it would replace. These are the highest-signal entries in the file:
|
|
3682
3700
|
each one is a page downloading rows to fold that it could have asked for
|
|
3683
3701
|
folded. -->
|
|
3684
|
-
`}function
|
|
3702
|
+
`}function $S(e,t){let r=t?`
|
|
3685
3703
|
# INSTANCE.md \u2014 the instance's grounding brief (see CLAUDE.md). Reuse the
|
|
3686
3704
|
# --records focus a previous run stamped into the file, so a refresh never
|
|
3687
3705
|
# narrows what an agent deliberately widened.
|
|
@@ -3722,8 +3740,8 @@ if turbobase project --help 2>&1 | grep -qE '^ +skills( |$)'; then
|
|
|
3722
3740
|
turbobase project skills >/dev/null \\
|
|
3723
3741
|
|| echo "turbobase: \\\`turbobase project skills\\\` failed (its error is above) \u2014 the platform skills were NOT refreshed." >&2
|
|
3724
3742
|
fi
|
|
3725
|
-
`}var
|
|
3726
|
-
name: ${
|
|
3743
|
+
`}var ih="Turbobase consultant",ES="turbobase-consultant",PS=`---
|
|
3744
|
+
name: ${ih}
|
|
3727
3745
|
description: For ERP consultants, NetSuite admins and business analysts \u2014 business-outcome framing, short answers, no unrequested code tours.
|
|
3728
3746
|
keep-coding-instructions: true
|
|
3729
3747
|
---
|
|
@@ -3796,8 +3814,8 @@ exists on purpose.
|
|
|
3796
3814
|
- Do not show a stack trace. Say what broke and what you are doing about it.
|
|
3797
3815
|
- Do not apologise repeatedly or pad with "great question".
|
|
3798
3816
|
- Do not use a table when a sentence works.
|
|
3799
|
-
`;function
|
|
3800
|
-
`}var
|
|
3817
|
+
`;function AS(e){let t=[{type:"command",command:"bash .claude/hooks/check-rule-placement.sh"},...e?[{type:"command",command:`bash ${ah}`}]:[]];return JSON.stringify({outputStyle:ih,hooks:{SessionStart:[{hooks:[{type:"command",command:"bash .claude/hooks/session-start-refresh-types.sh"}]}],PostToolUse:[{matcher:"Edit|Write",hooks:t}]}},null,2)+`
|
|
3818
|
+
`}var ah=".claude/hooks/format-edited-file.sh",CS=`#!/usr/bin/env bash
|
|
3801
3819
|
# PostToolUse (Edit|Write) \u2014 put the edited file in the house format.
|
|
3802
3820
|
#
|
|
3803
3821
|
# Runs \`code-standards fix --files <file>\` from this project's node_modules.
|
|
@@ -3808,7 +3826,7 @@ set -uo pipefail
|
|
|
3808
3826
|
command -v node >/dev/null 2>&1 || exit 0
|
|
3809
3827
|
|
|
3810
3828
|
exec node "$(dirname "$0")/format-edited-file.mjs"
|
|
3811
|
-
`,
|
|
3829
|
+
`,IS=String.raw`/**
|
|
3812
3830
|
* Format the file that was just edited, with the project's own
|
|
3813
3831
|
* @turbobase/code-standards. Reads the PostToolUse payload on stdin. Exit 0
|
|
3814
3832
|
* always: this hook formats, it never gates.
|
|
@@ -3850,7 +3868,7 @@ try {
|
|
|
3850
3868
|
// A formatter that fails leaves the file as written.
|
|
3851
3869
|
}
|
|
3852
3870
|
bail();
|
|
3853
|
-
`,
|
|
3871
|
+
`,OS=`#!/usr/bin/env bash
|
|
3854
3872
|
# PostToolUse (Edit|Write) \u2014 is this a business rule that belongs in hooks/?
|
|
3855
3873
|
#
|
|
3856
3874
|
# Advisory only: exits 0 always, and adds a note for the agent when the edited
|
|
@@ -3867,7 +3885,7 @@ set -uo pipefail
|
|
|
3867
3885
|
command -v node >/dev/null 2>&1 || exit 0
|
|
3868
3886
|
|
|
3869
3887
|
exec node "$(dirname "$0")/check-rule-placement.mjs"
|
|
3870
|
-
`,
|
|
3888
|
+
`,NS=String.raw`/**
|
|
3871
3889
|
* Is the file that was just edited enforcing a business rule inside the SPA?
|
|
3872
3890
|
*
|
|
3873
3891
|
* Reads the PostToolUse payload on stdin, and when BOTH signals are present —
|
|
@@ -3936,7 +3954,7 @@ process.stdout.write(
|
|
|
3936
3954
|
},
|
|
3937
3955
|
}),
|
|
3938
3956
|
);
|
|
3939
|
-
`,
|
|
3957
|
+
`,LS=`---
|
|
3940
3958
|
name: roles-and-permissions
|
|
3941
3959
|
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".
|
|
3942
3960
|
---
|
|
@@ -4169,7 +4187,7 @@ a denial look like emptiness.
|
|
|
4169
4187
|
- Does every write catch \`TurbobasePermissionError\`?
|
|
4170
4188
|
- Did you run \`turbobase apps plan . --app <slug>\`?
|
|
4171
4189
|
- Did you tell the user their administrator still has to ASSIGN the role?
|
|
4172
|
-
`,
|
|
4190
|
+
`,jS=`---
|
|
4173
4191
|
name: app-design
|
|
4174
4192
|
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.
|
|
4175
4193
|
---
|
|
@@ -4264,7 +4282,7 @@ The design system covers the look. Two rules it does not:
|
|
|
4264
4282
|
Load it in the browser and check: does it render with ZERO rows, with ONE row,
|
|
4265
4283
|
and with several hundred? Does it survive the query failing? Does tab reach every
|
|
4266
4284
|
control, with a visible focus ring? A green \`npm run build\` proves none of these.
|
|
4267
|
-
`,ds="",
|
|
4285
|
+
`,ds="",nh=String.raw`{
|
|
4268
4286
|
"_comment": [
|
|
4269
4287
|
"Declarative sync config — part of this repo's desired state.",
|
|
4270
4288
|
" turbobase ext plan --to prod shows the diff against your instance (writes nothing)",
|
|
@@ -4286,7 +4304,7 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
4286
4304
|
"fields": [],
|
|
4287
4305
|
"tables": []
|
|
4288
4306
|
}
|
|
4289
|
-
`,
|
|
4307
|
+
`,oh=String.raw`{
|
|
4290
4308
|
"_comment": [
|
|
4291
4309
|
"Scheduled jobs, as desired state. Applied by: turbobase ext deploy --to prod",
|
|
4292
4310
|
"Removing an entry does NOT remove the schedule unless you pass --prune.",
|
|
@@ -4302,60 +4320,60 @@ control, with a visible focus ring? A green \`npm run build\` proves none of the
|
|
|
4302
4320
|
],
|
|
4303
4321
|
"schedules": []
|
|
4304
4322
|
}
|
|
4305
|
-
`,
|
|
4323
|
+
`,DS=e=>`node_modules/
|
|
4306
4324
|
|
|
4307
4325
|
# Holds a live personal access token (written by \`turbobase ${e?"apps":"project"} init\`).
|
|
4308
4326
|
.mcp.json
|
|
4309
4327
|
|
|
4310
4328
|
.DS_Store
|
|
4311
|
-
`;function
|
|
4329
|
+
`;function La(e={}){let t=pS.replace(/__BASE_URL__/g,e.baseUrl??"https://<slug>.turbobase.app").replace(/__PAT__/g,e.token??"tb_pat_\u2026"),r=!!e.appSlug,n=r?"src/types.ts":"types.ts",o=r?{slug:e.appSlug}:void 0,s=[{path:".mcp.json",content:t,mode:384},{path:".gitignore",content:DS(r)},{path:"INSTANCE-LEARNINGS.md",content:TS(o)},{path:"TURBOBASE-FEEDBACK.md",content:RS(o)},{path:".claude/settings.json",content:AS(r)},{path:`.claude/output-styles/${ES}.md`,content:PS},{path:".claude/skills/generate-types/SKILL.md",content:hS(n)},{path:".claude/skills/record-learning/SKILL.md",content:xS(o)},...Na,{path:".claude/hooks/session-start-refresh-types.sh",content:$S(n,o),executable:!0},{path:".claude/hooks/check-rule-placement.sh",content:OS,executable:!0},{path:".claude/hooks/check-rule-placement.mjs",content:NS}];return r?[{path:"CLAUDE.md",content:gS(e.appSlug)},...s,{path:".claude/skills/preview-app/SKILL.md",content:vS},{path:".claude/skills/ship-app/SKILL.md",content:_S},{path:".claude/skills/app-design/SKILL.md",content:jS},{path:".claude/skills/roles-and-permissions/SKILL.md",content:LS},{path:ah,content:CS,executable:!0},{path:".claude/hooks/format-edited-file.mjs",content:IS},...wS(),{path:"conduits/.gitkeep",content:ds},{path:"turbobase/sync.json",content:nh},{path:"turbobase/schedules.json",content:oh},...th()]:[{path:"CLAUDE.md",content:uS},...s,{path:".claude/skills/mock-test/SKILL.md",content:mS},{path:".claude/skills/deploy/SKILL.md",content:fS},{path:"hooks/.gitkeep",content:ds},{path:"conduits/.gitkeep",content:ds},{path:"samples/.gitkeep",content:ds},{path:"turbobase/sync.json",content:nh},{path:"turbobase/schedules.json",content:oh}]}import{promises as Da}from"node:fs";import{dirname as US,join as wt,resolve as ph}from"node:path";function ch(e){return{version:1,...e?{tenant:e}:{},hooks:[],conduits:[],sync:{fields:[],tables:[]},guardrails:{validationHooks:[],fieldRules:[],conduits:[]},schedules:[]}}var Ln="bundle.json",us="turbobase";function dh(e){let t;try{t=JSON.parse(e)}catch(l){throw new Error(`bundle.json is not valid JSON: ${l instanceof Error?l.message:String(l)}`,{cause:l})}if(typeof t!="object"||t===null||Array.isArray(t))throw new Error("bundle.json must be a JSON object");let r=t,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 ja(a)}function ja(e){let t=r=>(n,o)=>r(n)<r(o)?-1:r(n)>r(o)?1:0;return{version:1,...e.tenant?{tenant:e.tenant}:{},hooks:[...e.hooks].sort(t(r=>r.id)),conduits:[...e.conduits].sort(t(r=>r.id)),sync:{fields:[...e.sync.fields].sort(t(lh)),tables:[...e.sync.tables].sort(t(r=>r.sourceRecordType))},guardrails:{validationHooks:[...e.guardrails.validationHooks].sort(),fieldRules:[...e.guardrails.fieldRules].sort(t(lh)),conduits:[...e.guardrails.conduits].sort(t(r=>r.conduitId))},schedules:[...e.schedules].sort(t(r=>r.name))}}function lh(e){return`${e.sourceSystem}::${e.recordType}::${e.fieldName}`}function uh(e,t){let r=(t??"").trim();if(!r)return{ok:!1,reason:"target instance slug is unknown \u2014 cannot confirm a promote"};let n=(e??"").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 hs="hooks",ms="conduits",hh="processes",Qt="turbobase/sync.json",er="turbobase/schedules.json";function Ua(e){let t=u=>{let p=new RegExp(`${u}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return p?p[2]:void 0},r=/\bdefineConduit\s*[<(]/.test(e),n=/\bdefineProcess\s*[<(]/.test(e),o=/\bdefineHook\s*[<(]/.test(e);if(!r&&!o&&!n)return null;let s=t("id"),i=t("recordType");if(n){let u=t("source")??"standalone";return s?{id:s,recordType:"*",event:"invoke",source:u,extensionKind:"process"}:null}if(r){let u=t("on"),p=t("source");return!s||!i||!u||!p?null:{id:s,recordType:i,event:u,source:p,extensionKind:"conduit"}}let a=t("event"),l=t("source")??"standalone";return!s||!i||!a?null:{id:s,recordType:i,event:a,source:l,extensionKind:"hook"}}function Ma(e,t){if(!e||typeof e!="object")return null;let r=e;if(r.error!=="extension_id_mismatch")return null;let n=String(r.claimed??""),o=String(r.definitionId??"");return`${t?`${t}: `:""}refused (extension_id_mismatch) \u2014 the first \`id:\` literal in the file is '${n}', but the module defines '${o}'. Nothing was deployed.
|
|
4312
4330
|
The deploy is stored under the first \`id:\` literal, and the runtime serves the module's own id, so the two have to agree.
|
|
4313
|
-
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
|
|
4314
|
-
`))r(i)}return n}async function
|
|
4315
|
-
`)}),n=t.sleep??
|
|
4331
|
+
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 mh(e){return e==="written"?"new":e==="duplicate"?"replaced existing":e}function qa(e){return/\bdefineProcess\s*[<(]/.test(e)?"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(e)?"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 jn(e){let t;try{t=await Da.readdir(e,{withFileTypes:!0})}catch{return[]}let r=[];for(let n of t){if(n.isDirectory()){if(n.name.startsWith(".")||n.name==="node_modules")continue;for(let o of await jn(wt(e,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 ps(e,t){let r;try{r=await Da.readFile(e,"utf8")}catch{return}try{return JSON.parse(r)}catch(n){throw new Error(`${t} is not valid JSON: ${n instanceof Error?n.message:String(n)}`,{cause:n})}}function MS(e){return{sourceSystem:String(e.sourceSystem??""),recordType:String(e.recordType??""),fieldName:String(e.fieldName??""),owningSide:e.owningSide==="pg"?"pg":"source",caseSensitive:!!e.caseSensitive}}function qS(e){return{sourceRecordType:String(e.sourceRecordType??""),kind:String(e.kind??""),sourceSystem:String(e.sourceSystem??"")}}function zS(e){let t={name:String(e.name??""),scheduleKind:String(e.scheduleKind??"cron"),scheduleExpr:String(e.scheduleExpr??""),scheduleTz:String(e.scheduleTz??"UTC"),body:e.body??{}};return typeof e.status=="string"&&(t.status=e.status),t}async function fh(e=process.cwd()){let t=ph(e),[r,n,o]=await Promise.all([jn(wt(t,hs)),jn(wt(t,ms)),jn(wt(t,hh))]);if(r.length>0||n.length>0||o.length>0)return!0;let[s,i]=await Promise.all([ps(wt(t,Qt),Qt).catch(()=>{}),ps(wt(t,er),er).catch(()=>{})]);return s!==void 0||i!==void 0}async function gh(e=process.cwd(),t={}){let r=ph(e),n=ch(t.tenant),o=[],s=[];for(let l of[hs,ms,hh])for(let u of await jn(wt(r,l))){let p=`${l}/${u}`,g=await Da.readFile(wt(r,l,u),"utf8"),x=t.inline?await t.inline(g,US(wt(r,l,u))):g,y=Ua(x);if(!y){/\bdefine(Hook|Conduit|Process)\s*[<(]/.test(x)&&s.push({file:p,reason:qa(x)});continue}let k={id:y.id,kind:y.extensionKind,recordType:y.recordType,event:y.event,source:y.source,sourceCode:x};y.extensionKind==="conduit"?n.conduits.push(k):n.hooks.push(k),o.push(p)}let i=await ps(wt(r,Qt),Qt);if(i!==void 0){if(typeof i!="object"||i===null||Array.isArray(i))throw new Error(`${Qt} 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(MS(u));for(let u of Array.isArray(l.tables)?l.tables:[])n.sync.tables.push(qS(u));o.push(Qt)}let a=await ps(wt(r,er),er);if(a!==void 0){let l=Array.isArray(a)?a:Array.isArray(a.schedules)?a.schedules:null;if(l===null)throw new Error(`${er} must be a JSON array, or an object with a "schedules" array.`);for(let u of l)n.schedules.push(zS(u));o.push(er)}return n.guardrails.fieldRules=[...n.sync.fields],n.guardrails.validationHooks=n.hooks.filter(l=>l.event==="before_save").map(l=>l.id).sort(),{manifest:ja(n),contributed:o,unparsed:s}}import{promises as Fa}from"node:fs";import{resolve as WS}from"node:path";var BS="For app developers \u2014 adopt these";function yh(e){let t=/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(e.trim());return t?{core:[Number(t[1]),Number(t[2]??0),Number(t[3]??0)],prerelease:t[4]??""}:null}function bh(e,t){let r=yh(e),n=yh(t);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 FS(e){return e.replace(/[‐-―]/g,"-").toLowerCase().replace(/\s+/g," ").trim()}var PN=FS(BS);$n();bt();var HS=e=>new Promise(t=>setTimeout(t,e));function wh(e){return e.stage==="completed"||e.stage==="failed"}function VS(e){return`[${e.stage}] ${e.percent}%${e.runStatus?` (${e.runStatus})`:""}`}function KS(e,t,r){let n=e.outputTail??"";if(n&&n!==t){let s=(n.startsWith(t)?n.slice(t.length):n).replace(/\n+$/,"");if(s)for(let i of s.split(`
|
|
4332
|
+
`))r(i)}return n}async function za(e,t={}){let r=t.sink??(x=>{process.stdout.write(`${x}
|
|
4333
|
+
`)}),n=t.sleep??HS,o=t.intervalMs??2e3,s=t.maxPolls??Number.POSITIVE_INFINITY,i=t.onStage??(x=>r(VS(x))),a=t.onPoll,l="",u="",p=x=>{a?.(x),x.stage!==u&&i(x),l=KS(x,l,r),u=x.stage},g=await e();if(p(g),wh(g))return g;for(let x=0;x<s;x+=1)if(await n(o),g=await e(),p(g),wh(g))return g;return g}var b=e=>{process.stdout.write(`${e}
|
|
4316
4334
|
`)},O=e=>{process.stderr.write(`${e}
|
|
4317
|
-
`)};function v(e){O(m.red(`turbobase: ${e}`)),process.exit(1)}var
|
|
4318
|
-
`)){let o=
|
|
4335
|
+
`)};function v(e){O(m.red(`turbobase: ${e}`)),process.exit(1)}var Vr=/\.tsx?$/.test(process.argv[1]??"")?"npx tsx src/cli/turbobase.ts":"turbobase";function vh(e,t){let r=t.json===!0||typeof t.reporter=="string";(e.color===!1||r)&&Ea(!1)}async function F(e){let t=await yt(e);if(t)return{baseUrl:t.baseUrl,token:t.token};let r=await Mt();if(e){let n=r.length?` Stored instances: ${r.map(o=>o.baseUrl).join(", ")}.`:"";v(`not signed in to ${st(e)}.${n} Run \`turbobase auth login --base-url ${st(e)} --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 Jo(n);let o=await yt();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 W(e,t,r){if(!(e instanceof Y)||e.status!==403)return;e.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 '${t}' scope. Re-run \`turbobase auth login\` with a token that has it.`)}async function Ba(e,t,r){let n=r?Number(r):void 0;if(is()){let s=Aa(t),i;try{i=await za(e,{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(`${t} --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 za(e,{sink:b,intervalMs:n})}catch(s){v(`${t} --follow failed: ${s instanceof Error?s.message:String(s)}`)}o.stage==="failed"&&v(`${t} failed${o.runStatus?` (${o.runStatus})`:""}.`),b(`${t} ${o.stage}.`)}var GS=/adopted-through=([0-9A-Za-z.+-]*[0-9A-Za-z+])/;async function JS(e){try{let t=await Fa.readFile(e,"utf8");return GS.exec(t)?.[1]??null}catch{return null}}var YS=/GENERATED by `turbobase project adopt`/,Sh=/^##[ \t]+v?(\d+(?:\.\d+){0,2}(?:-[0-9A-Za-z.-]+)?)[ \t]*$/,XS=/^[ \t]*[-*][ \t]+\[([ xX])\][ \t]+(.*)$/;function _h(e){let t=[],r=null;for(let n of e.split(`
|
|
4336
|
+
`)){let o=Sh.exec(n);if(o){r={version:o[1],items:[]},t.push(r);continue}if(/^#{1,6}[ \t]/.test(n)){r=null;continue}if(!r)continue;let s=XS.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 t}function ZS(e){let t=e.items.map(r=>[`- [${r.done?"x":" "}] ${r.text}`,...r.extra].join(`
|
|
4319
4337
|
`)).join(`
|
|
4320
4338
|
`);return`## v${e.version}
|
|
4321
4339
|
|
|
4322
|
-
${t}`}function
|
|
4323
|
-
`),a=i.findIndex(p=>
|
|
4340
|
+
${t}`}function QS(e,t){let r=_h(e);if(r.length===0&&!YS.test(e))return null;let n=new Map(r.map(p=>[p.version,p])),o=[],s=0;for(let p of _h(t)){let g=n.get(p.version);n.delete(p.version);let x=new Set(p.items.map(k=>k.key)),y=p.items.map(k=>{let T=g?.items.find($=>$.key===k.key);return T?{...k,done:T.done,extra:T.extra}:k});for(let k of g?.items??[])x.has(k.key)||k.done||(y.push(k),s+=1);o.push({version:p.version,items:y})}for(let p of n.values()){let g=p.items.filter(x=>!x.done);g.length!==0&&(s+=g.length,o.push({version:p.version,items:g}))}o.sort((p,g)=>bh(g.version,p.version));let i=t.split(`
|
|
4341
|
+
`),a=i.findIndex(p=>Sh.test(p)),l=(a===-1?i:i.slice(0,a)).join(`
|
|
4324
4342
|
`).replace(/\s+$/,"");return{markdown:o.length===0?`${l}
|
|
4325
4343
|
`:`${l}
|
|
4326
4344
|
|
|
4327
|
-
${o.map(
|
|
4345
|
+
${o.map(ZS).join(`
|
|
4328
4346
|
|
|
4329
4347
|
`)}
|
|
4330
|
-
`,carried:s}}function
|
|
4348
|
+
`,carried:s}}function kh(e){e.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 t=>{let{baseUrl:r,token:n}=await F(t.baseUrl),o=WS(process.cwd(),t.out),s=t.since?.trim()||await JS(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(($,P)=>$+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??"",x=`<!-- GENERATED by \`turbobase project adopt\` against ${r} \u2014 adopted-through=${g}. Re-run to refresh; delete this file once every line is done. -->
|
|
4331
4349
|
|
|
4332
|
-
`,y=await
|
|
4350
|
+
`,y=await Fa.readFile(o,"utf8").catch(()=>null),k=u.markdown,T=0;if(y!==null&&y.trim()!==""){let $=QS(y,u.markdown);$||v(`${o} was not written by \`turbobase project adopt\` (no generated header, no \`## v<version>\` section) \u2014 refusing to overwrite it. Move it aside, or write elsewhere with \`-o <file>\`.`),k=$.markdown,T=$.carried}await Fa.writeFile(o,x+k,"utf8"),b(`wrote ${o} \u2014 ${p} item(s) across ${u.releases.length} release(s)${s?` since v${s.replace(/^v/,"")}`:""}${T>0?`, keeping ${T} unticked item(s) already in the file`:""}.`)})}import{existsSync as ek,mkdirSync as tk,readFileSync as rk,writeFileSync as fs}from"node:fs";import{dirname as nk,join as ok}from"node:path";function xh(e){if(!e.startsWith(`---
|
|
4333
4351
|
`))return null;let t=e.indexOf(`
|
|
4334
4352
|
---
|
|
4335
|
-
`,4);return t<0?null:e.slice(0,t+5)}function
|
|
4336
|
-
`);for(let n of r.slice(0,
|
|
4337
|
-
`)),b(
|
|
4338
|
-
`))}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 \`${
|
|
4339
|
-
`))}async function
|
|
4340
|
-
`))r.push(` ${m.dim("|")} ${a}`)}r.push("")}),r}function
|
|
4341
|
-
`)),b(
|
|
4342
|
-
`)).trim();continue}t[i]=
|
|
4353
|
+
`,4);return t<0?null:e.slice(0,t+5)}function Th(e,t=Na){let r=[];for(let n of t){let o=ok(e,n.path);if(!ek(o)){tk(nk(o),{recursive:!0}),fs(o,n.content),r.push({path:n.path,outcome:"written"});continue}let s=rk(o,"utf8");if(s===n.content){r.push({path:n.path,outcome:"unchanged"});continue}if(s.includes(Oa)){fs(o,n.content),r.push({path:n.path,outcome:"updated"});continue}let i=xh(n.content);if(i!==null&&xh(s)===i){fs(`${o}.bak`,s),fs(o,n.content),r.push({path:n.path,outcome:"replaced-legacy"});continue}r.push({path:n.path,outcome:"kept-edited"})}return r}function Rh(e){switch(e.outcome){case"written":return`${e.path}: written`;case"updated":return`${e.path}: updated to this CLI's version`;case"unchanged":return`${e.path}: current`;case"replaced-legacy":return`${e.path}: replaced an older platform copy (saved as SKILL.md.bak)`;case"kept-edited":return`${e.path}: NOT updated \u2014 it was edited in this project. Move your notes to INSTANCE-LEARNINGS.md and delete the file to receive the platform version.`}}bt();var Dn=["suggested_kb_edit","kb_correction"];var sk=[{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 ik(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}var KN=new Map(sk.map(e=>[ik(e.heading),e]));var WN=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 ak(e){return e.diff??!!e.dryRun}var lk={update_page:"append to the existing page",new_page:"create a NEW page"},zt=(e,t)=>` ${m.dim(e.padEnd(11))}${t}`,Ph=e=>e.ownerEmail??e.ownerId;function Kr(e){return!e.needsPageRef&&!e.blockedBy}var gs=e=>m.green(e?` + ${e}`:" +"),ck=e=>m.red(e?` - ${e}`:" -"),vr=e=>m.dim(` ${e}`),dk=` ${m.dim(`\u2500 diff ${"\u2500".repeat(54)}`)}`,Ha=80;function uk(e){let t=[dk];e.target?(t.push(vr(`turbobase.document \xB7 ${e.target.slug}`)),e.withdraws?(t.push(ck(`visibility: ${e.target.visibility}`)),t.push(gs("visibility: admin"))):t.push(vr(`visibility: ${e.target.visibility} \u2014 unchanged`)),t.push(vr("title, slug, evidence: untouched")),t.push(vr("body_markdown: appended to \u2014 nothing already on the page is rewritten"))):(t.push(vr("turbobase.document \xB7 new")),t.push(gs(`title: ${e.pageTitle}`)),t.push(gs("visibility: admin \u2014 unpublished, outside the reader surface")),t.push(vr('filed under "From app developers" until an editor moves it'))),t.push(""),t.push(vr('appended under "## From app developers":'));let r=(e.appendedMarkdown??"").replace(/\s+$/,"").split(`
|
|
4354
|
+
`);for(let n of r.slice(0,Ha))t.push(gs(n?` ${n}`:""));return r.length>Ha&&t.push(m.yellow(` \u2026 ${r.length-Ha} more line(s) not shown \u2014 the full text lands on the page`)),t.push(""),t}function pk(e,t={}){let r=[];return e.forEach((n,o)=>{let{target:s,entries:i}=n;if(r.push(`${String(o+1).padStart(2)}. ${m.bold(n.pageTitle)}`),r.push(zt("page",s?`${s.title} (${s.slug}) [${s.visibility}]`:m.dim("new \u2014 no existing page matches"))),r.push(zt("action",Kr(n)?lk[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(zt("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(zt("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(zt("confidence",n.withdraws?m.red("WITHDRAWN from readers (text untouched)"):m.dim("untouched"))),n.supersedes&&r.push(zt("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(zt("blocked",m.red(`unpublished work on this page belongs to ${Ph(n.blockedBy)} \u2014 this page will be SKIPPED`))),n.alsoMatched.length>0&&r.push(zt("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=e.findIndex(g=>g.key===l),p=u>=0?e[u]:void 0;return p?`#${u+1} "${p.pageTitle}"`:l});r.push(zt("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.`)))}t.diff&&Kr(n)&&r.push(...uk(n)),r.push("")}),r}function hk(e){let t=u=>e.filter(u).length,r=e.reduce((u,p)=>u+p.entries.length,0),n=t(u=>u.withdraws),o=t(u=>u.blockedBy!=null),s=t(u=>u.needsPageRef),i=[`${r} finding${r===1?"":"s"}`,`${t(Kr)} page(s)`,`${t(u=>u.action==="update_page"&&Kr(u))} appended`,`${t(u=>u.action==="new_page"&&Kr(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 mk(e,t){let r=new Map(t.map(o=>[o.key,o])),n=[];for(let o of e){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?Ph(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 $h(e){if(e instanceof Y){let t=e.body;e.status===403&&t?.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."),e.status===404&&v("this instance does not serve /v1/learnings \u2014 it predates the app-developer learning loop. Ask for an instance upgrade.")}W(e,"extensions:deploy","learnings push-kb")}async function Un(e,t){let r;try{r=await X("re-reading pushed markdown",()=>e.learningsIngest(t))}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`.")):tp(o)?O(m.yellow(Eh(o))):O(m.yellow(`could not re-read the pushed markdown: ${Eh(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 Eh(e){return e instanceof Error?e.message:String(e)}async function Ah(e,t=r=>new z(r)){e.section&&!Dn.includes(e.section.trim())&&v(`unknown --section "${e.section}" \u2014 expected one of ${Dn.join(" | ")}.`),e.limit!==void 0&&(!Number.isFinite(e.limit)||e.limit<1)&&v("--limit must be a positive integer.");let r=await F(e.baseUrl),n=t(r),o={...e.app?{app:e.app}:{},...e.section?{section:e.section.trim()}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.group===!1?{group:!1}:{}},s=await Un(n,e.app),i;try{i=await X("reading the pending queue",()=>n.learningsPending(o))}catch(u){$h(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(b(pk(i.items,{diff:ak(e)}).join(`
|
|
4355
|
+
`)),b(hk(i.items)),e.dryRun){O(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.filter(Kr);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(!e.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));b(mk(u.applied,i.items).join(`
|
|
4356
|
+
`))}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 \`${Vr} kb push\` to review the current plan.`),process.exitCode=2;return}$h(u),O(m.red(`turbobase: ${u instanceof Error?u.message:String(u)}`)),process.exitCode=2}}bt();var Wr=e=>new z(e);async function Gr(e,t){let r=await F(e.baseUrl);return t(r)}async function ys(e,t,r,n){return n.yes?!0:Ne()?await Le(e,[{value:"yes",label:t,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 fk(e){return e.visibility!=="published"?m.dim("draft"):e.in_current_release?m.green("live"):m.yellow("unreleased")}function Ch(e,t){let r=e.replace(/\x1b\[[0-9;]*m/g,"").length;return e+" ".repeat(Math.max(0,t-r))}function gk(e){if(e.items.length===0)return["no pages in this knowledge base."];let t=Math.max(4,...e.items.map(s=>s.slug.length)),r=[];for(let s of e.items)r.push(`${Ch(m.bold(s.slug),t)} ${Ch(fk(s),10)} ${m.dim(s.path)}`);r.push("");let n=e.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=e.items.filter(s=>s.visibility!=="published").length;return r.push(`${e.items.length} page(s) \xB7 ${n} readable \xB7 ${o} draft`+(e.currentVersion==null?"":` \xB7 release v${e.currentVersion}`)),r}async function Ih(e,t=Wr){let r={};e.status&&(e.status!=="draft"&&e.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${e.status}').`),r.status=e.status);let n=await Gr(e,t),o;try{o=await X("reading the knowledge base",()=>n.docsList(r))}catch(s){W(s,"docs:publish","read the knowledge base"),v(`could not read the knowledge base: ${s instanceof Error?s.message:String(s)}`)}b(gk(o).join(`
|
|
4357
|
+
`))}async function Oh(e,t,r=Wr){let n=[...new Set(e.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Gr(t,r);if(!await ys(`Publish ${n.length} page(s)?`,"Yes \u2014 publish them","every member can read them, and retrieval can ground answers on them, from now on",t))return;let i;try{i=await X("publishing",()=>o.docsPublish(n))}catch(l){W(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&&(O(m.yellow(`no such page: ${i.missing.join(", ")}`)),process.exitCode=1),O(m.dim(`undo with: turbobase kb unpublish ${a.join(" ")}`))}async function Nh(e,t,r=Wr){let n=[...new Set(e.map(l=>l.trim()).filter(Boolean))];n.length===0&&v("name at least one page slug. `turbobase kb list` shows them.");let o=await Gr(t,r);if(!await ys(`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",t))return;let i;try{i=await X("unpublishing",()=>o.docsUnpublish(n))}catch(l){W(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.`)),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 Lh(e,t=Wr){let r=await Gr(e,t),n;try{n=await X("reading the releases",()=>r.docsVersions())}catch(o){W(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 jh(e,t,r=Wr){let n=Number(e);(!Number.isInteger(n)||n<1)&&v(`version must be a release number (got '${e}'). \`turbobase kb versions\` lists them.`);let o=await Gr(t,r);if(await ys(`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",t))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){W(i,"docs:publish","roll the knowledge base back"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function Dh(e,t,r=Wr){let n=(e??"").trim();n||v("name the page slug to delete. `turbobase kb list` shows them.");let o=await Gr(t,r);if(await ys(`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",t))try{let i=await X("deleting",()=>o.docsDelete(n));b(m.green(`deleted ${i.deleted} \u2014 restorable from the knowledge-base trash.`))}catch(i){W(i,"docs:publish","delete a page"),v(`delete failed: ${i instanceof Error?i.message:String(i)}`)}}bt();function yk(e){return e.diff??!!e.dryRun}function bk(e,t){let r=[];return e.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(t.diff){r.push("");for(let a of n.bodyMarkdown.split(`
|
|
4358
|
+
`))r.push(` ${m.dim("|")} ${a}`)}r.push("")}),r}function wk(e){let t=e.reduce((o,s)=>o+s.entries.length,0),r=e.filter(o=>o.targetPublished).length,n=[`${t} finding(s) \u2192 ${e.length} rule(s)`];return r>0&&n.push(m.yellow(`${r} amend a rule that is currently live`)),n.join(" \xB7 ")}async function Uh(e,t=r=>new z(r)){e.limit!==void 0&&(!Number.isFinite(e.limit)||e.limit<1)&&v("--limit must be a positive integer.");let r=await F(e.baseUrl),n=t(r),o={...e.app?{app:e.app}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.group===!1?{group:!1}:{},...e.reapply?{reapply:!0}:{}},s=await Un(n,e.app),i;try{i=await X("reading the pending rules",()=>n.rulesPending(o))}catch(l){W(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&&!e.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(b(bk(i.items,{diff:yk(e)}).join(`
|
|
4359
|
+
`)),b(wk(i.items)),e.dryRun){O(m.dim("dry run \u2014 nothing was written."));return}let a=i.items.reduce((l,u)=>l+u.entries.length,0);if(!e.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)}`)}b(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 Tk,readFile as Rk,stat as $k}from"node:fs/promises";import{join as zh,resolve as Ek}from"node:path";var Bt=class extends Error{constructor(t){super(t),this.name="SkillParseError"}},vk=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;function Mh(e){let t=e.replace(/^/,""),r=vk.exec(t);if(!r)throw new Bt("SKILL.md must begin with a `---` YAML frontmatter block");let[,n,o]=r,s=_k(n??""),i=s.name,a=s.description;if(!i)throw new Bt("SKILL.md frontmatter is missing required `name`");if(!a)throw new Bt("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 _k(e){let t={},r=e.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 Bt(`SKILL.md frontmatter: indented line not allowed in this parser: "${o.trim()}"`);let s=o.indexOf(":");if(s===-1)throw new Bt(`SKILL.md frontmatter: expected "key: value", got "${o.trim()}"`);let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(a=kk(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}t[i]=(a===">"?l.join(" "):l.join(`
|
|
4360
|
+
`)).trim();continue}t[i]=Sk(a),n+=1}return t}function Sk(e){return e.startsWith('"')&&e.endsWith('"')||e.startsWith("'")&&e.endsWith("'")?e.slice(1,-1):e}function kk(e){let t=!1,r=!1;for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="'"&&!r)t=!t;else if(o==='"'&&!t)r=!r;else if(o==="#"&&!t&&!r)return e.slice(0,n).trim()}return e}var xk=/^[a-z0-9][a-z0-9-]{1,58}[a-z0-9]$/;function qh(e){let t=[];e.length===0&&t.push("no skill files: expected <dir>/<slug>/SKILL.md"),e.length>50&&t.push(`${e.length} skill files; at most 50 per push`);let r=new Set;for(let n of e){let o=n.slug||"(unnamed)";xk.test(n.slug??"")||t.push(`${o}: the directory name must be lowercase letters, digits and hyphens (3\u201360 characters)`),r.has(n.slug)&&t.push(`${o}: two files share this slug`),r.add(n.slug),n.name?.trim()?n.name.length>200&&t.push(`${o}: \`name\` is over 200 characters`):t.push(`${o}: frontmatter \`name\` is empty`),n.description?.trim()?n.description.length>1024&&t.push(`${o}: \`description\` is over 1024 characters`):t.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&&t.push(`${o}: the body is over ${65536/1024} KB`):t.push(`${o}: the body after the frontmatter is empty`)}return t}bt();async function Pk(e){let t=Ek(e),r;try{r=(await Tk(t)).sort()}catch{v(`--from ${e}: no such directory.`)}let n=[];for(let o of r){let s=zh(t,o,"SKILL.md");if(await $k(s).then(a=>a.isFile()).catch(()=>!1))try{let a=Mh(await Rk(s,"utf8"));n.push({slug:o,name:a.frontmatter.name.trim(),description:a.frontmatter.description.trim(),body:a.body})}catch(a){throw a instanceof Bt&&v(`${zh(e,o,"SKILL.md")}: ${a.message}`),a}}return n}var bs={new:"new skill",update:"update skill",unchanged:"unchanged",refused:"REFUSED"},Ak={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 Ck(e){let t=[];for(let r of e.items){let n=r.action==="refused"?m.red(bs.refused):r.action==="unchanged"?m.dim(bs.unchanged):r.action==="new"?m.green(bs.new):m.yellow(bs.update),o=r.targetPublished?` ${m.yellow("[currently live]")}`:"";t.push(`${n} ${m.bold(r.slug)}${o} \u2014 ${r.name}`),r.reason&&t.push(` ${m.red(Ak[r.reason]??r.reason)}`)}for(let r of e.orphans)t.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 t}async function Bh(e,t=r=>new z(r)){e.app||v("--from needs --app <slug>: the skills are the app\u2019s own, and the app owns what it writes.");let r=await Pk(e.from),n=qh(r);n.length>0&&v(`nothing was sent:
|
|
4343
4361
|
${n.join(`
|
|
4344
|
-
`)}`);let o=await
|
|
4345
|
-
`));let l=a.items.filter(x=>x.action==="new"||x.action==="update").length,u=a.items.filter(x=>x.action==="refused").length;if(e.dryRun){O(m.dim("dry run \u2014 nothing was written.")),u>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!e.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)${e.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(x=>x.action==="new"||x.action==="update").map(x=>x.slug);if(b(`${g.length} written, ${p.items.filter(x=>x.action==="unchanged").length} unchanged, ${p.items.filter(x=>x.action==="refused").length} refused.`),e.publish&&g.length>0){let x;try{x=await X("publishing",()=>s.skillsPublish(g))}catch(y){W(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 ${x.published.join(", ")} \u2014 live as of release ${x.version.version_no}.`))}else e.publish?b(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(x=>x.action==="refused")&&(O(m.red("one or more skill files were refused and not written.")),process.exitCode=1)}bt();var
|
|
4346
|
-
`+m.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}b(lt(o.map(
|
|
4347
|
-
`))}async function
|
|
4362
|
+
`)}`);let o=await F(e.baseUrl),s=t(o),i=async x=>{try{return await X(x?"reading the plan":"writing the skills",()=>s.appSkillsPush(e.app,r,x))}catch(y){if(W(y,"extensions:deploy","push skill files"),y instanceof Y&&y.status===404){let k=y.body;v(k?.error==="app_not_found"?String(k.message):"this instance has no /v1/apps/:slug/skills \u2014 it predates `skills push --from`. Upgrade the instance first.")}v(`push failed: ${y instanceof Error?y.message:String(y)}`)}},a=await i(!0);b(Ck(a).join(`
|
|
4363
|
+
`));let l=a.items.filter(x=>x.action==="new"||x.action==="update").length,u=a.items.filter(x=>x.action==="refused").length;if(e.dryRun){O(m.dim("dry run \u2014 nothing was written.")),u>0&&(process.exitCode=1);return}let p=a;if(l>0){if(!e.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)${e.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(x=>x.action==="new"||x.action==="update").map(x=>x.slug);if(b(`${g.length} written, ${p.items.filter(x=>x.action==="unchanged").length} unchanged, ${p.items.filter(x=>x.action==="refused").length} refused.`),e.publish&&g.length>0){let x;try{x=await X("publishing",()=>s.skillsPublish(g))}catch(y){W(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 ${x.published.join(", ")} \u2014 live as of release ${x.version.version_no}.`))}else e.publish?b(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(x=>x.action==="refused")&&(O(m.red("one or more skill files were refused and not written.")),process.exitCode=1)}bt();var Ik=["proposed","active","rejected"],Ok=["mechanic","operator","learning","code-baseline"],ws=e=>new z(e);async function vs(e,t){let r=await F(e.baseUrl);return t(r)}function Fh(e,t,r){if(!e)return;let n=e.split(",").map(o=>o.trim()).filter(o=>o.length>0);if(n.length!==0){for(let o of n)t.includes(o)||v(`${r}: unknown value '${o}' \u2014 expected one of ${t.join(", ")}.`);return n}}function Nk(e){if(e===void 0)return;let t=Number(e);return(!Number.isFinite(t)||t<=0)&&v("--limit must be a positive number."),Math.floor(t)}function Kh(e){let t=Fh(e.status,Ik,"--status"),r=Fh(e.provenance,Ok,"--provenance"),n=Nk(e.limit);return{...t?{status:t}:{},...r?{provenance:r}:{},...e.recordType?{recordType:e.recordType}:{},...e.source?{source:e.source}:{},...n?{limit:n}:{}}}function Hh(e){return!!(e.provenance?.length||e.recordType||e.source)}var Wh=["ID","STATUS","PROVENANCE","RECORD","EVENT","SOURCE","EVIDENCE","ENFORCES"];function Lk(e){return e.status==="active"?m.green("active"):e.status==="rejected"?m.dim("rejected"):m.yellow("proposed")}function jk(e){return e.message?e.message:e.kind&&e.field?m.dim(`${e.kind} ${e.field}`):e.kind?m.dim(e.kind):m.dim("(no description)")}function Gh(e){return[e.hookId,Lk(e),e.provenance==="learning"?m.yellow(e.provenance):e.provenance,e.recordType,e.event,e.source,String(e.taughtBy.length),jk(e)]}async function Jh(e={},t=ws){let r=await vs(e,t),n=Kh(e),o;try{o=await r.proposals(n)}catch(i){W(i,"extensions:deploy","list hook proposals"),v(`list hook proposals failed: ${i instanceof Error?i.message:String(i)}`)}if(e.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.
|
|
4364
|
+
`+m.dim(" the Mechanic stages one when a sync failure teaches a repeatable invariant."))}b(lt(o.map(Gh),{head:Wh})),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 Dk(e,t,r){return r.yes?!0:Ne()?await Le(e,[{value:"yes",label:t},{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 Uk(e){return!(e instanceof Y)||e.status!==403?!1:e.body?.error==="insufficient_scope"}function Va(e,t){Uk(e)&&W(e,"extensions:deploy",t)}function Ka(e,t){let r=t instanceof Y?t.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:t instanceof Error?t.message:String(t);O(ve.error(`${m.bold(e)} \u2014 ${s}`))}async function Vh(e,t){try{let r=await e.proposalPromote(t);return b(ve.success(`${m.bold(t)} ${m.dim(`${r.previousStatus} \u2192`)} ${m.green(r.status)}`)),!0}catch(r){return Va(r,"promote a hook proposal"),Ka(t,r),!1}}async function Yh(e,t={},r=ws){!t.auto&&e.length===0&&v("promote: name at least one proposal id, or pass --auto with a filter."),t.auto&&e.length>0&&v("promote: pass ids OR --auto, not both \u2014 --auto selects by filter."),!t.auto&&(t.apply||t.all)&&v("promote: --apply / --all only mean something with --auto.");let n=await vs(t,r);if(!t.auto){let p=0;for(let g of e)await Vh(n,g)&&(p+=1);p>0&&b(m.dim(` ${p} hook(s) armed \u2014 the loader compiles them on its next reload.`)),p<e.length&&(process.exitCode=1);return}let o=Kh({...t,status:t.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){W(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(t.json&&(b(JSON.stringify({apply:!!t.apply,plan:a,skipped:i},null,2)),!t.apply))return;if(a.length===0){t.json||(b(`nothing to promote${Hh(o)?" for that filter":""}.`),i.length>0&&b(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 they need sign-off.`)));return}if(t.json||(b(t.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(lt(a.map(Gh),{head:Wh})),i.length>0&&b(m.dim(` ${i.length} learning-provenance row(s) skipped \u2014 armed through sign-off in the console.`))),!t.apply){b(""),b(ve.info("nothing was changed. Re-run with --apply to arm these."));return}if(!Hh(o)&&!t.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 Dk(`Arm ${a.length} hook proposal(s)? They start rejecting writes on the next loader reload.`,`Yes \u2014 promote ${a.length}`,t))return;let u=0;for(let p of a)await Vh(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 Xh(e,t={},r=ws){e.length===0&&v("retract: name at least one proposal id.");let n=await vs(t,r),o=0;for(let s of e)try{let i=await n.proposalRetract(s);b(ve.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.yellow(i.status)}`)),o+=1}catch(i){Va(i,"retract a hook proposal"),Ka(s,i)}o>0&&b(m.dim(" source kept \u2014 re-arm with `turbobase ext proposals promote <id>`.")),o<e.length&&(process.exitCode=1)}async function Zh(e,t={},r=ws){e.length===0&&v("reject: name at least one proposal id.");let n=await vs(t,r),o=0;for(let s of e)try{let i=await n.proposalReject(s,t.reason);b(ve.success(`${m.bold(s)} ${m.dim(`${i.previousStatus} \u2192`)} ${m.dim(i.status)}`)),o+=1}catch(i){Va(i,"reject a hook proposal"),Ka(s,i)}o<e.length&&(process.exitCode=1)}bt();var Wa=e=>new z(e);async function Mk(e,t){let r=await F(e.baseUrl);return t(r)}function qk(e){return!(e instanceof Y)||e.status!==403?!1:e.body?.error==="insufficient_scope"}function zk(e,t){let r=t instanceof Y?t.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:t instanceof Error?t.message:String(t);O(ve.error(`${m.bold(e)} \u2014 ${s}`))}async function Ga(e,t,r,n,o,s,i){t.length===0&&v(`${e}: name at least one extension id.`);let a=await Mk(r,n),l=[];for(let u of t)try{let p=await o(a,u);l.push(p),r.json||b(s(p))}catch(p){qk(p)&&W(p,"extensions:deploy",`${e} an extension`),zk(u,p)}if(r.json)b(JSON.stringify(l,null,2));else{let u=i(l.length);u&&b(m.dim(u))}l.length<t.length&&(process.exitCode=1)}async function Qh(e,t={},r=Wa){await Ga("disable",e,t,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 em(e,t={},r=Wa){await Ga("enable",e,t,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 tm(e,t={},r=Wa){await Ga("remove",e,t,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)}bt();var Jr=e=>new z(e);async function Yr(e,t){let r=await F(e.baseUrl);return t(r)}async function _s(e,t,r,n){return n.yes?!0:Ne()?await Le(e,[{value:"yes",label:t,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 Bk(e){return e.visibility!=="published"?m.dim("draft"):e.in_current_release?m.green("live"):m.yellow("unreleased")}function rm(e,t){let r=e.replace(/\x1b\[[0-9;]*m/g,"").length;return e+" ".repeat(Math.max(0,t-r))}function Fk(e){if(e.items.length===0)return["no skills on this instance."];let t=Math.max(4,...e.items.map(s=>s.slug.length)),r=[];for(let s of e.items)r.push(`${rm(m.bold(s.slug),t)} ${rm(Bk(s),10)} ${s.surfaces.join(",")||m.dim("none")}`),s.description&&r.push(` ${m.dim(s.description)}`);r.push("");let n=e.items.filter(s=>s.visibility==="published"&&s.in_current_release).length,o=e.items.filter(s=>s.visibility!=="published").length;return r.push(`${e.items.length} skill(s) \xB7 ${n} injected \xB7 ${o} draft`+(e.currentVersion==null?"":` \xB7 release v${e.currentVersion}`)),r}async function nm(e,t=Jr){let r={};e.status&&(e.status!=="draft"&&e.status!=="published"&&v(`--status must be 'draft' or 'published' (got '${e.status}').`),r.status=e.status);let n=await Yr(e,t),o;try{o=await X("reading the skills",()=>n.skillsList(r))}catch(s){W(s,"skills:publish","read the instance skills"),v(`could not read the skills: ${s instanceof Error?s.message:String(s)}`)}b(Fk(o).join(`
|
|
4365
|
+
`))}async function om(e,t,r=Jr){let n=[...new Set(e.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Yr(t,r);if(!await _s(`Publish ${n.length} skill(s)?`,"Yes \u2014 publish them","their text is injected into every matching turn from now on",t))return;let i;try{i=await X("publishing",()=>o.skillsPublish(n))}catch(a){W(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&&(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 sm(e,t,r=Jr){let n=[...new Set(e.map(a=>a.trim()).filter(Boolean))];n.length===0&&v("name at least one skill slug. `turbobase skills list` shows them.");let o=await Yr(t,r);if(!await _s(`Move ${n.length} skill(s) back to draft?`,"Yes \u2014 unpublish them","they stop being injected immediately; the text and its history are kept",t))return;let i;try{i=await X("unpublishing",()=>o.skillsUnpublish(n))}catch(a){W(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.`)),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 im(e,t,r=Jr){let n=Number(e);(!Number.isInteger(n)||n<1)&&v(`--version must be a release number (got '${e}'). \`turbobase skills releases\` lists them.`);let o=await Yr(t,r);if(await _s(`Roll the skills back to release v${n}?`,"Yes \u2014 restore that release","content only: a skill an operator has since unpublished stays off",t))try{let i=await X("rolling back",()=>o.skillsRollback(n));b(m.green(`rolled back to v${i.version.version_no}.`))}catch(i){W(i,"skills:publish","roll back a skills release"),v(`rollback failed: ${i instanceof Error?i.message:String(i)}`)}}async function am(e,t=Jr){let r=await Yr(e,t),n;try{n=await X("reading the releases",()=>r.skillsReleases())}catch(o){W(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}`:"";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 lm(e,t,r=Jr){let n=[...new Set((e??[]).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 Yr(t,r);if(!await _s(n.length===1?`Delete the skill '${n[0]}'?`:`Delete ${n.length} skills?
|
|
4348
4366
|
${n.join(`
|
|
4349
|
-
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",t))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(", ")}`)),W(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&&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
|
|
4350
|
-
`,{mode:384})}async function wx(e){let t=await sl();t.push(e),await ym(t)}async function bm(e){let t=await sl(),r=t.findIndex(o=>o.name===e);if(r===-1)return null;let[n]=t.splice(r,1);return await ym(t),n??null}async function ks(){return sl()}function il(e,t=Date.now()){let r=[],n=[];for(let o of e)ax(o.expiresAt,t)?n.push(o):r.push(o);return{active:r,expired:n}}async function wm(e,t){ol(e.target());let r=e.dataCopyUnavailable?.();if(r)throw new qn(r);let n=lx(t.sample),o=t.now??Date.now(),s=(t.nameGen??(u=>fx(u)))(t.fromTenant),i=yx(s);await e.createDatabase(i),await e.replayMigrations(i);let a=await e.readSourceTables(t.fromTenant);for(let u of a){let p=cx(u.rows,n),g=px(u.table,p,u.classification);g.length>0&&await e.copyRows(i,u.table,g)}let l={name:s,fromTenant:t.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ix(t.ttl,o),sampleFraction:n,url:bx(s,t.baseUrl)};return await wx(l),l}async function vm(e,t){ol(e.target());let n=(await ks()).find(o=>o.name===t);return n?(await e.dropDatabase(n.database),await bm(t),n):null}async function al(e,t=Date.now()){ol(e.target());let r=await ks(),{expired:n}=il(r,t),o=[];for(let s of n){try{await e.dropDatabase(s.database)}catch{continue}await bm(s.name),o.push(s)}return o}var zn={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"}},rj=Object.keys(zn).filter(e=>zn[e].mintable);var sj=zn.pat.prefix,vx=Object.entries(zn).map(([e,t])=>[t.prefix,e]),_x=/^[A-Za-z0-9_-]{20,}$/;function Sx(e){if(typeof e!="string")return null;for(let[t,r]of vx)if(e.startsWith(t)&&_x.test(e.slice(t.length)))return r;return null}function _m(e){return Sx(e)==="pat"}$n();var kx=8e3,xx={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 Tx(e){return xx[e]??`the instance rejected this token (${e}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function Rx(e,t,r=fetch){let n;try{n=await r(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(kx)})}catch(s){return{state:"unreachable",detail:s instanceof Error?s.message:String(s)}}if(n.status===200||n.status===403)return{state:"accepted"};if(n.status===401){let s=await n.json().catch(()=>null);return{state:"rejected",reason:typeof s?.reason=="string"&&s.reason?s.reason:"unknown"}}return(n.headers.get("content-type")??"").includes("application/json")?{state:"accepted"}:{state:"unreachable",detail:`HTTP ${n.status} \u2014 this host does not serve the /v1 API`}}function Sm(e){return e.state==="accepted"?Oe()?m.green("accepted"):"accepted":e.state==="rejected"?Oe()?m.red(`rejected \xB7 ${e.reason}`):`rejected \xB7 ${e.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function km(e={},t=fetch){let r=await Mt(),{file:n}=Go();if(r.length===0){b("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 yt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:e.probe===!1?{state:"accepted"}:await Rx(i.baseUrl,i.token,t)})));if(e.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(lt(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),Sm(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${Sm(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}: ${Tx(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 sI(e){let t=await Mt();t.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(e,t.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function iI(e,t){let r;try{r=await fetch(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,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 aI(e){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: ${e}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),O("")}async function lI(e,t,r){let n=await Ju({baseUrl:e,token:t}),o=(await Mt()).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).`:".")),aI(n.baseUrl),!r)return;let s=await iI(n.baseUrl,t);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 cI(e){let t=await _a(await Cn(e),Wt(e)),r=Da(t);return r||v(`${e}: ${Ma(t)}`),{...r,sourceCode:t}}async function Lr(e,t,r,n){try{return await ie.access(e),"skipped"}catch{}return await ie.mkdir(Wt(e),{recursive:!0}),await ie.writeFile(e,t,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(e,n),"wrote"}async function qw(e,t){if(Bw(e)!==".gitignore")return Lr(e,t.content,t.executable,t.mode);let r=await ie.readFile(e,"utf8").catch(()=>null);if(r===null)return Lr(e,t.content,t.executable,t.mode);let n=oh(r);return n===null?"skipped":(await ie.writeFile(e,n,"utf8"),"merged")}function cu(e){if(e!==void 0){if(e==="junit"||e==="json")return e;v(`unknown --reporter '${e}' (expected 'junit' or 'json').`)}}function Yi(e){process.exit(e)}function dI(e){return{name:"turbobase ext test",cases:e.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 uI(e,t){let r=t.warnings.length===0?[{name:`${e} (${t.kind})`,status:"passed"}]:t.warnings.map(n=>({name:`${e}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${e}`,cases:r}}function pI(e){let t=[];if(e.error)return t.push({name:`replay ${e.fixtureName}`,status:"failed",type:"error",detail:e.error}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t};for(let r of e.guards)t.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 e.whenPassed&&e.applyBranch&&t.push({name:`apply-branch: ${e.applyBranch}`,status:"passed",detail:`${e.masterAction??""} (${e.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t}}function zw(e){return`${(Math.ceil(e/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function fu({includeInternal:e=!0}={}){let t=new oI;t.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.48.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),t.addHelpText("beforeAll",d=>d.command.parent?"":`${Ea()}
|
|
4351
|
-
`),t.hook("preAction",(
|
|
4352
|
-
${
|
|
4353
|
-
`).length} lines).`)}),
|
|
4367
|
+
`)}`,"Yes \u2014 delete them","permanent: the rows and their text are removed. Prior releases keep their own copy.",t))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(", ")}`)),W(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&&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 cm}from"node:fs";import{join as Hk,relative as Vk,resolve as Kk,sep as Wk}from"node:path";var Gk=new Set(["node_modules","dist","build","coverage",".git",".claude",".turbobase",".next",".svelte-kit",".vercel",".cache"]),Jk=new Set([".mcp.json",".env"]);function Yk(e){return Jk.has(e)||e.startsWith(".env.")&&e!==".env.example"}function Xk(e){return Buffer.compare(Buffer.from(e.toString("utf8"),"utf8"),e)===0}function Zk(e){return e.includes(0)}async function Ja(e){let t=Kk(e),r={},n=[],o=[],s=[];async function i(a){let l=await cm.readdir(a,{withFileTypes:!0});for(let u of l){let p=Hk(a,u.name);if(Gk.has(u.name))continue;if(u.isDirectory()){await i(p);continue}if(!u.isFile())continue;let g=Vk(t,p).split(Wk).join("/");if(Yk(u.name)){o.push(g);continue}let x=await cm.readFile(p);if(!Xk(x)){n.push(g);continue}Zk(x)&&s.push(g),r[g]=x.toString("utf8")}}return await i(t),{files:r,skipped:n,secrets:o,unstorable:s}}import{randomBytes as Qk}from"node:crypto";var ex="/_tb/app-assets",tx=16,rx=/^[0-9a-f]{32}$/;function dm(){return Qk(tx).toString("hex")}function nx(e){return rx.test(e)}function um(e){if(!nx(e))throw new Error(`not a build id: ${e}`);return`${ex}/${e}/`}var pm=7;Xa();var Za=50*1024*1024;import Ss from"node:fs/promises";import Mn from"node:path";var Qa={esbuild:"0.28.1","isolated-vm":"6.1.2"},el="@turbobase/isolated-vm-prebuilds";function tl(e,t){return`${e}-${t}`}function rl(e=process.versions){return`abi${e.modules}`}var hm=["darwin-x64","win32-arm64"];async function mm(e){let t=e.platform??process.platform,r=e.arch??process.arch,n=tl(t,r),o=Mn.join(e.home,"node_modules"),s=Mn.join(o,...el.split("/"),"prebuilds",n),i=Mn.join(o,"isolated-vm","prebuilds",n),a;try{a=await Ss.readdir(s)}catch{return[]}let l=[];await Ss.mkdir(i,{recursive:!0});for(let u of a){if(!u.endsWith(".node"))continue;let p=Mn.join(i,u);try{await Ss.copyFile(Mn.join(s,u),p,Ss.constants?.COPYFILE_EXCL??1),l.push(u)}catch{}}return l}import{homedir as ox}from"node:os";import{join as fm}from"node:path";import{promises as nl}from"node:fs";function ym(){let e=process.env.TURBOBASE_HOME??fm(ox(),".turbobase");return{dir:e,file:fm(e,"sandboxes.json")}}var sx={s:1e3,m:6e4,h:36e5,d:864e5};function ix(e){let t=/^\s*(\d+)\s*([smhd])\s*$/.exec(e);if(!t)throw new Error(`invalid --ttl '${e}': expected <number><unit> where unit is s|m|h|d (e.g. 72h, 30m, 7d).`);let r=Number(t[1]);if(!Number.isFinite(r)||r<=0)throw new Error(`invalid --ttl '${e}': duration must be a positive integer.`);return r*sx[t[2]]}function ax(e,t=Date.now()){return new Date(t+ix(e)).toISOString()}function lx(e,t=Date.now()){let r=Date.parse(e);return Number.isNaN(r)?!0:r<=t}function cx(e){let t=/^\s*(\d+(?:\.\d+)?)\s*%?\s*$/.exec(e);if(!t)throw new Error(`invalid --sample '${e}': expected a percent like 2% (or a bare number).`);let r=Number(t[1]);if(!Number.isFinite(r)||r<0||r>100)throw new Error(`invalid --sample '${e}': percent must be between 0 and 100.`);return r/100}function dx(e,t){if(t>=1)return[...e];if(t<=0||e.length===0)return[];let r=Math.max(1,Math.round(1/t)),n=[];for(let o=0;o<e.length;o+=r)n.push(e[o]);return n}var ux="[REDACTED]",qn=class extends Error{constructor(t){super(t),this.name="SandboxDataCopyUnavailableError"}},ol=class extends Error{table;column;constructor(t,r,n){super(`Refusing to copy ${t}.${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=t,this.column=r}};function px(e,t,r){let n={};for(let[o,s]of Object.entries(t)){let i=r[o];if(i===void 0)throw new ol(e,o,"column has no PII classification (unknown = unsafe)");i==="pii"?n[o]=s==null?s:ux:n[o]=s}return n}function hx(e,t,r){return t.map(n=>px(e,n,r))}var gm=new Set(["localhost","127.0.0.1","::1","0.0.0.0"]),mx=["oraclecloud.com","us-ashburn-1","amazonaws.com","rds.","supabase.co","turbobase.app","turbobase.io"];function fx(e){let t=e.trim();try{let o=new URL(t);if(o.hostname)return o.hostname.toLowerCase()}catch{}let r=t.replace(/^[a-z]+:\/\//i,""),n=(r.split("/")[0]??r).split("@").pop()??r;return(n.split(":")[0]??n).toLowerCase()}function sl(e){if(!e||!e.trim())throw new Error("local-only guard: empty database target \u2014 refusing to proceed.");let t=e.toLowerCase();for(let n of mx)if(t.includes(n))throw new Error(`local-only guard: target '${e}' looks like a cloud/prod context (matched '${n}'). \`turbobase sandbox create\` is LOCAL-ONLY and will never touch a cloud database.`);let r=fx(e);if(!gm.has(r))throw new Error(`local-only guard: target host '${r}' is not a recognised local Postgres (${[...gm].join(", ")}). \`turbobase sandbox create\` is LOCAL-ONLY.`)}function gx(e,t=yx){return`sbx-${e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,24)||"tenant"}-${t()}`}function yx(){return Math.floor(Math.random()*16777215).toString(16).padStart(6,"0")}function bx(e){return`turbobase_${e.replace(/[^a-z0-9]+/gi,"_").toLowerCase()}`}function wx(e,t){return`${(t??process.env.TURBOBASE_SANDBOX_BASE_URL??"http://localhost:5173").replace(/\/+$/,"")}/?sandbox=${encodeURIComponent(e)}`}async function il(){let{file:e}=ym();try{let t=await nl.readFile(e,"utf8"),r=JSON.parse(t);return Array.isArray(r)?r:[]}catch(t){if(t.code==="ENOENT")return[];throw t}}async function bm(e){let{dir:t,file:r}=ym();await nl.mkdir(t,{recursive:!0}),await nl.writeFile(r,`${JSON.stringify(e,null,2)}
|
|
4368
|
+
`,{mode:384})}async function vx(e){let t=await il();t.push(e),await bm(t)}async function wm(e){let t=await il(),r=t.findIndex(o=>o.name===e);if(r===-1)return null;let[n]=t.splice(r,1);return await bm(t),n??null}async function ks(){return il()}function al(e,t=Date.now()){let r=[],n=[];for(let o of e)lx(o.expiresAt,t)?n.push(o):r.push(o);return{active:r,expired:n}}async function vm(e,t){sl(e.target());let r=e.dataCopyUnavailable?.();if(r)throw new qn(r);let n=cx(t.sample),o=t.now??Date.now(),s=(t.nameGen??(u=>gx(u)))(t.fromTenant),i=bx(s);await e.createDatabase(i),await e.replayMigrations(i);let a=await e.readSourceTables(t.fromTenant);for(let u of a){let p=dx(u.rows,n),g=hx(u.table,p,u.classification);g.length>0&&await e.copyRows(i,u.table,g)}let l={name:s,fromTenant:t.fromTenant,database:i,createdAt:new Date(o).toISOString(),expiresAt:ax(t.ttl,o),sampleFraction:n,url:wx(s,t.baseUrl)};return await vx(l),l}async function _m(e,t){sl(e.target());let n=(await ks()).find(o=>o.name===t);return n?(await e.dropDatabase(n.database),await wm(t),n):null}async function ll(e,t=Date.now()){sl(e.target());let r=await ks(),{expired:n}=al(r,t),o=[];for(let s of n){try{await e.dropDatabase(s.database)}catch{continue}await wm(s.name),o.push(s)}return o}var zn={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"}},nj=Object.keys(zn).filter(e=>zn[e].mintable);var ij=zn.pat.prefix,_x=Object.entries(zn).map(([e,t])=>[t.prefix,e]),Sx=/^[A-Za-z0-9_-]{20,}$/;function kx(e){if(typeof e!="string")return null;for(let[t,r]of _x)if(e.startsWith(t)&&Sx.test(e.slice(t.length)))return r;return null}function Sm(e){return kx(e)==="pat"}$n();var xx=8e3,Tx={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 Rx(e){return Tx[e]??`the instance rejected this token (${e}) \u2014 run \`turbobase auth login\` to store a fresh PAT`}async function $x(e,t,r=fetch){let n;try{n=await r(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,Accept:"application/json"},signal:AbortSignal.timeout(xx)})}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 km(e){return e.state==="accepted"?Oe()?m.green("accepted"):"accepted":e.state==="rejected"?Oe()?m.red(`rejected \xB7 ${e.reason}`):`rejected \xB7 ${e.reason}`:Oe()?m.yellow("unreachable"):"unreachable"}async function xm(e={},t=fetch){let r=await Mt(),{file:n}=Go();if(r.length===0){b("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 yt(),s=await Promise.all(r.map(async i=>({baseUrl:i.baseUrl,active:!!o&&i.baseUrl===o.baseUrl,updatedAt:i.updatedAt,check:e.probe===!1?{state:"accepted"}:await $x(i.baseUrl,i.token,t)})));if(e.probe===!1)for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} (updated ${i.updatedAt})`);else if(Oe())b(lt(s.map(i=>[i.active?m.green("*"):" ",m.bold(i.baseUrl),km(i.check),m.dim(i.updatedAt)]),{head:["","instance","token","updated"]}));else for(let i of s)b(`${i.active?"* ":" "}${i.baseUrl} ${km(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}: ${Rx(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 iI(e){let t=await Mt();t.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(e,t.map(r=>({value:r.baseUrl,label:r.baseUrl,description:`updated ${r.updatedAt}`})))}catch{v("cancelled.")}}async function aI(e,t){let r;try{r=await fetch(`${e}/v1/catalog/records`,{method:"GET",headers:{Authorization:`Bearer ${t}`,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 lI(e){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: ${e}/admin/settings \u2192 Telemetry \u2192 "Share learnings and platform feedback".`),O("")}async function cI(e,t,r){let n=await Yu({baseUrl:e,token:t}),o=(await Mt()).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).`:".")),lI(n.baseUrl),!r)return;let s=await aI(n.baseUrl,t);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 dI(e){let t=await Sa(await Cn(e),Wt(e)),r=Ua(t);return r||v(`${e}: ${qa(t)}`),{...r,sourceCode:t}}async function Lr(e,t,r,n){try{return await ie.access(e),"skipped"}catch{}return await ie.mkdir(Wt(e),{recursive:!0}),await ie.writeFile(e,t,{mode:n??(r?493:420)}),n!==void 0&&await ie.chmod(e,n),"wrote"}async function zw(e,t){if(Fw(e)!==".gitignore")return Lr(e,t.content,t.executable,t.mode);let r=await ie.readFile(e,"utf8").catch(()=>null);if(r===null)return Lr(e,t.content,t.executable,t.mode);let n=sh(r);return n===null?"skipped":(await ie.writeFile(e,n,"utf8"),"merged")}function du(e){if(e!==void 0){if(e==="junit"||e==="json")return e;v(`unknown --reporter '${e}' (expected 'junit' or 'json').`)}}function Yi(e){process.exit(e)}function uI(e){return{name:"turbobase ext test",cases:e.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 pI(e,t){let r=t.warnings.length===0?[{name:`${e} (${t.kind})`,status:"passed"}]:t.warnings.map(n=>({name:`${e}: ${n.rule}`,status:"failed",type:n.rule,detail:`${n.message} \u2192 fix: ${n.fix}`}));return{name:`turbobase ext lint ${e}`,cases:r}}function hI(e){let t=[];if(e.error)return t.push({name:`replay ${e.fixtureName}`,status:"failed",type:"error",detail:e.error}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t};for(let r of e.guards)t.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 e.whenPassed&&e.applyBranch&&t.push({name:`apply-branch: ${e.applyBranch}`,status:"passed",detail:`${e.masterAction??""} (${e.wouldWriteBindings.length} binding(s) would be written)`.trim()}),{name:`turbobase ext replay ${e.fixtureName}`,cases:t}}function Bw(e){return`${(Math.ceil(e/1048576*10)/10).toFixed(1).replace(/\.0$/,"")} MiB`}function gu({includeInternal:e=!0}={}){let t=new sI;t.name("turbobase").description("Build apps, author extensions, and drive your Turbobase instance.").version("1.49.0").option("--no-color","Disable ANSI colour + animations (also honoured via NO_COLOR / non-TTY)."),t.addHelpText("beforeAll",c=>c.command.parent?"":`${Pa()}
|
|
4369
|
+
`),t.hook("preAction",(c,h)=>{vh(t.opts(),h.opts())});let r=t.command("auth").description("Sign in to an instance and manage stored credentials."),n=t.command("project").description("Set up the local project and the files an agent session reads."),o=t.command("ext").description("Author, test, ship, and observe extensions \u2014 hooks and conduits."),s=t.command("kb").description("Write into the instance's knowledge base."),i=t.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 c=>{let h=st(c.baseUrl);c.token||v(`auth login needs --token. Mint a PAT in your Turbobase app (Settings \u203A Access tokens), then:
|
|
4370
|
+
${Vr} auth login --base-url ${h} --token tb_pat_\u2026`),Sm(c.token)||v("--token does not look like a Turbobase PAT (tb_pat_\u2026)."),await cI(h,c.token,c.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 c=>xm({probe:c.probe})),r.command("use [base-url]").description("Make an already-stored instance the active default (omit the arg to pick interactively).").action(async c=>{let h=c??await iI("Pick the active instance:"),w=await Jo(h);if(!w){let R=await Mt();v(`no stored sign-in for ${st(h)}.`+(R.length?` Stored: ${R.map(S=>S.baseUrl).join(", ")}.`:"")+` Run \`turbobase auth login --base-url ${st(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 c=>{if(c.all){let R=await Mt();for(let S of R)await ga(S.baseUrl);b(`removed ${R.length} stored sign-in${R.length===1?"":"s"}.`);return}let h=await ga(c.baseUrl);h||v(c.baseUrl?`no stored sign-in for ${st(c.baseUrl)}.`:"nothing to sign out of (or ambiguous \u2014 pass --base-url / --all).");let w=await yt();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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R;try{R=await br({baseUrl:h,token:w,recordsOnly:c.recordsOnly})}catch(f){let _=f instanceof Error?f.message:String(f);if(!c.recordsOnly&&/openapi\.json failed \(401/.test(_)){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{R=await br({baseUrl:h,token:w,recordsOnly:!0})}catch(E){v(`types generation failed: ${E instanceof Error?E.message:String(E)}`)}}else v(`types generation failed: ${_}`)}let S=ne(process.cwd(),c.out);await ie.writeFile(S,R,"utf8"),b(`wrote ${S} (${R.split(`
|
|
4371
|
+
`).length} lines).`)}),kh(n),n.command("skills").description("Rewrite the platform's own skills in .claude/skills from this CLI (never the project's own).").option("--dir <path>","Project directory",".").action(c=>{let h=Th(ne(process.cwd(),c.dir));for(let w of h)b(Rh(w))}),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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new URLSearchParams;c.records&&R.set("records",c.records),c.query&&R.set("query",c.query);let S=R.toString(),f=await fetch(`${h}/v1/catalog/grounding${S?`?${S}`:""}`,{headers:{Authorization:`Bearer ${w}`,Accept:"application/json"}});f.ok||v(`grounding fetch failed: GET /v1/catalog/grounding \u2192 ${f.status}`);let E=((await f.json()).markdown??"").trim(),A=ne(process.cwd(),c.out),I=c.records?` records=${c.records}`:"",N=`<!-- GENERATED by \`turbobase project grounding\` against ${h}${I} \u2014 do not edit; re-run to refresh. -->
|
|
4354
4372
|
|
|
4355
4373
|
`;await ie.writeFile(A,N+(E?`${E}
|
|
4356
4374
|
`:`(no grounding available yet)
|
|
4357
|
-
`),"utf8"),b(`wrote ${A}${E?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${Dn.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=>Ph(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=>Ch(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)=>Ih(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=>Nh(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)=>Lh(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)=>jh(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?zh({baseUrl:d.baseUrl,from:d.from,app:d.app,dryRun:d.dryRun,publish:d.publish,yes:d.yes}):Dh(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=>rm(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)=>nm(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)=>om(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=>im(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)=>sm(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)=>am(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=Ct("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=ne(process.cwd(),h.relativePath);await Lr(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=Ct("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=ne(process.cwd(),h.relativePath);await Lr(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=Ct("process",{recordType:d.record,then:d.then,onFailure:d.onFailure,id:d.id})}catch(_){v(_ instanceof Error?_.message:String(_))}let w=ne(process.cwd(),h.relativePath);await Lr(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=cu(h.reporter),T=await Cn(ne(process.cwd(),d)),_=ne(process.cwd(),h.samples),f=await An(_);f.length===0&&!w&&b(`no samples found under ${_} \u2014 add JSON fixtures to dry-run against.`);let S;try{S=await ns(T,f.map(I=>I.fixture),{resolveDir:Wt(ne(process.cwd(),d))})}catch(I){v(`bundle failed: ${I instanceof Error?I.message:String(I)}`)}if(w){let I=dI(S);b(ss(I,w)),Yi(I.cases.some(N=>N.status==="failed")?1:0)}let E=0;for(let I of S){let N=I.pass?m.green("PASS"):m.red("FAIL");I.pass||(E+=1);let M=I.error?` (error: ${I.error})`:I.observed!==I.expected?` (expected ${I.expected}, observed ${I.observed})`:I.rejection?` (rejected: ${I.rejection.code??"rejected"})`:"";b(` ${N} ${I.name}${M}`)}let A=`${S.length-E}/${S.length} sample(s) passed.`;b(`
|
|
4358
|
-
${E===0?m.green(A):m.yellow(A)}`),Yi(E>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(d,h)=>{if(h.to){let S=await du(),{baseUrl:E,token:A}=await B(h.baseUrl),I=new z({baseUrl:E,token:A});try{let N=await X(`applying bundle to ${h.to}`,()=>I.configApply(S,{prune:h.prune}));b(`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?Ua(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 cI(ne(process.cwd(),d)),f=new z({baseUrl:w,token:T});try{let S=await X(`deploying ${Bw(d)}`,()=>f.deploy(_)),E=hh(S.outcome);Oe()?b(Zt("Deployed",[`${m.bold(S.id)} ${Fr(S.status)} ${m.dim(E)}`])):b(`deployed ${S.id} \u2192 status=${S.status} (${E}).`)}catch(S){S instanceof Y&&S.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin.");let E=S instanceof Y?Ua(S.body,d):null;E&&v(E),v(`deploy failed: ${S instanceof Error?S.message:String(S)}`)}});let l=t.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 _=ne(process.cwd(),h??".");await ie.mkdir(_,{recursive:!0});let f=w.proposal??await $(_),{baseUrl:S,token:E}=await B(w.baseUrl),A=new z({baseUrl:S,token:E}),I=!1;try{I=(await A.appsList()).some(ue=>ue.slug===d||ue.id===d)}catch(ue){W(ue,"extensions:deploy","deploy"),v(`could not reach ${S}: ${ue instanceof Error?ue.message:String(ue)}`)}if(!I){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,E,{slug:d},{tolerateExisting:!0}));ue.existed||b(`created ${ue.slug??d}.`)}let N;if(w.replace)if(typeof w.replace=="string")N=w.replace;else{let{previews:ue}=await Re(S,E,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)b(` ${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 Re(S,E,d),At=Ie.filter(Qi=>Qi.label===ue);At.length>0?(N=At[0].previewId,At.length>1&&O(`${At.length} open previews carry the label "${ue}"; replacing the newest (${N}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${ue}" \u2014 opening one.`),M=ue}let L=ue=>ie.stat(nt(_,ue)).then(()=>!0).catch(()=>!1),J=d,ge=_,Q=w.build!==!1,be=!1;if(Q&&!await L("package.json"))if(await L("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 ue=await X(`pulling ${d}`,()=>x(S,E,d));J=ue.slug??d,await y(_,ue.files,!0),be=!0,b(`pulled generated source (rev ${ue.rev}).`)}let Ce;if(Q){let ue=cm();if(Ce={buildId:ue,assetBase:dm(ue)},w.install!==!1&&!await L("node_modules")){b("installing dependencies\u2026");try{await j(["install"],_)}catch(Ie){v(`npm install failed: ${Ie instanceof Error?Ie.message:String(Ie)}`)}}b("building\u2026");try{await j(["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.`),ge=nt(_,"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,E,J,ge,w.entry,f,Ce,T?{label:w.label??M,replacePreviewId:N}:void 0),Mo=null;if(w.source!==!1&&!be&&await L("package.json")&&(Mo=await C(S,E,J,_,f)),T){let ue=$e.previewUrl??"(no url returned)",Ie=$e.expiresAt?new Date($e.expiresAt).toLocaleDateString():`${um} days`,At=$e.replacedVersion==null?null:`replaced v${$e.replacedVersion} \u2014 same URL`;if(Oe())b(Zt(At?"Preview replaced":"Preview deployed",[`${m.bold(J)} ${m.green(`v${$e.version??"?"}`)} ${m.dim("not live")}`,`${m.bold(ue)}`,...At?[m.dim(At)]:[],m.dim(`expires ${Ie}`)]));else{let Qi=At?`; ${At}`:"";b(`preview ${J} v${$e.version??"?"} \u2192 ${ue} (expires ${Ie}; /a/${J} unchanged${Qi}).`)}Gt($e),b(`next: turbobase apps promote ${J} ${$e.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${$e.previewId??"<preview-id>"}`);return}Oe()?b(Zt("Deployed",[`${m.bold(J)} ${m.green(`v${$e.version??"?"}`)} ${m.dim($e.url??`/a/${J}`)}`])):b(`deployed ${J} \u2192 v${$e.version??"?"} (${$e.url??`/a/${J}`}).`),Gt($e),Pt($e),await Jt($e,_,Mo)}),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 mI(d??".");f||v(`no public/turbobase.json under ${ne(process.cwd(),d??".")}.`);let S=Array.isArray(f.manifest.tables)?f.manifest.tables:[],E=Array.isArray(f.manifest.writes)?f.manifest.writes:[],A=Array.isArray(f.manifest.roles)?f.manifest.roles:null,I=A??[],N=Array.isArray(f.manifest.labels)?f.manifest.labels:[],M=A!==null&&A.length===0;if(S.length===0&&E.length===0&&I.length===0&&N.length===0){if(!M)return b(`${f.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(_===null){for(let Q of Aa({app:null,roles:A}))b(Q.text);return}}let{baseUrl:L,token:J}=await B(h.baseUrl),ge=new z({baseUrl:L,token:J});if(S.length>0){let Q;try{Q=await X("planning tables",()=>ge.tablesPlan({claimedBy:h.as,tables:S}))}catch(be){W(be,"extensions:deploy","plan tables"),Do(be)}b(`claiming as ${m.bold(Q.claimedBy)}`);for(let be of Q.tables)jo(be,{showClaimants:!0})}if(E.length>0||I.length>0||N.length>0||M&&_!==null){let Q;try{Q=await X("checking declared writes, roles and labels",()=>ge.appsPlan({writes:E,...A!==null?{roles:A}:{},labels:N,..._!==null?{app:_}:{}}))}catch(be){W(be,"extensions:deploy","plan writes"),v(`plan writes failed: ${be instanceof Error?be.message:String(be)}`)}Q.roles&&Et("plan",Q.roles.verdicts,Q.roles.retired);for(let be of Aa({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(Ce=>Ce.name.length));for(let Ce of Q.labels.verdicts){let $e=Ce.name.padEnd(be);if(Ce.action==="create")b(` create ${$e} ${m.dim(Ce.color)}`);else{let Mo=Ce.declaredColor?`${Ce.color} \u2014 declared ${Ce.declaredColor}, the instance's colour is kept`:Ce.color;b(` ${m.dim("ok")} ${$e} ${m.dim(Mo)}`)}}b(m.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&b("");for(let be of Q.verdicts){let Ce=`${be.source} ${be.recordType}.${be.op}`;be.allowed?be.heldForApproval?b(`${m.dim("HELD")} ${Ce} \u2014 allowed, but each write waits for operator approval.`):b(`${m.dim("ok")} ${Ce}`):O(`${m.bold("DENIED")} ${Ce}${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 B(w.baseUrl),f=await X(`promoting ${h}`,()=>G(T,_,d,"promote",{previewId:h}));Oe()?b(Zt("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 S=Zp(f);Et("applied",S.verdicts,S.retired),Pt({labels:f.labels?{applied:!0,verdicts:f.labels}:null}),await Jt(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 Re(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 S=f.label?` ${f.label}`:"",E=f.expiresAt?new Date(f.expiresAt).toLocaleDateString():"?";b(`v${f.version} ${f.previewId}${S} ${f.url} (expires ${E})`)}}),u.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h,w)=>{let{baseUrl:T,token:_}=await B(w.baseUrl);await X(`discarding ${h}`,()=>G(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 B(h.baseUrl),_=await X(`creating ${d}`,()=>g(w,T,{slug:d,name:h.name,description:h.description})),f=_.slug??d;Oe()?b(Zt("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=Yo(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 x(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=ne(d),_=0;for(let[f,S]of Object.entries(h)){let E=ne(T,f);E!==T&&!E.startsWith(T+hu)&&v(`refusing to write outside ${T}: ${f}`),w||await ie.stat(E).then(()=>!0).catch(()=>!1)&&v(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ie.mkdir(Wt(E),{recursive:!0}),await ie.writeFile(E,S,"utf8"),_+=1}return _}function k(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=ne(d),_=async(S,E)=>{let A=ne(T,S);A!==T&&!A.startsWith(T+hu)&&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(Wt(A),{recursive:!0}),await ie.writeFile(A,E)},f=`# ${h.title||"App change request"}
|
|
4375
|
+
`),"utf8"),b(`wrote ${A}${E?"":" (instance returned no grounding \u2014 connect a source first?)"}`)}),s.command("push").description("Write pending app-dev findings into the knowledge base, grouped one page at a time. Shows the plan and asks first; pages land unpublished.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--app <slug-or-id>","Only findings from this app.").option("--section <section>",`Only this section (${Dn.join(" | ")}).`).option("--limit <n>","Cap how many findings to act on.",c=>Number.parseInt(c,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(c=>Ah(c)),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(c=>Ih(c)),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((c,h)=>Oh(c,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((c,h)=>Nh(c,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(c=>Lh(c)),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((c,h)=>jh(c,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((c,h)=>Dh(c,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.",c=>Number.parseInt(c,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(c=>(c.publish&&!c.from&&v("--publish applies to --from only: findings pushed from `## Agent rules` are published with `turbobase skills publish <slug>`."),c.from?Bh({baseUrl:c.baseUrl,from:c.from,app:c.app,dryRun:c.dryRun,publish:c.publish,yes:c.yes}):Uh(c))),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(c=>nm(c)),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((c,h)=>om(c,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((c,h)=>sm(c,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(c=>am(c)),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((c,h)=>im(c,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((c,h)=>lm(c,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 c=>{let h;try{h=Ct("hook",{recordType:c.record,event:c.event,template:c.template,field:c.field,regex:c.regex,source:c.source,id:c.id})}catch(S){v(S instanceof Error?S.message:String(S))}let w=ne(process.cwd(),h.relativePath);await Lr(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 c=>{let h;try{h=Ct("conduit",{recordType:c.record,source:c.source,to:c.to,toRecordType:c.toRecord,event:c.event,id:c.id})}catch(S){v(S instanceof Error?S.message:String(S))}let w=ne(process.cwd(),h.relativePath);await Lr(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 c=>{let h;try{h=Ct("process",{recordType:c.record,then:c.then,onFailure:c.onFailure,id:c.id})}catch(S){v(S instanceof Error?S.message:String(S))}let w=ne(process.cwd(),h.relativePath);await Lr(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(c,h)=>{let w=du(h.reporter),R=await Cn(ne(process.cwd(),c)),S=ne(process.cwd(),h.samples),f=await An(S);f.length===0&&!w&&b(`no samples found under ${S} \u2014 add JSON fixtures to dry-run against.`);let _;try{_=await ns(R,f.map(I=>I.fixture),{resolveDir:Wt(ne(process.cwd(),c))})}catch(I){v(`bundle failed: ${I instanceof Error?I.message:String(I)}`)}if(w){let I=uI(_);b(ss(I,w)),Yi(I.cases.some(N=>N.status==="failed")?1:0)}let E=0;for(let I of _){let N=I.pass?m.green("PASS"):m.red("FAIL");I.pass||(E+=1);let M=I.error?` (error: ${I.error})`:I.observed!==I.expected?` (expected ${I.expected}, observed ${I.observed})`:I.rejection?` (rejected: ${I.rejection.code??"rejected"})`:"";b(` ${N} ${I.name}${M}`)}let A=`${_.length-E}/${_.length} sample(s) passed.`;b(`
|
|
4376
|
+
${E===0?m.green(A):m.yellow(A)}`),Yi(E>0?1:0)}),o.command("deploy").argument("[file]","The extension file to deploy (single-file mode; omit with --to).").description("Deploy one extension (POST /v1/extensions) or the whole bundle (--to \u2192 /v1/config/apply).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--to <env>","Deploy the WHOLE project config (hooks/, conduits/, turbobase/) to this env (sandbox|prod).").option("--prune","Also REMOVE anything on the instance this project no longer declares. Off by default \u2014 see `ext plan` for what it would take.").action(async(c,h)=>{if(h.to){let _=await uu(),{baseUrl:E,token:A}=await F(h.baseUrl),I=new z({baseUrl:E,token:A});try{let N=await X(`applying bundle to ${h.to}`,()=>I.configApply(_,{prune:h.prune}));b(`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?Ma(N.body):null;M&&v(`bundle apply failed \u2014 ${M}`),v(`bundle apply failed: ${N instanceof Error?N.message:String(N)}`)}return}c||v("deploy needs a <file> (single-file mode) or --to <env> (whole-bundle mode).");let{baseUrl:w,token:R}=await F(h.baseUrl),S=await dI(ne(process.cwd(),c)),f=new z({baseUrl:w,token:R});try{let _=await X(`deploying ${Fw(c)}`,()=>f.deploy(S)),E=mh(_.outcome);Oe()?b(Zt("Deployed",[`${m.bold(_.id)} ${Br(_.status)} ${m.dim(E)}`])):b(`deployed ${_.id} \u2192 status=${_.status} (${E}).`)}catch(_){_ instanceof Y&&_.status===403&&v("deploy forbidden (403) \u2014 the stored PAT is not for an admin.");let E=_ instanceof Y?Ma(_.body,c):null;E&&v(E),v(`deploy failed: ${_ instanceof Error?_.message:String(_)}`)}});let l=t.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(c,h,w)=>{let R=!!(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 S=ne(process.cwd(),h??".");await ie.mkdir(S,{recursive:!0});let f=w.proposal??await $(S),{baseUrl:_,token:E}=await F(w.baseUrl),A=new z({baseUrl:_,token:E}),I=!1;try{I=(await A.appsList()).some(ue=>ue.slug===c||ue.id===c)}catch(ue){W(ue,"extensions:deploy","deploy"),v(`could not reach ${_}: ${ue instanceof Error?ue.message:String(ue)}`)}if(!I){w.create||v(`no app "${c}" on ${_} \u2014 create it with \`turbobase apps create ${c}\`, or pass --create.`);let ue=await X(`creating app ${c}`,()=>g(_,E,{slug:c},{tolerateExisting:!0}));ue.existed||b(`created ${ue.slug??c}.`)}let N;if(w.replace)if(typeof w.replace=="string")N=w.replace;else{let{previews:ue}=await Re(_,E,c);if(ue.length===0&&v(`no open preview on ${c} 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)b(` ${Ie.previewId} v${Ie.version}${Ie.label?` ${Ie.label}`:""} ${Ie.url}`);v(`${c} 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 Re(_,E,c),At=Ie.filter(ea=>ea.label===ue);At.length>0?(N=At[0].previewId,At.length>1&&O(`${At.length} open previews carry the label "${ue}"; replacing the newest (${N}). Close the others with \`turbobase apps preview discard\`.`)):b(`no open preview labelled "${ue}" \u2014 opening one.`),M=ue}let L=ue=>ie.stat(nt(S,ue)).then(()=>!0).catch(()=>!1),J=c,ge=S,Q=w.build!==!1,be=!1;if(Q&&!await L("package.json"))if(await L("index.html"))b("no package.json but index.html present \u2014 deploying as a prebuilt bundle."),Q=!1;else if(w.pull===!1)v(`${S} 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 ${c}`,()=>x(_,E,c));J=ue.slug??c,await y(S,ue.files,!0),be=!0,b(`pulled generated source (rev ${ue.rev}).`)}let Ce;if(Q){let ue=dm();if(Ce={buildId:ue,assetBase:um(ue)},w.install!==!1&&!await L("node_modules")){b("installing dependencies\u2026");try{await j(["install"],S)}catch(Ie){v(`npm install failed: ${Ie instanceof Error?Ie.message:String(Ie)}`)}}b("building\u2026");try{await j(["run","build"],S,{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 ${S} \u2014 check the app's build script.`),ge=nt(S,"dist")}R&&!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(_,E,J,ge,w.entry,f,Ce,R?{label:w.label??M,replacePreviewId:N}:void 0),Mo=null;if(w.source!==!1&&!be&&await L("package.json")&&(Mo=await C(_,E,J,S,f)),R){let ue=$e.previewUrl??"(no url returned)",Ie=$e.expiresAt?new Date($e.expiresAt).toLocaleDateString():`${pm} days`,At=$e.replacedVersion==null?null:`replaced v${$e.replacedVersion} \u2014 same URL`;if(Oe())b(Zt(At?"Preview replaced":"Preview deployed",[`${m.bold(J)} ${m.green(`v${$e.version??"?"}`)} ${m.dim("not live")}`,`${m.bold(ue)}`,...At?[m.dim(At)]:[],m.dim(`expires ${Ie}`)]));else{let ea=At?`; ${At}`:"";b(`preview ${J} v${$e.version??"?"} \u2192 ${ue} (expires ${Ie}; /a/${J} unchanged${ea}).`)}Gt($e),b(`next: turbobase apps promote ${J} ${$e.previewId??"<preview-id>"} # make it live`),b(` turbobase apps preview discard ${$e.previewId??"<preview-id>"}`);return}Oe()?b(Zt("Deployed",[`${m.bold(J)} ${m.green(`v${$e.version??"?"}`)} ${m.dim($e.url??`/a/${J}`)}`])):b(`deployed ${J} \u2192 v${$e.version??"?"} (${$e.url??`/a/${J}`}).`),Gt($e),Pt($e),await Jt($e,S,Mo)}),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(c,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 R=h.app?.trim()??"";R&&w&&R!==w&&v(`--app ${R} and --as app:${w} name two different apps \u2014 pass one slug.`);let S=R||w||null,f=await fI(c??".");f||v(`no public/turbobase.json under ${ne(process.cwd(),c??".")}.`);let _=Array.isArray(f.manifest.tables)?f.manifest.tables:[],E=Array.isArray(f.manifest.writes)?f.manifest.writes:[],A=Array.isArray(f.manifest.roles)?f.manifest.roles:null,I=A??[],N=Array.isArray(f.manifest.labels)?f.manifest.labels:[],M=A!==null&&A.length===0;if(_.length===0&&E.length===0&&I.length===0&&N.length===0){if(!M)return b(`${f.manifestPath} declares no tables, writes, roles or labels \u2014 nothing to plan.`);if(S===null){for(let Q of Ca({app:null,roles:A}))b(Q.text);return}}let{baseUrl:L,token:J}=await F(h.baseUrl),ge=new z({baseUrl:L,token:J});if(_.length>0){let Q;try{Q=await X("planning tables",()=>ge.tablesPlan({claimedBy:h.as,tables:_}))}catch(be){W(be,"extensions:deploy","plan tables"),Do(be)}b(`claiming as ${m.bold(Q.claimedBy)}`);for(let be of Q.tables)jo(be,{showClaimants:!0})}if(E.length>0||I.length>0||N.length>0||M&&S!==null){let Q;try{Q=await X("checking declared writes, roles and labels",()=>ge.appsPlan({writes:E,...A!==null?{roles:A}:{},labels:N,...S!==null?{app:S}:{}}))}catch(be){W(be,"extensions:deploy","plan writes"),v(`plan writes failed: ${be instanceof Error?be.message:String(be)}`)}Q.roles&&Et("plan",Q.roles.verdicts,Q.roles.retired);for(let be of Ca({app:S,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(Ce=>Ce.name.length));for(let Ce of Q.labels.verdicts){let $e=Ce.name.padEnd(be);if(Ce.action==="create")b(` create ${$e} ${m.dim(Ce.color)}`);else{let Mo=Ce.declaredColor?`${Ce.color} \u2014 declared ${Ce.declaredColor}, the instance's colour is kept`:Ce.color;b(` ${m.dim("ok")} ${$e} ${m.dim(Mo)}`)}}b(m.dim(" labels are launcher navigation \u2014 a chip on the app card and a filter pill on /apps. They grant nothing."))}E.length>0&&b("");for(let be of Q.verdicts){let Ce=`${be.source} ${be.recordType}.${be.op}`;be.allowed?be.heldForApproval?b(`${m.dim("HELD")} ${Ce} \u2014 allowed, but each write waits for operator approval.`):b(`${m.dim("ok")} ${Ce}`):O(`${m.bold("DENIED")} ${Ce}${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(c,h,w)=>{let{baseUrl:R,token:S}=await F(w.baseUrl),f=await X(`promoting ${h}`,()=>G(R,S,c,"promote",{previewId:h}));Oe()?b(Zt("Promoted",[`${m.bold(c)} ${m.green(`v${f.version??"?"}`)} ${m.dim(f.url??`/a/${c}`)}`])):b(`promoted ${c} \u2192 v${f.version??"?"} is now live at ${f.url??`/a/${c}`}.`);let _=Qp(f);Et("applied",_.verdicts,_.retired),Pt({labels:f.labels?{applied:!0,verdicts:f.labels}:null}),await Jt(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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=await Re(w,R,c);if(h.json)return b(JSON.stringify(S.previews,null,2));if(S.previews.length===0){b(`no open previews for ${c}.`);return}for(let f of S.previews){let _=f.label?` ${f.label}`:"",E=f.expiresAt?new Date(f.expiresAt).toLocaleDateString():"?";b(`v${f.version} ${f.previewId}${_} ${f.url} (expires ${E})`)}}),u.command("discard").description("Close a preview. The URL stops resolving; the version stays in deploy history.").argument("<app>","App slug or id.").argument("<preview-id>","The preview to discard.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(c,h,w)=>{let{baseUrl:R,token:S}=await F(w.baseUrl);await X(`discarding ${h}`,()=>G(R,S,c,"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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=await X(`creating ${c}`,()=>g(w,R,{slug:c,name:h.name,description:h.description})),f=S.slug??c;Oe()?b(Zt("Created",[`${m.bold(f)} ${m.dim(S.url??`/a/${f}`)}`])):b(`created ${f} (${S.url??`/a/${f}`}).`),b(`next: turbobase apps push ${f} . # store the source`),b(` turbobase apps deploy ${f} # build + go live`)});let p=Yo(fetch);async function g(c,h,w,R={}){let S=`${c.replace(/\/+$/,"")}/v1/apps`,f;try{f=await p(S,{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(_){v(`create request failed: ${_ instanceof Error?_.message:String(_)}`)}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(R.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 x(c,h,w){let R=`${c.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/pull`,S;try{S=await p(R,{headers:{Authorization:`Bearer ${h}`}})}catch(f){v(`pull request failed: ${f instanceof Error?f.message:String(f)}`)}return S.status===401&&v("pull unauthorized (401) \u2014 re-run `turbobase auth login`."),S.status===403&&v("pull forbidden (403) \u2014 the PAT is not for an admin."),S.status===404&&v(`no generated source for "${w}" \u2014 generate it from its proposal first (Studio \u2192 Generate app source).`),S.ok||v(`pull failed: HTTP ${S.status} ${(await S.text().catch(()=>"")).slice(0,200)}`),await S.json()}async function y(c,h,w){let R=ne(c),S=0;for(let[f,_]of Object.entries(h)){let E=ne(R,f);E!==R&&!E.startsWith(R+mu)&&v(`refusing to write outside ${R}: ${f}`),w||await ie.stat(E).then(()=>!0).catch(()=>!1)&&v(`${E} already exists \u2014 pass --force to overwrite, or pull into an empty dir.`),await ie.mkdir(Wt(E),{recursive:!0}),await ie.writeFile(E,_,"utf8"),S+=1}return S}function k(c){let h=c.indexOf(","),w=c.startsWith("data:")?h>=0?c.slice(h+1):"":c;if(!w)return null;try{let R=Buffer.from(w,"base64");return R.length>0?new Uint8Array(R):null}catch{return null}}async function T(c,h,w){let R=ne(c),S=async(_,E)=>{let A=ne(R,_);A!==R&&!A.startsWith(R+mu)&&v(`refusing to write outside ${R}: ${_}`),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(Wt(A),{recursive:!0}),await ie.writeFile(A,E)},f=`# ${h.title||"App change request"}
|
|
4359
4377
|
|
|
4360
4378
|
> Widget proposal \`${h.proposalId}\` \u2014 build this change, then ship it with
|
|
4361
4379
|
> \`turbobase apps deploy ${h.appSlug}\`. The deploy stamps this proposal complete.
|
|
@@ -4365,37 +4383,37 @@ ${h.bodyMarkdown||"_No description provided._"}
|
|
|
4365
4383
|
## Screen context
|
|
4366
4384
|
|
|
4367
4385
|
`+(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.
|
|
4368
|
-
`);if(await
|
|
4369
|
-
`)}async function $(d){try{let h=await ie.readFile(nt(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(E){if(E instanceof Y){let A=E.body;if(E.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&W(E,"extensions:deploy","push app source"),E.status===404&&v(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let I=A?.path?` in ${A.path}`:"",N=A?.reason?` (${A.reason})`:"";v(`push rejected: ${A?.error??"bad request"}${N}${I}.`)}}v(`push failed: ${E instanceof Error?E.message:String(E)}`)}}async function C(d,h,w,T,_){let f;try{f=await Ga(T)}catch(M){return O(`source not recorded: could not read ${T} (${M instanceof Error?M.message:String(M)}).`),null}let{files:S,skipped:E,secrets:A,unstorable:I}=f,N=Object.keys(S).length;if(N===0)return O(`source not recorded: no source files found under ${T}.`),null;if(I.length>0){for(let M of I)O(`${M} contains a NUL byte (U+0000), which cannot be stored.`);return O(`source not recorded: ${I.length} ${I.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 E)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 b(`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 j(d,h,w){return new Promise((T,_)=>{let f=mu("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(()=>""),E=S.slice(0,300);try{let A=JSON.parse(S);E=A.message??A.error??E}catch{}v(`failed: HTTP ${f.status} ${E}`)}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 Re(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,E){let A;try{A=await X(`zipping ${T}`,()=>kp(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>Xa&&v(`${T} zips to ${zw(A.buffer.byteLength)} \u2014 over the ${zw(Xa)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let I={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};_&&(I["x-app-entry"]=_),f&&(I["x-proposal-id"]=f),S&&(I["x-app-build-id"]=S.buildId,I["x-app-asset-base"]=S.assetBase),E&&(I["x-app-channel"]="preview",E.label&&(I["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(I["x-app-preview-replace"]=E.replacePreviewId));let N=`${d.replace(/\/+$/,"")}/v1/apps/${encodeURIComponent(w)}/deploy`,M;try{M=await X(`deploying ${w} (${A.fileCount} file${A.fileCount===1?"":"s"})`,()=>p(N,{method:"POST",headers:I,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 ge=JSON.parse(L);J=ge.message??ge.error??J}catch{}v(`deploy failed: HTTP ${M.status} ${J}`)}return await M.json().catch(()=>({}))}function Et(d,h,w){for(let T of Xp({mode:d,verdicts:h,retired:w}))(T.stream==="err"?O:b)(T.text)}function Gt(d){let h=d.roles;h&&Et(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function Pt(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 S=_.declaredColor?`${_.color} \u2014 declared ${_.declaredColor}, the instance's colour is kept`:_.color;b(` added ${f} ${m.dim(S)}`)}}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 Jt(d,h,w){let T=Hp(d,{localDocsModifiedAt:await Lo(h),recordedSourceRev:w});T&&b(T.level==="warn"?m.yellow(T.message):m.dim(T.message))}async function Lo(d){if(!d)return null;let h=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let T=await ie.stat(nt(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:_}),I;try{I=await X(`fetching proposal ${w.proposal}`,()=>A.appPullContext(w.proposal))}catch(ge){W(ge,"extensions:deploy","pull proposal"),ge instanceof Y&&ge.status===404&&v(`no widget proposal "${w.proposal}" on ${T}.`),v(`could not fetch proposal ${w.proposal}: ${ge instanceof Error?ge.message:String(ge)}`)}let N=await X(`pulling ${I.appSlug}`,()=>x(T,_,I.appSlug)),M=h??d,L=ne(process.cwd(),M??I.appSlug);await ie.mkdir(L,{recursive:!0});let J=await y(L,N.files,!!w.force);await R(L,I,!!w.force),b(`pulled ${J} file${J===1?"":"s"} \u2192 ${L} (rev ${N.rev}), linked to proposal ${I.proposalId}.`),b(`next: cd ${Xi(process.cwd(),L)||"."} && turbobase apps deploy ${I.appSlug}`);return}d||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let f=await X(`pulling ${d}`,()=>x(T,_,d)),S=ne(process.cwd(),h??f.slug??d);await ie.mkdir(S,{recursive:!0});let E=await y(S,f.files,!!w.force);b(`pulled ${E} file${E===1?"":"s"} \u2192 ${S} (rev ${f.rev}).`),b(`next: cd ${Xi(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=ne(process.cwd(),h??d),_=await yt(w.baseUrl).catch(()=>null),{scaffoldAppFiles:f,starterApp:S}=await Promise.resolve().then(()=>(Jm(),Gm)),E=w.title??d,A=f({slug:d,title:E,appTsx:S(E),instanceOrigin:_?.baseUrl});await ie.mkdir(T,{recursive:!0});let I=await y(T,A,!!w.force);if(b(`scaffolded ${I} file${I===1?"":"s"} \u2192 ${T}`),w.claude!==!1){let M=Na({baseUrl:_?.baseUrl,token:_?.token,appSlug:d}),L=0;for(let J of M){let ge=await qw(nt(T,J.path),J);(ge==="wrote"||ge==="merged")&&(L+=1)}b(`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=Xi(process.cwd(),T)||".";b(`next: cd ${N} && npm install && npm run dev`),b(` turbobase apps create ${d}`),b(` turbobase apps push ${d} .`),b(` turbobase apps deploy ${d} .`)}),l.command("list").description("List the hosted apps on your instance.").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON instead of a table.").action(async d=>{let{baseUrl:h,token:w}=await B(d.baseUrl),T=new z({baseUrl:h,token:w}),_;try{_=await T.appsList()}catch(f){W(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(lt(_.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=ne(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),E=w.proposal??await $(T),{files:A,skipped:I,secrets:N,unstorable:M}=await Ga(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 I)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,E));b(`pushed ${J.files} file${J.files===1?"":"s"} \u2192 ${J.slug} rev ${J.rev} (source only, nothing deployed).`);let ge=await Un(new z({baseUrl:f,token:S}),J.slug);ge&&ge.entriesAdded>0&&b(`${ge.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 du(),{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)}`)}gI(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 du(),{baseUrl:w,token:T}=await B(d.baseUrl),_=h.tenant??yI(w),f=dh(d.confirm,_);f.ok||v(`promote refused (fail-closed): ${f.reason}`);let S=new z({baseUrl:w,token:T});try{let E=await X(`promoting ${d.from} \u2192 ${d.to} (${_})`,()=>S.configApply(h,{prune:d.prune}));if(Oe()){let I=[`${m.bold(`${d.from} \u2192 ${d.to}`)} ${m.dim(_??"")}`,`${Xt.add(String(E.applied.add))} ${Xt.change(String(E.applied.change))} ${Xt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&I.push(m.dim(`${E.backfillsQueued.length} backfill(s) queued`)),b(Zt("Promoted",I))}else b(`promoted ${d.from} \u2192 ${d.to} (${_}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let A=E.skippedDestroys??[];if(A.length>0){O(`${A.length} resource(s) on ${d.to} are not declared by this project \u2014 NOT removed:`);for(let I of A)O(` ${I.kind} ${I.id}`);O("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof Y&&E.status===403&&v("promote forbidden (403) \u2014 the stored PAT is not for an admin."),v(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),o.command("lint").argument("<file>","The hook, conduit or process definition file to lint").description("Statically lint a hook/conduit/process 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=cu(h.reporter),T=ne(process.cwd(),d),_=await Cn(T),f=Rp(_);w?b(ss(uI(d,f),w)):b($p(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=cu(h.reporter),T=await yp(ne(process.cwd(),d));if(h.against){h.against!=="sandbox"&&v(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await fp(xa(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 gp(ne(process.cwd(),h.fixture))}catch(S){v(`could not read fixture ${h.fixture}: ${S instanceof Error?S.message:String(S)}`)}let f=await mp(T,_,h.fixture,{resolveDir:Wt(ne(process.cwd(),d))});if(w){let S=pI(f);b(ss(S,w)),Yi(S.cases.some(E=>E.status==="failed")?1:0)}b(bp(f,!!h.trace)),Yi(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 Np(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 fr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");fr.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 Gh(d)}),fr.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 Jh(d??[],h)}),fr.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 Yh(d,h)}),fr.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 Xh(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 Zh(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 Qh(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 em(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=wa();f||v(`marketplace not configured \u2014 set ${qr} and ${Xo}.
|
|
4370
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
4371
|
-
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let
|
|
4372
|
-
project init: ${
|
|
4386
|
+
`);if(await S("PROPOSAL.md",f),h.screenshot){let _=k(h.screenshot);_&&await S("proposal-screenshot.png",_)}await S(nt(".turbobase","proposal.json"),`${JSON.stringify({proposalId:h.proposalId},null,2)}
|
|
4387
|
+
`)}async function $(c){try{let h=await ie.readFile(nt(c,".turbobase","proposal.json"),"utf8"),w=JSON.parse(h);return typeof w.proposalId=="string"&&w.proposalId?w.proposalId:void 0}catch{return}}async function P(c,h,w,R,S,f){let _=new z({baseUrl:c,token:h});try{return await _.appsPush(w,R,{note:S,proposalId:f})}catch(E){if(E instanceof Y){let A=E.body;if(E.status===401&&v("push unauthorized (401) \u2014 re-run `turbobase auth login`."),E.status===403&&A?.error==="admin_required"&&v("push forbidden (403) \u2014 the PAT is not for an admin."),E.status===403&&W(E,"extensions:deploy","push app source"),E.status===404&&v(`no app "${w}" on this instance \u2014 create it with \`turbobase apps create ${w}\`.`),E.status===413&&(A?.code==="FST_ERR_CTP_BODY_TOO_LARGE"&&v("push rejected: the request body exceeded the instance limit."),v(`push rejected: ${A?.error??"too large"} (limit ${A?.limit??"?"}).`)),E.status===400){let I=A?.path?` in ${A.path}`:"",N=A?.reason?` (${A.reason})`:"";v(`push rejected: ${A?.error??"bad request"}${N}${I}.`)}}v(`push failed: ${E instanceof Error?E.message:String(E)}`)}}async function C(c,h,w,R,S){let f;try{f=await Ja(R)}catch(M){return O(`source not recorded: could not read ${R} (${M instanceof Error?M.message:String(M)}).`),null}let{files:_,skipped:E,secrets:A,unstorable:I}=f,N=Object.keys(_).length;if(N===0)return O(`source not recorded: no source files found under ${R}.`),null;if(I.length>0){for(let M of I)O(`${M} contains a NUL byte (U+0000), which cannot be stored.`);return O(`source not recorded: ${I.length} ${I.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 E)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:c,token:h}).appsPush(w,_,{...S?{proposalId:S}:{}});return b(`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 j(c,h,w){return new Promise((R,S)=>{let f=fu("npm",c,{cwd:h,stdio:"inherit",...w?{env:{...process.env,...w}}:{}});f.on("error",S),f.on("exit",_=>_===0?R():S(new Error(`npm ${c.join(" ")} exited ${_??"?"}`)))})}async function H(c,h,w,R){let S=`${c.replace(/\/+$/,"")}${w}`,f;try{f=await p(S,{method:R.method,headers:{Authorization:`Bearer ${h}`,...R.body?{"content-type":"application/json"}:{}},...R.body?{body:JSON.stringify(R.body)}:{}})}catch(_){v(`request failed: ${_ instanceof Error?_.message:String(_)}`)}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 _=await f.text().catch(()=>""),E=_.slice(0,300);try{let A=JSON.parse(_);E=A.message??A.error??E}catch{}v(`failed: HTTP ${f.status} ${E}`)}return await f.json().catch(()=>({}))}async function G(c,h,w,R,S){return await H(c,h,`/v1/apps/${encodeURIComponent(w)}/preview/${R}`,{method:"POST",body:S})}async function Re(c,h,w){return{previews:(await H(c,h,`/v1/apps/${encodeURIComponent(w)}/previews`,{method:"GET"})).previews??[]}}async function qe(c,h,w,R,S,f,_,E){let A;try{A=await X(`zipping ${R}`,()=>xp(R))}catch(L){v(`could not zip ${R}: ${L instanceof Error?L.message:String(L)}`)}A.fileCount===0&&v(`${R} is empty \u2014 the build produced nothing.`),A.buffer.byteLength>Za&&v(`${R} zips to ${Bw(A.buffer.byteLength)} \u2014 over the ${Bw(Za)} deploy limit. Check the build output for node_modules, source maps or media that should not ship.`);let I={Authorization:`Bearer ${h}`,"Content-Type":"application/zip"};S&&(I["x-app-entry"]=S),f&&(I["x-proposal-id"]=f),_&&(I["x-app-build-id"]=_.buildId,I["x-app-asset-base"]=_.assetBase),E&&(I["x-app-channel"]="preview",E.label&&(I["x-app-preview-label"]=encodeURIComponent(E.label)),E.replacePreviewId&&(I["x-app-preview-replace"]=E.replacePreviewId));let N=`${c.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:I,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 ${c} \u2014 create it with \`turbobase apps create ${w}\`.`)}if(!M.ok){let L=await M.text().catch(()=>""),J=L.slice(0,300);try{let ge=JSON.parse(L);J=ge.message??ge.error??J}catch{}v(`deploy failed: HTTP ${M.status} ${J}`)}return await M.json().catch(()=>({}))}function Et(c,h,w){for(let R of Zp({mode:c,verdicts:h,retired:w}))(R.stream==="err"?O:b)(R.text)}function Gt(c){let h=c.roles;h&&Et(h.applied?"applied":"preview",h.verdicts??[],h.retired)}function Pt(c){let h=c.labels;if(!h||h.verdicts.length===0)return;let w=h.verdicts.filter(S=>S.action!=="noop");if(w.length===0)return;b(""),b(m.bold(h.applied?"labels":"labels (preview \u2014 not applied)"));let R=Math.max(...w.map(S=>S.name.length));for(let S of w){let f=S.name.padEnd(R);if(S.action==="detach")b(` removed ${f} ${m.dim("no longer declared in the manifest")}`);else if(S.action==="create")b(` created ${f} ${m.dim(S.color)}`);else{let _=S.declaredColor?`${S.color} \u2014 declared ${S.declaredColor}, the instance's colour is kept`:S.color;b(` added ${f} ${m.dim(_)}`)}}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 Jt(c,h,w){let R=Vp(c,{localDocsModifiedAt:await Lo(h),recordedSourceRev:w});R&&b(R.level==="warn"?m.yellow(R.message):m.dim(R.message))}async function Lo(c){if(!c)return null;let h=null;for(let w of["INSTANCE-LEARNINGS.md","TURBOBASE-FEEDBACK.md"])try{let R=await ie.stat(nt(c,w));(h===null||R.mtimeMs>h)&&(h=R.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(c,h,w)=>{let{baseUrl:R,token:S}=await F(w.baseUrl);if(w.proposal){let A=new z({baseUrl:R,token:S}),I;try{I=await X(`fetching proposal ${w.proposal}`,()=>A.appPullContext(w.proposal))}catch(ge){W(ge,"extensions:deploy","pull proposal"),ge instanceof Y&&ge.status===404&&v(`no widget proposal "${w.proposal}" on ${R}.`),v(`could not fetch proposal ${w.proposal}: ${ge instanceof Error?ge.message:String(ge)}`)}let N=await X(`pulling ${I.appSlug}`,()=>x(R,S,I.appSlug)),M=h??c,L=ne(process.cwd(),M??I.appSlug);await ie.mkdir(L,{recursive:!0});let J=await y(L,N.files,!!w.force);await T(L,I,!!w.force),b(`pulled ${J} file${J===1?"":"s"} \u2192 ${L} (rev ${N.rev}), linked to proposal ${I.proposalId}.`),b(`next: cd ${Xi(process.cwd(),L)||"."} && turbobase apps deploy ${I.appSlug}`);return}c||v("pull needs an <app> slug/id, or --proposal <id> to pull the app behind a widget proposal.");let f=await X(`pulling ${c}`,()=>x(R,S,c)),_=ne(process.cwd(),h??f.slug??c);await ie.mkdir(_,{recursive:!0});let E=await y(_,f.files,!!w.force);b(`pulled ${E} file${E===1?"":"s"} \u2192 ${_} (rev ${f.rev}).`),b(`next: cd ${Xi(process.cwd(),_)||"."} && 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(c,h,w)=>{let R=ne(process.cwd(),h??c),S=await yt(w.baseUrl).catch(()=>null),{scaffoldAppFiles:f,starterApp:_}=await Promise.resolve().then(()=>(Ym(),Jm)),E=w.title??c,A=f({slug:c,title:E,appTsx:_(E),instanceOrigin:S?.baseUrl});await ie.mkdir(R,{recursive:!0});let I=await y(R,A,!!w.force);if(b(`scaffolded ${I} file${I===1?"":"s"} \u2192 ${R}`),w.claude!==!1){let M=La({baseUrl:S?.baseUrl,token:S?.token,appSlug:c}),L=0;for(let J of M){let ge=await zw(nt(R,J.path),J);(ge==="wrote"||ge==="merged")&&(L+=1)}b(`wired Claude Code: ${L} file${L===1?"":"s"} (CLAUDE.md, .mcp.json, .claude/).`),S||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=Xi(process.cwd(),R)||".";b(`next: cd ${N} && npm install && npm run dev`),b(` turbobase apps create ${c}`),b(` turbobase apps push ${c} .`),b(` turbobase apps deploy ${c} .`)}),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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await R.appsList()}catch(f){W(f,"extensions:deploy","list apps"),v(`list apps failed: ${f instanceof Error?f.message:String(f)}`)}if(c.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no hosted apps yet \u2014 create one with `turbobase apps create <slug>`.");b(lt(S.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(c,h,w)=>{let R=ne(process.cwd(),h??".");await ie.stat(R).then(Q=>Q.isDirectory()).catch(()=>!1)||v(`${R} is not a directory.`);let{baseUrl:f,token:_}=await F(w.baseUrl),E=w.proposal??await $(R),{files:A,skipped:I,secrets:N,unstorable:M}=await Ja(R),L=Object.keys(A).length;if(L===0&&v(`no source files found under ${R} (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 I)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,_,c,A,w.note,E));b(`pushed ${J.files} file${J.files===1?"":"s"} \u2192 ${J.slug} rev ${J.rev} (source only, nothing deployed).`);let ge=await Un(new z({baseUrl:f,token:_}),J.slug);ge&&ge.entriesAdded>0&&b(`${ge.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 c=>{let h=await uu(),{baseUrl:w,token:R}=await F(c.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await X(`planning against ${c.to??w}`,()=>S.configPlan(h))}catch(_){v(`plan failed: ${_ instanceof Error?_.message:String(_)}`)}yI(f,c.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 c=>{let h=await uu(),{baseUrl:w,token:R}=await F(c.baseUrl),S=h.tenant??bI(w),f=uh(c.confirm,S);f.ok||v(`promote refused (fail-closed): ${f.reason}`);let _=new z({baseUrl:w,token:R});try{let E=await X(`promoting ${c.from} \u2192 ${c.to} (${S})`,()=>_.configApply(h,{prune:c.prune}));if(Oe()){let I=[`${m.bold(`${c.from} \u2192 ${c.to}`)} ${m.dim(S??"")}`,`${Xt.add(String(E.applied.add))} ${Xt.change(String(E.applied.change))} ${Xt.destroy(String(E.applied.destroy))}`];E.backfillsQueued.length&&I.push(m.dim(`${E.backfillsQueued.length} backfill(s) queued`)),b(Zt("Promoted",I))}else b(`promoted ${c.from} \u2192 ${c.to} (${S}): +${E.applied.add} ~${E.applied.change} -${E.applied.destroy}`+(E.backfillsQueued.length?` (${E.backfillsQueued.length} backfill(s) queued)`:""));let A=E.skippedDestroys??[];if(A.length>0){O(`${A.length} resource(s) on ${c.to} are not declared by this project \u2014 NOT removed:`);for(let I of A)O(` ${I.kind} ${I.id}`);O("Re-run with --prune to remove them, or add them to this repo.")}}catch(E){E instanceof Y&&E.status===403&&v("promote forbidden (403) \u2014 the stored PAT is not for an admin."),v(`promote failed: ${E instanceof Error?E.message:String(E)}`)}}),o.command("lint").argument("<file>","The hook, conduit or process definition file to lint").description("Statically lint a hook/conduit/process 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(c,h)=>{let w=du(h.reporter),R=ne(process.cwd(),c),S=await Cn(R),f=$p(S);w?b(ss(pI(c,f),w)):b(Ep(c,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(c,h)=>{let w=du(h.reporter),R=await bp(ne(process.cwd(),c));if(h.against){h.against!=="sandbox"&&v(`unknown --against target '${h.against}' (only 'sandbox' is supported).`);try{await gp(Ta(R))}catch(_){v(_ instanceof Error?_.message:String(_))}return}h.fixture||v("replay needs a --fixture <file> (offline) or --against sandbox (online).");let S;try{S=await yp(ne(process.cwd(),h.fixture))}catch(_){v(`could not read fixture ${h.fixture}: ${_ instanceof Error?_.message:String(_)}`)}let f=await fp(R,S,h.fixture,{resolveDir:Wt(ne(process.cwd(),c))});if(w){let _=hI(f);b(ss(_,w)),Yi(_.cases.some(E=>E.status==="failed")?1:0)}b(wp(f,!!h.trace)),Yi(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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w});try{await Lp(R,{status:c.status,retry:c.retry,limit:c.limit?Number(c.limit):void 0,sink:b})}catch(S){S instanceof Y&&S.status===403&&v("forbidden (403) \u2014 binding --retry requires an admin PAT."),S instanceof Y&&S.status===409&&v("binding is not retryable (only divergent/blocked bindings can be retried)."),v(`ext binding failed: ${S instanceof Error?S.message:String(S)}`)}});let fr=o.command("proposals").description("Review the hook proposals waiting on a decision \u2014 list, promote, retract, reject.");fr.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 c=>{await Jh(c)}),fr.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(c,h)=>{await Yh(c??[],h)}),fr.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(c,h)=>{await Xh(c,h)}),fr.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(c,h)=>{await Zh(c,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(c,h)=>{await Qh(c,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(c,h)=>{await em(c,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(c,h)=>{await tm(c,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(c,h)=>{let w=c.lastIndexOf("@"),R=w>0?c.slice(0,w):c,S=w>0?c.slice(w+1):void 0,f=va();f||v(`marketplace not configured \u2014 set ${Mr} and ${Xo}.
|
|
4388
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let _=_a(f.registryUrl);_&&v(_);let{baseUrl:E,token:A}=await F(h.baseUrl),I=new En(f),N;try{N=await X(`fetching ${c}`,()=>I.fetchBundle(R,S))}catch(Q){v(`marketplace fetch failed for ${c}: ${Q instanceof Error?Q.message:String(Q)}`)}let M=qo(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=mI(N.bundle,N.name,N.kind),ge=new z({baseUrl:E,token:A});try{let Q=await X(`installing ${N.name}@${N.version}`,()=>ge.deploy({...J,provenance:"marketplace",...L?{connectionId:L}:{}}));b(`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(c,h)=>{let w=va();w||v(`marketplace not configured \u2014 set ${Mr} and ${Xo}.
|
|
4389
|
+
Ask Turbobase support to issue a registry token for your instance (it is separate from your PAT).`);let R=_a(w.registryUrl);R&&v(R);let S=ne(process.cwd(),c),f=await Cn(S),_=/\bdefineConduit\s*[<(]/.test(f)?"conduit":"hook",E={};if(h.manifest){let N=ne(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."),E=L}try{na(E,f)}catch(N){N instanceof Yt&&v(N.message),v(`manifest validation failed: ${N instanceof Error?N.message:String(N)}`)}let A=new En(w);try{await X(`publishing ${h.name}@${h.pkgVersion}`,()=>A.publish({name:h.name,version:h.pkgVersion,kind:_,bundle:f,manifest:E}))}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 I=qo(E);b(`published ${h.name}@${h.pkgVersion} (kind=${_}) to the marketplace.`),I.length>0&&b(` declares ${I.length} connection input(s): ${I.map(N=>N.source_system).join(", ")} \u2014 bound at install.`)}),n.command("init").description("Scaffold a Claude-Code extension project in the current dir.").option("--base-url <url>","Instance to wire .mcp.json to (defaults to the active instance).").action(async c=>{let h=await yt(c.baseUrl).catch(()=>null),w=La({baseUrl:h?.baseUrl,token:h?.token}),R=0,S=0,f=0;for(let _ of w){let E=ne(process.cwd(),_.path),A=await zw(E,_);A==="wrote"?(R+=1,b(` wrote ${_.path}`)):A==="merged"?(f+=1,b(` merged ${_.path} (added the .mcp.json rule)`)):(S+=1,b(` skipped ${_.path} (exists)`))}b(`
|
|
4390
|
+
project init: ${R} written, ${f} merged, ${S} skipped.`)}),n.command("ci").description(`Write the reusable release-deploy GitHub Action to ${Ia} (non-destructive).`).action(async()=>{let c=eh(),h=0,w=0;for(let R of c){let S=ne(process.cwd(),R.path);await Lr(S,R.content,R.executable)==="wrote"?(h+=1,b(` wrote ${R.path}`)):(w+=1,b(` skipped ${R.path} (exists)`))}b(`
|
|
4373
4391
|
project ci: ${h} written, ${w} skipped.`),h>0&&(b(`
|
|
4374
|
-
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
|
|
4375
|
-
`;
|
|
4376
|
-
samples init: ${E} written, ${A} skipped.`)});let Ut=t.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),
|
|
4377
|
-
`+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(lt(_.map(Fw),{head:Hw})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),Ut.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){W(S,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${S instanceof Error?S.message:String(S)}`)}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>`))}),Ut.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){W(S,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${S instanceof Error?S.message:String(S)}`)}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"]])Ut.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),E=new z({baseUrl:f,token:S});try{await E.guardrailUpdate(T,{status:h})}catch(A){W(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."))});Ut.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){W(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`)}),Ut.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(I){W(I,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}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 S=d.trim().toLowerCase();S!=="allow"&&S!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await _.guardrailPostureSet(S)}catch(A){W(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(E.mode))}`),E.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>`."))}),Ut.command("test").description("What happens to this write? Runs the real evaluator; writes nothing.").requiredOption("--source <system>","Adapter id the write targets.").requiredOption("--record <type>","Record type the write targets.").option("--actor <actor>","Caller to simulate, e.g. 'agent:ai' or 'user:<id>'.").option("--external-id <id>","Source-side row id, for target-scoped rules.").option("--fields <json>","A candidate row as JSON, so `when` predicates can be decided.").option("--op <op>","Write op: 'delete' tests <record>.delete; omitted tests <record>.write.").option("--phase <phase>","boundary | cdc | worker | adapter. Defaults to worker (the last gate).").option("--base-url <url>","Instance base URL (defaults to the active instance).").option("--json","Emit raw JSON.").action(async d=>{let h;if(d.fields)try{h=JSON.parse(d.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token: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(E){W(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(d.json)return b(JSON.stringify(f,null,2));let S=`${d.source}/${f.op??d.record}`;f.degraded?(b(`${m.red("\u2717")} ${S} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${f.reason}`))):f.allowed?b(`${m.green("\u2713")} ${S} \u2014 ${f.decision}`+(f.blockedBy?m.dim(` (rule ${f.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${S} \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 xn=t.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),jo=(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 Do(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 gu=async d=>{let h=nt(ne(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})};xn.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){W(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(lt(_.map(f=>[f.table,f.displayName,String(f.fields.length),f.status,f.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),xn.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 gu(d??".");if(w||v(`no public/turbobase.json under ${ne(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${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(E){W(E,"extensions:deploy","plan tables"),Do(E)}b(`claiming as ${m.bold(S.claimedBy)}`);for(let E of S.tables)jo(E,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),xn.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 gu(d??".");if(w||v(`no public/turbobase.json under ${ne(process.cwd(),d??".")}.`),w.tables.length===0)return b(`${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(E){W(E,"extensions:deploy","apply tables"),Do(E)}for(let E of S.tables)jo(E,{showClaimants:!0});b(`applied ${S.tables.length} table${S.tables.length===1?"":"s"} as ${S.claimedBy}.`)}),xn.command("create").description('Create a single table without a manifest (the CLI twin of "New custom table").').argument("<slug>","Table slug; the physical table is cr_<slug>.").requiredOption("-f, --field <name:type>","Field as name:type[:required] \u2014 text|number|date|bool|select. Repeatable.",(d,h)=>[...h??[],d],[]).option("--name <displayName>","Human label for the table (defaults to the slug).").option("--restrict-to-owner","Non-admins see only rows they created.").option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(d,h)=>{let w=h.field.map(E=>{let[A,I,N]=E.split(":");return(!A||!I)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:A,type:I,...N==="required"?{required:!0}:{}}}),{baseUrl: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(E){W(E,"extensions:deploy","create a table"),Do(E)}for(let E of S.tables)jo(E);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),xn.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){W(S,"extensions:deploy","drop a table"),v(`drop failed: ${S instanceof Error?S.message:String(S)}`)}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 Zi=t.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=uu(),w;try{w=await wm(h,{fromTenant:d.from,ttl:d.ttl,sample:d.sample,baseUrl:d.baseUrl})}catch(T){T instanceof qn&&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}`)}),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=uu();await al(h).catch(()=>[]);let w;try{w=await vm(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}).`)}),Zi.command("list").description("List active sandboxes with TTL/expiry; reaps any past their TTL.").action(async()=>{let d=uu(),h=await al(d).catch(()=>[]),w=await ks(),{active:T}=il(w);if(T.length===0)b("no active sandboxes.");else{for(let _ of T)b(` ${_.name} from=${_.fromTenant} expires=${_.expiresAt} ${_.url}`);b(`
|
|
4378
|
-
${
|
|
4379
|
-
`,
|
|
4380
|
-
`).length} lines).`)});let
|
|
4381
|
-
run \`${
|
|
4392
|
+
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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await R.catalogRecords()}catch(I){I instanceof Y&&(I.status===401||I.status===403)&&v("catalog read forbidden \u2014 the stored PAT lacks catalog:read. Re-run `turbobase auth login`."),v(`catalog fetch failed: ${I instanceof Error?I.message:String(I)}`)}if(S.length===0){b("no records in the instance catalog \u2014 nothing to generate.");return}let f=ne(process.cwd(),c.out),_=_p(S,{event:c.event}),E=0,A=0;for(let{recordType:I,fixture:N}of _){let M=nt(f,`${I}.json`),L=`${JSON.stringify(N,null,2)}
|
|
4393
|
+
`;c.force?(await ie.mkdir(Wt(M),{recursive:!0}),await ie.writeFile(M,L,{mode:420}),E+=1,b(` wrote ${c.out}/${I}.json`)):await Lr(M,L)==="wrote"?(E+=1,b(` wrote ${c.out}/${I}.json`)):(A+=1,b(` skipped ${c.out}/${I}.json (exists \u2014 use --force to overwrite)`))}b(`
|
|
4394
|
+
samples init: ${E} written, ${A} skipped.`)});let Ut=t.command("guardrails").description("Control PG\u2192source write-back with policy rules (staged write rollout)."),Hw=c=>[c.name??m.dim(c.id.slice(0,8)),c.status==="active"?m.green("active"):c.status==="proposed"?m.yellow("proposed"):m.dim("inactive"),c.decision==="deny"?m.red(c.decision):c.decision==="require_confirm"?m.yellow(c.decision):m.green(c.decision),String(c.priority),c.source,c.record??c.op,c.actor??m.dim("any"),c.when||m.dim("(always)"),c.reason??""],Vw=["NAME","STATUS","DECISION","PRIO","SOURCE","RECORD","ACTOR","WHEN","REASON"];Ut.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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await R.guardrailsList()}catch(f){W(f,"extensions:deploy","list guardrails"),v(`list guardrails failed: ${f instanceof Error?f.message:String(f)}`)}if(c.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b(`no write guardrails \u2014 every record the admin entitlement allows is writable.
|
|
4395
|
+
`+m.dim("create one with `turbobase guardrails create <name> --source <s> --record <r>`"));b(lt(S.map(Hw),{head:Vw})),b(m.dim(" first match wins; lower PRIO is evaluated first."))}),Ut.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).",c=>Number(c)).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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.guardrailCreate({name:c,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(_){W(_,"extensions:deploy","create a guardrail"),v(`create guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}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>`))}),Ut.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.",c=>Number(c)).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(c,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:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.guardrailUpdate(c,{...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(_){W(_,"extensions:deploy","edit a guardrail"),v(`edit guardrail failed: ${_ instanceof Error?_.message:String(_)}`)}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[c,h,w]of[["activate","active","activated"],["deactivate","inactive","deactivated"]])Ut.command(`${c} <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(R,S)=>{let{baseUrl:f,token:_}=await F(S.baseUrl),E=new z({baseUrl:f,token:_});try{await E.guardrailUpdate(R,{status:h})}catch(A){W(A,"extensions:deploy",`${c} a guardrail`),v(`${c} guardrail failed: ${A instanceof Error?A.message:String(A)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(R)} ${w}`),h==="inactive"&&b(m.dim(" writes it was gating now fall through to the other rules."))});Ut.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R});try{await S.guardrailDelete(c)}catch(f){W(f,"extensions:deploy","delete a guardrail"),v(`delete guardrail failed: ${f instanceof Error?f.message:String(f)}`)}b(`${m.green("\u2713")} guardrail ${m.bold(c)} deleted`)}),Ut.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f=A=>A==="deny"?"deny-by-default (allow-list)":"allow-by-default (deny-list)";if(c===void 0){let A;try{A=await S.guardrailPostureGet()}catch(I){W(I,"extensions:deploy","read the guardrail posture"),v(`read posture failed: ${I instanceof Error?I.message:String(I)}`)}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 _=c.trim().toLowerCase();_!=="allow"&&_!=="deny"&&v("posture must be 'allow' or 'deny'.");let E;try{E=await S.guardrailPostureSet(_)}catch(A){W(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(E.mode))}`),E.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>`."))}),Ut.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 c=>{let h;if(c.fields)try{h=JSON.parse(c.fields)}catch(E){v(`--fields must be valid JSON: ${E instanceof Error?E.message:String(E)}`)}let{baseUrl:w,token:R}=await F(c.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.guardrailTest({source:c.source,record:c.record,...c.actor?{actor:c.actor}:{},...c.externalId?{externalId:c.externalId}:{},...h?{fields:h}:{},...c.op?{op:c.op}:{},...c.phase?{phase:c.phase}:{}})}catch(E){W(E,"extensions:deploy","test guardrails"),v(`guardrails test failed: ${E instanceof Error?E.message:String(E)}`)}if(c.json)return b(JSON.stringify(f,null,2));let _=`${c.source}/${f.op??c.record}`;f.degraded?(b(`${m.red("\u2717")} ${_} \u2014 guardrail policy is UNREADABLE; writes fail closed`),b(m.dim(` ${f.reason}`))):f.allowed?b(`${m.green("\u2713")} ${_} \u2014 ${f.decision}`+(f.blockedBy?m.dim(` (rule ${f.blockedBy})`):m.dim(" (no rule matched)"))):(b(`${m.red("\u2717")} ${_} \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 kn=t.command("tables").description("Author custom tables on your instance (create, evolve, inspect)."),jo=(c,h={})=>{let w=`${m.bold(c.table)} ${m.dim(c.displayName)}`;b(c.exists===!1?`${w} ${m.dim("(new)")}`:w);for(let R of c.fields){let S=[R.required?"required":null].filter(Boolean).join(", "),f=h.showClaimants&&R.claimedBy?.length?` ${m.dim(`\u2190 ${R.claimedBy.join(", ")}`)}`:"";b(` ${R.column.padEnd(28)} ${R.type}${S?` (${S})`:""}${f}`)}h.showClaimants&&c.claimants.length>1&&b(m.dim(` claimed by ${c.claimants.join(", ")}`))};function Do(c){if(c instanceof Y&&c.status===409){let h=c.body;h?.error==="table_conflict"&&h.message&&(O(h.message),process.exit(1))}v(`tables: ${c instanceof Error?c.message:String(c)}`)}let yu=async c=>{let h=nt(ne(process.cwd(),c),"public","turbobase.json"),w=await ie.readFile(h,"utf8").catch(()=>null);if(w===null)return null;let R;try{R=JSON.parse(w)}catch(f){v(`${h} is not valid JSON: ${f instanceof Error?f.message:String(f)}`)}let S=R.tables;return S===void 0?{tables:[],manifestPath:h}:(Array.isArray(S)||v(`${h}: "tables" must be an array.`),{tables:S,manifestPath:h})};kn.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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await R.tablesList()}catch(f){W(f,"extensions:deploy","list tables"),v(`list tables failed: ${f instanceof Error?f.message:String(f)}`)}if(c.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b("no custom tables yet \u2014 create one with `turbobase tables create <slug>`.");b(lt(S.map(f=>[f.table,f.displayName,String(f.fields.length),f.status,f.claimedBy.join(", ")||"\u2014"]),{head:["TABLE","NAME","FIELDS","STATUS","CLAIMED BY"]}))}),kn.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(c,h)=>{let w=await yu(c??".");if(w||v(`no public/turbobase.json under ${ne(process.cwd(),c??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to plan.`);let{baseUrl:R,token:S}=await F(h.baseUrl),f=new z({baseUrl:R,token:S}),_;try{_=await X("planning tables",()=>f.tablesPlan({claimedBy:h.as,tables:w.tables}))}catch(E){W(E,"extensions:deploy","plan tables"),Do(E)}b(`claiming as ${m.bold(_.claimedBy)}`);for(let E of _.tables)jo(E,{showClaimants:!0});b(""),b(m.dim("nothing was applied \u2014 run `turbobase tables apply` (or deploy the app) to make it so."))}),kn.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(c,h)=>{let w=await yu(c??".");if(w||v(`no public/turbobase.json under ${ne(process.cwd(),c??".")}.`),w.tables.length===0)return b(`${w.manifestPath} declares no tables \u2014 nothing to apply.`);let{baseUrl:R,token:S}=await F(h.baseUrl),f=new z({baseUrl:R,token:S}),_;try{_=await X("applying tables",()=>f.tablesApply({claimedBy:h.as,tables:w.tables}))}catch(E){W(E,"extensions:deploy","apply tables"),Do(E)}for(let E of _.tables)jo(E,{showClaimants:!0});b(`applied ${_.tables.length} table${_.tables.length===1?"":"s"} as ${_.claimedBy}.`)}),kn.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.",(c,h)=>[...h??[],c],[]).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(c,h)=>{let w=h.field.map(E=>{let[A,I,N]=E.split(":");return(!A||!I)&&v(`--field "${E}" must be name:type[:required] (e.g. title:text:required).`),N!==void 0&&N!=="required"&&v(`--field "${E}": the third part may only be "required".`),{name:A,type:I,...N==="required"?{required:!0}:{}}}),{baseUrl:R,token:S}=await F(h.baseUrl),f=new z({baseUrl:R,token:S}),_;try{_=await X(`creating cr_${c}`,()=>f.tablesApply({tables:[{slug:c,displayName:h.name??c,fields:w,...h.restrictToOwner?{rowLevelOwner:!0}:{}}]}))}catch(E){W(E,"extensions:deploy","create a table"),Do(E)}for(let E of _.tables)jo(E);b(""),b(m.dim("grant access under Settings \u203A Users, or in the Records page permissions matrix."))}),kn.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(c,h)=>{h.confirm!==c&&v(`drop refused: --confirm "${h.confirm}" does not match "${c}".`);let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await X(`dropping cr_${c}`,()=>S.tablesDrop(c,h.confirm))}catch(_){W(_,"extensions:deploy","drop a table"),v(`drop failed: ${_ instanceof Error?_.message:String(_)}`)}if(!f.removed)return b(`no table named "${c}" on this instance \u2014 nothing dropped.`);b(`dropped ${f.table} and every row in it.`)});let Zi=t.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 c=>{process.env.TURBOBASE_SANDBOX="1";let h=pu(),w;try{w=await vm(h,{fromTenant:c.from,ttl:c.ttl,sample:c.sample,baseUrl:c.baseUrl})}catch(R){R instanceof qn&&v(R.message),v(`sandbox create failed: ${R instanceof Error?R.message:String(R)}`)}b(`sandbox ${w.name} ready.`),b(` source: ${w.fromTenant} (sampled ${Math.round(w.sampleFraction*100)}%, redacted)`),b(` url: ${w.url}`),b(` 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 c=>{let h=pu();await ll(h).catch(()=>[]);let w;try{w=await _m(h,c)}catch(R){v(`sandbox destroy failed: ${R instanceof Error?R.message:String(R)}`)}w||v(`no sandbox named '${c}'.`),b(`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 c=pu(),h=await ll(c).catch(()=>[]),w=await ks(),{active:R}=al(w);if(R.length===0)b("no active sandboxes.");else{for(let S of R)b(` ${S.name} from=${S.fromTenant} expires=${S.expiresAt} ${S.url}`);b(`
|
|
4396
|
+
${R.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.",us).action(async c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await X("exporting instance config",()=>R.configExport())}catch(E){E instanceof Y&&(E.status===401||E.status===403)&&v("ext export forbidden \u2014 the stored PAT lacks extensions:deploy. Re-run `turbobase auth login`."),v(`ext export failed: ${E instanceof Error?E.message:String(E)}`)}let f=typeof S.serialized=="string"?S.serialized:`${JSON.stringify(S.manifest??S,null,2)}
|
|
4397
|
+
`,_=ne(process.cwd(),c.out,Ln);await ie.mkdir(Wt(_),{recursive:!0}),await ie.writeFile(_,f,"utf8"),b(`wrote ${c.out}/${Ln} (${f.split(`
|
|
4398
|
+
`).length} lines).`)});let bu=o.command("extras").description("Manage the optional native packages `ext test` and `ext replay` need."),Kw=[{name:"esbuild",needs:"compiling an extension (`test`, `replay`)"},{name:"isolated-vm",needs:"executing an extension in the sandbox (`test`, `replay`)"}],wu=()=>process.env.TURBOBASE_HOME?.trim()||nt(oI(),".turbobase"),Ww=()=>"1.49.0",Uo=async()=>Promise.all(Kw.map(async c=>{try{return await import(c.name),{...c,present:!0}}catch{return{...c,present:!1}}}));bu.command("status").description("Report which optional native packages are installed.").action(async()=>{let c=await Uo();for(let h of c)b(`${h.present?ve.success("installed"):ve.warn("missing")} ${m.bold(h.name)} \u2014 ${h.needs}`);c.some(h=>!h.present)&&b(`
|
|
4399
|
+
run \`${Vr} ext extras install\` to fetch them into ${wu()}.`)}),bu.command("install").description("Install the optional native packages into $TURBOBASE_HOME (needs npm).").action(async()=>{let c=await Uo();if(c.every(A=>A.present)){b(ve.success("extras already installed \u2014 nothing to do."));return}let h=wu();await ie.mkdir(h,{recursive:!0});let w=c.filter(A=>!A.present).map(A=>A.name),R=tl(process.platform,process.arch),S=async(A,I)=>{let{code:N,stderr:M}=await No("npm",["install","--prefix",h,"--no-audit","--no-fund",...A]);N!==0&&v(`extras install failed while installing ${I} (npm exited ${N}).
|
|
4382
4400
|
${M.trim()}
|
|
4383
|
-
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(I=>`${I}@${
|
|
4401
|
+
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(I=>`${I}@${Qa[I]??"latest"}`);b(`installing ${A.join(", ")} \u2192 ${h}/node_modules \u2026`),await S(A,f.join(", "))}if(w.includes("isolated-vm")){let A=`isolated-vm@${Qa["isolated-vm"]}`;if(b(`installing ${A} \u2192 ${h}/node_modules \u2026`),await S(["--ignore-scripts",A],"isolated-vm"),hm.includes(R)){let N=`${el}@${Ww()}`;b(`fetching ${N} (no upstream binary for ${R}) \u2026`);let{code:M}=await No("npm",["install","--prefix",h,"--no-audit","--no-fund","--ignore-scripts",N]);M!==0&&b(ve.warn(`could not fetch ${N} \u2014 falling back to a source build.`))}let I=await mm({home:h});I.length>0&&b(` ${ve.success("prebuilt")} ${I.join(", ")} \u2192 isolated-vm/prebuilds/${R}`)}let _=await Uo(),E=_.filter(A=>!A.present).map(A=>A.name);if(E.includes("isolated-vm")){b(ve.warn(`no prebuilt isolated-vm for ${R} / Node ${process.versions.node} (${rl()}) \u2014 building from source. This needs Python and a C++ toolchain, and takes a few minutes.`));let{code:A}=await No("npm",["rebuild","--prefix",h,"isolated-vm"]);A===0&&(_=await Uo(),E=_.filter(I=>!I.present).map(I=>I.name))}E.length>0&&v(`npm succeeded but ${E.join(", ")} still will not load \u2014 no prebuilt binary for ${R} / Node ${process.versions.node} (${rl()}), and the source build did not produce one either. Everything except \`test\` and \`replay\` works without them.`),b(ve.success("extras installed \u2014 `turbobase ext test` and `turbobase ext replay` are ready."))});let jr=t.command("release").description("Ship a release to your instance: deploy | status | rollback | list.");jr.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 c=>{let h=c.target==="approved"?"approved":c.target==="auto"?"auto":null;h||v(`--target must be 'auto' or 'approved' (got '${c.target}').`);let w=await wI(ne(process.cwd(),c.project??".")),R=Object.keys(w).length;!c.solution&&R===0&&v("release deploy needs --solution <id> (live-fetch) or an SDF project (a src/ dir under --project, default cwd) to upload.");let f=(c.ref?await hu(["rev-parse",c.ref])??c.ref:null)??process.env.GITHUB_SHA??await hu(["rev-parse","HEAD"]),_=c.gitRepo??process.env.GITHUB_REPOSITORY??await hu(["remote","get-url","origin"]),E=c.gitRef??process.env.GITHUB_REF??null,A=c.prUrl??process.env.PR_URL??null,{baseUrl:I,token:N}=await F(c.baseUrl),M=new z({baseUrl:I,token:N}),L;try{L=await M.releaseDeploy({solutionId:c.solution??null,target:h,approvedBy:c.approvedBy??null,files:R>0?w:null,gitRepo:_,gitRef:E,gitSha:f,prUrl:A})}catch(J){W(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 ${L.releaseId} enqueued \u2192 taskId=${L.taskId} (target=${h}`+(R>0?`, uploaded ${R} bundle file(s)`:", live-fetch")+")."),c.follow&&await Ba(()=>M.releaseStatus(L.releaseId),`release ${L.releaseId}`,c.intervalMs)}),jr.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.releaseFiles(c)}catch(A){A instanceof Y&&A.status===404&&v(`release ${c} not found.`),A instanceof Y&&A.status===409&&v(`no built project was retained for release ${c}. Files are kept for a FAILED attempt only \u2014 a shipped bundle is recoverable from the account.`),W(A,"releases:write","pull a release"),v(`release pull failed: ${A instanceof Error?A.message:String(A)}`)}let _=ne(process.cwd(),h.dir),E=0;for(let[A,I]of[["owned",f.owned],["context",f.context]])for(let[N,M]of Object.entries(I)){let L=nt(_,A,N);await ie.mkdir(Wt(L),{recursive:!0}),await ie.writeFile(L,M,"utf8"),E++}await ie.writeFile(nt(_,".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 ${_}
|
|
4384
4402
|
${Object.keys(f.owned).length} owned file(s), ${Object.keys(f.context).length} context file(s), ${E} total
|
|
4385
4403
|
`+(f.logTail?`
|
|
4386
4404
|
the failure these bytes produced:
|
|
4387
4405
|
${f.logTail.trim()}
|
|
4388
4406
|
`:"")+`
|
|
4389
4407
|
edit the files under owned/, then:
|
|
4390
|
-
turbobase release push ${f.releaseId} --dir ${h.dir}`)}),jr.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(
|
|
4408
|
+
turbobase release push ${f.releaseId} --dir ${h.dir}`)}),jr.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f=ne(process.cwd(),h.dir),_;try{_=await S.releaseFiles(c)}catch(L){L instanceof Y&&L.status===404&&v(`release ${c} not found.`),W(L,"releases:write","push a release"),v(`release push failed: ${L instanceof Error?L.message:String(L)}`)}let E=async(L,J)=>{try{return await ie.readFile(nt(f,L,J),"utf8")}catch{return null}},A=[];for(let[L,J]of Object.entries(_.context)){let ge=await E("context",L);ge!==null&&ge!==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:
|
|
4391
4409
|
`+A.map(L=>` context/${L}`).join(`
|
|
4392
|
-
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let I={...
|
|
4410
|
+
`)+"\n\nRevert them (re-run `release pull`) and put your changes under owned/.");let I={..._.context},N=0;for(let[L,J]of Object.entries(_.owned)){let ge=await E("owned",L);I[L]=ge??J,ge!==null&&ge!==J&&N++}N===0&&b("nothing changed under owned/ \u2014 pushing the same bytes the release already built.");let M=h.target==="approved"?"approved":"auto";try{let L=await S.releasePush(c,{files:I,target:M,...h.approvedBy?{approvedBy:h.approvedBy}:{}});b(`pushed ${Object.keys(I).length} file(s) (${N} edited) \u2192 release ${L.releaseId} (task ${L.taskId}).
|
|
4393
4411
|
follow it with:
|
|
4394
|
-
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."),W(L,"releases:write","push a release"),v(`release push failed: ${L instanceof Error?L.message:String(L)}`)}}),jr.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(
|
|
4395
|
-
${
|
|
4396
|
-
`+m.dim(" pairs are discovered when a source is reconciled; nothing can be switched on until one is."));b(lt(
|
|
4397
|
-
`+m.dim(` ${E}: ${h.on?"on":"off"}`));b(`${
|
|
4398
|
-
`)),e&&void 0,t}function
|
|
4399
|
-
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return
|
|
4400
|
-
${e.add.length} to add, ${e.change.length} to change, ${e.destroy.length} to destroy.`+(e.add.length+e.change.length+e.destroy.length===0?" (no changes \u2014 up to date.)":""))}function
|
|
4412
|
+
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."),W(L,"releases:write","push a release"),v(`release push failed: ${L instanceof Error?L.message:String(L)}`)}}),jr.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R});if(h.follow){await Ba(()=>S.releaseStatus(c),`release ${c}`,h.intervalMs);return}let f;try{f=await S.releaseStatus(c)}catch(_){W(_,"releases:write","release status"),_ instanceof Y&&_.status===404&&v(`release ${c} not found.`),v(`release status failed: ${_ instanceof Error?_.message:String(_)}`)}b(`release ${c}: status=${f.releaseStatus??"?"} stage=${f.stage} ${f.percent}%`+(f.runStatus?` (${f.runStatus})`:"")),f.outputTail&&b(f.outputTail.replace(/\n+$/,""))}),jr.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R}),f;try{f=await S.releaseRollback(c)}catch(_){W(_,"releases:write","release rollback"),_ instanceof Y&&_.status===404&&v(`release ${c} not found.`),_ instanceof Y&&_.status===409&&v(`release ${c} cannot be rolled back (not live, or a newer release advanced past it).`),v(`release rollback failed: ${_ instanceof Error?_.message:String(_)}`)}b(`release ${f.releaseId} rolled back \u2192 status=${f.release?.status??"rolled_back"}.`)}),jr.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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await R.releaseList()}catch(f){W(f,"releases:write","release list"),v(`release list failed: ${f instanceof Error?f.message:String(f)}`)}if(S.length===0){b("no releases.");return}if(Oe())b(lt(S.map(f=>[f.id,Br(f.status),f.target,f.backend,f.solutionTitles?.length?f.solutionTitles.map(_=>`"${_}"`).join(", "):m.dim("\u2014")]),{head:["id","status","target","backend","delivered"]}));else for(let f of S){let _=f.solutionTitles?.length?` "${f.solutionTitles.join('", "')}"`:"";b(` ${f.id} ${f.status.padEnd(11)} target=${f.target} backend=${f.backend}${_}`)}b(`
|
|
4413
|
+
${S.length} release(s).`)});let xn=t.command("processes").description("See what processes are deployed, how they are triggered, and what they have done.");xn.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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w});try{let S=await R.processes();c.json?b(JSON.stringify(S,null,2)):Mp(S,b)}catch(S){v(`processes list failed: ${S instanceof Error?S.message:String(S)}`)}}),xn.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R});try{let f=await S.processRuns(c);h.json?b(JSON.stringify(f,null,2)):qp(c,f,b)}catch(f){v(`processes runs failed: ${f instanceof Error?f.message:String(f)}`)}}),xn.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(c,h)=>{let{baseUrl:w,token:R}=await F(h.baseUrl),S=new z({baseUrl:w,token:R});try{let f=await S.processRun(c);h.json?b(JSON.stringify(f,null,2)):ls(f,b)}catch(f){v(`processes run failed: ${f instanceof Error?f.message:String(f)}`)}}),xn.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(c,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 _,E=h.input!==void 0?"--input":"--input-file";if(h.input!==void 0)_=h.input;else try{_=await ie.readFile(ne(process.cwd(),h.inputFile),"utf8")}catch{v(`input file not found at ${h.inputFile}.`)}let A=Bp(_,E);A.ok||v(A.message),w=A.input}let{baseUrl:R,token:S}=await F(h.baseUrl),f=new z({baseUrl:R,token:S});try{let _=await f.invokeProcess(c,w,h.sync?"sync":"async");h.json?b(JSON.stringify(_,null,2)):Fp(_,c,Vr,b)}catch(_){_ instanceof Y&&_.status===403&&_.body?.reason==="admin_required"&&v("processes invoke forbidden (403) \u2014 the token's owner must be an administrator to start a process."),W(_,"extensions:deploy","processes invoke"),v(`processes invoke failed: ${_ instanceof Error?_.message:String(_)}`)}});let Qi=c=>{xn.command(c.name).description(c.description).argument("<run-id>",c.argument).option("--base-url <url>","Instance base URL (defaults to the active instance).").action(async(h,w)=>{let{baseUrl:R,token:S}=await F(w.baseUrl),f=new z({baseUrl:R,token:S});try{c.report(await c.call(f,h),h)}catch(_){v(`processes ${c.name} failed: ${_ instanceof Error?_.message:String(_)}`)}})};Qi({name:"cancel",description:"Stop one run \u2014 a queued run never executes, a running one stops at its next step.",argument:"The run to stop.",call:(c,h)=>c.cancelProcessRun(h),report:(c,h)=>{b(`cancelled ${c.runId??h} (${c.state??"cancelled"}).`),b("A run already going stops at its next step boundary; writes it has already made stay.")}}),Qi({name:"rollback",description:"Undo a finished run \u2014 delete, newest first, the records its ledger proves it created.",argument:"The finished run to roll back.",call:(c,h)=>c.rollbackProcessRun(h),report:(c,h)=>{if(!c.queued){b(`${c.runId??h} is already rolled back \u2014 nothing to do.`);return}b(`rollback queued for ${c.runId??h} (was ${c.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 ${c.runId??h}\`.`)}}),Qi({name:"resume",description:"Carry on a run that stopped waiting on the connected system \u2014 it writes nothing twice.",argument:"The stopped run to carry on.",call:(c,h)=>c.resumeProcessRun(h),report:(c,h)=>{b(`resume queued for ${c.runId??h} (now ${c.state??"running"}).`),b(`The same run carries on at the step it stopped on, so nothing it already wrote is written again \u2014 follow with \`turbobase processes run ${c.runId??h}\`.`)}}),t.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(c,h,w)=>{let{baseUrl:R,token:S}=await F(w.baseUrl),f=new z({baseUrl:R,token:S});try{let _=await f.settleRow(c,h);if(w.json){b(JSON.stringify(_,null,2));return}b(`linked ${c} ${_.pgRowId} to ${_.externalId}.`),_.discarded.length>0&&b(`discarded the inbound copy of the same record: ${_.discarded.join(", ")}.`)}catch(_){v(`data settle failed: ${_ instanceof Error?_.message:String(_)}`)}});let vu=t.command("relationships").description('List the linked record pairs on your instance and switch either "re-read" on or off.'),_u=c=>c===null?m.dim("off"):`${m.green("on")} ${m.dim(new Date(c).toISOString().replace("T"," ").replace(/:\d\d\.\d+Z$/," UTC"))}`,Gw=c=>[c.source_system,c.source_table,c.source_jsonb_key??m.dim("(none)"),c.target_table,_u(c.children_refresh_marked_at),_u(c.rollup_marked_at)],Jw=["SOURCE","LINE TABLE","LINK FIELD","PARENT","LINES","PARENT RE-READ"];return vu.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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S;try{S=await R.relationshipsList(c.source)}catch(f){W(f,"extensions:deploy","list relationships"),v(`relationships list failed: ${f instanceof Error?f.message:String(f)}`)}if(c.json)return b(JSON.stringify(S,null,2));if(S.length===0)return b(`no linked record pairs are declared on this instance yet.
|
|
4414
|
+
`+m.dim(" pairs are discovered when a source is reconciled; nothing can be switched on until one is."));b(lt(S.map(Gw),{head:Jw})),b(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."))}),vu.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(c,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:R,token:S}=await F(h.baseUrl),f=new z({baseUrl:R,token:S});try{let _=await f.relationshipRefresh(c,{marker:w,enabled:h.on===!0,...h.source?{source:h.source}:{}});if(h.json)return b(JSON.stringify(_,null,2));let E=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(!_.changed)return b(`${_.relation.alias} was already ${h.on?"on":"off"} \u2014 nothing changed.
|
|
4415
|
+
`+m.dim(` ${E}: ${h.on?"on":"off"}`));b(`${_.relation.alias}: ${h.on?m.green("on"):m.dim("off")} \u2014 ${E}.`),h.on&&b(m.dim(" this costs one source query per parent commit plus one re-read per line."))}catch(_){W(_,"extensions:deploy","change a relationship refresh"),v(`relationships refresh failed: ${_ instanceof Error?_.message:String(_)}`)}}),t.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 c=>{let{baseUrl:h,token:w}=await F(c.baseUrl),R=new z({baseUrl:h,token:w}),S=c.limit?Number(c.limit):void 0,f=c.intervalMs?Number(c.intervalMs):void 0;if(c.processRun){try{await zp(R,c.processRun,{...c.follow?{follow:!0}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(_){v(`logs --process-run failed: ${_ instanceof Error?_.message:String(_)}`)}return}if(c.conduit){try{await Np(R,c.conduit,{...c.follow?{follow:!0}:{},...S!==void 0?{limit:S}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(_){v(`logs --conduit failed: ${_ instanceof Error?_.message:String(_)}`)}return}if(c.extension){try{let _=await R.logs(c.extension,S);_.length===0&&b(`no logs for ${c.extension}.`);for(let E of _)b(` [${E.level}] ${E.ts??""} ${E.message}`)}catch(_){v(`logs --extension failed: ${_ instanceof Error?_.message:String(_)}`)}return}try{await jp(R,{...c.subsystem?{subsystem:c.subsystem}:{},...c.severity?{severity:c.severity}:{},...c.code?{code:c.code}:{},...c.since?{since:c.since}:{},...c.correlationId?{correlationId:c.correlationId}:{},...c.follow?{follow:!0}:{},...c.json?{json:!0}:{},...S!==void 0?{limit:S}:{},...f!==void 0?{intervalMs:f}:{},sink:b})}catch(_){v(`logs failed: ${_ instanceof Error?_.message:String(_)}`)}}),t.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 c=>{let{runAuthoringMcpServer:h}=await Promise.resolve().then(()=>(qw(),Mw));await h({baseUrl:c.baseUrl})}),t.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(`
|
|
4416
|
+
`)),e&&void 0,t}function mI(e,t,r){let n=o=>{let s=new RegExp(`${o}\\s*:\\s*(['"\`])([^'"\`]+)\\1`).exec(e);return s?s[2]:void 0};return{id:n("id")??`marketplace:${t}`,recordType:n("recordType")??"*",event:n("event")??"before_save",source:n("source")??"standalone",sourceCode:e,extensionKind:r||"hook"}}async function fI(e){let t=nt(ne(process.cwd(),e),"public","turbobase.json"),r=await ie.readFile(t,"utf8").catch(()=>null);if(r===null)return null;let n;try{n=JSON.parse(r)}catch(o){v(`${t} is not valid JSON: ${o instanceof Error?o.message:String(o)}`)}return(typeof n!="object"||n===null||Array.isArray(n))&&v(`${t} must be a JSON object.`),{manifest:n,manifestPath:t}}async function gI(){let e=ne(process.cwd(),us,Ln),t;try{t=await ie.readFile(e,"utf8")}catch{v(`no config found \u2014 this project authors none (no ${hs}/, ${ms}/, ${Qt} or ${er}) and there is no ${us}/${Ln}.
|
|
4417
|
+
Author a hook with \`turbobase ext new hook\`, or adopt an existing instance with \`turbobase ext export\`.`)}try{return dh(t)}catch(r){v(`bundle is invalid: ${r instanceof Error?r.message:String(r)}`)}}async function uu(){let e=process.cwd();if(!await fh(e))return gI();let t;try{t=await gh(e,{inline:Sa})}catch(r){v(`could not build the config bundle from this project: ${r instanceof Error?r.message:String(r)}`)}for(let r of t.unparsed)O(`${r.file}: ${r.reason} \u2014 NOT included in the plan.`);return t.unparsed.length>0&&v(`${t.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.`),t.manifest}function yI(e,t){b(`plan against ${t}:`);for(let r of e.add)b(` ${Xt.add(`${r.kind} ${r.id}`)}`);for(let r of e.change)b(` ${Xt.change(`${r.kind} ${r.id}`)}`);for(let r of e.destroy)b(` ${Xt.destroy(`${r.kind} ${r.id}`)}`);b(`
|
|
4418
|
+
${e.add.length} to add, ${e.change.length} to change, ${e.destroy.length} to destroy.`+(e.add.length+e.change.length+e.destroy.length===0?" (no changes \u2014 up to date.)":""))}function bI(e){try{let r=new URL(e).hostname.split(".")[0];return r&&r!=="localhost"?r:void 0}catch{return}}function No(e,t,r){return new Promise(n=>{let o=fu(e,t,{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 pu(){let e=process.env.SANDBOX_LOCAL_DATABASE_URL??"postgres://postgres:postgres@127.0.0.1:54322/postgres",t=async(r,n)=>{let o=n?e.replace(/\/[^/]*$/,`/${n}`):e,s=await No("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:()=>e,createDatabase:async r=>{await t(`CREATE DATABASE ${r};`)},replayMigrations:async r=>{let n=e.replace(/\/[^/]*$/,`/${r}`),o=await No("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 t(`INSERT INTO turbobase.${n} (${s.join(", ")}) VALUES ${i};`,r)},dropDatabase:async r=>{await t(`DROP DATABASE IF EXISTS ${r} WITH (FORCE);`)}}}async function wI(e){let t=ne(e,"src"),r={},n=async o=>{let s;try{s=await ie.readdir(o,{withFileTypes:!0})}catch{return}for(let i of s){let a=nt(o,i.name);if(i.isDirectory())await n(a);else if(i.isFile()){let l=Xi(t,a).split(mu).join("/");r[l]=await ie.readFile(a,"utf8")}}};return await n(t),r}function hu(e){return new Promise(t=>{let r=fu("git",e,{stdio:["ignore","pipe","ignore"]}),n="";r.stdout?.on("data",o=>{n+=o.toString()}),r.on("error",()=>t(null)),r.on("exit",o=>t(o===0&&n.trim()?n.trim():null))})}var vI=!1;vI&&gu().parseAsync(process.argv).catch(e=>v(e instanceof Error?e.message:String(e)));gu().parseAsync(process.argv).catch(e=>{process.stderr.write(`turbobase: ${e instanceof Error?e.message:String(e)}
|
|
4401
4419
|
`),process.exit(1)});
|