@adhd/backlog 1.0.0 → 1.0.2

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/index.js CHANGED
@@ -1,362 +1,50 @@
1
1
  #!/usr/bin/env node
2
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const J=require("node:fs"),mt=require("node:os"),L=require("node:path"),$s=require("node:url"),Lg=require("@adhd/sox-telemetry"),Ne=require("node:module"),pt=require("pino"),ia=require("ajv"),aa=require("ajv-formats"),pn=require("@adhd/sox-store-adapter"),tE=require("@adhd/sox-graph-store"),kn=require("node:crypto"),sl=require("node:fs/promises"),nE=require("fastify"),mp=require("node:http"),rE=require("@modelcontextprotocol/sdk/server/index.js"),oE=require("@modelcontextprotocol/sdk/server/stdio.js"),sE=require("@modelcontextprotocol/sdk/server/sse.js"),iE=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),gp=require("@modelcontextprotocol/sdk/types.js"),aE=require("@adhd/sox-hybrid-search");var D=typeof document<"u"?document.currentScript:null;function Dg(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const n in t)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:()=>t[n]})}}return e.default=t,Object.freeze(e)}const Ic=Dg(L),or=Dg(sl),Pc="$apigen";let yp=class extends Error{constructor(e){super(e),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function cE(t){const e=new Map;return{register(n,r){if(e.has(n.id)&&!(r!=null&&r.override))throw new yp(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);e.set(n.id,n)},resolve(n){for(const r of e.values())if(r.matches(n))return r},get(n){return e.get(n)},ids(){return[...e.keys()]},freeze(){const n=new Map(e),r={register(){throw new yp("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const il="x-apigen-logical",al="x-apigen-codec",xc="x-apigen-ctor",Rc="x-apigen-tojson",uE="0.1.0";function wp(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...e}}function xr(t,e,n){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return xr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=Ug(t,s,e,n);return xr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return Mo(t,e,n);const a=e.items;if(!a)return t.map(u=>sr(u));const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?sr(u):xr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>xr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return Mo(t,e,n);const a=e.properties;if(!a)return sr(t);const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=xr(f,d,{...n,path:`${c}/${l}`}))}return u}return i==null?Mo(t,e,n):sr(t)}function Rr(t,e,n){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Rr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=Ug(t,s,e,n);return Rr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?u:Rr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Rr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Rr(f,d,{...n,path:`${c}/${l}`}))}for(const[l,d]of Object.entries(t))!(l in a)&&d!==void 0&&(u[l]=d);return u}return i==null?Tc(t,n):t}function Ug(t,e,n,r){var o;const s=n.discriminator;if(s!=null&&s.propertyName){const u=s.propertyName,l=t!==null&&typeof t=="object"?t[u]:void 0;if(typeof l=="string"){if(s.mapping){const d=s.mapping[l];if(d){const f=e.find(g=>g.$ref===d);if(f)return f}}for(const d of e){const f=(o=Mi(d,r).properties)==null?void 0:o[u];if(!f)continue;const g=f.enum;if(f.const===l||Array.isArray(g)&&g.includes(l))return d}}}const i=lE(t,e,r);if(i)return i;let a,c=-1;for(const u of e){const l=Mi(u,r),d=Bg(t,l,r);d!==null&&d>c&&(c=d,a=u)}return a!==void 0?a:e[0]??{}}function Mi(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function vp(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function lE(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t,o=e.map(i=>Mi(i,n)),s=new Set;for(const i of o){const a=i.properties;if(a)for(const[c,u]of Object.entries(a))vp(u)!==void 0&&s.add(c)}for(const i of s){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[i];return p?vp(p):void 0}),c=a.filter(f=>f!==void 0),u=new Set(c);if(c.length<2||u.size!==c.length)continue;const l=r[i];if(l===void 0)continue;const d=a.findIndex(f=>f===l);if(d!==-1)return e[d]}}function dE(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function Bg(t,e,n){const r=e.oneOf;if(Array.isArray(r)){let l=null;for(const d of r){const f=Bg(t,Mi(d,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,s=dE(t);if(typeof o=="string"){if(!(o===s||o==="number"&&s==="integer"))return null}else if(Array.isArray(o)&&!o.some(l=>l===s||l==="number"&&s==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const i=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(i[l]===void 0)return null;c+=2}}const u=e.properties;if(u){for(const l of Object.keys(u))i[l]!==void 0&&(c+=1);for(const l of Object.keys(i))u[l]===void 0&&(c-=1)}return c}function Mo(t,e,n){var r;for(const o of n.registry.ids()){const s=n.registry.get(o);if((r=s==null?void 0:s.ownsValue)!=null&&r.call(s,t))return{[Pc]:o,v:s.encode(t,s.schema,n)}}if(Array.isArray(t))return t.map(o=>Mo(o,{},n));if(Fg(t)){const o={};for(const[s,i]of Object.entries(t))i!==void 0&&(o[s]=Mo(i,{},n));return o}return sr(t)}function Fg(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Tc(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&Pc in t){const n=t,r=n[Pc],o=e.registry.get(r);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>Tc(n,e));if(Fg(t)){const n={};for(const[r,o]of Object.entries(t))n[r]=Tc(o,e);return n}return t}function sr(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(sr);if(typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=sr(r));return e}return null}function fE(t){return{encode(e,n,r){const o=wp(t,r);return xr(e,n,o)},decode(e,n,r){const o=wp(t,r);return Rr(e,n,o)}}}const cl={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},ul={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}},ll={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},dl={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},pE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,fl={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!pE.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},Cc="NaN",Mc="Infinity",Lc="-Infinity",hE=new Set([Cc,Mc,Lc]),pl={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?Cc:t===1/0?Mc:t===-1/0?Lc:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===Cc)return NaN;if(t===Mc)return 1/0;if(t===Lc)return-1/0;const r=Number(t);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...hE].join(", ")}.`);return NaN}},mE=[cl,ul,ll,dl,fl,pl];function gE(t,e={}){for(const n of mE)t.register(n,{override:e.override??!1})}const yE=12;function wE(t,e){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(t);if(!n)return;const[,r,o]=n,s=r==="$defs"?e.$defs:e.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function $p(t){return Array.isArray(t)&&t.length>0?t[0]:void 0}function vE(t){if(Array.isArray(t.type))return t.type.find(e=>e!=="null")??t.type[0];if(typeof t.type=="string")return t.type;if(t.properties)return"object"}function $E(t){switch(t.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function bp(t,e,n){const r=t.properties??{},o=t.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?ns(a,e,n+1):`<${i}>`}return s}function bE(t,e,n){const r=Array.isArray(t.items)?t.items[0]:t.items;return r?[ns(r,e,n+1)]:[]}function ns(t,e=t??{},n=0){if(!t||n>yE)return null;if(typeof t.$ref=="string"){const o=wE(t.$ref,e);return o!==void 0?ns(o,e,n+1):null}if(t.const!==void 0)return t.const;if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum[0];if(Array.isArray(t.allOf)&&t.allOf.length>0){const o={},s=[];for(const i of t.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return bp({...t,properties:o,required:s},e,n)}const r=$p(t.oneOf)??$p(t.anyOf);if(r)return ns(r,e,n+1);switch(vE(t)){case"object":return bp(t,e,n);case"array":return bE(t,e,n);case"string":return $E(t);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function EE(t){if(!t)return;const e=ns(t);return`Example: ${JSON.stringify(e)}`}cl.id,ul.id,ll.id,dl.id,fl.id,pl.id;const qg=cE();gE(qg);const Kg=fE(qg.freeze());function Vg(t,e){var n;const r=((n=t.input)==null?void 0:n.properties)??{};return e in r}function Dc(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function SE(t,e){var n,r,o;const s=(o=(r=(n=t.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[e];return i!==void 0?i:void 0}function _E(t,e){return e===void 0||t===void 0?t:Kg.decode(t,e)}function Ja(t,e){const n=e.output;return!n||Object.keys(n).length===0?t:Kg.encode(t,n)}async function NE(t,e,n,r,o,s){const i=Dc(n).map(c=>_E(s[c],SE(n,c)));if(Vg(n,"session")&&e){const c=await e({session:o.session}),u=await t[r](c,...i);return Ja(u,n)}if(n.hasCtx){const c=e?await e(o):void 0,u=await t[r](c,...i);return Ja(u,n)}const a=await t[r](...i);return Ja(a,n)}let Gg=class{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};function OE(t=[]){return async function(e,n,r){const o=r.schemas[e];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${e}"`);const s=()=>NE(r.fns,r.createClient,o,e,n.envelope,n.domainArgs);return t.reduceRight((i,a)=>()=>a(n,i),s)()}}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const kE={"decimal.js":"Decimal"};function jE(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(kE).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${jE(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function AE(t={}){const e=t.level??"info",n=typeof t.destination=="string"&&t.destination.length>0,r=!n&&!!process.stderr.isTTY,o=t.format??(r?"pretty":"json"),s={level:e};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:t.destination,mkdir:!0}:{destination:2}}},pt(s);const i=n?pt.destination({dest:t.destination,mkdir:!0,sync:!0}):pt.destination(2);return pt(s,i)}function IE(t){if(!t||t.type!=="object"||!t.properties)return;const e=Object.entries(t.properties);if(e.length===0)return;const n=new Set(t.required??[]);return`{ ${e.map(([r,o])=>`${r}${n.has(r)?"":"?"}: ${ca(o)}`).join(", ")} }`}function PE(t){return typeof t=="string"?`'${t}'`:JSON.stringify(t)}function xE(t){const e=t.enum??[];return e.length===0?"unknown":e.map(PE).join("|")}function RE(t,e){return t.map(n=>ca(n,e)).join(" | ")}function ca(t,e=0){if(!t)return"unknown";if(t.type==="array")return`${ca(t.items,0)}[]`;if(t.enum)return xE(t);if(t.$ref)return String(t.$ref).split("/").pop()||"object";const n=t.anyOf??t.oneOf;return n?n.length===0?"unknown":e>=2?RE(n,e-1):"union":e>=1&&t.type==="object"?IE(t)??"object":t.type??"object"}function TE(t){var e;const n=(e=((t==null?void 0:t.input)??{}).properties)==null?void 0:e.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:ca(c,2),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let CE=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};const ua=new ia({allErrors:!0});aa(ua);for(const t of[il,al,xc,Rc,"discriminator"])ua.addKeyword({keyword:t,valid:!0});ua.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function ME(t){return t.map(e=>`${e.instancePath||"(root)"} ${e.message??"failed schema check"}`).join("; ")}function LE(t,e){const n=EE(e),r=[`Validation failed: ${ME(t)}`];return n&&r.push(n),r.join(" — ")}function DE(t){return async function(e,n){const r=e.operation.id,o=t[r];if(o===void 0)return n();const s={data:e.domainArgs,...e.envelope},i=ua.compile(o.input);if(!i(s)){const a=i.errors??[];throw new CE("invalid_argument",LE(a,o.input),a)}return n()}}function UE(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}let qn=class extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}};function Qa(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function zg(t,e){const n=t[al];if(typeof n=="string"){const r=e.registry.get(n);if(r)return r}return e.registry.resolve(t)}function BE(t,e,n){const r=zg(e,n);return r?r.encode(t,e,n):t}function FE(t,e,n){const r=zg(e,n);return r?r.decode(t,e,n):t}function qE(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(r){if(r[il]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Qa(r)!==void 0},encode(r,o,s){const i=Qa(o);if(!i)throw new qn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new qn("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),d=c[l];if(!d)throw new qn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=s.resolve(d);return BE(r,f,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new qn("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${p}.`)}const i=r,a=Qa(o);if(!a)throw new qn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new qn("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const d=String(l),f=u[d];if(!f)throw new qn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${d}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const g=s.resolve(f);return FE(r,g,{...s,path:`${s.path}[${d}]`})}}}const KE="x-apigen-instances";let Rs=class extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}};function Ep(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function VE(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function Sp(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n)}return t}function GE(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n)}return t}function zE(t){const{id:e,schema:n,ctor:r}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[il]==="nominal"?!0:o[al]===e},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Rs("E_NOMINAL_CYCLE",`[${e}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Ep(s),c=typeof s[Rc]=="string"?s[Rc]:"toJSON",u=o[c];if(typeof u=="function"){const p=u.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[w,h]of Object.entries(p))y[w]=Sp(h,a[w],{...i,path:`${i.path}/${w}`});return y}return p}const l={},d=Object.keys(a),f=o,g=d.length>0?d:Object.keys(f);for(const p of g){const y=f[p];y!==void 0&&(l[p]=Sp(y,a[p],{...i,path:`${i.path}/${p}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Rs("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of VE(s))if(!(l in a))throw new Rs("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${i.path}".`);if(s[KE]===!1)throw new Rs("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Ep(s),u={};for(const[l,d]of Object.entries(a))u[l]=GE(d,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[xc]=="string"?s[xc]:"fromJSON",d=r[l];if(typeof d=="function")return d.call(r,u);const f=r;return new f(u)}return u}}}const WE=[cl,ul,ll,dl,fl,pl],HE={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},_p=zE({id:"ts.NominalSentinel",schema:HE}),JE={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Np=qE({id:"ts.UnionSentinel",schema:JE});function QE(){const t=[...WE.map(e=>[e.id,e]),[_p.id,_p],[Np.id,Np]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:uE,codecs:QE()});Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const Op=new Set(["string","number","boolean","integer"]);function YE(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Op.has(n):Array.isArray(n)?n.every(r=>Op.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function ZE(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(YE)}const XE={"decimal.js":"Decimal"};function eS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(XE).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${eS(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function kp(t){return t.words.join("-")}function jp(t){return t.words.map(sS).join("")}function Ap(t){return t.words.join("_")}function tS(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||ZE(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>kp(g)).join("/"),c=o.map(g=>Ap(g)).join("_"),u=o.map(g=>Ap(g)).slice(0,-1).join("."),l=jp(o[o.length-2]??o[0]),d=jp(o[o.length-1]),f=o.map(g=>kp(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function nS(t,e){return`x-${t}-${e}`}function rS(t,e){return`--${t}-${e}`}function oS(t,e){const n=r=>r.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function sS(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function hl(t){return t.anyOf??t.oneOf}function iS(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=hl(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function aS(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=hl(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function cS(t){if(!t)return!1;if(t.type==="number"||t.type==="integer")return!0;const e=hl(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function uS(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function lS(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Ip(t){return typeof t.handler=="function"}function dS(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=nS(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:rS(i,s),envVar:oS(i,s)})}return o}function fS(t,e,n,r){e===n||t.has(e)||t.set(e,{...r,aliasOf:n})}function pS(t,e){const n=new Map,{props:r}=lS(t);for(const[o,s]of Object.entries(r)){let i="string";aS(s)?i="boolean":(iS(s)||cS(s))&&(i="json");const a=uS(o),c={camelKey:o,kind:"domain",valueKind:i};n.set(a,c),fS(n,o,a,c)}for(const o of e){const s=o.cliFlag.replace(/^--/,""),i={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(s,i)}return n}function Wg(t){const{op:e,schema:n,transport:r,projection:o}=t,s=tS(e,o),i=n?dS(n):[],a=n?pS(n,i):new Map,c=n?TE(n).params:void 0,u={op:e,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:e.streaming,isMount:Ip(e)};if(Ip(e)){const l=e.handler;u.mountHandler=async d=>l(d)}return u}function hS(t){const e=t.usePlugins;return Array.isArray(e)?e:[]}function mS(t){const e=t.exitCode;return typeof e=="function"?e:void 0}function gS(t){const e=t.useOptions;return e&&typeof e=="object"?e:{}}function yS(t){return async function(e,n){const r=Object.assign(e,{data:e.domainArgs});return await t.layer(r,n)}}function Ya(t,e){var n;const r=[];for(const o of e){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(yS(s))}return r.push(DE(t)),OE(r)}function wS(){const t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}const vS={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Pp(t,e,n,r){const o={...n,operation:{id:t.op.id},ctx:new Gg};if(t.isMount){const s=t.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${t.op.id}" has isMount=true but no mountHandler`);const i={operation:t.op,data:n.domainArgs,envelope:n.envelope,ctx:wS(),transport:t.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[t.op.id]:()=>s(i)},schemas:{[t.op.id]:vS}};return e(t.op.id,o,a)}return e(t.op.id,o,r)}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const $S={"decimal.js":"Decimal"};function bS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries($S).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${bS(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function ES(t,e){return`--${t}-${e}`}function SS(t,e){const n=r=>r.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function Uc(t){let e=t.replace(/[^a-zA-Z0-9_$]/g,"_");return(e===""||/^[0-9]/.test(e))&&(e=`_${e}`),e}const _S=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],xp={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};let Li=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function Bc(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&_S.includes(t.code)&&typeof t.toJSON=="function"}function Hg(t){return t.anyOf??t.oneOf}function NS(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd";o.push({field:s,pluginId:i,flag:ES(i,s),envVar:SS(i,s)})}return o}function Fc(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=Hg(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function OS(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=Hg(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Rp(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function kS(t){const e=/^#\/oneOf\/(\d+)$/.exec(t);if(e)return Number(e[1])}function jS(t){const e=ml(t).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return e.length>0?e.toLowerCase():"branch"}function Za(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data;if(!r)return;const o=r.oneOf,s=r.discriminator;if(!o||!s)return;const i=[];for(const[a,c]of Object.entries(s.mapping)){const u=kS(c);if(u===void 0)continue;const l=o[u];if(!l)continue;const d=l.properties??{},f=l.required??[];i.push({value:a,commandName:jS(a),props:d,required:f})}if(i.length!==0)return{discriminatorProperty:s.propertyName,branches:i}}function ml(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function AS(t,e){if(!Ic.isAbsolute(e))return e;const n=Ic.relative(t,e);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const IS=["function __apigenParseJsonArg(flag: string, raw: unknown): unknown {"," if (raw === undefined) return undefined"," if (typeof raw !== 'string') return raw"," try {"," return JSON.parse(raw)"," } catch (err) {"," throw new Error(`Invalid JSON for --${flag}: ${(err as Error).message}`)"," }","}"].join(`
3
- `);function Jg(t,e,n){for(const r of e){const o=r.flag.replace(/^--/,"");t.push(` .option('${r.flag} <${o}>', '${r.field} (env: ${r.envVar})')`)}n&&!e.some(r=>r.field==="session")&&t.push(" .option('--session <key>', 'Session key')")}function Qg(t,e,n,r){var o;for(const s of e){const i=ml(s),a=OS(n[s]),c=r.includes(s);a?(t.push(` .option('--${i}')`),((o=n[s])==null?void 0:o.default)===!0&&t.push(` .option('--no-${i}')`)):c?t.push(` .requiredOption('--${i} <${i}>')`):t.push(` .option('--${i} <${i}>')`)}}function Yg(t,e,n){return`${t}:${e}::${n}`}function Zg(t,e){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,paramNames:a,schemaProps:c,literalDomainArgs:u}=e,l=e.dispatchSchemaKey??`${r}:${o}`;t.push(" .action(async (opts: Record<string, unknown>) => {");const d=Object.entries(u??{}).map(([g,p])=>`'${g}': ${p}`),f=a.map(g=>Fc(c[g])?`'${g}': __apigenParseJsonArg('${ml(g)}', opts['${g}'])`:`'${g}': opts['${g}']`);if(t.push(` const domainArgs: Record<string, unknown> = { ${[...d,...f].join(", ")} }`),s.length>0){const g=s.map(p=>{const y=p.flag.replace(/^--/,"").replace(/-([a-z])/g,(w,h)=>h.toUpperCase());return`'${p.field}': opts['${y}'] ?? process.env['${p.envVar}']`});t.push(` const envelope: Record<string, unknown> = { ${g.join(", ")} }`)}else i?t.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):t.push(" const envelope: Record<string, unknown> = {}");t.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),t.push(" console.log(JSON.stringify(result))"),t.push(" })")}function PS(t,e){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,rootUnion:a}=e,c=Uc(`${r}_${o}_cmd`);t.push(`const ${c} = program.command('${o}')`);for(const u of a.branches){const l=Object.keys(u.props).filter(f=>f!==a.discriminatorProperty),d=u.required.filter(f=>f!==a.discriminatorProperty);t.push(`${c}`),t.push(` .command('${u.commandName}')`),Jg(t,s,i),Qg(t,l,u.props,d),Zg(t,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:Yg(r,o,u.commandName),bindings:s,needsSession:i,paramNames:l,schemaProps:u.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(u.value)}})}}function xS(t){const e=t.options.name??"cli",n=t.options.version??"0.1.0",r=t.packages.some(i=>Object.values(i.schemas).some(a=>{const c=Za(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(d=>d!==c.discriminatorProperty).some(d=>Fc(l.props[d])));const{props:u}=Rp(a);return Dc(a).some(l=>Fc(u[l]))})),o=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const i of t.packages){const a=Uc(i.id),c=AS(t.outputDir,i.importPath);o.push(`import * as ${a}_ns from '${c}'`),o.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}o.push(""),r&&(o.push(IS),o.push(""));const s=Object.fromEntries(t.packages.flatMap(i=>Object.entries(i.schemas).map(([a,c])=>[`${i.id}:${a}`,c])));for(const i of t.packages)for(const[a,c]of Object.entries(i.schemas)){const u=Za(c);if(u)for(const l of u.branches){const d=Yg(i.id,a,l.commandName);s[d]={input:{type:"object",properties:{data:{type:"object",properties:l.props,additionalProperties:!1,...l.required.length>0?{required:l.required}:{}}},required:["data"]},output:{},...c.hasCtx?{hasCtx:!0}:{}}}}o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(s,null,2)}`),o.push(""),o.push(`const program = new Command().name('${e}').version('${n}')`),o.push("");for(const i of t.packages){const a=Uc(i.id);for(const[c,u]of Object.entries(i.schemas)){const l=Vg(u,"session"),d=NS(u),f=Za(u);if(f){PS(o,{varName:a,pkgId:i.id,fnName:c,bindings:d,needsSession:l,rootUnion:f});continue}const g=Dc(u),{props:p,required:y}=Rp(u);o.push("program"),o.push(` .command('${c}')`),Jg(o,d,l),Qg(o,g,p,y),Zg(o,{varName:a,pkgId:i.id,fnName:c,bindings:d,needsSession:l,paramNames:g,schemaProps:p})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
4
- `)}]}}function RS(t){return{props:t.properties??{},required:t.required??[]}}function TS(t){const e=t??{},n=Array.isArray(e.oneOf)&&e.oneOf.length>0?e.oneOf:[e],r={},o=new Map;for(const i of n){const{props:a,required:c}=RS(i);for(const[u,l]of Object.entries(a))u in r||(r[u]=l);for(const u of c)o.set(u,(o.get(u)??0)+1)}const s=[...o.entries()].filter(([,i])=>i===n.length).map(([i])=>i);return{input:{type:"object",properties:{data:{type:"object",properties:r,required:s}},required:["data"]},output:{}}}function CS(t){const e=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(t);)e.push(r[1]??r[2]??r[3]);return e}function MS(t){const e=t.argv;return Array.isArray(e)?e.map(String):typeof e=="string"?CS(e):process.argv.slice(2)}function LS(t,e){return{id:t,host:"ts",namespace:{raw:t,words:[t]},path:[],kind:"action",async:!1,streaming:!1,safe:e["x-apigen-safe"]??!1,input:e.input??{},output:e.output??{},envelope:{},typeText:null}}function DS(t){const e=new Map;for(const r of t.operations??[]){const o=r.path[r.path.length-1];o&&e.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of t.packages)for(const[o,s]of Object.entries(r.schemas)){const i=e.get(`${r.id}:${o}`)??LS(o,s),a=Wg({op:i,schema:s,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:r.id,fnName:o,schema:s,cliPath:c,plan:a})}return n}function US(t,e){let n=0;for(;n<t.length&&!t[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=e.get(t.slice(0,r).join(" "));if(o)return{entry:o,rest:t.slice(r)}}return null}function Xg(t){return!t||t.length===0?"":t.map(e=>`${e.name}${e.required?"":"?"}: ${e.type}`).join(", ")}function Tp(t){const e=["Available commands:",""],n=[...t.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const s=Xg(o.params);e.push(` ${r}${s?` { ${s} }`:""}`)}return e.join(`
5
- `)}function Ts(t){return new Li("invalid_argument",t)}function BS(t,e){var n;const r={},o={};let s=0;for(;s<t.length;){const i=t[s];if(!i.startsWith("--"))throw Ts(`Unexpected positional argument: "${i}"`);let a=i.slice(2),c;const u=a.indexOf("=");u!==-1&&(c=a.slice(u+1),a=a.slice(0,u));let l=!1,d=a;a.startsWith("no-")&&((n=e.get(a.slice(3)))==null?void 0:n.valueKind)==="boolean"&&(l=!0,d=a.slice(3));const f=e.get(d);if(!f)throw Ts(`Unknown option: --${a}. Available: ${[...e.entries()].filter(([,p])=>p.aliasOf===void 0).map(([p])=>p).sort().map(p=>`--${p}`).join(", ")}`);s++;let g;if(f.valueKind==="boolean")l?g=!1:c===void 0?g=!0:g=c!=="false";else{const p=c!==void 0?c:t[s++];if(p===void 0)throw Ts(`Missing value for --${a}`);if(f.valueKind==="json")try{g=JSON.parse(p)}catch(y){throw Ts(`Invalid JSON for --${a}: ${y.message}`)}else g=p}f.kind==="domain"?r[f.camelKey]=g:o[f.camelKey]=g}for(const i of e.values()){if(i.kind!=="envelope"||!i.envVar||o[i.camelKey]!==void 0)continue;const a=process.env[i.envVar];a!==void 0&&(o[i.camelKey]=a)}return{domainArgs:r,envelope:o}}function ey(t){const e=Bc(t)?t.toJSON():{code:"internal",message:t instanceof Error?t.message:String(t)};console.error(JSON.stringify(e)),process.exitCode=Bc(t)?xp[t.code]:xp.internal}function FS(t,e,n){if(Bc(n)&&n.code!=="internal"){t.error({command:e,code:n.code,message:n.message},`✗ ${e}`);return}t.error({command:e,err:n},`✗ ${e}`)}let qS=class{constructor(e,n){this.signal=e,this.exitCodeHook=n,this.routes=new Map}registerRoute(e,n){this.routes.set(e.cli.path.join(" "),{plan:e,dispatch:n})}routeTable(){return this.routes}readCall(e,n){const{domainArgs:r,envelope:o}=BS(e.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(e,n,r){var o;if(UE(n))throw new Li("invalid_argument",`Command "${r.cli.path.join(" ")}" produced a streaming result, which is not supported over the cli transport.`);console.log(JSON.stringify(n===void 0?null:n));const s=(o=this.exitCodeHook)==null?void 0:o.call(this,n);typeof s=="number"&&s!==0&&(process.exitCode=s)}writeError(e,n,r){ey(n)}};function KS(t,e,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of t){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,e[c.id],o);for(const d of l)d.transports&&!d.transports.includes("cli")||i.push(d)}return i}async function VS(t){var e,n,r;const o=t.logger??AE();if((e=t.signal)!=null&&e.aborted){o.info("cli run: signal already aborted before dispatch — skipping");return}let s=MS(t.options);s[0]==="--"&&(s=s.slice(1));const i=hS(t.options),a=gS(t.options),c=new qS(t.signal,mS(t.options)),u=DS(t),l=new Map;for(const C of u.values()){const G=l.get(C.pkgId);G?G.push(C):l.set(C.pkgId,[C])}const d={},f={};for(const C of t.packages){const G=l.get(C.id);if(!G||G.length===0)continue;if(!C.fns)throw new Error(`apigen-plugin-cli-output: package "${C.id}" has no functions`);const H=C.fns,Z={},ue={};for(const pe of G)Z[pe.plan.op.id]=pe.schema,ue[pe.plan.op.id]=H[pe.fnName],d[pe.plan.op.id]=pe.schema,f[pe.plan.op.id]=H[pe.fnName];const fe=Ya(Z,i),he={fns:ue,createClient:C.createClient,schemas:Z};for(const pe of G)c.registerRoute(pe.plan,Oe=>Pp(pe.plan,fe,Oe,he))}const g=((n=t.packages[0])==null?void 0:n.id)??"ts",p=Ya(d,i),y={invoke:(C,G,H)=>p(C,{operation:{id:C},ctx:new Gg,domainArgs:G.domainArgs,envelope:G.envelope,signal:G.signal},H),invokeOptions:{fns:f,schemas:d,createClient:(r=t.packages[0])==null?void 0:r.createClient}},w=KS(i,a,g,t.operations??[],y);if(w.length>0){const C=Ya({},i),G={fns:{},schemas:{}};for(const H of w){const Z=Wg({op:H,schema:TS(H.input),transport:"cli"});c.registerRoute(Z,ue=>Pp(Z,C,ue,G))}}const h=c.routeTable();if(s.length===0||s[0]==="--help"||s[0]==="-h"){console.log(Tp(h));return}const v=US(s,h);if(!v){ey(new Li("not_found",`Unknown command: ${s.join(" ")}
2
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O=require("node:fs"),W=require("node:os"),k=require("node:path"),et=require("node:url"),Mn=require("@adhd/sox-telemetry"),st=require("pino"),Zr=require("ajv"),ka=require("ajv-formats"),pe=require("@adhd/sox-store-adapter"),Aa=require("@adhd/sox-graph-store"),Ct=require("node:fs/promises"),ue=require("node:crypto"),ja=require("fastify"),To=require("node:http"),_a=require("@modelcontextprotocol/sdk/server/index.js"),Na=require("@modelcontextprotocol/sdk/server/stdio.js"),Oa=require("@modelcontextprotocol/sdk/server/sse.js"),Ra=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),$o=require("@modelcontextprotocol/sdk/types.js"),Ia=require("@adhd/sox-hybrid-search"),Fn=require("node:module"),Ta=require("yaml");var $=typeof document<"u"?document.currentScript:null;function ei(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const n in e)if(n!=="default"){const r=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(t,n,r.get?r:{enumerable:!0,get:()=>e[n]})}}return t.default=e,Object.freeze(t)}const cn=ei(k),ge=ei(Ct),dn="$apigen";class Co extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function $a(e){const t=new Map;return{register(r,o){if(t.has(r.id)&&!(o!=null&&o.override))throw new Co(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const o of t.values())if(o.matches(r))return o},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),o={register(){throw new Co("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(i){for(const s of r.values())if(s.matches(i))return s},get(i){return r.get(i)},ids(){return[...r.keys()]},freeze(){return o}};return o}}}const Ae="x-apigen-logical",Bn="x-apigen-codec",ln="x-apigen-ctor",un="x-apigen-tojson",Ca="0.1.0";function Po(e,t){return{registry:e,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...t}}function Re(e,t,n){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Re(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=ti(e,i,t,n);return Re(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return Ve(e,t,n);const a=t.items;if(!a)return e.map(d=>Ee(d));const c=n.path;return Array.isArray(a)?e.map((d,l)=>{const u=a[l];return u===void 0?Ee(d):Re(d,u,{...n,path:`${c}/${l}`})}):e.map((d,l)=>Re(d,a,{...n,path:`${c}/${l}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Ve(e,t,n);const a=t.properties;if(!a)return Ee(e);const c=n.path,d={};for(const[l,u]of Object.entries(a)){const f=e[l];f!==void 0&&(d[l]=Re(f,u,{...n,path:`${c}/${l}`}))}return d}return s==null?Ve(e,t,n):Ee(e)}function Ie(e,t,n){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n);const o=t.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ie(e,a,n)}const i=t.oneOf;if(Array.isArray(i)){const a=ti(e,i,t,n);return Ie(e,a,n)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const c=n.path;return Array.isArray(a)?e.map((d,l)=>{const u=a[l];return u===void 0?d:Ie(d,u,{...n,path:`${c}/${l}`})}):e.map((d,l)=>Ie(d,a,{...n,path:`${c}/${l}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,d={};for(const[l,u]of Object.entries(a)){const f=e[l];f!==void 0&&(d[l]=Ie(f,u,{...n,path:`${c}/${l}`}))}for(const[l,u]of Object.entries(e))!(l in a)&&u!==void 0&&(d[l]=u);return d}return s==null?fn(e,n):e}function ti(e,t,n,r){var c;const o=n.discriminator;if(o!=null&&o.propertyName){const d=o.propertyName,l=e!==null&&typeof e=="object"?e[d]:void 0;if(typeof l=="string"){if(o.mapping){const u=o.mapping[l];if(u){const f=t.find(g=>g.$ref===u);if(f)return f}}for(const u of t){const g=(c=kt(u,r).properties)==null?void 0:c[d];if(!g)continue;const p=g.enum;if(g.const===l||Array.isArray(p)&&p.includes(l))return u}}}const i=Pa(e,t,r);if(i)return i;let s,a=-1;for(const d of t){const l=kt(d,r),u=qn(e,l,r);u!==null&&u>a&&(a=u,s=d)}return s!==void 0?s:t[0]??{}}function kt(e,t){const n=e.$ref;return typeof n=="string"?t.resolve(n):e}function xo(e){if("const"in e)return e.const;const t=e.enum;if(Array.isArray(t)&&t.length===1)return t[0]}function Pa(e,t,n){if(e===null||typeof e!="object"||Array.isArray(e))return;const r=e,o=t.map(s=>kt(s,n)),i=new Set;for(const s of o){const a=s.properties;if(a)for(const[c,d]of Object.entries(a))xo(d)!==void 0&&i.add(c)}for(const s of i){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[s];return p?xo(p):void 0}),c=a.filter(f=>f!==void 0),d=new Set(c);if(c.length<2||d.size!==c.length)continue;const l=r[s];if(l===void 0)continue;const u=a.findIndex(f=>f===l);if(u!==-1&&qn(e,o[u],n)!==null)return t[u]}}function xa(e){if(e===null)return"null";if(Array.isArray(e))return"array";const t=typeof e;return t==="number"?Number.isInteger(e)?"integer":"number":t}function qn(e,t,n){const r=t.oneOf;if(Array.isArray(r)){let l=null;for(const u of r){const f=qn(e,kt(u,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=t.type,i=xa(e);if(typeof o=="string"){if(!(o===i||o==="number"&&i==="integer"))return null}else if(Array.isArray(o)&&!o.some(u=>u===i||u==="number"&&i==="integer"))return null;if(e===null||typeof e!="object"||Array.isArray(e))return typeof o=="string"?1:0;const s=e,a=t.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(s[l]===void 0)return null;c+=2}}const d=t.properties;if(d){for(const l of Object.keys(d))s[l]!==void 0&&(c+=1);for(const l of Object.keys(s))d[l]===void 0&&(c-=1)}return c}function Ve(e,t,n){var r;for(const o of n.registry.ids()){const i=n.registry.get(o);if((r=i==null?void 0:i.ownsValue)!=null&&r.call(i,e))return{[dn]:o,v:i.encode(e,i.schema,n)}}if(Array.isArray(e))return e.map(o=>Ve(o,{},n));if(ni(e)){const o={};for(const[i,s]of Object.entries(e))s!==void 0&&(o[i]=Ve(s,{},n));return o}return Ee(e)}function ni(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function fn(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&dn in e){const n=e,r=n[dn],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}if(Array.isArray(e))return e.map(n=>fn(n,t));if(ni(e)){const n={};for(const[r,o]of Object.entries(e))n[r]=fn(o,t);return n}return e}function Ee(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Ee);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Ee(r));return t}return null}function Lo(e,t){const n=new Set,r=[e];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const i=o.$ref;if(typeof i=="string"){if(t){const u=t[i];if(!u){const f=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${f}`)}r.push(u)}continue}const s=o.oneOf;if(Array.isArray(s))for(const u of s)typeof u=="object"&&u!==null&&r.push(u);const a=o.properties;if(a)for(const u of Object.values(a))r.push(u);const c=o.items;if(Array.isArray(c))for(const u of c)typeof u=="object"&&u!==null&&r.push(u);else typeof c=="object"&&c!==null&&r.push(c);const d=o.additionalProperties;typeof d=="object"&&d!==null&&r.push(d);const l=o.propertyNames;typeof l=="object"&&l!==null&&r.push(l)}}function La(e){return{encode(t,n,r){const o=Po(e,r);return Re(t,n,o)},decode(t,n,r){const o=Po(e,r);return Ie(t,n,o)}}}const Kn={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},ownsValue(e){return e instanceof Date},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof e}`);return new Date(String(e))}if(n.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},Hn={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},ownsValue(e){return typeof e=="bigint"},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}};const Vn={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,n){return e},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return e}},Gn={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},ownsValue(e){return e instanceof Uint8Array},encode(e,t,n){return Buffer.from(e).toString("base64")},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},Ua=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Jn={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,n){return e.toLowerCase()},decode(e,t,n){if(typeof e!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode==="strict"&&!Ua.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},pn="NaN",mn="Infinity",gn="-Infinity",Da=new Set([pn,mn,gn]),Wn={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},ownsValue(e){return typeof e=="number"&&!Number.isFinite(e)},encode(e,t,n){return Number.isNaN(e)?pn:e===1/0?mn:e===-1/0?gn:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===pn)return NaN;if(e===mn)return 1/0;if(e===gn)return-1/0;const r=Number(e);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Da].join(", ")}.`);return NaN}},Ma=[Kn,Hn,Vn,Gn,Jn,Wn];function Fa(e,t={}){for(const n of Ma)e.register(n,{override:t.override??!1})}const Ba=12;function qa(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,i=r==="$defs"?t.$defs:t.definitions;return i==null?void 0:i[decodeURIComponent(o)]}function Uo(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function Ka(e){if(Array.isArray(e.type))return e.type.find(t=>t!=="null")??e.type[0];if(typeof e.type=="string")return e.type;if(e.properties)return"object"}function Ha(e){switch(e.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function Do(e,t,n){const r=e.properties??{},o=e.required??[],i={};for(const s of o){const a=r[s];i[s]=a!==void 0?Je(a,t,n+1):`<${s}>`}return i}function Va(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Je(r,t,n+1)]:[]}function Je(e,t=e??{},n=0){if(!e||n>Ba)return null;if(typeof e.$ref=="string"){const i=qa(e.$ref,t);return i!==void 0?Je(i,t,n+1):null}if(e.const!==void 0)return e.const;if(Array.isArray(e.enum)&&e.enum.length>0)return e.enum[0];if(Array.isArray(e.allOf)&&e.allOf.length>0){const i={},s=[];for(const a of e.allOf){Object.assign(i,a.properties??{});for(const c of a.required??[])s.includes(c)||s.push(c)}return Do({...e,properties:i,required:s},t,n)}const r=Uo(e.oneOf)??Uo(e.anyOf);if(r)return Je(r,t,n+1);switch(Ka(e)){case"object":return Do(e,t,n);case"array":return Va(e,t,n);case"string":return Ha(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function oi(e){if(!e)return;const t=Je(e);return`Example: ${JSON.stringify(t)}`}Kn.id,Hn.id,Vn.id,Gn.id,Jn.id,Wn.id;const ri=$a();Fa(ri);const ii=La(ri.freeze());function si(e,t){var r;const n=((r=e.input)==null?void 0:r.properties)??{};return t in n}function hn(e){var n,r;const t=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data;return Object.keys((t==null?void 0:t.properties)??{})}function Ga(e,t){var o,i,s;const n=(s=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data)==null?void 0:s.properties,r=n==null?void 0:n[t];return r!==void 0?r:void 0}function Ja(e,t){return t===void 0||e===void 0?e:ii.decode(e,t)}function Xt(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:ii.encode(e,n)}async function Wa(e,t,n,r,o,i){const a=hn(n).map(d=>Ja(i[d],Ga(n,d)));if(si(n,"session")&&t){const d=await t({session:o.session}),l=await e[r](d,...a);return Xt(l,n)}if(n.hasCtx){const d=t?await t(o):void 0,l=await e[r](d,...a);return Xt(l,n)}const c=await e[r](...a);return Xt(c,n)}class tt{constructor(){this._map=new Map}set(t,n){this._map.set(t,n)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}}function za(e=[]){return async function(n,r,o){const i=o.schemas[n];if(!i)throw new Error(`apigen/invoke: no schema found for operation "${n}"`);const s=()=>Wa(o.fns,o.createClient,i,n,r.envelope,r.domainArgs);return e.reduceRight((c,d)=>()=>d(r,c),s)()}}function Mo(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function ai(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(d=>d.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...i]=r,s=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Mo(s),path:i.map(Mo),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}const ce=Fn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href);let at;function ci(){return at||(at=ce("ts-morph").Project,at)}const di=Symbol.for("adhd.apigen.extraction-session");function zn(e,t){const n=[...e.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...e.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!t.has(o)){t.add(o);try{r.refreshFromFileSystemSync()}catch{}zn(r,t)}}}function li(e){try{const t=O.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const bt=new Map,Fo=new Map;function Ya(e,t,n){const r=t??"",o=bt.get(r);let i=n;if(o&&o.fileVersions.size>0){const c=[n],d=[...o.fileVersions.entries()].sort(([l],[u])=>l.localeCompare(u));for(const[l,u]of d)l!==e&&c.push(`${l}:${u}`);i=c.join("|")}const s=`${e}\0${t??""}`;let a=Fo.get(s);return(a==null?void 0:a.version)!==i&&(a={version:i,schemas:new Map},Fo.set(s,a)),a.schemas}let Qt;function Xa(){if(!Qt){const e=ci();Qt=new e({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})}return Qt}function ui(e){const t=Xa(),n=t.getSourceFile(e),r=n??t.addSourceFileAtPath(e);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([e]);return zn(r,o),[...o].sort()}function Qa(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[di]:!0,stats:e,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(o){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const i=o??"",s=o?this.statVersion(o):"";let a=bt.get(i);if(a&&a.tsconfigVersion!==s&&(a=void 0),!a){const c=ci();a={project:o?new c({tsConfigFilePath:o,skipAddingFilesFromTsConfig:!0}):new c({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},bt.set(i,a),e.projectsBuilt++}return a.project},sourceFileFor(o,i){const s=this.projectFor(i),a=bt.get(i??""),c=this.statVersion(o);let d=s.getSourceFile(o);if(d===void 0?d=s.addSourceFileAtPath(o):a&&a.fileVersions.get(o)!==c&&d.refreshFromFileSystemSync(),a==null||a.fileVersions.set(o,c),a){const l=new Set([o]);zn(d,l);for(const u of l)u!==o&&a.fileVersions.set(u,this.statVersion(u))}return d},statVersion(o){let i=t.get(o);return i===void 0&&(i=li(o),t.set(o,i)),i},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function Za(e){const t=e;if(t[di]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const Bo=new Set(["string","number","boolean","integer"]);function ec(e){if(typeof e!="object"||e===null)return!1;const t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;const{type:n}=t;return typeof n=="string"?Bo.has(n):Array.isArray(n)?n.every(r=>Bo.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function fi(e){if(!e||typeof e!="object")return!1;const t=e.properties;return t===void 0||typeof t!="object"||t===null?!1:Object.values(t).every(ec)}function tc(e){const t={},n=r=>{for(const o of["definitions","$defs"]){const i=r[o];if(i)for(const[s,a]of Object.entries(i)){const c=s.startsWith("#/")?s:`#/${o}/${s}`;t[c]=a}}};for(const r of Object.values(e.schemas))n(r.input),n(r.output);if(Object.keys(t).length!==0)for(const[r,o]of Object.entries(e.schemas))try{Lo(o.input,t),Lo(o.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${i.message}`)}}function nc(e,t){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(t?".":" (an empty object for this zero-parameter tool).")];return e.length>0&&n.push(`Field(s) ${e.map(r=>`"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function oc(e,t,n){tc(e);const r={};for(const[o,i]of Object.entries(e.schemas)){const s={},a=i.input.properties??{},c=i.input.required??[],d={},l=[],u={};for(const v of t)if(v.envelope&&s[v.id]!==!1)for(const[h,y]of Object.entries(v.envelope))d[h]=y,u[h]=v.id,l.includes(h)||l.push(h);const f={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},g=i.safe===!0||fi(i.input),p=i.input.definitions,m=i.input.$defs;r[o]={input:{type:"object",properties:{...d,data:f},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:nc(Object.keys(d),Object.keys(a).length>0),...p?{definitions:p}:{},...m?{$defs:m}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":g,...Object.keys(u).length>0?{"x-apigen-envelope":u}:{}}}return r}const rc=8;function ic(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let sc=0;async function ac(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${sc++}`;let i;try{i=t.addTypeAlias({name:o,type:n});const s=i.getType();return await r(s)}catch{return}finally{try{i==null||i.remove()}catch{}}}async function pi(e,t,n){if(n>rc)return{};if(e.isString()||e.isStringLiteral())return e.isStringLiteral()?{type:"string",enum:[e.getLiteralValue()]}:{type:"string"};if(e.isNumber()||e.isNumberLiteral())return e.isNumberLiteral()?{type:"number",enum:[e.getLiteralValue()]}:{type:"number"};if(e.isBoolean())return{type:"boolean"};if(e.isBooleanLiteral())return{type:"boolean",const:e.getText()==="true"};if(e.isNull()||e.isUndefined()||e.isVoid())return{type:"null"};if(e.isUnion()){const r=e.getUnionTypes(),o=r.filter(p=>p.isBooleanLiteral()),i=o.some(p=>p.getText()==="true"),s=o.some(p=>p.getText()==="false");let a=!1;const c=r.filter(p=>p.isBooleanLiteral()?a?!1:(a=!0,!0):!0);if(r.every(p=>p.isStringLiteral())&&r.length>0)return{type:"string",enum:r.map(p=>p.getLiteralValue())};if(r.every(p=>p.isNumberLiteral())&&r.length>0)return{type:"number",enum:r.map(p=>p.getLiteralValue())};const u=await Promise.all(c.map(async p=>p.isBooleanLiteral()?i&&s?{type:"boolean"}:{type:"boolean",const:i}:pi(p,t,n+1))),f=Pt(u);return{oneOf:uc(lc(u)),...f?{discriminator:f}:{},[Ae]:"union"}}if(e.isArray()){const r=e.getArrayElementType();return{type:"array",items:r?await t(r.getText()):{}}}if(e.isTuple()){const r=e.getTupleElements(),o=await Promise.all(r.map(i=>t(i.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const r=e.getStringIndexType(),o=e.getNumberIndexType(),i=r??o,s=e.getProperties();if(i&&s.length===0)return{type:"object",additionalProperties:await t(i.getText())};const a={},c=[];for(const d of s){const l=d.getName(),f=d.getDeclarations()[0];let g;if(f)try{g=d.getTypeAtLocation(f)}catch{g=void 0}if(g!==void 0&&g.getCallSignatures().length>0)continue;const p=g!==void 0?ic(g,f):void 0;a[l]=p!==void 0?await t(p):{},d.isOptional()||c.push(l)}if(Object.keys(a).length>0){const d=i?await t(i.getText()):!1;return{type:"object",properties:a,...c.length>0?{required:c}:{},additionalProperties:d}}return{}}return{}}function cc(e){return Object.keys(e).length===0?!0:e.type==="object"&&e.additionalProperties!==void 0&&e.additionalProperties!==!1&&(e.properties===void 0||Object.keys(e.properties).length===0)}const dc=new Set(["required","enum","type"]);function yn(e,t){if(e===null||typeof e!="object")return JSON.stringify(e)??"undefined";if(Array.isArray(e)){const o=e.map(i=>yn(i));return t!==void 0&&dc.has(t)&&o.sort(),`[${o.join(",")}]`}const n=e;return`{${Object.keys(n).filter(o=>n[o]!==void 0).sort().map(o=>`${JSON.stringify(o)}:${yn(n[o],o)}`).join(",")}}`}function lc(e){const t=new Set,n=[];for(const r of e){const o=yn(r);t.has(o)||(t.add(o),n.push(r))}return n}function uc(e){if(e.length<2)return e.slice();const t=e.map(cc),n=e.map((o,i)=>t[i]?i:-1).filter(o=>o>=0);if(n.length===0||n.length===e.length)return e.slice();const r=e.map((o,i)=>t[i]?-1:i).filter(o=>o>=0);return e.map((o,i)=>{if(!t[i])return o;const s=e.filter((a,c)=>c!==i&&(r.includes(c)||t[c]&&c<i));return{allOf:[o,{not:{anyOf:s}}]}})}function Pt(e){if(e.length<2)return;const t=[];for(const r of e){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;t.push(o)}const n=Object.keys(t[0]).filter(r=>t.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let i=!0;for(const a of t){const c=a[r],d=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!d||!Array.isArray(l)||l.length!==1){i=!1;break}o.push(String(l[0]))}if(!i||new Set(o).size!==o.length)continue;const s={};return o.forEach((a,c)=>{s[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:s}}}function St(e,t,n){if(t>6)return{};const r=e.trim();if(r==="string")return{type:"string"};if(r==="number")return{type:"number"};if(r==="boolean")return{type:"boolean"};if(r==="null")return{type:"null"};if(r==="undefined")return{type:"null"};const o=wn[r];if(o!==void 0)return o;if(n!=null&&n.size){const i=n.get(r);if(i!==void 0){const s=wn[i];if(s!==void 0)return s}}if(r.endsWith("[]"))return{type:"array",items:St(r.slice(0,-2),t+1,n)};if(r.includes("|")){const i=r.split("|").map(c=>c.trim());if(i.every(c=>c.startsWith("'")))return{type:"string",enum:i.map(c=>c.replace(/'/g,""))};const s=i.map(c=>St(c,t+1,n)),a=Pt(s);return{oneOf:s,...a?{discriminator:a}:{},[Ae]:"union"}}if(r.startsWith("{")&&r.endsWith("}")){const i=r.slice(1,-1).trim(),s={};for(const a of i.split(";").filter(Boolean)){const[c,d]=a.split(":").map(l=>l.trim());c&&d&&(s[c.replace("?","")]=St(d,t+1,n))}return{type:"object",properties:s}}return{}}function mi(e){const t=[];let n=0,r=0;for(let i=0;i<e.length;i++){const s=e[i];s==="<"||s==="["||s==="{"||s==="("?n++:s===">"||s==="]"||s==="}"||s===")"?n--:s===","&&n===0&&(t.push(e.slice(r,i).trim()),r=i+1)}const o=e.slice(r).trim();return o.length>0&&t.push(o),t}function fc(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function pc(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function mc(e){let t=e.trim();if(t.startsWith("readonly ")&&(t=t.slice(9).trim()),!t.startsWith("[")||!t.endsWith("]"))return;const n=t.slice(1,-1).trim();if(n.length!==0)return mi(n)}async function gc(e,t){const n=e.trim(),r=fc(n);if(r!==void 0){const s=mi(r);if(s.length===2){const[a,c]=await Promise.all([t(s[0]),t(s[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=pc(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const i=mc(n);if(i!==void 0){const s=await Promise.all(i.map(a=>t(a)));return{type:"array",items:s,minItems:s.length,maxItems:s.length}}}const gi={"decimal.js":"Decimal"},wn={Date:{type:"string",format:"date-time"},bigint:{type:"string",format:"int64"},Uint8Array:{type:"string",format:"byte"},Buffer:{type:"string",format:"byte"},URL:{type:"string",format:"uri"},RegExp:{type:"string",format:"regex"},Decimal:{type:"string",format:"decimal"}},qo={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Ko(e){var n;const t=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),i=gi[o];if(!i)continue;const s=r.getDefaultImport();if(s){const a=s.getText();a!==i&&t.set(a,i)}for(const a of r.getNamedImports()){const c=((n=a.getAliasNode())==null?void 0:n.getText())??a.getName();c!==i&&t.set(c,i)}}return t}function hc(e,t){return n=>{n.addNodeParser({supportsNode(r){var i,s,a;if(r.kind!==t)return!1;const o=((i=r.typeName)==null?void 0:i.escapedText)??((a=(s=r.typeName)==null?void 0:s.right)==null?void 0:a.escapedText);return o!==void 0&&Object.prototype.hasOwnProperty.call(qo,o)},createType(r){var a,c,d;const o=((a=r.typeName)==null?void 0:a.escapedText)??((d=(c=r.typeName)==null?void 0:c.right)==null?void 0:d.escapedText),{AnnotatedType:i,StringType:s}=vn();return new i(new s,{format:qo[o]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){const{AnnotatedType:r,StringType:o}=vn();return new r(new o,{format:"int64"},!1)}})}}let ct;function vn(){return ct||(ct=ce("ts-json-schema-generator"),ct)}let Be;function yc(){if(Be)return Be;try{const e=k.dirname(ce.resolve("ts-json-schema-generator/package.json"));Be=ce(ce.resolve("typescript",{paths:[e]}))}catch{Be=ce("typescript")}return Be}const me=new Map;function wc(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function vc(e){const t=me.get(e);return t&&(me.delete(e),me.set(e,t)),t}function bc(e,t){const n=wc();if(n!==0)for(me.delete(e),me.set(e,t);me.size>n;){const r=me.keys().next().value;me.delete(r)}}function Sc(e,t){return`${e}\0${t??""}`}const Ec=new Set(["zod",/^zod\/./]);function kc(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of Ec)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function Ac(e){for(const t of["$defs","definitions"]){const n=e[t];if(!n||typeof n!="object")continue;const r=Object.keys(n);if(r.length===0)continue;const o=new Set(r.filter(i=>/zod/i.test(i)));for(const[i,s]of Object.entries(n)){if(o.has(i)||typeof s!="object"||s===null)continue;const a=s,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const d of o)if(c.includes(d)){o.add(i);break}}}for(const i of o)delete n[i]}bn(e)}function bn(e,t){if(!e||typeof e!="object")return;const n=t??new WeakSet;if(!n.has(e)){n.add(e);for(const r of Object.keys(e))if(r==="$ref"&&typeof e[r]=="string"){const o=e[r];/zod/i.test(o)&&delete e[r]}for(const[,r]of Object.entries(e))if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const o of r)typeof o=="object"&&o!==null&&bn(o,n);else bn(r,n)}}function jc(e){const t=new Set;for(const r of["$defs","definitions"]){const o=e[r];if(o&&typeof o=="object")for(const i of Object.keys(o))t.add(i)}const n=Sn(e,t);if(n.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${n.length} unresolvable $ref(s): ${n.join(", ")}. This usually means zod-internal definitions were stripped but $ref references to them remain. Check the source file's imports or the ts-json-schema-generator output.`)}function Sn(e,t){if(!e||typeof e!="object")return[];const n=[];for(const[r,o]of Object.entries(e))if(r==="$ref"&&typeof o=="string"){const i=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);i&&!t.has(i[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const i of o)typeof i=="object"&&i!==null&&n.push(...Sn(i,t));else n.push(...Sn(o,t));return n}function _c(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=Pt(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[Ae]:o[Ae]??"union"}}function Nc(e,t,n){const{DEFAULT_CONFIG:r}=ce("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},i=o.path,s=Sc(i,o.tsconfig);let a;a=n?n.statVersion(i):li(i);let c;if(s!==void 0){const l=(n==null?void 0:n.generatorCache.get(s))??vc(s);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=ce("ts-json-schema-generator/dist/factory/program.js"),{createParser:u,createFormatter:f,SchemaGenerator:g}=vn(),p=yc(),m=hc(p.SyntaxKind.BigIntKeyword,p.SyntaxKind.TypeReference),v=l(o),h=u(v,o,m),y=f(o);if(c=new g(v,h,y,o),n&&n.stats.generatorsBuilt++,s!==void 0&&a!==void 0){const w={version:a,gen:c};bc(s,w),n==null||n.generatorCache.set(s,w)}}const d=c.createSchema(o.type);return Ac(d),jc(d),d}function Oc(e,t){let n=e.trim();if(n=yi(n),t!=null&&t.size){const o=t.get(n);if(o!==void 0)return o}const r=n.match(/^ReadonlyArray<(.+)>$/);for(r&&(n=`${r[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function hi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Rc=Object.entries(gi).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${hi(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function yi(e){let t=e;for(const{pattern:n,key:r}of Rc)t=t.replace(n,r);return t}function Ic(e,t){let n=yi(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${hi(r)}\\b`,"g"),o);return n}async function We(e,t,n,r,o,i){const s=t.getFilePath(),a=`${s}\0${r??""}\0${n}`,c=i??new Set;if(c.has(a))return{};if(!o){const p=new Set(c);return p.add(a),Ho(e,t,n,r,void 0,p)}const d=o.schemaCache.get(a);if(d!==void 0)return o.stats.schemaCacheHits++,d;const l=Ya(s,r,o.statVersion(s)),u=l.get(n);if(u!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(u)),u;o.stats.schemaCacheMisses++;const f=new Set(c);f.add(a);const g=Ho(e,t,n,r,o,f).then(p=>(l.set(n,p),p)).catch(p=>{throw o.schemaCache.delete(a),p});return o.schemaCache.set(a,g),g}async function Ho(e,t,n,r,o,i){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let s;if(o){const f=o.aliasCache.get(t);s=f??Ko(t),f||o.aliasCache.set(t,s)}else s=Ko(t);const a=Oc(n,s),c=wn[a];if(c!==void 0)return c;const d=await gc(a,f=>We(e,t,f,r,o,i));if(d!==void 0)return d;const l=(o==null?void 0:o.zodImportCache.get(t))??kc(t);if(o&&o.zodImportCache.set(t,l),!l)try{const f={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},g=Nc(f,!0,o);return _c(g)}catch{}try{const f=await ac(e,t,a,g=>pi(g,p=>We(e,t,p,r,o,i),0));if(f!==void 0)return f}catch{}const u=Ic(a,s);return St(u,0,s)}function Yn(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return Tc(n,t)}function Tc(e,t){var s;const n=e,r=((s=n==null?void 0:n.getJsDocs)==null?void 0:s.call(n))??[],o=t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[\\s*${o}\\s*=\\s*([^\\]]+)\\]`);for(const a of r)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const d=c.getText().match(i);if(d)return d[1].trim()}}function $c(e){const t=e.trim(),n=t.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[2];if(t==="true")return!0;if(t==="false")return!1;if(t==="null")return null;if(t!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(t))return Number(t);try{return JSON.parse(t)}catch{return t}}}function Cc(e,t){const n=$c(t);if(n===void 0)return;e.default=n;const r=typeof n=="string"?n:JSON.stringify(n),o=typeof e.description=="string"?e.description:void 0;e.description=o?`${o} (default: ${r})`:`(default: ${r})`}let dt;function Pc(){return dt||(dt=ce("ts-morph").SyntaxKind,dt)}function xt(e){try{if(!e)return;const t=Pc();if(e.getKind()!==t.TypeReference)return;const n=e;if(n.getTypeArguments().length>0)return;const r=n.getTypeName();if(r.getKind()!==t.Identifier)return;const i=r.getSymbol();if(!i)return;const s=i.getDeclarations().find(u=>u.getKindName()==="TypeAliasDeclaration");if(!s)return;const a=s,c=a.getType();if(!(c.isString()||c.isNumber()||c.isBoolean()))return;const l=a.getJsDocs();for(const u of l)for(const f of u.getTags())if(f.getTagName()==="format"){const g=f.getCommentText();if(g!==void 0)return g.trim()}return}catch{return}}const xc=new Set(["AsyncGenerator","AsyncIterableIterator","AsyncIterable","Generator","IterableIterator","Iterable","ApiStream"]);function Lc(e){const t=[];let n=0,r="";for(const o of e)o==="<"||o==="("||o==="["||o==="{"?n++:(o===">"||o===")"||o==="]"||o==="}")&&n--,o===","&&n===0?(t.push(r.trim()),r=""):r+=o;return r.trim().length>0&&t.push(r.trim()),t}function Uc(e){const t=e.trim(),n=t.indexOf("<");if(n===-1||!t.endsWith(">"))return null;const r=t.slice(0,n),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;if(!xc.has(o))return null;let i=0;for(let c=n;c<t.length;c++){const d=t[c];if(d==="<")i++;else if(d===">"&&(i--,i===0&&c!==t.length-1))return null}if(i!==0)return null;const s=t.slice(n+1,-1),a=Lc(s);return a.length>0?a[0]:null}async function wi(e){const t=e.session===void 0,n=Za(e.session??Qa());try{return await Dc(e,n)}finally{t&&n.dispose()}}async function Dc(e,t){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:i}=e,s=t.projectFor(i),a=t.sourceFileFor(n,i),c=k.basename(n),d=ae(Fc(c)),l=o?null:d,u=ae(r),f=[];for(const[m,v]of a.getExportedDeclarations()){if(m==="default"||ut(m))continue;const h=qc(v);if(h){const S=h.getSignature(),E=Jo(S,h),A=S.getReturnType().getText(),j=ve(S);f.push(await lt(s,a,u,l,m,E,A,h.isAsync(),i,t,j));continue}const y=v.find(S=>S.getKindName()==="VariableDeclaration");if(!y)continue;const w=y.getInitializer(),b=w==null?void 0:w.getKindName();if(w&&["ArrowFunction","FunctionExpression"].includes(b??"")){const E=y.getType().getCallSignatures();if(E.length===0)continue;const A=E[0],j=Wo(A,y,y.getVariableStatement()),N=A.getReturnType().getText(),_=ve(A),R=w.isAsync();f.push(await lt(s,a,u,l,m,j,N,R,i,t,_))}else if(b==="ObjectLiteralExpression"){const S=y.getType();for(const E of S.getProperties()){const A=E.getName();if(ut(A))continue;const N=E.getTypeAtLocation(y).getCallSignatures();if(N.length===0)continue;const _=N[0],R=Wo(_,y,y.getVariableStatement()),T=_.getReturnType().getText(),C=ve(_),q=[...l?[l]:[],ae(m),ae(A)];f.push(await Et(s,a,u,q,A,R,T,!1,i,t,C))}}else{const S=y.getType(),E=S.getText();if(Se(S,y)){const A=await We(s,a,E,i,t);f.push(Mc(u,l,m,A))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${m}`)}}const g=a.getDefaultExportSymbol();if(g){const m=a.getExportAssignment(v=>!v.isExportEquals());if(m){const v=m.getExpression(),h=v.getKindName();if(["ArrowFunction","FunctionExpression"].includes(h)){const w=v.getType().getCallSignatures();if(w.length>0){const b=w[0],S=Zt(b,m),E=b.getReturnType().getText(),A=ve(b),j=v.isAsync();f.push(await lt(s,a,u,l,"default",S,E,j,i,t,A))}}else{const y=v.getType();for(const w of y.getProperties()){const b=w.getName();if(ut(b))continue;const E=w.getTypeAtLocation(m).getCallSignatures();if(E.length===0)continue;const A=E[0],j=Zt(A,m),N=A.getReturnType().getText(),_=ve(A),R=[...l?[l]:[],ae("default"),ae(b)];f.push(await Et(s,a,u,R,b,j,N,!1,i,t,_))}}}else{const v=g.getDeclarations();for(const h of v){if(h.getKindName()!=="FunctionDeclaration")continue;const y=h,w=y.getName(),b=w&&w.length>0?w:"default",S=y.getSignature(),E=Jo(S,y),A=S.getReturnType().getText(),j=ve(S);f.push(await lt(s,a,u,l,b,E,A,y.isAsync(),i,t,j))}}}const p=Bc(a);if(p.length>0)for(const{name:m,sig:v}of p){if(ut(m))continue;const h=Zt(v),y=v.getReturnType().getText(),w=ve(v),b=[...l?[l]:[],ae(m)];f.push(await Et(s,a,u,b,m,h,y,!1,i,t,w))}return f}function Vo(e,t,n,r){const o=new Set,i=s=>{if(Array.isArray(s))return s.map(i);if(!s||typeof s!="object"||o.has(s))return s;o.add(s);try{const a=s,c={};for(const[d,l]of Object.entries(a)){if(d==="definitions"||d==="$defs"){const u=d,f=t[u];for(const[g,p]of Object.entries(l)){const m=i(p),v=f[g];if(v!==void 0&&JSON.stringify(v)!==JSON.stringify(m))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${u}.${g}" definition that conflicts with an identically-named definition already hoisted from another param/output in the same function. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one function-level schema.`);f[g]=m}continue}c[d]=i(l)}return c}finally{o.delete(s)}};return i(e)}function Go(e,t){if(!t||e.format!==void 0||"$ref"in e||"properties"in e||"items"in e)return;const n=e.type;(n==="string"||n==="number"||n==="integer"||n==="boolean")&&(e.format=t)}function ve(e){var t;try{return xt((t=e.getDeclaration())==null?void 0:t.getReturnTypeNode())}catch{return}}async function lt(e,t,n,r,o,i,s,a,c,d,l){const u=ae(o);return Et(e,t,n,r?[r,u]:[u],o,i,s,a,c,d,l)}async function Et(e,t,n,r,o,i,s,a,c,d,l){const u=i.length>0&&i[0].name==="ctx",f=i.filter(_=>_.name!=="ctx"),g=f.filter(_=>!_.optional).map(_=>_.name),p={},m={definitions:{},$defs:{}};for(const _ of f){const R=await We(e,t,_.type,c,d),T=Vo(R,m,o,_.name);_.defaultValue!==void 0&&Cc(T,_.defaultValue),Go(T,_.format),p[_.name]=T}const v=s.replace(/^Promise<(.+)>$/,"$1").trim(),h=Uc(v),y=h!==null,w=y?h:v,b=await We(e,t,w,c,d),S={definitions:{},$defs:{}},E=Vo(b,S,o,"<return>"),A=l?{...E}:E;Go(A,l),Object.keys(S.definitions).length>0&&(A.definitions={...A.definitions,...S.definitions}),Object.keys(S.$defs).length>0&&(A.$defs={...A.$defs,...S.$defs});const j={type:"object",properties:p,required:g,...Object.keys(m.definitions).length>0?{definitions:m.definitions}:{},...Object.keys(m.$defs).length>0?{$defs:m.$defs}:{}};return{id:vi(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:y,safe:!1,input:j,output:A,envelope:{},typeText:{lang:"ts",input:Kc(i),output:w},...u?{hasCtx:!0}:{}}}function Mc(e,t,n,r){const o=ae(n),i=t?[t,o]:[o];return{id:vi(e,i),host:"ts",namespace:e,path:i,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function vi(e,t){return(e.raw?[e,...t]:t).map(r=>r.words.join("-")).join("/")}function ze(e){return e.split(/[-_.]+/).flatMap(t=>t.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(t=>t.toLowerCase()).filter(Boolean)}function ae(e){return{raw:e,words:ze(e)}}function Fc(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Bc(e){const t=[];for(const n of e.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const o=r;if(o.getLeft().getText().trim()!=="module.exports"||o.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=o.getRight(),a=s.getType();for(const c of a.getProperties()){const l=c.getTypeAtLocation(s).getCallSignatures();l.length!==0&&t.push({name:c.getName(),sig:l[0]})}}return t}function qc(e){let t;for(const n of e){if(n.getKindName()!=="FunctionDeclaration")continue;const r=n;if(t||(t=r),r.getBody())return r}return t}function Jo(e,t){return e.getParameters().map(n=>{var s;const r=n.getDeclarations(),o=r.length>0&&r[0].getKindName()==="Parameter"?r[0]:null,i=n.isOptional()||((o==null?void 0:o.hasInitializer())??!1)||(((s=o==null?void 0:o.hasQuestionToken)==null?void 0:s.call(o))??!1);return{name:n.getName(),type:n.getTypeAtLocation(e.getDeclaration()).getText(),optional:i,defaultValue:Yn(o,n.getName(),t),format:xt(o==null?void 0:o.getTypeNode())}})}function Wo(e,t,n){return e.getParameters().map(r=>{var a;const o=r.getDeclarations(),i=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,s=r.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((a=i==null?void 0:i.hasQuestionToken)==null?void 0:a.call(i))??!1);return{name:r.getName(),type:r.getTypeAtLocation(t).getText(),optional:s,defaultValue:Yn(i,r.getName(),n??t),format:xt(i==null?void 0:i.getTypeNode())}})}function Zt(e,t){return e.getParameters().map(n=>{var s,a,c;const r=n.getDeclarations(),o=r.length>0&&r[0].getKindName()==="Parameter"?r[0]:null,i=n.isOptional()||((o==null?void 0:o.hasInitializer())??!1)||(((s=o==null?void 0:o.hasQuestionToken)==null?void 0:s.call(o))??!1);return{name:n.getName(),type:o?o.getType().getText():((c=(a=n.getValueDeclaration())==null?void 0:a.getType())==null?void 0:c.getText())??"unknown",optional:i,defaultValue:Yn(o,n.getName(),t),format:xt(o==null?void 0:o.getTypeNode())}})}function Kc(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function ut(e){return!!(e==="__samples__"||e.startsWith("__"))}function Se(e,t,n=new Set){if(e.getCallSignatures().length>0||e.getConstructSignatures().length>0)return!1;if(e.isString()||e.isNumber()||e.isBoolean()||e.isNull()||e.isUndefined()||e.isStringLiteral()||e.isNumberLiteral()||e.isBooleanLiteral()||e.isEnumLiteral())return!0;if(e.isArray()||e.isReadonlyArray()){const r=e.getArrayElementType();return r?Se(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>Se(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>Se(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>Se(r,t,n));if(e.isObject()){const r=e.getText(t);if(n.has(r))return!0;n.add(r);const o=e.getStringIndexType(),i=e.getNumberIndexType();if(o||i)return[o,i].every(a=>!a||Se(a,t,n));const s=e.getProperties();return s.length===0?!0:s.every(a=>{const c=a.getTypeAtLocation(t);return Se(c,t,n)})}return!1}function Hc(e,t){return async n=>{let r=()=>t(n);for(let o=e.length-1;o>=0;o--){const i=e[o],s=r;r=()=>i(n,s)}return r()}}function Vc(e,t){return Hc(e,t)}function Gc(e,t,n={}){const r=e.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return Vc(r,t)}function Jc(e){return{oneOf:[{type:"object",required:["index","status","value"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},value:e}},{type:"object",required:["index","status","chunks"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},chunks:{type:"array"}}},{type:"object",required:["index","status","reason"],properties:{index:{type:"integer"},status:{type:"string",enum:["rejected"]},reason:{},chunksDelivered:{type:"integer"}}}]}}function Wc(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:Jc(e.output)}}function zc(e,t={}){const n=new Set(t.exclude??[]),r=new Map;for(const o of e){if(n.has(o.id))continue;const i=r.get(o.kind);i?i.push(o):r.set(o.kind,[o])}return r}function zo(e){return{type:"string",enum:[e]}}function Yo(e,t){return{type:"object",required:["input"],properties:{input:{type:"object",required:["operation","items"],properties:{operation:t,items:{type:"array",items:e.itemsSchema},concurrency:{type:"number"},mode:{type:"string",enum:["parallel","serial","chained"]},onItemError:{type:"string",enum:["continue","abort"]},itemTimeoutMs:{type:"number"}},additionalProperties:!0}},additionalProperties:!1}}function Xo(e,t){const n={},r={},o=[["definitions",n],["$defs",r]];for(const i of e){const s=t(i);for(const[a,c]of o){const d=s[a];if(d)for(const[l,u]of Object.entries(d)){const f=c[l];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(u))throw new Error(`[apigen-core-client] _batch mount: operation "${i.id}" contributes a "${a}.${l}" definition that conflicts with an identically-named definition already hoisted from another batched operation. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one _batch/<kind> schema.`);c[l]=u}}}return{...Object.keys(n).length>0?{definitions:n}:{},...Object.keys(r).length>0?{$defs:r}:{}}}function Yc(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(Wc),n=Xo(e,s=>s.input),r=Xo(e,s=>s.output);if(e.length===1){const[s]=e,[a]=t;return{input:{...Yo(a,zo(s.id)),...n},output:{type:"array",items:a.resultSchema,...r}}}const o=e.map((s,a)=>Yo(t[a],zo(s.id))),i=Pt(o);return{input:{oneOf:o,...i?{discriminator:i}:{},...n},output:{oneOf:t.map(s=>({type:"array",items:s.resultSchema})),...r},...i?{discriminator:i}:{}}}function Xc(e,t={}){const n=zc(e.operations,t),r=[];for(const[o,i]of n){const{input:s,output:a}=Yc(i),c=ai(`_batch/${o}`,e,{kind:o,safe:o==="query",input:s,output:a});r.push({...c,operationIds:i.map(d=>d.id)})}return r}function Xn(e={}){const t=e.level??"info",n=typeof e.destination=="string"&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,o=e.format??(r?"pretty":"json"),i={level:t};if(o==="pretty")return i.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},st(i);const s=n?st.destination({dest:e.destination,mkdir:!0,sync:!0}):st.destination(2);return st(i,s)}function Qc(e){if((e==null?void 0:e.type)!=="object"||!e.properties)return;const t=Object.entries(e.properties);if(t.length===0)return;const n=new Set(e.required??[]);return`{ ${t.map(([o,i])=>`${o}${n.has(o)?"":"?"}: ${Lt(i)}`).join(", ")} }`}function Zc(e){return typeof e=="string"?`'${e}'`:JSON.stringify(e)}function ed(e){const t=e.enum??[];return t.length===0?"unknown":t.map(Zc).join("|")}function td(e,t){return e.map(n=>Lt(n,t)).join(" | ")}function Lt(e,t=0){if(!e)return"unknown";if(e.type==="array")return`${Lt(e.items,0)}[]`;if(e.enum)return ed(e);if(e.$ref)return String(e.$ref).split("/").pop()||"object";const n=e.anyOf??e.oneOf;return n?n.length===0?"unknown":t>=2?td(n,t-1):"union":t>=1&&e.type==="object"?Qc(e)??"object":e.type??"object"}function bi(e){var a;const n=(a=((e==null?void 0:e.input)??{}).properties)==null?void 0:a.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),i=Object.entries(r).map(([c,d])=>({name:c,type:Lt(d,2),required:o.has(c)})),s=i.map(c=>`${c.name}${c.required?"":"?"}: ${c.type}`).join(", ");return{params:i,text:s}}function nd(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function od(e,t){var i,s;const r=((s=(i=((t==null?void 0:t.input)??{}).properties)==null?void 0:i.data)==null?void 0:s.properties)??{},o={...e};for(const[a,c]of Object.entries(r)){const d=o[a];if(typeof d!="string")continue;const l=nd(c==null?void 0:c.type);if(l==="number"||l==="integer"){const u=Number(d);!Number.isNaN(u)&&d.trim()!==""&&(o[a]=u)}else l==="boolean"&&(d==="true"?o[a]=!0:d==="false"&&(o[a]=!1))}return o}const rd=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],id={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500},Qo={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};class L extends Error{constructor(t,n,r){super(n),this.name="ApiError",this.code=t,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const t={code:this.code,message:this.message};return this.details!==void 0&&(t.details=this.details),t}}function re(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&rd.includes(e.code)&&typeof e.toJSON=="function"}function Zo(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Ut=new Zr({allErrors:!0});ka(Ut);for(const e of[Ae,Bn,ln,un,"discriminator"])Ut.addKeyword({keyword:e,valid:!0});Ut.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function sd(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function ad(e,t){const n=oi(t),r=[`Validation failed: ${sd(e)}`];return n&&r.push(n),r.join(" — ")}function cd(e){return async function(n,r){const o=n.operation.id,i=e[o];if(i===void 0)return r();const s={data:n.domainArgs,...n.envelope},a=Ut.compile(i.input);if(!a(s)){const d=a.errors??[];throw new L("invalid_argument",ad(d,i.input),d)}return r()}}async function Si(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=re(n)?n:new L("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:Zo("before-first-chunk",r)}:{ok:!1,carrier:Zo("after-first-chunk",r,t.length)}}}function Dt(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class be extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function en(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const n=t;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function Ei(e,t){const n=e[Bn];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function dd(e,t,n){const r=Ei(t,n);return r?r.encode(e,t,n):e}function ld(e,t,n){const r=Ei(t,n);return r?r.decode(e,t,n):e}function ud(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Ae]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:en(r)!==void 0},encode(r,o,i){const s=en(o);if(!s)throw new be("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=s,d=r[a];if(d==null)throw new be("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${i.path}" is missing the discriminator property "${a}".`);const l=String(d),u=c[l];if(!u)throw new be("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=i.resolve(u);return dd(r,f,{...i,path:`${i.path}[${l}]`})},decode(r,o,i){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new be("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${p}.`)}const s=r,a=en(o);if(!a)throw new be("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:d}=a,l=s[c];if(l==null)throw new be("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${i.path}" is missing the discriminator property "${c}".`);const u=String(l),f=d[u];if(!f)throw new be("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${u}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(d).join(", ")}).`);const g=i.resolve(f);return ld(r,g,{...i,path:`${i.path}[${u}]`})}}}const fd="x-apigen-instances";class ft extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function er(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function pd(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function tr(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function md(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function gd(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Ae]==="nominal"?!0:o[Bn]===t},encode(o,i,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new ft("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${s.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}s.seen.add(o);try{const a=er(i),c=typeof i[un]=="string"?i[un]:"toJSON",d=o[c];if(typeof d=="function"){const p=d.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const m={};for(const[v,h]of Object.entries(p))m[v]=tr(h,a[v],{...s,path:`${s.path}/${v}`});return m}return p}const l={},u=Object.keys(a),f=o,g=u.length>0?u:Object.keys(f);for(const p of g){const m=f[p];m!==void 0&&(l[p]=tr(m,a[p],{...s,path:`${s.path}/${p}`}))}return l}finally{s.seen.delete(o)}},decode(o,i,s){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new ft("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${l}.`)}const a=o;for(const l of pd(i))if(!(l in a))throw new ft("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${s.path}".`);if(i[fd]===!1)throw new ft("E_NOMINAL_NONRECONSTRUCTABLE",`[${t}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=er(i),d={};for(const[l,u]of Object.entries(a))d[l]=md(u,c[l],{...s,path:`${s.path}/${l}`});if(r){const l=typeof i[ln]=="string"?i[ln]:"fromJSON",u=r[l];if(typeof u=="function")return u.call(r,d);const f=r;return new f(d)}return d}}}const hd=[Kn,Hn,Vn,Gn,Jn,Wn],yd={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},nr=gd({id:"ts.NominalSentinel",schema:yd}),wd={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},or=ud({id:"ts.UnionSentinel",schema:wd});function vd(){const e=[...hd.map(t=>[t.id,t]),[nr.id,nr],[or.id,or]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Ca,codecs:vd()});function En(e,t,n){var s;const r=typeof((s=t==null?void 0:t.input)==null?void 0:s.description)=="string"?t.input.description:void 0,o=oi(t==null?void 0:t.input),i=[n,r,o].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):e}function ki(e){if(!e||typeof e!="object"||Array.isArray(e)||Object.keys(e).length===0)return{outputSchema:void 0,wrapped:!1};const t=e;return t.type==="object"?{outputSchema:t,wrapped:!0}:{outputSchema:void 0,wrapped:!1}}function bd(e,t){if(e)return t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const Sd=4,Ed=32;function kn(e){return re(e)?e:e instanceof Error?new L("internal",e.message):e}function kd(e,t){if(e==="serial"||e==="chained")return 1;const n=t??Sd;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Ed)}function Ad(){}function jd(e,t){var i;if(!e&&!t)return{signal:void 0,dispose:Ad};const n=new AbortController,r=()=>{n.abort(e==null?void 0:e.reason)};e&&(e.aborted?n.abort(e.reason):e.addEventListener("abort",r,{once:!0}));let o;return t!==void 0&&!n.signal.aborted&&(o=setTimeout(()=>{n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(i=o.unref)==null||i.call(o)),{signal:n.signal,dispose(){e&&e.removeEventListener("abort",r),o&&clearTimeout(o)}}}async function rr(e,t,n,r,o,i){const s=jd(r.signal,i);try{const a=s.signal?{...r,signal:s.signal}:r,c=await e(t,a,o);if(Dt(c)){const d=await Si(c);if(!d.ok){const l=d.carrier;return{index:n,status:"rejected",reason:kn(l.error),...l.phase==="after-first-chunk"?{chunksDelivered:l.chunksDelivered}:{}}}return{index:n,status:"fulfilled",chunks:d.chunks}}return{index:n,status:"fulfilled",value:c}}catch(a){return{index:n,status:"rejected",reason:kn(a)}}finally{s.dispose()}}async function _d(e,t,n,r,o={}){const i=o.mode??"parallel",s=o.onItemError??"continue",a=kd(i,o.concurrency),c=new Array(n.length),d=p=>({index:p,status:"rejected",reason:kn(new Error("apigen/invokeBatch: not attempted — an earlier item failed and "+(i==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(i==="serial"||i==="chained"){let p=!1;for(let m=0;m<n.length;m++){if(p){c[m]=d(m);continue}const v=await rr(e,t,m,n[m],r,o.itemTimeoutMs);c[m]=v,v.status==="rejected"&&(i==="chained"||s==="abort")&&(p=!0)}return c}let l=0,u=!1;const f=Math.max(1,Math.min(a,n.length)),g=Array.from({length:f},async()=>{for(;;){const p=l++;if(p>=n.length)return;if(u){c[p]=d(p);continue}const m=await rr(e,t,p,n[p],r,o.itemTimeoutMs);c[p]=m,m.status==="rejected"&&s==="abort"&&(u=!0)}});return await Promise.all(g),c}function ir(e){return e.words.join("-")}function sr(e){return e.words.map(Rd).join("")}function ar(e){return e.words.join("_")}function Nd(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Me(e,t={}){var f,g;const n=[e.namespace,...e.path],r=e.safe||fi(e.input)?"GET":"POST",o=((g=(f=t.http)==null?void 0:f.verb)==null?void 0:g[e.id])??r,i="/"+n.map(p=>ir(p)).join("/"),s=n.map(p=>ar(p)).join("_"),c=n.map(p=>ar(p)).slice(0,-1).join("."),d=sr(n[n.length-2]??n[0]),l=sr(n[n.length-1]),u=n.map(p=>ir(p));return{http:{verb:o,route:i},mcp:{name:s},grpc:{package:c,service:d,method:l},cli:{path:u}}}function Ai(e,t){return`x-${e}-${t}`}function ji(e,t){return`--${e}-${t}`}function _i(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function At(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}function Od(e){const t=new Set,n=[];for(const r of e){const o=At(r);let i=o,s=2;for(;t.has(i);)i=`${o}_${s}`,s+=1;t.add(i),n.push(i)}return n}function Rd(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Ni(e){return e.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function se(e){return Ni(JSON.stringify(e))}function Id(e,t=3e3){if(e==null)return t;if(typeof e!="string"&&typeof e!="number")throw new TypeError(`apigen: invalid port option ${JSON.stringify(e)} — expected an integer in [0, 65535]`);if(typeof e=="string"&&e.trim()==="")throw new TypeError(`apigen: invalid port option ${JSON.stringify(e)} — expected an integer in [0, 65535]`);const n=Number(e);if(!Number.isInteger(n)||n<0||n>65535)throw new TypeError(`apigen: invalid port option ${JSON.stringify(e)} — expected an integer in [0, 65535]`);return n}function Qn(e){return e.anyOf??e.oneOf}function Td(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Qn(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function $d(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Qn(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Cd(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Qn(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function Pd(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function xd(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},r=(t==null?void 0:t.required)??[];return{props:n,required:r}}function cr(e){return typeof e.handler=="function"}function Ld(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd",a=Ai(s,i);r.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:ji(s,i),envVar:_i(s,i)})}return r}function Ud(e,t,n,r){t===n||e.has(t)||e.set(t,{...r,aliasOf:n})}function Dd(e,t){const n=new Map,{props:r}=xd(e);for(const[o,i]of Object.entries(r)){let s="string";$d(i)?s="boolean":(Td(i)||Cd(i))&&(s="json");const a=Pd(o),c={camelKey:o,kind:"domain",valueKind:s};n.set(a,c),Ud(n,o,a,c)}for(const o of t){const i=o.cliFlag.replace(/^--/,""),s={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(i,s)}return n}function ye(e){const{op:t,schema:n,transport:r,projection:o}=e,i=Me(t,o),s=n?Ld(n):[],a=n?Dd(n,s):new Map,c=n?bi(n).params:void 0,d={op:t,transport:r,http:i.http,mcp:i.mcp,cli:i.cli,grpc:i.grpc,params:c,envelope:s,cliFlags:a,streaming:t.streaming,isMount:cr(t)};if(cr(t)){const l=t.handler;d.mountHandler=async u=>l(u)}return d}function Zn(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Md(e){const t=e.exitCode;return typeof t=="function"?t:void 0}function eo(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Fd(e){return async function(n,r){const o=Object.assign(n,{data:n.domainArgs});return await e.layer(o,r)}}function de(e,t){var r;const n=[];for(const o of t){const i=(r=o.capabilities)==null?void 0:r.layer;i&&n.push(Fd(i))}return n.push(cd(e)),za(n)}function Bd(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const qd={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function xe(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new tt};if(e.isMount){const i=e.mountHandler;if(!i)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const s={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:Bd(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:qd}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}function Oi(e){return e.anyOf??e.oneOf}function Kd(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd";r.push({field:i,pluginId:s,flag:ji(s,i),envVar:_i(s,i)})}return r}function An(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Oi(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function Hd(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Oi(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function dr(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,n=(t==null?void 0:t.properties)??{},r=(t==null?void 0:t.required)??[];return{props:n,required:r}}function Vd(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function Gd(e){const n=to(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return n.length>0?n.toLowerCase():"branch"}function tn(e){var i,s;const t=(s=(i=e.input)==null?void 0:i.properties)==null?void 0:s.data;if(!t)return;const n=t.oneOf,r=t.discriminator;if(!n||!r)return;const o=[];for(const[a,c]of Object.entries(r.mapping)){const d=Vd(c);if(d===void 0)continue;const l=n[d];if(!l)continue;const u=l.properties??{},f=l.required??[];o.push({value:a,commandName:Gd(a),props:u,required:f})}if(o.length!==0)return{discriminatorProperty:r.propertyName,branches:o}}function to(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Jd(e,t){if(!cn.isAbsolute(t))return t;const n=cn.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const Wd=["function __apigenParseJsonArg(flag: string, raw: unknown): unknown {"," if (raw === undefined) return undefined"," if (typeof raw !== 'string') return raw"," try {"," return JSON.parse(raw)"," } catch (err) {"," throw new Error(`Invalid JSON for --${flag}: ${(err as Error).message}`)"," }","}"].join(`
3
+ `);function Ri(e,t,n){for(const r of t){const o=r.flag.replace(/^--/,"");e.push(` .option('${r.flag} <${o}>', '${r.field} (env: ${r.envVar})')`)}n&&!t.some(r=>r.field==="session")&&e.push(" .option('--session <key>', 'Session key')")}function Ii(e,t,n,r){var o;for(const i of t){const s=to(i),a=Hd(n[i]),c=r.includes(i);a?(e.push(` .option('--${s}')`),((o=n[i])==null?void 0:o.default)===!0&&e.push(` .option('--no-${s}')`)):c?e.push(` .requiredOption('--${s} <${s}>')`):e.push(` .option('--${s} <${s}>')`)}}function Ti(e,t,n){return`${e}:${t}::${n}`}function $i(e,t){const{varName:n,pkgId:r,fnName:o,bindings:i,needsSession:s,paramNames:a,schemaProps:c,literalDomainArgs:d}=t,l=t.dispatchSchemaKey??`${r}:${o}`;e.push(" .action(async (opts: Record<string, unknown>) => {");const u=Object.entries(d??{}).map(([g,p])=>`'${g}': ${p}`),f=a.map(g=>An(c[g])?`'${g}': __apigenParseJsonArg('${to(g)}', opts['${g}'])`:`'${g}': opts['${g}']`);if(e.push(` const domainArgs: Record<string, unknown> = { ${[...u,...f].join(", ")} }`),i.length>0){const g=i.map(p=>{const v=p.flag.replace(/^--/,"").replace(/-([a-z])/g,(h,y)=>y.toUpperCase());return`'${p.field}': opts['${v}'] ?? process.env['${p.envVar}']`});e.push(` const envelope: Record<string, unknown> = { ${g.join(", ")} }`)}else s?e.push(" const envelope: Record<string, unknown> = { session: opts['session'] }"):e.push(" const envelope: Record<string, unknown> = {}");e.push(` const result = await dispatch(${n}_fns as any, undefined, schemas['${l}'] as any, '${o}', envelope, domainArgs)`),e.push(" console.log(JSON.stringify(result))"),e.push(" })")}function zd(e,t){const{varName:n,pkgId:r,fnName:o,bindings:i,needsSession:s,rootUnion:a}=t,c=At(`${r}_${o}_cmd`);e.push(`const ${c} = program.command('${o}')`);for(const d of a.branches){const l=Object.keys(d.props).filter(f=>f!==a.discriminatorProperty),u=d.required.filter(f=>f!==a.discriminatorProperty);e.push(`${c}`),e.push(` .command('${d.commandName}')`),Ri(e,i,s),Ii(e,l,d.props,u),$i(e,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:Ti(r,o,d.commandName),bindings:i,needsSession:s,paramNames:l,schemaProps:d.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(d.value)}})}}function Yd(e){const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=e.packages.some(s=>Object.values(s.schemas).some(a=>{const c=tn(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(u=>u!==c.discriminatorProperty).some(u=>An(l.props[u])));const{props:d}=dr(a);return hn(a).some(l=>An(d[l]))})),o=["#!/usr/bin/env node","// Auto-generated by @adhd/apigen-cli — do not edit","import { Command } from 'commander'","import { dispatch, buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const s of e.packages){const a=At(s.id),c=Jd(e.outputDir,s.importPath);o.push(`import * as ${a}_ns from '${c}'`),o.push(`const ${a}_fns = buildFnTable(${a}_ns as Record<string, unknown>)`)}o.push(""),r&&(o.push(Wd),o.push(""));const i=Object.fromEntries(e.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,c])));for(const s of e.packages)for(const[a,c]of Object.entries(s.schemas)){const d=tn(c);if(d)for(const l of d.branches){const u=Ti(s.id,a,l.commandName);i[u]={input:{type:"object",properties:{data:{type:"object",properties:l.props,additionalProperties:!1,...l.required.length>0?{required:l.required}:{}}},required:["data"]},output:{},...c.hasCtx?{hasCtx:!0}:{}}}}o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(i,null,2)}`),o.push(""),o.push(`const program = new Command().name('${t}').version('${n}')`),o.push("");for(const s of e.packages){const a=At(s.id);for(const[c,d]of Object.entries(s.schemas)){const l=si(d,"session"),u=Kd(d),f=tn(d);if(f){zd(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,rootUnion:f});continue}const g=hn(d),{props:p,required:m}=dr(d);o.push("program"),o.push(` .command('${c}')`),Ri(o,u,l),Ii(o,g,p,m),$i(o,{varName:a,pkgId:s.id,fnName:c,bindings:u,needsSession:l,paramNames:g,schemaProps:p})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
4
+ `)}]}}function Xd(e){return{props:e.properties??{},required:e.required??[]}}function Qd(e){const t=e??{},r=Array.isArray(t.oneOf)&&t.oneOf.length>0?t.oneOf:[t],o={},i=new Map;for(const a of r){const{props:c,required:d}=Xd(a);for(const[l,u]of Object.entries(c))l in o||(o[l]=u);for(const l of d)i.set(l,(i.get(l)??0)+1)}const s=[...i.entries()].filter(([,a])=>a===r.length).map(([a])=>a);return{input:{type:"object",properties:{data:{type:"object",properties:o,required:s}},required:["data"]},output:{}}}function Zd(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(e);)t.push(r[1]??r[2]??r[3]);return t}function el(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?Zd(t):process.argv.slice(2)}function tl(e,t){return{id:e,host:"ts",namespace:{raw:e,words:[e]},path:[],kind:"action",async:!1,streaming:!1,safe:t["x-apigen-safe"]??!1,input:t.input??{},output:t.output??{},envelope:{},typeText:null}}function nl(e){const t=new Map;for(const r of e.operations??[]){const o=r.path[r.path.length-1];o&&t.set(`${r.namespace.raw}:${o.raw}`,r)}const n=new Map;for(const r of e.packages)for(const[o,i]of Object.entries(r.schemas)){const s=t.get(`${r.id}:${o}`)??tl(o,i),a=ye({op:s,schema:i,transport:"cli"}),c=a.cli.path;n.set(c.join(" "),{pkgId:r.id,fnName:o,schema:i,cliPath:c,plan:a})}return n}function ol(e,t){let n=0;for(;n<e.length&&!e[n].startsWith("-");)n++;for(let r=n;r>=1;r--){const o=t.get(e.slice(0,r).join(" "));if(o)return{entry:o,rest:e.slice(r)}}return null}function Ci(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function lr(e){const t=["Available commands:",""],n=[...e.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const i=Ci(o.params);t.push(` ${r}${i?` { ${i} }`:""}`)}return t.join(`
5
+ `)}function pt(e){return new L("invalid_argument",e)}function rl(e,t){var i;const n={},r={};let o=0;for(;o<e.length;){const s=e[o];if(!s.startsWith("--"))throw pt(`Unexpected positional argument: "${s}"`);let a=s.slice(2),c;const d=a.indexOf("=");d!==-1&&(c=a.slice(d+1),a=a.slice(0,d));let l=!1,u=a;a.startsWith("no-")&&((i=t.get(a.slice(3)))==null?void 0:i.valueKind)==="boolean"&&(l=!0,u=a.slice(3));const f=t.get(u);if(!f)throw pt(`Unknown option: --${a}. Available: ${[...t.entries()].filter(([,p])=>p.aliasOf===void 0).map(([p])=>p).sort().map(p=>`--${p}`).join(", ")}`);o++;let g;if(f.valueKind==="boolean")l?g=!1:c===void 0?g=!0:g=c!=="false";else{const p=c!==void 0?c:e[o++];if(p===void 0)throw pt(`Missing value for --${a}`);if(f.valueKind==="json")try{g=JSON.parse(p)}catch(m){throw pt(`Invalid JSON for --${a}: ${m.message}`)}else g=p}f.kind==="domain"?n[f.camelKey]=g:r[f.camelKey]=g}for(const s of t.values()){if(s.kind!=="envelope"||!s.envVar||r[s.camelKey]!==void 0)continue;const a=process.env[s.envVar];a!==void 0&&(r[s.camelKey]=a)}return{domainArgs:n,envelope:r}}function Pi(e){const t=re(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:String(e)};console.error(JSON.stringify(t)),process.exitCode=re(e)?Qo[e.code]:Qo.internal}function il(e,t,n){if(re(n)&&n.code!=="internal"){e.error({command:t,code:n.code,message:n.message},`✗ ${t}`);return}e.error({command:t,err:n},`✗ ${t}`)}class sl{constructor(t,n){this.signal=t,this.exitCodeHook=n,this.routes=new Map}registerRoute(t,n){this.routes.set(t.cli.path.join(" "),{plan:t,dispatch:n})}routeTable(){return this.routes}readCall(t,n){const{domainArgs:r,envelope:o}=rl(t.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(t,n,r){var i;if(Dt(n))throw new L("invalid_argument",`Command "${r.cli.path.join(" ")}" produced a streaming result, which is not supported over the cli transport.`);console.log(JSON.stringify(n===void 0?null:n));const o=(i=this.exitCodeHook)==null?void 0:i.call(this,n);typeof o=="number"&&o!==0&&(process.exitCode=o)}writeError(t,n,r){Pi(n)}}function al(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("cli")||i.push(u)}return i}async function cl(e){var E,A,j;const t=e.logger??Xn();if((E=e.signal)!=null&&E.aborted){t.info("cli run: signal already aborted before dispatch — skipping");return}let n=el(e.options);n[0]==="--"&&(n=n.slice(1));const r=Zn(e.options),o=eo(e.options),i=new sl(e.signal,Md(e.options)),s=nl(e),a=new Map;for(const N of s.values()){const _=a.get(N.pkgId);_?_.push(N):a.set(N.pkgId,[N])}const c={},d={};for(const N of e.packages){const _=a.get(N.id);if(!_||_.length===0)continue;if(!N.fns)throw new Error(`apigen-plugin-cli-output: package "${N.id}" has no functions`);const R=N.fns,T={},C={};for(const P of _)T[P.plan.op.id]=P.schema,C[P.plan.op.id]=R[P.fnName],c[P.plan.op.id]=P.schema,d[P.plan.op.id]=R[P.fnName];const q=de(T,r),x={fns:C,createClient:N.createClient,schemas:T};for(const P of _)i.registerRoute(P.plan,Y=>xe(P.plan,q,Y,x))}const l=((A=e.packages[0])==null?void 0:A.id)??"ts",u=de(c,r),f={invoke:(N,_,R)=>u(N,{operation:{id:N},ctx:new tt,domainArgs:_.domainArgs,envelope:_.envelope,signal:_.signal},R),invokeOptions:{fns:d,schemas:c,createClient:(j=e.packages[0])==null?void 0:j.createClient}},g=al(r,o,l,e.operations??[],f);if(g.length>0){const N=de({},r),_={fns:{},schemas:{}};for(const R of g){const T=ye({op:R,schema:Qd(R.input),transport:"cli"});i.registerRoute(T,C=>xe(T,N,C,_))}}const p=i.routeTable();if(n.length===0||n[0]==="--help"||n[0]==="-h"){console.log(lr(p));return}const m=ol(n,p);if(!m){Pi(new L("not_found",`Unknown command: ${n.join(" ")}
6
6
 
7
- ${Tp(h)}`));return}const{entry:b,rest:E}=v,{plan:N,dispatch:j}=b,T=N.cli.path.join(" ");if(E.includes("--help")||E.includes("-h")){const C=Xg(N.params);console.log(`${T}${C?` { ${C} }`:""}`);return}const M={rest:E};try{if(N.streaming)throw new Li("invalid_argument",`Command "${T}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const C=await c.readCall(M,N),G=Date.now(),H=await j(C);await c.writeResult(M,H,N),o.info({command:T,ms:Date.now()-G},`→ ${T}`)}catch(C){FS(o,T,C),await c.writeError(M,C,N)}}const GS={id:"cli",description:"Emit a Commander CLI program where each exported function becomes a subcommand",language:"ts",optionsSchema:{type:"object",properties:{name:{type:"string",default:"cli"},version:{type:"string",default:"0.1.0"},argv:{anyOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},generate(t){return xS(t)},run(t){return VS(t)}};let qt=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function Cp(t){return{raw:t,words:t.split(/(?=[A-Z])|[-_]/).map(e=>e.toLowerCase()).filter(Boolean)}}function zS(t,e,n={}){const r=t.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${t}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:t,host:e.host,namespace:Cp(i),path:s.map(Cp),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);function WS(t){if(t.length<2)return;const e=[];for(const r of t){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;e.push(o)}const n=Object.keys(e[0]).filter(r=>e.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of e){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}const HS={"decimal.js":"Decimal"};function JS(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(HS).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${JS(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function QS(t){return{oneOf:[{type:"object",required:["index","status","value"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},value:t}},{type:"object",required:["index","status","chunks"],properties:{index:{type:"integer"},status:{type:"string",enum:["fulfilled"]},chunks:{type:"array"}}},{type:"object",required:["index","status","reason"],properties:{index:{type:"integer"},status:{type:"string",enum:["rejected"]},reason:{},chunksDelivered:{type:"integer"}}}]}}function YS(t){return{operationConst:t.id,itemsSchema:t.input,resultSchema:QS(t.output)}}function ZS(t,e={}){const n=new Set(e.exclude??[]),r=new Map;for(const o of t){if(n.has(o.id))continue;const s=r.get(o.kind);s?s.push(o):r.set(o.kind,[o])}return r}function Mp(t){return{type:"string",enum:[t]}}function Lp(t,e){return{type:"object",required:["input"],properties:{input:{type:"object",required:["operation","items"],properties:{operation:e,items:{type:"array",items:t.itemsSchema},concurrency:{type:"number"},mode:{type:"string",enum:["parallel","serial","chained"]},onItemError:{type:"string",enum:["continue","abort"]},itemTimeoutMs:{type:"number"}},additionalProperties:!0}},additionalProperties:!1}}function Dp(t,e){const n={},r={},o=[["definitions",n],["$defs",r]];for(const s of t){const i=e(s);for(const[a,c]of o){const u=i[a];if(u)for(const[l,d]of Object.entries(u)){const f=c[l];if(f!==void 0&&JSON.stringify(f)!==JSON.stringify(d))throw new Error(`[apigen-core-client] _batch mount: operation "${s.id}" contributes a "${a}.${l}" definition that conflicts with an identically-named definition already hoisted from another batched operation. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one _batch/<kind> schema.`);c[l]=d}}}return{...Object.keys(n).length>0?{definitions:n}:{},...Object.keys(r).length>0?{$defs:r}:{}}}function XS(t){if(t.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const e=t.map(YS),n=Dp(t,i=>i.input),r=Dp(t,i=>i.output);if(t.length===1){const[i]=t,[a]=e;return{input:{...Lp(a,Mp(i.id)),...n},output:{type:"array",items:a.resultSchema,...r}}}const o=t.map((i,a)=>Lp(e[a],Mp(i.id))),s=WS(o);return{input:{oneOf:o,...s?{discriminator:s}:{},...n},output:{oneOf:e.map(i=>({type:"array",items:i.resultSchema})),...r},...s?{discriminator:s}:{}}}function e_(t,e={}){const n=ZS(t.operations,e),r=[];for(const[o,s]of n){const{input:i,output:a}=XS(s),c=zS(`_batch/${o}`,t,{kind:o,safe:o==="query",input:i,output:a});r.push({...c,operationIds:s.map(u=>u.id)})}return r}const qc="$apigen";let Up=class extends Error{constructor(e){super(e),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function t_(t){const e=new Map;return{register(n,r){if(e.has(n.id)&&!(r!=null&&r.override))throw new Up(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);e.set(n.id,n)},resolve(n){for(const r of e.values())if(r.matches(n))return r},get(n){return e.get(n)},ids(){return[...e.keys()]},freeze(){const n=new Map(e),r={register(){throw new Up("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const gl="x-apigen-logical",yl="x-apigen-codec",Kc="x-apigen-ctor",Vc="x-apigen-tojson",n_="0.1.0";function Bp(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...e}}function Tr(t,e,n){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Tr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=ty(t,s,e,n);return Tr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return Lo(t,e,n);const a=e.items;if(!a)return t.map(u=>ir(u));const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?ir(u):Tr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Tr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return Lo(t,e,n);const a=e.properties;if(!a)return ir(t);const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Tr(f,d,{...n,path:`${c}/${l}`}))}return u}return i==null?Lo(t,e,n):ir(t)}function Cr(t,e,n){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Cr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=ty(t,s,e,n);return Cr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?u:Cr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Cr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Cr(f,d,{...n,path:`${c}/${l}`}))}for(const[l,d]of Object.entries(t))!(l in a)&&d!==void 0&&(u[l]=d);return u}return i==null?Gc(t,n):t}function ty(t,e,n,r){var o;const s=n.discriminator;if(s!=null&&s.propertyName){const u=s.propertyName,l=t!==null&&typeof t=="object"?t[u]:void 0;if(typeof l=="string"){if(s.mapping){const d=s.mapping[l];if(d){const f=e.find(g=>g.$ref===d);if(f)return f}}for(const d of e){const f=(o=Di(d,r).properties)==null?void 0:o[u];if(!f)continue;const g=f.enum;if(f.const===l||Array.isArray(g)&&g.includes(l))return d}}}const i=r_(t,e,r);if(i)return i;let a,c=-1;for(const u of e){const l=Di(u,r),d=ny(t,l,r);d!==null&&d>c&&(c=d,a=u)}return a!==void 0?a:e[0]??{}}function Di(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function Fp(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function r_(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t,o=e.map(i=>Di(i,n)),s=new Set;for(const i of o){const a=i.properties;if(a)for(const[c,u]of Object.entries(a))Fp(u)!==void 0&&s.add(c)}for(const i of s){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[i];return p?Fp(p):void 0}),c=a.filter(f=>f!==void 0),u=new Set(c);if(c.length<2||u.size!==c.length)continue;const l=r[i];if(l===void 0)continue;const d=a.findIndex(f=>f===l);if(d!==-1)return e[d]}}function o_(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function ny(t,e,n){const r=e.oneOf;if(Array.isArray(r)){let l=null;for(const d of r){const f=ny(t,Di(d,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,s=o_(t);if(typeof o=="string"){if(!(o===s||o==="number"&&s==="integer"))return null}else if(Array.isArray(o)&&!o.some(l=>l===s||l==="number"&&s==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const i=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(i[l]===void 0)return null;c+=2}}const u=e.properties;if(u){for(const l of Object.keys(u))i[l]!==void 0&&(c+=1);for(const l of Object.keys(i))u[l]===void 0&&(c-=1)}return c}function Lo(t,e,n){var r;for(const o of n.registry.ids()){const s=n.registry.get(o);if((r=s==null?void 0:s.ownsValue)!=null&&r.call(s,t))return{[qc]:o,v:s.encode(t,s.schema,n)}}if(Array.isArray(t))return t.map(o=>Lo(o,{},n));if(ry(t)){const o={};for(const[s,i]of Object.entries(t))i!==void 0&&(o[s]=Lo(i,{},n));return o}return ir(t)}function ry(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Gc(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&qc in t){const n=t,r=n[qc],o=e.registry.get(r);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>Gc(n,e));if(ry(t)){const n={};for(const[r,o]of Object.entries(t))n[r]=Gc(o,e);return n}return t}function ir(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(ir);if(typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=ir(r));return e}return null}function s_(t){return{encode(e,n,r){const o=Bp(t,r);return Tr(e,n,o)},decode(e,n,r){const o=Bp(t,r);return Cr(e,n,o)}}}const wl={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},vl={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}},$l={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},bl={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},i_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,El={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!i_.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},zc="NaN",Wc="Infinity",Hc="-Infinity",a_=new Set([zc,Wc,Hc]),Sl={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?zc:t===1/0?Wc:t===-1/0?Hc:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===zc)return NaN;if(t===Wc)return 1/0;if(t===Hc)return-1/0;const r=Number(t);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...a_].join(", ")}.`);return NaN}},c_=[wl,vl,$l,bl,El,Sl];function u_(t,e={}){for(const n of c_)t.register(n,{override:e.override??!1})}wl.id,vl.id,$l.id,bl.id,El.id,Sl.id;const oy=t_();u_(oy);s_(oy.freeze());let l_=class{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const d_={"decimal.js":"Decimal"};function f_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(d_).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${f_(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));const p_=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];let sy=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function iy(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&p_.includes(t.code)&&typeof t.toJSON=="function"}function qp(t,e,n=0){return t==="before-first-chunk"?{phase:t,error:e}:{phase:t,error:e,chunksDelivered:n}}const _l=new ia({allErrors:!0});aa(_l);for(const t of[gl,yl,Kc,Vc,"discriminator"])_l.addKeyword({keyword:t,valid:!0});_l.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);async function h_(t){const e=[];try{for await(const n of t)e.push(n);return{ok:!0,chunks:e}}catch(n){const r=iy(n)?n:new sy("internal",n instanceof Error?n.message:String(n));return e.length===0?{ok:!1,carrier:qp("before-first-chunk",r)}:{ok:!1,carrier:qp("after-first-chunk",r,e.length)}}}function m_(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}let Kn=class extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}};function Xa(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function ay(t,e){const n=t[yl];if(typeof n=="string"){const r=e.registry.get(n);if(r)return r}return e.registry.resolve(t)}function g_(t,e,n){const r=ay(e,n);return r?r.encode(t,e,n):t}function y_(t,e,n){const r=ay(e,n);return r?r.decode(t,e,n):t}function w_(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(r){if(r[gl]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Xa(r)!==void 0},encode(r,o,s){const i=Xa(o);if(!i)throw new Kn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new Kn("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),d=c[l];if(!d)throw new Kn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=s.resolve(d);return g_(r,f,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new Kn("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${p}.`)}const i=r,a=Xa(o);if(!a)throw new Kn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new Kn("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const d=String(l),f=u[d];if(!f)throw new Kn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${d}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const g=s.resolve(f);return y_(r,g,{...s,path:`${s.path}[${d}]`})}}}const v_="x-apigen-instances";let Cs=class extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}};function Kp(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function $_(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function Vp(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n)}return t}function b_(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n)}return t}function E_(t){const{id:e,schema:n,ctor:r}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[gl]==="nominal"?!0:o[yl]===e},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Cs("E_NOMINAL_CYCLE",`[${e}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Kp(s),c=typeof s[Vc]=="string"?s[Vc]:"toJSON",u=o[c];if(typeof u=="function"){const p=u.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[w,h]of Object.entries(p))y[w]=Vp(h,a[w],{...i,path:`${i.path}/${w}`});return y}return p}const l={},d=Object.keys(a),f=o,g=d.length>0?d:Object.keys(f);for(const p of g){const y=f[p];y!==void 0&&(l[p]=Vp(y,a[p],{...i,path:`${i.path}/${p}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new Cs("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of $_(s))if(!(l in a))throw new Cs("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${i.path}".`);if(s[v_]===!1)throw new Cs("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Kp(s),u={};for(const[l,d]of Object.entries(a))u[l]=b_(d,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Kc]=="string"?s[Kc]:"fromJSON",d=r[l];if(typeof d=="function")return d.call(r,u);const f=r;return new f(u)}return u}}}const S_=[wl,vl,$l,bl,El,Sl],__={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Gp=E_({id:"ts.NominalSentinel",schema:__}),N_={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},zp=w_({id:"ts.UnionSentinel",schema:N_});function O_(){const t=[...S_.map(e=>[e.id,e]),[Gp.id,Gp],[zp.id,zp]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:n_,codecs:O_()});const k_=4,j_=32;function Jc(t){return iy(t)?t:t instanceof Error?new sy("internal",t.message):t}function A_(t,e){if(t==="serial"||t==="chained")return 1;const n=e??k_;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),j_)}function I_(){}function P_(t,e){var n;if(!t&&!e)return{signal:void 0,dispose:I_};const r=new AbortController,o=()=>{r.abort(t==null?void 0:t.reason)};t&&(t.aborted?r.abort(t.reason):t.addEventListener("abort",o,{once:!0}));let s;return e!==void 0&&!r.signal.aborted&&(s=setTimeout(()=>{r.abort(new DOMException(`apigen/invokeBatch: item timed out after ${e}ms`,"TimeoutError"))},e),(n=s.unref)==null||n.call(s)),{signal:r.signal,dispose(){t&&t.removeEventListener("abort",o),s&&clearTimeout(s)}}}async function Wp(t,e,n,r,o,s){const i=P_(r.signal,s);try{const a=i.signal?{...r,signal:i.signal}:r,c=await t(e,a,o);if(m_(c)){const u=await h_(c);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const l=u.carrier;return{index:n,status:"rejected",reason:Jc(l.error),...l.phase==="after-first-chunk"?{chunksDelivered:l.chunksDelivered}:{}}}return{index:n,status:"fulfilled",value:c}}catch(a){return{index:n,status:"rejected",reason:Jc(a)}}finally{i.dispose()}}async function x_(t,e,n,r,o={}){const s=o.mode??"parallel",i=o.onItemError??"continue",a=A_(s,o.concurrency),c=new Array(n.length),u=p=>({index:p,status:"rejected",reason:Jc(new Error("apigen/invokeBatch: not attempted — an earlier item failed and "+(s==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(s==="serial"||s==="chained"){let p=!1;for(let y=0;y<n.length;y++){if(p){c[y]=u(y);continue}const w=await Wp(t,e,y,n[y],r,o.itemTimeoutMs);c[y]=w,w.status==="rejected"&&(s==="chained"||i==="abort")&&(p=!0)}return c}let l=0,d=!1;const f=Math.max(1,Math.min(a,n.length)),g=Array.from({length:f},async()=>{for(;;){const p=l++;if(p>=n.length)return;if(d){c[p]=u(p);continue}const y=await Wp(t,e,p,n[p],r,o.itemTimeoutMs);c[p]=y,y.status==="rejected"&&i==="abort"&&(d=!0)}});return await Promise.all(g),c}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const R_={"decimal.js":"Decimal"};function T_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(R_).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${T_(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function C_(t,e){const n=t.input;if(n===null||typeof n!="object"||Array.isArray(n))throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input" must be an object containing {operation, items, ...}');const r=n,o=r.operation;if(typeof o!="string"||o.length===0)throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.operation" must be a non-empty string naming the target operation id');if(!e.includes(o))throw new qt("invalid_argument",`@adhd/apigen-plugin-batch: "input.operation" ("${o}") is not one of this mount's batchable operations: ${e.join(", ")}`);const s=r.items;if(!Array.isArray(s))throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.items" must be an array');const i=r.concurrency;if(i!==void 0&&typeof i!="number")throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.concurrency" must be a number');const a=r.mode;if(a!==void 0&&a!=="parallel"&&a!=="serial"&&a!=="chained")throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.mode" must be one of "parallel" | "serial" | "chained"');const c=r.onItemError;if(c!==void 0&&c!=="continue"&&c!=="abort")throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.onItemError" must be one of "continue" | "abort"');const u=r.itemTimeoutMs;if(u!==void 0&&typeof u!="number")throw new qt("invalid_argument",'@adhd/apigen-plugin-batch: "input.itemTimeoutMs" must be a number');return{operation:o,items:s,concurrency:i,mode:a,onItemError:c,itemTimeoutMs:u}}function M_(t,e){return async n=>{if(!e)throw new qt("internal","@adhd/apigen-plugin-batch: this host has not supplied a MountHostBridge to MountCapability.operations() (BATCH_0.0.1.md §2/§F1) — `_batch` cannot invoke another operation without one. Upgrade the host's run.ts to thread a MountHostBridge through its mount-collection call site, or do not mount the `batch` plugin (`--use batch`) on this host.");const r=C_(n.data,t),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},s=r.items.map(i=>({operation:{id:r.operation},ctx:new l_,domainArgs:i??{},envelope:n.envelope,signal:n.signal}));return x_(e.invoke,r.operation,s,e.invokeOptions,o)}}function L_(t,e={},n){return e_(t,e).map(r=>({...r,handler:M_(r.operationIds,n)}))}const Ui={id:"batch",description:"Mount plugin: exposes _batch/<kind> generic N-way fan-out over already-mounted operations (BATCH_0.0.1.md)",language:"ts",optionsSchema:{type:"object",properties:{exclude:{type:"array",items:{type:"string"},description:"Operation ids to exclude from every _batch/<kind> branch set"}},additionalProperties:!1},capabilities:{mount:{operations(t,e,n){return L_(t,e,n)}}}};Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const Hp=new Set(["string","number","boolean","integer"]);function D_(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Hp.has(n):Array.isArray(n)?n.every(r=>Hp.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function U_(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(D_)}const B_={"decimal.js":"Decimal"};function F_(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(B_).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${F_(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function Jp(t){return t.words.join("-")}function Qp(t){return t.words.map(q_).join("")}function Yp(t){return t.words.join("_")}function la(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||U_(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>Jp(g)).join("/"),c=o.map(g=>Yp(g)).join("_"),u=o.map(g=>Yp(g)).slice(0,-1).join("."),l=Qp(o[o.length-2]??o[0]),d=Qp(o[o.length-1]),f=o.map(g=>Jp(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function q_(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}const Zp={validateKind(){},validateRel(){},validateEdge(){}},K_=5,V_=20,G_=500;function z_(t){return pn.isBusyError(t)||pn.isConcurrentConflict(t)}function W_(t){return new Promise(e=>setTimeout(e,Math.max(0,Math.round(t))))}async function H_(t,e={}){const n=e.maxAttempts??K_;for(let r=0;;r++)try{return await t()}catch(o){if(!z_(o)||r>=n-1)throw o;const s=Math.min(G_,V_*2**r);await W_(s*(.5+Math.random()*.5))}}const Nl=new Set(["project","component","location","issue","kind","edge_kind","status","priority","agent","note","citation","transition","audit"]);class cy extends Error{constructor(e,n){const r=e.length>0?e.map(o=>`${o.kind}=${o.count}`).join(", "):"(none)";super(`backlog: store vocabulary mismatch — refusing to read or write a store this build cannot address.
7
+ ${lr(p)}`));return}const{entry:v,rest:h}=m,{plan:y,dispatch:w}=v,b=y.cli.path.join(" ");if(h.includes("--help")||h.includes("-h")){const N=Ci(y.params);console.log(`${b}${N?` { ${N} }`:""}`);return}const S={rest:h};try{if(y.streaming)throw new L("invalid_argument",`Command "${b}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const N=await i.readCall(S,y),_=Date.now(),R=await w(N);await i.writeResult(S,R,y),t.info({command:b,ms:Date.now()-_},`→ ${b}`)}catch(N){il(t,b,N),await i.writeError(S,N,y)}}const dl={id:"cli",description:"Emit a Commander CLI program where each exported function becomes a subcommand",language:"ts",optionsSchema:{type:"object",properties:{name:{type:"string",default:"cli"},version:{type:"string",default:"0.1.0"},argv:{anyOf:[{type:"array",items:{type:"string"}},{type:"string"}]}}},generate(e){return Yd(e)},run(e){return cl(e)}};function ll(e,t){const n=e.input;if(n===null||typeof n!="object"||Array.isArray(n))throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input" must be an object containing {operation, items, ...}');const r=n,o=r.operation;if(typeof o!="string"||o.length===0)throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.operation" must be a non-empty string naming the target operation id');if(!t.includes(o))throw new L("invalid_argument",`@adhd/apigen-plugin-batch: "input.operation" ("${o}") is not one of this mount's batchable operations: ${t.join(", ")}`);const i=r.items;if(!Array.isArray(i))throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.items" must be an array');const s=r.concurrency;if(s!==void 0&&typeof s!="number")throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.concurrency" must be a number');const a=r.mode;if(a!==void 0&&a!=="parallel"&&a!=="serial"&&a!=="chained")throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.mode" must be one of "parallel" | "serial" | "chained"');const c=r.onItemError;if(c!==void 0&&c!=="continue"&&c!=="abort")throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.onItemError" must be one of "continue" | "abort"');const d=r.itemTimeoutMs;if(d!==void 0&&typeof d!="number")throw new L("invalid_argument",'@adhd/apigen-plugin-batch: "input.itemTimeoutMs" must be a number');return{operation:o,items:i,concurrency:s,mode:a,onItemError:c,itemTimeoutMs:d}}function ul(e,t){return async n=>{if(!t)throw new L("internal","@adhd/apigen-plugin-batch: this host has not supplied a MountHostBridge to MountCapability.operations() (BATCH_0.0.1.md §2/§F1) — `_batch` cannot invoke another operation without one. Upgrade the host's run.ts to thread a MountHostBridge through its mount-collection call site, or do not mount the `batch` plugin (`--use batch`) on this host.");const r=ll(n.data,e),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},i=r.items.map(s=>({operation:{id:r.operation},ctx:new tt,domainArgs:s??{},envelope:n.envelope,signal:n.signal}));return _d(t.invoke,r.operation,i,t.invokeOptions,o)}}function fl(e,t={},n){return Xc(e,t).map(o=>({...o,handler:ul(o.operationIds,n)}))}const jt={id:"batch",description:"Mount plugin: exposes _batch/<kind> generic N-way fan-out over already-mounted operations (BATCH_0.0.1.md)",language:"ts",optionsSchema:{type:"object",properties:{exclude:{type:"array",items:{type:"string"},description:"Operation ids to exclude from every _batch/<kind> branch set"}},additionalProperties:!1},capabilities:{mount:{operations(e,t,n){return fl(e,t,n)}}}},ur={validateKind(){},validateRel(){},validateEdge(){}},pl=5,ml=20,gl=500;function hl(e){return pe.isBusyError(e)||pe.isConcurrentConflict(e)}function yl(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}async function wl(e,t={}){const n=t.maxAttempts??pl;for(let r=0;;r++)try{return await e()}catch(o){if(!hl(o)||r>=n-1)throw o;const i=Math.min(gl,ml*2**r);await yl(i*(.5+Math.random()*.5))}}const no=new Set(["project","component","location","issue","kind","edge_kind","status","priority","agent","note","citation","transition","audit"]);class xi extends Error{constructor(t,n){const r=t.length>0?t.map(o=>`${o.kind}=${o.count}`).join(", "):"(none)";super(`backlog: store vocabulary mismatch — refusing to read or write a store this build cannot address.
8
8
  expected node kind(s): ${n.join(", ")}
9
9
  found in store: ${r}
10
10
  The store holds live node(s) but none of a kind this build recognizes, so every item read would match zero rows and report a misleading "0 items".
11
- Likely cause: this store was written by a build with a different item vocabulary and was never converted to the one this build uses. Refusing rather than returning an empty result.`),this.observed=e,this.recognized=n,this.name="StoreVocabularyMismatchError"}}async function uy(t){const{rows:e}=await t.executeAll("SELECT kind, COUNT(*) AS n FROM node WHERE t_invalid IS NULL GROUP BY kind ORDER BY n DESC"),n=e.map(o=>({kind:String(o.kind),count:Number(o.n)}));return{total:n.reduce((o,s)=>o+s.count,0),observed:n}}async function J_(t){const e=[...Nl],n=e.map(()=>"?").join(", "),{rows:r}=await t.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,e);return r.length>0}async function Ol(t){if(await J_(t))return;const{total:e,observed:n}=await uy(t);if(e!==0)throw new cy(n,[...Nl])}const Q_=3e4,Xp=new WeakMap;function Y_(t){let e=Xp.get(t);return e||(e=new Set,Xp.set(t,e)),e}function ly(t){const e=Y_(t);return{register(n){e.add(n);let r=!1;return()=>{r||(r=!0,e.delete(n))}},get size(){return e.size},snapshot(){return[...e]},async drain(n){const r=(n==null?void 0:n.timeoutMs)??Q_,o=Date.now()+r;let s=0;for(;;){const a=[...e].filter(l=>l.outcome==="pending");if(a.length===0)break;const c=o-Date.now();if(c<=0)break;const u=await Z_(Promise.allSettled(a.map(l=>l.settled)),c);if(s+=a.filter(l=>l.outcome!=="pending").length,u==="timeout")break}const i=[...e];return{drained:s,stillPending:i.filter(a=>a.outcome==="pending"),recordedAsFailed:0,unrecorded:i.filter(a=>a.outcome==="unrecorded")}}}}async function Z_(t,e){let n;const r=new Promise(o=>{n=setTimeout(()=>o("timeout"),e),typeof n=="object"&&n!==null&&"unref"in n&&n.unref()});try{return await Promise.race([t,r])}finally{n!==void 0&&clearTimeout(n)}}class Ke extends Error{constructor(e,n=void 0,r){super(e),this.name=new.target.name,this.cause=n,this.retry_after_ms=r}}class dy extends Ke{constructor(e,n){super(`Write contention: exhausted the retry budget (last backoff ${e}ms)`,n,e),this.code="E_CONTENTION",this.retryable=!0}}class kl extends Ke{constructor(e){super("Write I/O failure: an unclassified driver/connection error surfaced from the underlying transaction",e),this.code="E_IO",this.retryable=!0}}class da extends Ke{constructor(e,n){super(n===void 0?`Issue "${e}" was already superseded by a concurrent write; re-get and retry`:`Issue "${e}" was superseded by a body edit and is no longer the live issue; it now lives under "${n}"`),this.uid=e,this.successorUid=n,this.code="E_CONSTRAINT",this.retryable=!1}}class Xe extends Ke{constructor(e,n){super(`${e} "${n}" was not found`),this.catalogKind=e,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class oe extends Ke{constructor(e,n){super(n?`Invalid argument "${e}": ${n}`:`Invalid argument "${e}"`),this.field=e,this.code="E_VALIDATION",this.retryable=!1}}class fa extends Ke{constructor(e){super(`No live issue found for uid "${e}"`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class Bi extends Ke{constructor(e,n){super(`Claim already held by "${e}" since ${n}`),this.heldBy=e,this.heldSince=n,this.code="E_VALIDATION",this.retryable=!1}}class fy extends Ke{constructor(e,n){super(`Issue "${e}" is in terminal status "${n}" and cannot be claimed; re-open it via "transition" first`),this.uid=e,this.status=n,this.code="E_VALIDATION",this.retryable=!1}}class Qc extends Ke{constructor(e){const n=e.side==="source"?`"${e.rel}" already has a single target (${e.conflictingUid}) for source "${e.cappedUid}"`:`"${e.rel}" already has a single source (${e.conflictingUid}) for target "${e.cappedUid}"`;super(n),this.code="E_VALIDATION",this.retryable=!1,this.side=e.side,this.cappedUid=e.cappedUid,this.rel=e.rel,this.conflictingUid=e.conflictingUid}}class jl extends Ke{constructor(e){super(`Citation target "${e}" could not be verified and this project requires a real sha`),this.target=e,this.code="E_VALIDATION",this.retryable=!1}}class py extends Ke{constructor(e){super(`A note is required to transition issue "${e}" (project_policy.transition_requires_note)`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class hy extends Ke{constructor(e){super(`At least one citation is required to close issue "${e}" (project_policy.citation_required)`),this.uid=e,this.code="E_VALIDATION",this.retryable=!1}}class Er extends Ke{constructor(e,n){super(n?`Invalid "${e}": ${n}`:`Invalid "${e}"`),this.field=e,this.code="E_VALIDATION",this.retryable=!1}}function X_(t){const e=t instanceof Error?t.message:String(t);return pn.isBusyError(t)||pn.isConcurrentConflict(t)?{code:"E_CONTENTION",retryable:!0,message:e,cause:t}:pn.isUniqueConstraintError(t)||pn.isForeignKeyError(t)?{code:"E_CONSTRAINT",retryable:!1,message:e,cause:t}:pn.isDatabaseError(t)?{code:"E_IO",retryable:!0,message:e,cause:t}:{code:"E_IO",retryable:!1,message:e,cause:t}}const eN=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function jt(t,e){if(eN.has(e.trim().toLowerCase()))throw new oe(t,`"${e}" is a bare role literal, not a real identity — use "\${agentName}:\${instanceId}" (e.g. "claude:1"), never a bare role word`)}function my(t){if(t!=null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}function gy(t){return{rowid:t.rowid,uid:t.uid,kind:t.kind,name:t.name,content:t.content??"",metadata:my(t.meta),tInvalid:t.t_invalid,isSuperseded:t.is_superseded===1}}function He(){return new Date().toISOString()}function Al(t){return kn.createHash("sha256").update(t).digest("hex")}function yy(t){return JSON.stringify(Yc(t))}function Yc(t){if(Array.isArray(t))return t.map(Yc);if(t!==null&&typeof t=="object"){const e=t,n={};for(const r of Object.keys(e).sort())e[r]!==void 0&&(n[r]=Yc(e[r]));return n}return t}async function pa(t,e){const n=await t.executeGet("SELECT * FROM node WHERE uid = ?",[e]);return n?gy(n):null}async function _n(t,e){const n=await pa(t,e);if(!n||n.kind!=="issue"||n.tInvalid!==null)throw new fa(e);if(n.isSuperseded)throw new da(e);return n}async function sn(t,e){const n=await t.executeGet("SELECT * FROM node WHERE rowid = ?",[e]);return n?gy(n):null}const tN=["off","on"];function nN(){const t=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(t===void 0)return"off";if(tN.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_DEDUPE_MODE="${t}" is not a recognized dedupe mode (expected "off" or "on"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "off" so a mistyped negative control can never pass for the wrong reason.`)}async function ct(t,e){const n=e.at??He(),r=e.content??e.name??"",o=Al(r.trim().toLowerCase());if(nN()==="on"){const c=await t.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[o]);if(c)return{rowid:c.rowid,uid:c.uid}}const s=kn.randomUUID(),i=e.metadata!==void 0?JSON.stringify(e.metadata):null,a=await t.executeGet(`INSERT INTO node (uid, kind, content, name, summary, topic, tags, importance,
11
+ Likely cause: this store was written by a build with a different item vocabulary and was never converted to the one this build uses. Refusing rather than returning an empty result.`),this.observed=t,this.recognized=n,this.name="StoreVocabularyMismatchError"}}async function Li(e){const{rows:t}=await e.executeAll("SELECT kind, COUNT(*) AS n FROM node WHERE t_invalid IS NULL GROUP BY kind ORDER BY n DESC"),n=t.map(o=>({kind:String(o.kind),count:Number(o.n)}));return{total:n.reduce((o,i)=>o+i.count,0),observed:n}}async function vl(e){const t=[...no],n=t.map(()=>"?").join(", "),{rows:r}=await e.executeAll(`SELECT 1 AS one FROM node WHERE t_invalid IS NULL AND kind IN (${n}) LIMIT 1`,t);return r.length>0}async function oo(e){if(await vl(e))return;const{total:t,observed:n}=await Li(e);if(t!==0)throw new xi(n,[...no])}const bl=3e4,fr=new WeakMap;function Sl(e){let t=fr.get(e);return t||(t=new Set,fr.set(e,t)),t}function Ui(e){const t=Sl(e);return{register(n){t.add(n);let r=!1;return()=>{r||(r=!0,t.delete(n))}},get size(){return t.size},snapshot(){return[...t]},async drain(n){const r=(n==null?void 0:n.timeoutMs)??bl,o=Date.now()+r;let i=0;for(;;){const a=[...t].filter(l=>l.outcome==="pending");if(a.length===0)break;const c=o-Date.now();if(c<=0)break;const d=await El(Promise.allSettled(a.map(l=>l.settled)),c);if(i+=a.filter(l=>l.outcome!=="pending").length,d==="timeout")break}const s=[...t];return{drained:i,stillPending:s.filter(a=>a.outcome==="pending"),recordedAsFailed:0,unrecorded:s.filter(a=>a.outcome==="unrecorded")}}}}async function El(e,t){let n;const r=new Promise(o=>{n=setTimeout(()=>o("timeout"),t),typeof n=="object"&&n!==null&&"unref"in n&&n.unref()});try{return await Promise.race([e,r])}finally{n!==void 0&&clearTimeout(n)}}function jn(){return[]}function kl(e){const t=W.homedir();if(e===t)return"~";const n=t.endsWith(k.sep)?t:t+k.sep;return e.startsWith(n)?"~"+e.slice(t.length):e}function Al(e,t){if(e===t)return!0;const n=k.relative(e,t);return n!==".."&&!n.startsWith(`..${k.sep}`)&&!k.isAbsolute(n)}function ro(e){const t=e==null?void 0:e.code;return t==="ENOENT"||t==="ENOTDIR"}async function _n(e){const t=k.resolve(e);try{return await Ct.realpath(t)}catch(n){if(!ro(n))throw n;const r=k.dirname(t);if(r===t)throw n;return k.join(await _n(r),k.basename(t))}}async function Di(e,t,n){const r=k.isAbsolute(t)?k.resolve(t):k.resolve(e,t),o=await _n(r);return{accepted:(await Promise.all([e,...n].map(a=>_n(a)))).some(a=>Al(a,o)),candidate:o}}class B extends Error{constructor(t,n=void 0,r){super(t),this.name=new.target.name,this.cause=n,this.retry_after_ms=r}}class Mi extends B{constructor(t,n){super(`Write contention: exhausted the retry budget (last backoff ${t}ms)`,n,t),this.code="E_CONTENTION",this.retryable=!0}}class Fi extends B{constructor(t){const n=Bi(t);super(`Write I/O failure: an unclassified driver/connection error surfaced from the underlying transaction: ${n.message}`,t),this.code="E_IO",this.retryable=!0,this.causeMessage=n.message,n.code!==void 0&&(this.causeCode=n.code)}}function Bi(e){if(e instanceof Error){const t=e.code;return{message:e.message,...typeof t=="string"?{code:t}:{},...e.stack!==void 0?{stack:e.stack}:{}}}if(typeof e=="object"&&e!==null){const t=e;return{message:typeof t.message=="string"?t.message:JSON.stringify(e),...typeof t.code=="string"?{code:t.code}:{}}}return{message:String(e)}}const jl="backlog.write.io_failure";function Nn(e,t,n){const r=Bi(e);Mn.log.error(jl,{origin:t,retryable:n,error:r.message,...r.code!==void 0?{error_code:r.code}:{},...r.stack!==void 0?{stack:r.stack}:{}})}class Mt extends B{constructor(t,n){super(n===void 0?`Issue "${t}" was already superseded by a concurrent write; re-get and retry`:`Issue "${t}" was superseded by a body edit and is no longer the live issue; it now lives under "${n}"`),this.uid=t,this.successorUid=n,this.code="E_CONSTRAINT",this.retryable=!1}}class G extends B{constructor(t,n){super(`${t} "${n}" was not found`),this.catalogKind=t,this.ref=n,this.code="E_VALIDATION",this.retryable=!1}}class I extends B{constructor(t,n){super(n?`Invalid argument "${t}": ${n}`:`Invalid argument "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}class Ft extends B{constructor(t){super(`No live issue found for uid "${t}"`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class _t extends B{constructor(t,n){super(`Claim already held by "${t}" since ${n}`),this.heldBy=t,this.heldSince=n,this.code="E_VALIDATION",this.retryable=!1}}class qi extends B{constructor(t,n){super(`Issue "${t}" is in terminal status "${n}" and cannot be claimed; re-open it via "transition" first`),this.uid=t,this.status=n,this.code="E_VALIDATION",this.retryable=!1}}class On extends B{constructor(t){const n=t.side==="source"?`"${t.rel}" already has a single target (${t.conflictingUid}) for source "${t.cappedUid}"`:`"${t.rel}" already has a single source (${t.conflictingUid}) for target "${t.cappedUid}"`;super(n),this.code="E_VALIDATION",this.retryable=!1,this.side=t.side,this.cappedUid=t.cappedUid,this.rel=t.rel,this.conflictingUid=t.conflictingUid}}class io extends B{constructor(t,n){const r=n.length===0?"the project root":n.map(kl).join(", "),o=n.length===0?"project_policy.citationAllowedExternalRoots is empty":"project_policy.citationAllowedExternalRoots";super(`Citation target "${t}" could not be verified and this project requires a real sha — accepted only under: ${r} (${o})`),this.target=t,this.allowedExternalRoots=n,this.code="E_VALIDATION",this.retryable=!1}}class _l extends B{constructor(t){super(`Citation target "${t}" is a directory, not a file — a citation must name a file inside it (use the citation's \`lines\` field for a range) so its content can be hashed`),this.target=t,this.code="E_VALIDATION",this.retryable=!1}}function Ki(e,t){return(e==null?void 0:e.code)==="EISDIR"?new _l(t):(Nn(e,"citation_sha",!0),new Fi(e))}class Hi extends B{constructor(t){super(`A note is required to transition issue "${t}" (project_policy.transition_requires_note)`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class Vi extends B{constructor(t){super(`At least one citation is required to close issue "${t}" (project_policy.citation_required)`),this.uid=t,this.code="E_VALIDATION",this.retryable=!1}}class je extends B{constructor(t,n){super(n?`Invalid "${t}": ${n}`:`Invalid "${t}"`),this.field=t,this.code="E_VALIDATION",this.retryable=!1}}function Nl(e){const t=e instanceof Error?e.message:String(e);return pe.isBusyError(e)||pe.isConcurrentConflict(e)?{code:"E_CONTENTION",retryable:!0,message:t,cause:e}:pe.isUniqueConstraintError(e)||pe.isForeignKeyError(e)?{code:"E_CONSTRAINT",retryable:!1,message:t,cause:e}:pe.isDatabaseError(e)?(Nn(e,"transaction",!0),{code:"E_IO",retryable:!0,message:t,cause:e}):(Nn(e,"transaction",!1),{code:"E_IO",retryable:!1,message:t,cause:e})}const Ol=new Set(["agent","user","system","human","unknown","anonymous","admin","bot","claude","assistant"]);function Q(e,t){if(Ol.has(t.trim().toLowerCase()))throw new I(e,`"${t}" is a bare role literal, not a real identity — use "\${agentName}:\${instanceId}" (e.g. "claude:1"), never a bare role word`)}function Gi(e){if(e!=null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}function Ji(e){return{rowid:e.rowid,uid:e.uid,kind:e.kind,name:e.name,content:e.content??"",metadata:Gi(e.meta),tInvalid:e.t_invalid,isSuperseded:e.is_superseded===1}}function V(){return new Date().toISOString()}function so(e){return ue.createHash("sha256").update(e).digest("hex")}function Wi(e){return JSON.stringify(Rn(e))}function Rn(e){if(Array.isArray(e))return e.map(Rn);if(e!==null&&typeof e=="object"){const t=e,n={};for(const r of Object.keys(t).sort())t[r]!==void 0&&(n[r]=Rn(t[r]));return n}return e}async function Bt(e,t){const n=await e.executeGet("SELECT * FROM node WHERE uid = ?",[t]);return n?Ji(n):null}async function we(e,t){const n=await Bt(e,t);if((n==null?void 0:n.kind)!=="issue"||n.tInvalid!==null)throw new Ft(t);if(n.isSuperseded)throw new Mt(t);return n}async function fe(e,t){const n=await e.executeGet("SELECT * FROM node WHERE rowid = ?",[t]);return n?Ji(n):null}const Rl=["off","on"];function Il(){const e=process.env.ADHD_BACKLOG_UNSAFE_DEDUPE_MODE;if(e===void 0)return"off";if(Rl.includes(e))return e;throw new Error(`ADHD_BACKLOG_UNSAFE_DEDUPE_MODE="${e}" is not a recognized dedupe mode (expected "off" or "on"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "off" so a mistyped negative control can never pass for the wrong reason.`)}async function J(e,t){const n=t.at??V(),r=t.content??t.name??"",o=so(r.trim().toLowerCase());if(Il()==="on"){const c=await e.executeGet("SELECT rowid, uid FROM node WHERE content_hash = ?",[o]);if(c)return{rowid:c.rowid,uid:c.uid}}const i=ue.randomUUID(),s=t.metadata!==void 0?JSON.stringify(t.metadata):null,a=await e.executeGet(`INSERT INTO node (uid, kind, content, name, summary, topic, tags, importance,
12
12
  confidence, content_hash, namespace, meta, agent_id, session_id, source,
13
13
  project_path, t_occurred, t_expires, t_created, t_valid)
14
14
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
15
- RETURNING rowid`,[s,e.kind,r,e.name??null,null,null,null,1,null,o,"global",i,null,null,null,null,n,null,n,n]);if(!a)throw new Error(`writeNodeTx: INSERT returned no rowid for kind="${e.kind}" name="${e.name??""}"`);return{rowid:a.rowid,uid:s}}async function rN(t,e){const{multiplicity:n}=e.rule;if(n==="n:m")return;if(n==="n:1"){const o=await t.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.dst
16
- WHERE e.src = ? AND e.rel = ? AND e.dst != ? AND e.t_invalid IS NULL LIMIT 1`,[e.srcRowid,e.rel,e.dstRowid]);if(o)throw new Qc({side:"source",cappedUid:e.srcUid,rel:e.rel,conflictingUid:o.uid});return}const r=await t.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.src
17
- WHERE e.dst = ? AND e.rel = ? AND e.src != ? AND e.t_invalid IS NULL LIMIT 1`,[e.dstRowid,e.rel,e.srcRowid]);if(r)throw new Qc({side:"target",cappedUid:e.dstUid,rel:e.rel,conflictingUid:r.uid})}async function Re(t,e){const{rule:n}=e;if(n.sourceKind!=="*"&&n.sourceKind!==e.srcKind)throw new eh(e.rel,"source",n.sourceKind,e.srcKind);if(n.targetKind!==e.dstKind)throw new eh(e.rel,"target",n.targetKind,e.dstKind);await rN(t,e),e.typePolicy.validateEdge?e.typePolicy.validateEdge(e.srcKind,e.rel,e.dstKind):e.typePolicy.validateRel(e.rel);const r=e.at??He(),o=e.metadata!==void 0?JSON.stringify(e.metadata):null;await t.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
15
+ RETURNING rowid`,[i,t.kind,r,t.name??null,null,null,null,1,null,o,"global",s,null,null,null,null,n,null,n,n]);if(!a)throw new Error(`writeNodeTx: INSERT returned no rowid for kind="${t.kind}" name="${t.name??""}"`);return{rowid:a.rowid,uid:i}}async function Tl(e,t){const{multiplicity:n}=t.rule;if(n==="n:m")return;if(n==="n:1"){const o=await e.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.dst
16
+ WHERE e.src = ? AND e.rel = ? AND e.dst != ? AND e.t_invalid IS NULL LIMIT 1`,[t.srcRowid,t.rel,t.dstRowid]);if(o)throw new On({side:"source",cappedUid:t.srcUid,rel:t.rel,conflictingUid:o.uid});return}const r=await e.executeGet(`SELECT n.uid AS uid FROM edge e JOIN node n ON n.rowid = e.src
17
+ WHERE e.dst = ? AND e.rel = ? AND e.src != ? AND e.t_invalid IS NULL LIMIT 1`,[t.dstRowid,t.rel,t.srcRowid]);if(r)throw new On({side:"target",cappedUid:t.dstUid,rel:t.rel,conflictingUid:r.uid})}async function M(e,t){const{rule:n}=t;if(n.sourceKind!=="*"&&n.sourceKind!==t.srcKind)throw new pr(t.rel,"source",n.sourceKind,t.srcKind);if(n.targetKind!==t.dstKind)throw new pr(t.rel,"target",n.targetKind,t.dstKind);await Tl(e,t),t.typePolicy.validateEdge?t.typePolicy.validateEdge(t.srcKind,t.rel,t.dstKind):t.typePolicy.validateRel(t.rel);const r=t.at??V(),o=t.metadata!==void 0?JSON.stringify(t.metadata):null;await e.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
18
18
  VALUES (?, ?, ?, ?, 'user_asserted', ?, ?, ?)
19
19
  ON CONFLICT(src, dst, rel) DO UPDATE SET
20
20
  meta = excluded.meta, weight = excluded.weight,
21
- t_invalid = NULL, t_valid = excluded.t_valid`,[e.srcRowid,e.dstRowid,e.rel,e.weight??1,o,r,r])}class eh extends Ke{constructor(e,n,r,o){super(`"${e}" requires a ${n} of kind "${r}", got "${o}"`),this.code="E_VALIDATION",this.retryable=!1}}async function Sr(t,e){const n=await t.executeGet("SELECT rowid, meta FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[e.srcRowid,e.dstRowid,e.rel]);if(!n)return;const r=e.at??He(),o={...my(n.meta)??{},invalidatedAt:r,...e.reason!==void 0?{invalidatedReason:e.reason}:{}};await t.executeRun("UPDATE edge SET t_invalid = ?, meta = ? WHERE rowid = ?",[r,JSON.stringify(o),n.rowid])}const Ms=[250,500];function oN(t){return new Promise(e=>setTimeout(e,t))}const sN=["immediate","deferred"];function iN(){const t=process.env.ADHD_BACKLOG_UNSAFE_TX_MODE;if(t===void 0)return"immediate";if(sN.includes(t))return t;throw new Error(`ADHD_BACKLOG_UNSAFE_TX_MODE="${t}" is not a recognized transaction mode (expected "immediate" or "deferred"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "immediate" so a mistyped negative control can never pass for the wrong reason.`)}async function lt(t,e){let n=0;for(;;)try{return await t.adapter.transaction(e,{mode:iN()})}catch(r){if(r instanceof Ke)throw r;const o=X_(r);if(o.code==="E_CONTENTION"){if(n<Ms.length){const s=Ms[n];n+=1,await oN(s);continue}throw new dy(Ms[Ms.length-1],r)}throw o.code==="E_IO"&&o.retryable?new kl(r):r}}function Il(t){if(t!==null)try{const e=JSON.parse(t);return e!==null&&typeof e=="object"?e:void 0}catch{return}}const aN=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _r(t){return aN.test(t)}async function bs(t,e,n){const r=await pa(t,n);if(!r||r.tInvalid!==null||r.kind!==e)throw new Xe(e,n);const{name:o}=r;if(o===null)throw new Xe(e,n);return{...r,name:o}}async function rs(t,e){if(_r(e)){const o=await bs(t,"project",e);return{rowid:o.rowid,uid:o.uid,name:o.name,metadata:o.metadata}}const n=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[e]);if(!n)throw new Xe("project",e);let r;if(n.meta!==null)try{r=JSON.parse(n.meta)}catch{r=void 0}return{rowid:n.rowid,uid:n.uid,name:n.name??e,metadata:r}}async function Pl(t,e){var r;if(_r(e.ref)){const o=await bs(t,"component",e.ref);if(((r=o.metadata)==null?void 0:r.projectUid)!==e.projectUid)throw new Xe("component",e.ref);return{rowid:o.rowid,uid:o.uid,name:o.name}}const n=await t.executeGet(`SELECT rowid, uid, name FROM node
21
+ t_invalid = NULL, t_valid = excluded.t_valid`,[t.srcRowid,t.dstRowid,t.rel,t.weight??1,o,r,r])}class pr extends B{constructor(t,n,r,o){super(`"${t}" requires a ${n} of kind "${r}", got "${o}"`),this.code="E_VALIDATION",this.retryable=!1}}async function _e(e,t){const n=await e.executeGet("SELECT rowid, meta FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[t.srcRowid,t.dstRowid,t.rel]);if(!n)return;const r=t.at??V(),o={...Gi(n.meta)??{},invalidatedAt:r,...t.reason!==void 0?{invalidatedReason:t.reason}:{}};await e.executeRun("UPDATE edge SET t_invalid = ?, meta = ? WHERE rowid = ?",[r,JSON.stringify(o),n.rowid])}const mt=[250,500];function $l(e){return new Promise(t=>setTimeout(t,e))}const Cl=["immediate","deferred"];function Pl(){const e=process.env.ADHD_BACKLOG_UNSAFE_TX_MODE;if(e===void 0)return"immediate";if(Cl.includes(e))return e;throw new Error(`ADHD_BACKLOG_UNSAFE_TX_MODE="${e}" is not a recognized transaction mode (expected "immediate" or "deferred"). This variable exists solely for negative-control test runs and must never be set in normal operation; an unrecognized value fails loudly rather than silently defaulting to "immediate" so a mistyped negative control can never pass for the wrong reason.`)}async function z(e,t){let n=0;for(;;)try{return await e.adapter.transaction(t,{mode:Pl()})}catch(r){if(r instanceof B)throw r;const o=Nl(r);if(o.code==="E_CONTENTION"){if(n<mt.length){const i=mt[n];n+=1,await $l(i);continue}throw new Mi(mt[mt.length-1],r)}throw o.code==="E_IO"&&o.retryable?new Fi(r):r}}function ao(e){if(e!==null)try{const t=JSON.parse(e);return t!==null&&typeof t=="object"?t:void 0}catch{return}}const xl=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Ne(e){return xl.test(e)}async function nt(e,t,n){const r=await Bt(e,n);if((r==null?void 0:r.tInvalid)!==null||r.kind!==t)throw new G(t,n);const{name:o}=r;if(o===null)throw new G(t,n);return{...r,name:o}}async function Ye(e,t){if(Ne(t)){const o=await nt(e,"project",t);return{rowid:o.rowid,uid:o.uid,name:o.name,metadata:o.metadata}}const n=await e.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[t]);if(!n)throw new G("project",t);let r;if(n.meta!==null)try{r=JSON.parse(n.meta)}catch{r=void 0}return{rowid:n.rowid,uid:n.uid,name:n.name??t,metadata:r}}async function co(e,t){var r;if(Ne(t.ref)){const o=await nt(e,"component",t.ref);if(((r=o.metadata)==null?void 0:r.projectUid)!==t.projectUid)throw new G("component",t.ref);return{rowid:o.rowid,uid:o.uid,name:o.name}}const n=await e.executeGet(`SELECT rowid, uid, name FROM node
22
22
  WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
23
23
  AND json_extract(meta, '$.projectUid') = ?
24
- LIMIT 1`,[e.ref,e.projectUid]);if(!n)throw new Xe("component",e.ref);return{rowid:n.rowid,uid:n.uid,name:n.name??e.ref}}async function wy(t,e){const n=await t.executeGet(`SELECT c.rowid AS rowid, c.uid AS uid, c.name AS name
24
+ LIMIT 1`,[t.ref,t.projectUid]);if(!n)throw new G("component",t.ref);return{rowid:n.rowid,uid:n.uid,name:n.name??t.ref}}async function zi(e,t){const n=await e.executeGet(`SELECT c.rowid AS rowid, c.uid AS uid, c.name AS name
25
25
  FROM edge e JOIN node c ON c.rowid = e.dst
26
26
  WHERE e.src = ? AND e.rel = 'owns_project' AND e.t_invalid IS NULL
27
27
  AND c.name = '(root)' AND c.t_invalid IS NULL
28
- LIMIT 1`,[e.projectRowid]);if(!n)throw new Xe("component","(root)");return{rowid:n.rowid,uid:n.uid,name:n.name??"(root)"}}async function mn(t,e){if(_r(e.ref)){const s=await bs(t,e.catalogKind,e.ref);return{rowid:s.rowid,uid:s.uid,name:s.name}}const n=await t.executeGet("SELECT rowid, uid, name FROM node WHERE kind = ? AND name = ? AND t_invalid IS NULL LIMIT 1",[e.catalogKind,e.ref]);if(n)return{rowid:n.rowid,uid:n.uid,name:n.name??e.ref};const r=e.mintMetadata?await e.mintMetadata(t):{},o=await ct(t,{kind:e.catalogKind,name:e.ref,metadata:r,at:e.at});return{rowid:o.rowid,uid:o.uid,name:e.ref}}async function vy(t){const e=await t.executeGet("SELECT MAX(CAST(json_extract(meta, '$.rank') AS INTEGER)) AS maxRank FROM node WHERE kind = 'priority' AND t_invalid IS NULL"),n=(e==null?void 0:e.maxRank)??null;return n===null?0:n+1}const cN=[{rel:"owns_project",sourceKind:"project",targetKind:"component",multiplicity:"1:n"},{rel:"owns_component",sourceKind:"component",targetKind:"issue",multiplicity:"1:n"},{rel:"has_kind",sourceKind:"issue",targetKind:"kind",multiplicity:"n:1"},{rel:"has_status",sourceKind:"issue",targetKind:"status",multiplicity:"n:1"},{rel:"has_priority",sourceKind:"issue",targetKind:"priority",multiplicity:"n:1"},{rel:"authored_by",sourceKind:"issue",targetKind:"agent",multiplicity:"n:1"},{rel:"has_note",sourceKind:"issue",targetKind:"note",multiplicity:"1:n"},{rel:"has_citation",sourceKind:"issue",targetKind:"citation",multiplicity:"1:n"},{rel:"has_transition",sourceKind:"issue",targetKind:"transition",multiplicity:"1:n"},{rel:"audits",sourceKind:"*",targetKind:"audit",multiplicity:"1:n"},{rel:"depends_on",sourceKind:"component",targetKind:"component",multiplicity:"n:m"},{rel:"has_location",sourceKind:"component",targetKind:"location",multiplicity:"1:n"},{rel:"relates_to",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"supersedes",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"blocks",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"duplicate_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"part_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"}],th=new Map(cN.map(t=>[t.rel,t]));async function Te(t,e){const n=await t.executeGet("SELECT rowid, meta FROM node WHERE kind = 'edge_kind' AND name = ? AND t_invalid IS NULL ORDER BY rowid ASC LIMIT 1",[e]);if(n){const o=Il(n.meta)??{},s=typeof o.source_kind=="string"?o.source_kind:void 0,i=typeof o.target_kind=="string"?o.target_kind:void 0,a=o.multiplicity;if(s&&i&&a)return{rel:e,sourceKind:s,targetKind:i,multiplicity:a};const c=th.get(e);if(!c)throw new Xe("edge_kind",e);return await t.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[He(),n.rowid]),await ct(t,{kind:"edge_kind",name:e,metadata:{source_kind:c.sourceKind,target_kind:c.targetKind,multiplicity:c.multiplicity}}),c}const r=th.get(e);if(!r)throw new Xe("edge_kind",e);return await ct(t,{kind:"edge_kind",name:e,metadata:{source_kind:r.sourceKind,target_kind:r.targetKind,multiplicity:r.multiplicity}}),r}const It=Object.freeze({transitionRequiresNote:!0,citationRequired:!1,citationRequiresSha:!0,dedupeScanEnabled:!0,dedupeThreshold:.8,claimStaleAfterMin:30,allowedStatuses:[],allowedKinds:[],requiredFields:[]});function Lt(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}function Zr(t){var r;const e=(r=t.metadata)==null?void 0:r.policy;if(e===null||typeof e!="object")return{...It};const n=e;return{transitionRequiresNote:n.transitionRequiresNote??It.transitionRequiresNote,citationRequired:n.citationRequired??It.citationRequired,citationRequiresSha:n.citationRequiresSha??It.citationRequiresSha,defaultStatus:n.defaultStatus,defaultKind:n.defaultKind,dedupeScanEnabled:n.dedupeScanEnabled??It.dedupeScanEnabled,dedupeThreshold:n.dedupeThreshold??It.dedupeThreshold,claimStaleAfterMin:n.claimStaleAfterMin??It.claimStaleAfterMin,allowedStatuses:n.allowedStatuses??It.allowedStatuses,allowedKinds:n.allowedKinds??It.allowedKinds,requiredFields:n.requiredFields??It.requiredFields}}function ha(t){var n;const e=(n=t.metadata)==null?void 0:n.path;return typeof e=="string"&&e.length>0}function Fi(t,e){const n={...t};for(const[r,o]of Object.entries(e))o!==void 0&&(n[r]=o);return n}async function uN(t,e){return Lt("name",e.name),Lt("by",e.by),jt("by",e.by),lt(t,n=>lN(n,t,e))}async function lN(t,e,n){const r=He(),o=await t.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[n.name]),s={path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description};if(o){const l=Fi(Il(o.meta)??{},s);return await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(l),o.rowid]),await Pe({tx:t,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:n.by,action:"updated",at:r}),{uid:o.uid,created:!1,project:{uid:o.uid,name:o.name??n.name,path:l.path,repoUrl:l.repoUrl,monorepo:l.monorepo,description:l.description}}}const i=Fi({},s),a=await ct(t,{kind:"project",name:n.name,metadata:i,at:r}),c=await ct(t,{kind:"component",name:"(root)",metadata:{projectUid:a.uid},at:r}),u=await Te(t,"owns_project");return await Re(t,{at:r,srcRowid:a.rowid,srcUid:a.uid,srcKind:"project",dstRowid:c.rowid,dstUid:c.uid,dstKind:"component",rel:"owns_project",rule:u,typePolicy:e.typePolicy}),await Pe({tx:t,typePolicy:e.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"project",actor:n.by,action:"created",at:r}),{uid:a.uid,created:!0,project:{uid:a.uid,name:n.name,path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description}}}async function dN(t,e){return Lt("project",e.project),Lt("name",e.name),Lt("by",e.by),jt("by",e.by),lt(t,n=>fN(n,t,e))}async function fN(t,e,n){const r=He(),o=await rs(t,n.project),s=await t.executeGet(`SELECT rowid, uid, name, meta FROM node
28
+ LIMIT 1`,[t.projectRowid]);if(!n)throw new G("component","(root)");return{rowid:n.rowid,uid:n.uid,name:n.name??"(root)"}}async function he(e,t){if(Ne(t.ref)){const i=await nt(e,t.catalogKind,t.ref);return{rowid:i.rowid,uid:i.uid,name:i.name}}const n=await e.executeGet("SELECT rowid, uid, name FROM node WHERE kind = ? AND name = ? AND t_invalid IS NULL LIMIT 1",[t.catalogKind,t.ref]);if(n)return{rowid:n.rowid,uid:n.uid,name:n.name??t.ref};const r=t.mintMetadata?await t.mintMetadata(e):{},o=await J(e,{kind:t.catalogKind,name:t.ref,metadata:r,at:t.at});return{rowid:o.rowid,uid:o.uid,name:t.ref}}async function Yi(e){const t=await e.executeGet("SELECT MAX(CAST(json_extract(meta, '$.rank') AS INTEGER)) AS maxRank FROM node WHERE kind = 'priority' AND t_invalid IS NULL"),n=(t==null?void 0:t.maxRank)??null;return n===null?0:n+1}const Ll=[{rel:"owns_project",sourceKind:"project",targetKind:"component",multiplicity:"1:n"},{rel:"owns_component",sourceKind:"component",targetKind:"issue",multiplicity:"1:n"},{rel:"has_kind",sourceKind:"issue",targetKind:"kind",multiplicity:"n:1"},{rel:"has_status",sourceKind:"issue",targetKind:"status",multiplicity:"n:1"},{rel:"has_priority",sourceKind:"issue",targetKind:"priority",multiplicity:"n:1"},{rel:"authored_by",sourceKind:"issue",targetKind:"agent",multiplicity:"n:1"},{rel:"has_note",sourceKind:"issue",targetKind:"note",multiplicity:"1:n"},{rel:"has_citation",sourceKind:"issue",targetKind:"citation",multiplicity:"1:n"},{rel:"has_transition",sourceKind:"issue",targetKind:"transition",multiplicity:"1:n"},{rel:"audits",sourceKind:"*",targetKind:"audit",multiplicity:"1:n"},{rel:"depends_on",sourceKind:"component",targetKind:"component",multiplicity:"n:m"},{rel:"has_location",sourceKind:"component",targetKind:"location",multiplicity:"1:n"},{rel:"relates_to",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"supersedes",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"blocks",sourceKind:"issue",targetKind:"issue",multiplicity:"n:m"},{rel:"duplicate_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"},{rel:"part_of",sourceKind:"issue",targetKind:"issue",multiplicity:"n:1"}],mr=new Map(Ll.map(e=>[e.rel,e]));async function F(e,t){const n=await e.executeGet("SELECT rowid, meta FROM node WHERE kind = 'edge_kind' AND name = ? AND t_invalid IS NULL ORDER BY rowid ASC LIMIT 1",[t]);if(n){const o=ao(n.meta)??{},i=typeof o.source_kind=="string"?o.source_kind:void 0,s=typeof o.target_kind=="string"?o.target_kind:void 0,a=o.multiplicity;if(i&&s&&a)return{rel:t,sourceKind:i,targetKind:s,multiplicity:a};const c=mr.get(t);if(!c)throw new G("edge_kind",t);return await e.executeRun("UPDATE node SET t_invalid = ? WHERE rowid = ? AND t_invalid IS NULL",[V(),n.rowid]),await J(e,{kind:"edge_kind",name:t,metadata:{source_kind:c.sourceKind,target_kind:c.targetKind,multiplicity:c.multiplicity}}),c}const r=mr.get(t);if(!r)throw new G("edge_kind",t);return await J(e,{kind:"edge_kind",name:t,metadata:{source_kind:r.sourceKind,target_kind:r.targetKind,multiplicity:r.multiplicity}}),r}const ee=Object.freeze({transitionRequiresNote:!0,citationRequired:!1,citationRequiresSha:!0,citationAllowedExternalRoots:Object.freeze([]),dedupeScanEnabled:!0,dedupeThreshold:.8,claimStaleAfterMin:30,allowedStatuses:[],allowedKinds:[],requiredFields:[]});function oe(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}function Le(e){var r;const t=(r=e.metadata)==null?void 0:r.policy;if(t===null||typeof t!="object")return{...ee,citationAllowedExternalRoots:jn()};const n=t;return{transitionRequiresNote:n.transitionRequiresNote??ee.transitionRequiresNote,citationRequired:n.citationRequired??ee.citationRequired,citationRequiresSha:n.citationRequiresSha??ee.citationRequiresSha,citationAllowedExternalRoots:Ul(n),defaultStatus:n.defaultStatus,defaultKind:n.defaultKind,dedupeScanEnabled:n.dedupeScanEnabled??ee.dedupeScanEnabled,dedupeThreshold:n.dedupeThreshold??ee.dedupeThreshold,claimStaleAfterMin:n.claimStaleAfterMin??ee.claimStaleAfterMin,allowedStatuses:n.allowedStatuses??ee.allowedStatuses,allowedKinds:n.allowedKinds??ee.allowedKinds,requiredFields:n.requiredFields??ee.requiredFields}}function Ul(e){const t=e.citationAllowedExternalRoots;return t===void 0||!Array.isArray(t)||!t.every(n=>typeof n=="string")?jn():t}function qt(e){var n;const t=(n=e.metadata)==null?void 0:n.path;return typeof t=="string"&&t.length>0}function Nt(e,t){const n={...e};for(const[r,o]of Object.entries(t))o!==void 0&&(n[r]=o);return n}async function Dl(e,t){return oe("name",t.name),oe("by",t.by),Q("by",t.by),z(e,n=>Ml(n,e,t))}async function Ml(e,t,n){const r=V(),o=await e.executeGet("SELECT rowid, uid, name, meta FROM node WHERE kind = 'project' AND name = ? AND t_invalid IS NULL LIMIT 1",[n.name]),i={path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description};if(o){const l=Nt(ao(o.meta)??{},i);return await e.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(l),o.rowid]),await U({tx:e,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"project",actor:n.by,action:"updated",at:r}),{uid:o.uid,created:!1,project:{uid:o.uid,name:o.name??n.name,path:l.path,repoUrl:l.repoUrl,monorepo:l.monorepo,description:l.description}}}const s=Nt({},i),a=await J(e,{kind:"project",name:n.name,metadata:s,at:r}),c=await J(e,{kind:"component",name:"(root)",metadata:{projectUid:a.uid},at:r}),d=await F(e,"owns_project");return await M(e,{at:r,srcRowid:a.rowid,srcUid:a.uid,srcKind:"project",dstRowid:c.rowid,dstUid:c.uid,dstKind:"component",rel:"owns_project",rule:d,typePolicy:t.typePolicy}),await U({tx:e,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"project",actor:n.by,action:"created",at:r}),{uid:a.uid,created:!0,project:{uid:a.uid,name:n.name,path:n.path,repoUrl:n.repoUrl,monorepo:n.monorepo,description:n.description}}}async function Fl(e,t){return oe("project",t.project),oe("name",t.name),oe("by",t.by),Q("by",t.by),z(e,n=>Bl(n,e,t))}async function Bl(e,t,n){const r=V(),o=await Ye(e,n.project),i=await e.executeGet(`SELECT rowid, uid, name, meta FROM node
29
29
  WHERE kind = 'component' AND name = ? AND t_invalid IS NULL
30
30
  AND json_extract(meta, '$.projectUid') = ?
31
- LIMIT 1`,[n.name,o.uid]),i={path:n.path,description:n.description};let a,c,u,l,d;if(s)d=Fi({...Il(s.meta)??{},projectUid:o.uid},i),await t.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(d),s.rowid]),a=s.rowid,c=s.uid,u=s.name??n.name,l=!1;else{d=Fi({projectUid:o.uid},i);const g=await ct(t,{kind:"component",name:n.name,metadata:d,at:r});a=g.rowid,c=g.uid,u=n.name,l=!0}const f=await Te(t,"owns_project");return await Re(t,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"project",dstRowid:a,dstUid:c,dstKind:"component",rel:"owns_project",rule:f,typePolicy:e.typePolicy}),await Pe({tx:t,typePolicy:e.typePolicy,subjectRowid:a,subjectUid:c,subjectKind:"component",actor:n.by,action:l?"created":"updated",at:r}),{uid:c,created:l,component:{uid:c,name:u,projectUid:o.uid,path:d.path,description:d.description}}}const nh=["path","url","tool"];async function pN(t,e){if(Lt("component",e.component),Lt("value",e.value),Lt("by",e.by),jt("by",e.by),!nh.includes(e.locType))throw new oe("locType",`must be one of ${nh.join(", ")}`);return lt(t,async n=>{const r=He();let o;if(_r(e.component)){const u=await bs(n,"component",e.component);o={rowid:u.rowid,uid:u.uid,name:u.name}}else{if(e.project===void 0||e.project.trim().length===0)throw new oe("component",'a bare component name requires "project" to disambiguate — pass a component uid instead if unavailable');const u=await rs(n,e.project);o=await Pl(n,{projectUid:u.uid,ref:e.component})}const s=await n.executeGet(`SELECT rowid, uid FROM node
31
+ LIMIT 1`,[n.name,o.uid]),s={path:n.path,description:n.description};let a,c,d,l,u;if(i)u=Nt({...ao(i.meta)??{},projectUid:o.uid},s),await e.executeRun("UPDATE node SET meta = ? WHERE rowid = ?",[JSON.stringify(u),i.rowid]),a=i.rowid,c=i.uid,d=i.name??n.name,l=!1;else{u=Nt({projectUid:o.uid},s);const g=await J(e,{kind:"component",name:n.name,metadata:u,at:r});a=g.rowid,c=g.uid,d=n.name,l=!0}const f=await F(e,"owns_project");return await M(e,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"project",dstRowid:a,dstUid:c,dstKind:"component",rel:"owns_project",rule:f,typePolicy:t.typePolicy}),await U({tx:e,typePolicy:t.typePolicy,subjectRowid:a,subjectUid:c,subjectKind:"component",actor:n.by,action:l?"created":"updated",at:r}),{uid:c,created:l,component:{uid:c,name:d,projectUid:o.uid,path:u.path,description:u.description}}}const gr=["path","url","tool"];async function ql(e,t){if(oe("component",t.component),oe("value",t.value),oe("by",t.by),Q("by",t.by),!gr.includes(t.locType))throw new I("locType",`must be one of ${gr.join(", ")}`);return z(e,async n=>{const r=V();let o;if(Ne(t.component)){const d=await nt(n,"component",t.component);o={rowid:d.rowid,uid:d.uid,name:d.name}}else{if(t.project===void 0||t.project.trim().length===0)throw new I("component",'a bare component name requires "project" to disambiguate — pass a component uid instead if unavailable');const d=await Ye(n,t.project);o=await co(n,{projectUid:d.uid,ref:t.component})}const i=await n.executeGet(`SELECT rowid, uid FROM node
32
32
  WHERE kind = 'location' AND t_invalid IS NULL
33
33
  AND json_extract(meta, '$.componentUid') = ?
34
34
  AND json_extract(meta, '$.locType') = ?
35
35
  AND json_extract(meta, '$.value') = ?
36
- LIMIT 1`,[o.uid,e.locType,e.value]);if(s)return{uid:s.uid,created:!1,location:{uid:s.uid,locType:e.locType,value:e.value,componentUid:o.uid}};const i={componentUid:o.uid,locType:e.locType,value:e.value},a=await ct(n,{kind:"location",name:e.value,metadata:i,at:r}),c=await Te(n,"has_location");return await Re(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"component",dstRowid:a.rowid,dstUid:a.uid,dstKind:"location",rel:"has_location",rule:c,typePolicy:t.typePolicy}),await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"location",actor:e.by,action:"created",at:r}),{uid:a.uid,created:!0,location:{uid:a.uid,locType:e.locType,value:e.value,componentUid:o.uid}}})}async function hN(t,e){return Lt("uid",e.uid),Lt("by",e.by),jt("by",e.by),lt(t,async n=>{var c;const r=He(),o=await bs(n,"location",e.uid),s={...o.metadata??{},...e.reason!==void 0?{invalidatedReason:e.reason}:{},invalidatedAt:r},i=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[r,JSON.stringify(s),o.rowid]);if(i.rowsAffected!==1)throw new Error(`rmLocation: invalidate UPDATE affected ${i.rowsAffected} rows for uid="${e.uid}", expected exactly 1.`);const a=typeof((c=o.metadata)==null?void 0:c.componentUid)=="string"?o.metadata.componentUid:void 0;if(a!==void 0){const u=await pa(n,a);u&&u.tInvalid===null&&await Sr(n,{srcRowid:u.rowid,dstRowid:o.rowid,rel:"has_location",reason:e.reason,at:r})}return await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"location",actor:e.by,action:"deleted",note:e.reason,at:r}),{uid:o.uid,invalidated:!0}})}async function Pe(t){const e=t.at??He(),n={actor:t.actor,action:t.action,target_uid:t.subjectUid,from:t.from??null,to:t.to??null,note:t.note??null,at:e},r=Al(yy(n)),o={...n,sha:r},s=await ct(t.tx,{at:e,kind:"audit",name:t.action,content:t.note??t.action,metadata:o}),i=await Te(t.tx,"audits");return await Re(t.tx,{at:e,srcRowid:t.subjectRowid,srcUid:t.subjectUid,srcKind:t.subjectKind,dstRowid:s.rowid,dstUid:s.uid,dstKind:"audit",rel:"audits",rule:i,typePolicy:t.typePolicy}),{rowid:s.rowid,uid:s.uid,sha:r}}const mN="embed did not settle before store close — recorded by the close-time drain (RAG-SPEC.md §2.2)";function xl(t,e){return`${t}
37
- ${e}`.trim()}function qi(t,e){const n=t.embedding;if(!n)return Promise.resolve();const r=gN(t,n,e),o={subjectRowid:e.subjectRowid,subjectUid:e.subjectUid,actor:e.actor,action:e.action,settled:r,outcome:"pending"},s=ly(t.adapter).register(o);return r.then(i=>{o.outcome=i,i!=="unrecorded"&&s()},()=>{o.outcome="unrecorded"}),r.then(()=>{})}async function gN(t,e,n){let r,o;try{if(n.action==="upsert"){const s=await e.embedDocument(n.content);await e.upsertVector(n.subjectRowid,s),r="embedding_upserted"}else await e.deleteVector(n.subjectRowid),r="embedding_deleted"}catch(s){r="embedding_failed",o=s instanceof Error?s.message:String(s),console.error(`scheduleIssueEmbedding: embed round-trip failed for issue uid="${n.subjectUid}" (action="${n.action}") — degrading to an "embedding_failed" audit row.`,s)}try{await lt(t,async s=>{await Pe({tx:s,typePolicy:t.typePolicy,subjectRowid:n.subjectRowid,subjectUid:n.subjectUid,subjectKind:"issue",actor:n.actor,action:r,note:o})})}catch(s){return console.error(`scheduleIssueEmbedding: failed to persist "${r}" audit row for issue uid="${n.subjectUid}" — the embedding outcome itself is unrecorded.`,s),"unrecorded"}switch(r){case"embedding_upserted":return"upserted";case"embedding_deleted":return"deleted";case"embedding_failed":return"failed"}}async function yN(t,e){const n=[],r=[];for(const o of e)try{await lt(t,async s=>{await Pe({tx:s,typePolicy:t.typePolicy,subjectRowid:o.subjectRowid,subjectUid:o.subjectUid,subjectKind:"issue",actor:o.actor,action:"embedding_failed",note:mN})}),o.outcome="failed",n.push(o)}catch(s){o.outcome="unrecorded",r.push(o),console.error(`recordUnsettledEmbedsAsFailed: could not persist the "embedding_failed" audit row for issue uid="${o.subjectUid}" — this embed outcome is UNRECORDED.`,s)}return{recorded:n,unrecorded:r}}async function Ki(t,e=5e3){if(t!==":memory:"&&J.mkdirSync(L.dirname(t),{recursive:!0}),!Number.isInteger(e)||e<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${e}`);const n=await pn.createStoreAdapter({dbPath:t});await n.pragmaSet("busy_timeout",e);const r=tE.createGraphBackend(n,{typePolicy:Zp});await H_(()=>r.applySchema());try{await Ol(n)}catch(s){throw await n.close().catch(()=>{}),s}return{adapter:n,graph:r,typePolicy:Zp,flushEmbeds:s=>ly(n).drain(s)}}async function $y(t,e){const n=await t.flushEmbeds(e);let r=0,o=[...n.unrecorded];try{if(n.stillPending.length>0){const s=await yN(t,n.stillPending);r=s.recorded.length,o=[...o,...s.unrecorded]}}finally{await t.adapter.close()}return{drained:n.drained,stillPending:n.stillPending,recordedAsFailed:r,unrecorded:o}}async function Zc(t){if(!t)return;let e;try{e=await $y(t)}catch(n){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${n instanceof Error?n.message:String(n)}`);return}e.unrecorded.length>0?(console.error(`backlog: ${e.unrecorded.length} scheduled embed(s) died UNRECORDED — the store closed before they settled and the embedding_failed audit row could not be written. The subject write(s) are durable; the vector(s) are missing. Re-run the embedding backfill.`),process.exitCode||(process.exitCode=1)):e.stillPending.length>0&&console.error(`backlog: ${e.stillPending.length} scheduled embed(s) did not settle before close — recorded as embedding_failed. The subject write(s) are durable.`)}const Xc=["SIGINT","SIGTERM"];function by(t,e=n=>process.exit(n)){let n=!1;const r=s=>{n||(n=!0,t().catch(i=>{console.error(`backlog: signal cleanup failed (${s}): ${i instanceof Error?i.message:String(i)}`)}).finally(()=>{o(),e(128+mt.constants.signals[s])}))},o=()=>{for(const s of Xc)process.removeListener(s,r)};for(const s of Xc)process.on(s,r);return{dispose:o}}function wN(){return Xc.some(t=>process.listenerCount(t)>0)}const vN=[".git",".adhd","adhd.environment.yaml"];function ec(t){let e=L.resolve(t);const{root:n}=L.parse(e);for(;;){for(const o of vN)if(J.existsSync(`${e}/${o}`))return e;if(e===n)return;const r=L.dirname(e);if(r===e)return;e=r}}const $N=new Set(["system","global","project"]);function bN(t,e){const n=t.cwd??process.cwd();if(t.scope)return t.scope==="project"?{scope:"project",projectRoot:ec(n)??n}:{scope:t.scope};const r=e.ADHD_ENV_SCOPE;if(r!==void 0&&$N.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:ec(n)??n}:{scope:s}}const o=ec(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function rh(t){return`.${t}`}function EN(t){const e=mt.homedir();if(process.platform==="darwin")return L.join(e,"Library","Application Support",t);if(process.platform==="win32"){const r=process.env.APPDATA??L.join(e,"AppData","Roaming");return L.join(r,t)}const n=process.env.XDG_DATA_HOME??L.join(e,".local","share");return L.join(n,t)}function SN(t){const e=t.orgNamespace,n=t.adhdRoot??L.join(mt.homedir(),rh(e)),r=t.adhdRoot??EN(e),o={system:L.join(r,t.project,t.namespace),global:L.join(n,t.project,t.namespace)};return t.projectRoot&&(o.project=L.join(t.projectRoot,rh(e),t.project,t.namespace)),o}function Ey(t,e){return e==="project"?t.project??t.global:t[e]}function _N(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function NN(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var o=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return t[r]}})}),n}const ke={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},I={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},di="tag:yaml.org,2002:",gn={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function oh(t){const e=[0];let n=t.indexOf(`
38
- `);for(;n!==-1;)n+=1,e.push(n),n=t.indexOf(`
39
- `,n);return e}function Sy(t){let e,n;return typeof t=="string"?(e=oh(t),n=t):(Array.isArray(t)&&(t=t[0]),t&&t.context&&(t.lineStarts||(t.lineStarts=oh(t.context.src)),e=t.lineStarts,n=t.context.src)),{lineStarts:e,src:n}}function eu(t,e){if(typeof t!="number"||t<0)return null;const{lineStarts:n,src:r}=Sy(e);if(!n||!r||t>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(t<i)return{line:s,col:t-n[s-1]+1};if(t===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:t-n[o-1]+1}}function ON(t,e){const{lineStarts:n,src:r}=Sy(e);if(!n||!(t>=1)||t>n.length)return null;const o=n[t-1];let s=n[t];for(;s&&s>o&&r[s-1]===`
40
- `;)--s;return r.slice(o,s)}function kN({start:t,end:e},n,r=80){let o=ON(t.line,n);if(!o)return null;let{col:s}=t;if(o.length>r)if(s<=r-10)o=o.substr(0,r-1)+"…";else{const l=Math.round(r/2);o.length>s+l&&(o=o.substr(0,s+l-1)+"…"),s-=o.length-r,o="…"+o.substr(1-r)}let i=1,a="";e&&(e.line===t.line&&s+(e.col-t.col)<=r+1?i=e.col-t.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
41
- ${c}${u}${a}`}let be=class _y{static copy(e){return new _y(e.start,e.end)}constructor(e,n){this.start=e,this.end=n||e}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(e,n){const{start:r,end:o}=this;if(e.length===0||o<=e[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<e.length&&!(e[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<e.length&&!(e[s]>=o);)++s;return this.origEnd=o+s,i}},B=class Kt{static addStringTerminator(e,n,r){if(r[r.length-1]===`
42
- `)return r;const o=Kt.endOfWhiteSpace(e,n);return o>=e.length||e[o]===`
43
- `?r+`
44
- `:r}static atDocumentBoundary(e,n,r){const o=e[n];if(!o)return!0;const s=e[n-1];if(s&&s!==`
45
- `)return!1;if(r){if(o!==r)return!1}else if(o!==ke.DIRECTIVES_END&&o!==ke.DOCUMENT_END)return!1;const i=e[n+1],a=e[n+2];if(i!==o||a!==o)return!1;const c=e[n+3];return!c||c===`
46
- `||c===" "||c===" "}static endOfIdentifier(e,n){let r=e[n];const o=r==="<",s=o?[`
47
- `," "," ",">"]:[`
48
- `," "," ","[","]","{","}",","];for(;r&&s.indexOf(r)===-1;)r=e[n+=1];return o&&r===">"&&(n+=1),n}static endOfIndent(e,n){let r=e[n];for(;r===" ";)r=e[n+=1];return n}static endOfLine(e,n){let r=e[n];for(;r&&r!==`
49
- `;)r=e[n+=1];return n}static endOfWhiteSpace(e,n){let r=e[n];for(;r===" "||r===" ";)r=e[n+=1];return n}static startOfLine(e,n){let r=e[n-1];if(r===`
50
- `)return n;for(;r&&r!==`
51
- `;)r=e[n-=1];return n+1}static endOfBlockIndent(e,n,r){const o=Kt.endOfIndent(e,r);if(o>r+n)return o;{const s=Kt.endOfWhiteSpace(e,o),i=e[s];if(!i||i===`
52
- `)return s}return null}static atBlank(e,n,r){const o=e[n];return o===`
53
- `||o===" "||o===" "||r&&!o}static nextNodeIsIndented(e,n,r){return!e||n<0?!1:n>0?!0:r&&e==="-"}static normalizeOffset(e,n){const r=e[n];return r?r!==`
54
- `&&e[n-1]===`
55
- `?n-1:Kt.endOfWhiteSpace(e,n):n}static foldNewline(e,n,r){let o=0,s=!1,i="",a=e[n+1];for(;a===" "||a===" "||a===`
56
- `;){switch(a){case`
57
- `:o=0,n+=1,i+=`
58
- `;break;case" ":o<=r&&(s=!0),n=Kt.endOfWhiteSpace(e,n+2)-1;break;case" ":o+=1,n+=1;break}a=e[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(e,n,r){Object.defineProperty(this,"context",{value:r||null,writable:!0}),this.error=null,this.range=null,this.valueRange=null,this.props=n||[],this.type=e,this.value=null}getPropValue(e,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[e];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let e=0;e<this.props.length;++e){const n=this.getPropValue(e,ke.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const e=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,ke.COMMENT,!0);r!=null&&e.push(r)}return e.length>0?e.join(`
59
- `):null}commentHasRequiredWhitespace(e){const{src:n}=this.context;if(this.header&&e===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return e!==r||Kt.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:e}=this.context;for(let n=0;n<this.props.length;++n)if(e[this.props[n].start]===ke.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:e}=this.context;for(let n=0;n<this.props.length;++n)if(e[this.props[n].start]!==ke.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[I.FLOW_MAP,I.FLOW_SEQ,I.QUOTE_DOUBLE,I.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const e=eu(this.range.start,this.context.root);if(!e)return;const n=eu(this.range.end,this.context.root);return{start:e,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:e,end:n}=this.valueRange;return this.context.src.slice(e,n)}get tag(){for(let e=0;e<this.props.length;++e){const n=this.getPropValue(e,ke.TAG,!1);if(n!=null){if(n[1]==="<")return{verbatim:n.slice(2,-1)};{const[r,o,s]=n.match(/^(.*!)([^!]*)$/);return{handle:o,suffix:s}}}}return null}get valueRangeContainsNewline(){if(!this.valueRange||!this.context)return!1;const{start:e,end:n}=this.valueRange,{src:r}=this.context;for(let o=e;o<n;++o)if(r[o]===`
60
- `)return!0;return!1}parseComment(e){const{src:n}=this.context;if(n[e]===ke.COMMENT){const r=Kt.endOfLine(n,e+1),o=new be(e,r);return this.props.push(o),r}return e}setOrigRanges(e,n){return this.range&&(n=this.range.setOrigRange(e,n)),this.valueRange&&this.valueRange.setOrigRange(e,n),this.props.forEach(r=>r.setOrigRange(e,n)),n}toString(){const{context:{src:e},range:n,value:r}=this;if(r!=null)return r;const o=e.slice(n.start,n.end);return Kt.addStringTerminator(e,n.end,o)}},hr=class extends Error{constructor(e,n,r){if(!r||!(n instanceof B))throw new Error(`Invalid arguments for new ${e}`);super(),this.name=e,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const e=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new be(this.offset,this.offset+1);const n=e&&eu(this.offset,e);if(n){const r={line:n.line,col:n.col+1};this.linePos={start:n,end:r}}delete this.offset}else this.range=this.source.range,this.linePos=this.source.rangeAsLinePos;if(this.linePos){const{line:n,col:r}=this.linePos.start;this.message+=` at line ${n}, column ${r}`;const o=e&&kN(this.linePos,e);o&&(this.message+=`:
61
-
62
- ${o}
63
- `)}delete this.source}},os=class extends hr{constructor(e,n){super("YAMLReferenceError",e,n)}},X=class extends hr{constructor(e,n){super("YAMLSemanticError",e,n)}},Fe=class extends hr{constructor(e,n){super("YAMLSyntaxError",e,n)}},co=class extends hr{constructor(e,n){super("YAMLWarning",e,n)}};function ze(t,e,n){return(e=AN(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function jN(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function AN(t){var e=jN(t,"string");return typeof e=="symbol"?e:e+""}let Ny=class tu extends B{static endOfLine(e,n,r){let o=e[n],s=n;for(;o&&o!==`
64
- `&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=e[s+1];if(o===":"&&(!i||i===`
65
- `||i===" "||i===" "||r&&i===",")||(o===" "||o===" ")&&i==="#")break;s+=1,o=i}return s}get strValue(){if(!this.valueRange||!this.context)return null;let{start:e,end:n}=this.valueRange;const{src:r}=this.context;let o=r[n-1];for(;e<n&&(o===`
66
- `||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=e;a<n;++a){const c=r[a];if(c===`
67
- `){const{fold:u,offset:l}=B.foldNewline(r,a,-1);s+=u,a=l}else if(c===" "||c===" "){const u=a;let l=r[a+1];for(;a<n&&(l===" "||l===" ");)a+=1,l=r[a+1];l!==`
68
- `&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[e];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new X(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new X(this,a)],str:s}}default:return s}}parseBlockValue(e){const{indent:n,inFlow:r,src:o}=this.context;let s=e,i=e;for(let a=o[s];a===`
69
- `&&!B.atDocumentBoundary(o,s+1);a=o[s]){const c=B.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
70
- `?s=c:(i=tu.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=e),this.valueRange.end=i,i}parse(e,n){this.context=e;const{inFlow:r,src:o}=e;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
71
- `&&(s=tu.endOfLine(o,n,r)),this.valueRange=new be(n,s),s=B.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}},ss=class extends B{constructor(){super(I.BLANK_LINE)}get includesTrailingLines(){return!0}parse(e,n){return this.context=e,this.range=new be(n,n+1),n+1}},Rl=class extends B{constructor(e,n){super(e,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let{atLineStart:s,lineStart:i}=e;!s&&this.type===I.SEQ_ITEM&&(this.error=new X(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:e.indent;let c=B.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",d=[];let f=null;for(;u===`
72
- `||u==="#";){if(u==="#"){const p=B.endOfLine(o,c+1);d.push(new be(c,p)),c=p}else{s=!0,i=c+1;const p=B.endOfWhiteSpace(o,i);o[p]===`
73
- `&&d.length===0&&(f=new ss,i=f.parse({src:o},i)),c=B.endOfIndent(o,i)}u=o[c]}if(B.nextNodeIsIndented(u,c-(i+a),this.type!==I.SEQ_ITEM)?this.node=r({atLineStart:s,inCollection:!1,indent:a,lineStart:i,parent:this},c):u&&i>n+1&&(c=i-1),this.node){if(f){const p=e.parent.items||e.parent.contents;p&&p.push(f)}d.length&&Array.prototype.push.apply(this.props,d),c=this.node.range.end}else if(l){const p=d[0];this.props.push(p),c=p.end}else c=B.endOfLine(o,n+1);const g=this.node?this.node.valueRange.end:c;return this.valueRange=new be(n,g),c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.node?this.node.setOrigRanges(e,n):n}toString(){const{context:{src:e},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?e.slice(r.start,n.range.start)+String(n):e.slice(r.start,r.end);return B.addStringTerminator(e,r.end,s)}},Do=class extends B{constructor(){super(I.COMMENT)}parse(e,n){this.context=e;const r=this.parseComment(n);return this.range=new be(n,r),r}};function nu(t){let e=t;for(;e instanceof Rl;)e=e.node;if(!(e instanceof Oy))return null;const n=e.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=e.items[i];if(a.type===I.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===I.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=e.items.splice(r,n-r),s=o[0].range.start;for(;e.range.end=s,e.valueRange&&e.valueRange.end>s&&(e.valueRange.end=s),e!==t;)e=e.context.parent;return o}let Oy=class ru extends B{static nextContentHasIndent(e,n,r){const o=B.endOfLine(e,n)+1;n=B.endOfWhiteSpace(e,o);const s=e[n];return s?n>=o+r?!0:s!=="#"&&s!==`
74
- `?!1:ru.nextContentHasIndent(e,n,r):!1}constructor(e){super(e.type===I.SEQ_ITEM?I.SEQ:I.MAP);for(let r=e.props.length-1;r>=0;--r)if(e.props[r].start<e.context.lineStart){this.props=e.props.slice(0,r+1),e.props=e.props.slice(r+1);const o=e.props[0]||e.valueRange;e.range.start=o.start;break}this.items=[e];const n=nu(e);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let s=B.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=be.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=B.normalizeOffset(o,c);let u=o[c],l=B.endOfWhiteSpace(o,s)===c,d=!1;for(;u;){for(;u===`
75
- `||u==="#";){if(l&&u===`
76
- `&&!d){const p=new ss;if(c=p.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(p),c-=1}else if(u==="#"){if(c<s+a&&!ru.nextContentHasIndent(o,c,a))return c;const p=new Do;if(c=p.parse({indent:a,lineStart:s,src:o},c),this.items.push(p),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=B.endOfIndent(o,s),B.atBlank(o,c)){const p=B.endOfWhiteSpace(o,c),y=o[p];(!y||y===`
77
- `||y==="#")&&(c=p)}u=o[c],l=!0}if(!u)break;if(c!==s+a&&(l||u!==":")){if(c<s+a){s>n&&(c=s);break}else if(!this.error){const p="All collection items must start at the same column";this.error=new Fe(this,p)}}if(i.type===I.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const p=o[c+1];if(!p||p===`
78
- `||p===" "||p===" "){const y="A collection cannot be both a mapping and a sequence";this.error=new Fe(this,y)}}const f=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!f)return c;if(this.items.push(f),this.valueRange.end=f.valueRange.end,c=B.normalizeOffset(o,f.range.end),u=o[c],l=!1,d=f.includesTrailingLines,u){let p=c-1,y=o[p];for(;y===" "||y===" ";)y=o[--p];y===`
79
- `&&(s=p+1,l=!0)}const g=nu(f);g&&Array.prototype.push.apply(this.items,g)}return c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.items.forEach(r=>{n=r.setOrigRanges(e,n)}),n}toString(){const{context:{src:e},items:n,range:r,value:o}=this;if(o!=null)return o;let s=e.slice(r.start,n[0].range.start)+String(n[0]);for(let i=1;i<n.length;++i){const a=n[i],{atLineStart:c,indent:u}=a.context;if(c)for(let l=0;l<u;++l)s+=" ";s+=String(a)}return B.addStringTerminator(e,r.end,s)}};class IN extends B{constructor(){super(I.DIRECTIVE),this.name=null}get parameters(){const e=this.rawValue;return e?e.trim().split(/[ \t]+/):[]}parseName(e){const{src:n}=this.context;let r=e,o=n[r];for(;o&&o!==`
80
- `&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(e,r),r}parseParameters(e){const{src:n}=this.context;let r=e,o=n[r];for(;o&&o!==`
81
- `&&o!=="#";)o=n[r+=1];return this.valueRange=new be(e,r),r}parse(e,n){this.context=e;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new be(n,r),r}}let PN=class ou extends B{static startCommentOrEndBlankLine(e,n){const r=B.endOfWhiteSpace(e,n),o=e[r];return o==="#"||o===`
82
- `?r:n}constructor(){super(I.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(e){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=e;for(;!B.atDocumentBoundary(n,s,ke.DIRECTIVES_END);)switch(s=ou.startCommentOrEndBlankLine(n,s),n[s]){case`
83
- `:if(r){const i=new ss;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new Do;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new IN;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new X(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new be(s,s+3),s+3):(o?this.error=new X(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(e){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=e;for(;r[o-1]==="-";)o-=1;let s=B.endOfWhiteSpace(r,e),i=o===e;for(this.valueRange=new be(s);!B.atDocumentBoundary(r,s,ke.DOCUMENT_END);){switch(r[s]){case`
84
- `:if(i){const a=new ss;s=a.parse({src:r},s),s<r.length&&this.contents.push(a)}else s+=1,i=!0;o=s;break;case"#":{const a=new Do;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=B.endOfIndent(r,s),c=n({atLineStart:i,indent:-1,inFlow:!1,inCollection:!1,lineStart:o,parent:this},a);if(!c)return this.valueRange.end=a;this.contents.push(c),s=c.range.end,i=!1;const u=nu(c);u&&Array.prototype.push.apply(this.contents,u)}}s=ou.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new be(s,s+3),s+=3,r[s])){if(s=B.endOfWhiteSpace(r,s),r[s]==="#"){const a=new Do;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
85
- `:s+=1;break;case void 0:break;default:this.error=new Fe(this,"Document end marker line cannot have a non-comment suffix")}}return s}parse(e,n){e.root=this,this.context=e;const{src:r}=e;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.directives.forEach(r=>{n=r.setOrigRanges(e,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(e,n)),this.contents.forEach(r=>{n=r.setOrigRanges(e,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(e,n)),n}toString(){const{contents:e,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return e.length>0&&((n.length>0||e[0].type===I.COMMENT)&&(o+=`---
86
- `),o+=e.join("")),o[o.length-1]!==`
87
- `&&(o+=`
88
- `),o}},xN=class extends B{parse(t,e){this.context=t;const{src:n}=t;let r=B.endOfIdentifier(n,e+1);return this.valueRange=new be(e+1,r),r=B.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const an={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class RN extends B{constructor(e,n){super(e,n),this.blockIndent=null,this.chomping=an.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===an.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:e,end:n}=this.valueRange;const{indent:r,src:o}=this.context;if(this.valueRange.isEmpty())return"";let s=null,i=o[n-1];for(;i===`
89
- `||i===" "||i===" ";){if(n-=1,n<=e){if(this.chomping===an.KEEP)break;return""}i===`
90
- `&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===an.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===I.BLOCK_FOLDED;let l=!0,d="",f="",g=!1;for(let p=e;p<n;++p){for(let w=0;w<c&&o[p]===" ";++w)p+=1;const y=o[p];if(y===`
91
- `)f===`
92
- `?d+=`
93
- `:f=`
94
- `;else{const w=B.endOfLine(o,p),h=o.slice(p,w);p=w,u&&(y===" "||y===" ")&&p<a?(f===" "?f=`
95
- `:!g&&!l&&f===`
96
- `&&(f=`
97
-
98
- `),d+=f+h,f=w<n&&o[w]||"",g=!0):(d+=f+h,f=u&&p<a?" ":`
99
- `,g=!1),l&&h!==""&&(l=!1)}}return this.chomping===an.STRIP?d:d+`
100
- `}parseBlockHeader(e){const{src:n}=this.context;let r=e+1,o="";for(;;){const s=n[r];switch(s){case"-":this.chomping=an.STRIP;break;case"+":this.chomping=an.KEEP;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o+=s;break;default:return this.blockIndent=Number(o)||null,this.header=new be(e,r),r}r+=1}}parseBlockValue(e){const{indent:n,src:r}=this.context,o=!!this.blockIndent;let s=e,i=e,a=1;for(let c=r[s];c===`
101
- `&&(s+=1,!B.atDocumentBoundary(r,s));c=r[s]){const u=B.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],d=u-(s+n);if(this.blockIndent){if(l&&l!==`
102
- `&&d<this.blockIndent){if(r[u]==="#")break;if(!this.error){const f=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new X(this,f)}}}else if(r[u]!==`
103
- `){if(d<a){const f="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new X(this,f)}this.blockIndent=d}else d>a&&(a=d);r[u]===`
104
- `?s=u:s=i=B.endOfLine(r,u)}return this.chomping!==an.KEEP&&(s=r[i]?i+1:i),this.valueRange=new be(e+1,s),s}parse(e,n){this.context=e;const{src:r}=e;let o=this.parseBlockHeader(n);return o=B.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.header?this.header.setOrigRange(e,n):n}}class TN extends B{constructor(e,n){super(e,n),this.items=null}prevNodeIsJsonLike(e=this.items.length){const n=this.items[e-1];return!!n&&(n.jsonLike||n.type===I.COMMENT&&this.prevNodeIsJsonLike(e-1))}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let{indent:s,lineStart:i}=e,a=o[n];this.items=[{char:a,offset:n}];let c=B.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
105
- `:{i=c+1;const u=B.endOfWhiteSpace(o,i);if(o[u]===`
106
- `){const l=new ss;i=l.parse({src:o},i),this.items.push(l)}if(c=B.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new X(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new Do;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
107
- `||u===" "||u===" "||u===","||a===":"&&this.prevNodeIsJsonLike()){this.items.push({char:a,offset:c}),c+=1;break}}default:{const u=r({atLineStart:!1,inCollection:!1,inFlow:!0,indent:-1,lineStart:i,parent:this},c);if(!u)return this.valueRange=new be(n,c),c;this.items.push(u),c=B.normalizeOffset(o,u.range.end)}}c=B.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new be(n,c+1),a&&(this.items.push({char:a,offset:c}),c=B.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.items.forEach(r=>{if(r instanceof B)n=r.setOrigRanges(e,n);else if(e.length===0)r.origOffset=r.offset;else{let o=n;for(;o<e.length&&!(e[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:e},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof B);let i="",a=r.start;return s.forEach(c=>{const u=e.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
108
- `&&e[a-1]!==`
109
- `&&e[a]===`
110
- `&&(a+=1)}),i+=e.slice(a,r.end),B.addStringTerminator(e,r.end,i)}}let CN=class ky extends B{static endOfQuote(e,n){let r=e[n];for(;r&&r!=='"';)n+=r==="\\"?2:1,r=e[n];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const e=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=='"'&&e.push(new Fe(this,'Missing closing "quote'));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
111
- `){B.atDocumentBoundary(s,a+1)&&e.push(new X(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:d}=B.foldNewline(s,a,o);i+=u,a=l,d&&e.push(new X(this,"Multi-line double-quoted string needs to be sufficiently indented"))}else if(c==="\\")switch(a+=1,s[a]){case"0":i+="\0";break;case"a":i+="\x07";break;case"b":i+="\b";break;case"e":i+="\x1B";break;case"f":i+="\f";break;case"n":i+=`
112
- `;break;case"r":i+="\r";break;case"t":i+=" ";break;case"v":i+="\v";break;case"N":i+="…";break;case"_":i+=" ";break;case"L":i+="\u2028";break;case"P":i+="\u2029";break;case" ":i+=" ";break;case'"':i+='"';break;case"/":i+="/";break;case"\\":i+="\\";break;case" ":i+=" ";break;case"x":i+=this.parseCharCode(a+1,2,e),a+=2;break;case"u":i+=this.parseCharCode(a+1,4,e),a+=4;break;case"U":i+=this.parseCharCode(a+1,8,e),a+=8;break;case`
113
- `:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:e.push(new Fe(this,`Invalid escape sequence ${s.substr(a-1,2)}`)),i+="\\"+s[a]}else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
114
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return e.length>0?{errors:e,str:i}:i}parseCharCode(e,n,r){const{src:o}=this.context,s=o.substr(e,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;return isNaN(i)?(r.push(new Fe(this,`Invalid escape sequence ${o.substr(e-2,n+2)}`)),o.substr(e-2,n+2)):String.fromCodePoint(i)}parse(e,n){this.context=e;const{src:r}=e;let o=ky.endOfQuote(r,n+1);return this.valueRange=new be(n,o),o=B.endOfWhiteSpace(r,o),o=this.parseComment(o),o}},MN=class jy extends B{static endOfQuote(e,n){let r=e[n];for(;r;)if(r==="'"){if(e[n+1]!=="'")break;r=e[n+=2]}else r=e[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const e=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&e.push(new Fe(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
115
- `){B.atDocumentBoundary(s,a+1)&&e.push(new X(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:d}=B.foldNewline(s,a,o);i+=u,a=l,d&&e.push(new X(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&e.push(new Fe(this,"Unescaped single quote? This should not happen."));else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
116
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return e.length>0?{errors:e,str:i}:i}parse(e,n){this.context=e;const{src:r}=e;let o=jy.endOfQuote(r,n+1);return this.valueRange=new be(n,o),o=B.endOfWhiteSpace(r,o),o=this.parseComment(o),o}};function LN(t,e){switch(t){case I.ALIAS:return new xN(t,e);case I.BLOCK_FOLDED:case I.BLOCK_LITERAL:return new RN(t,e);case I.FLOW_MAP:case I.FLOW_SEQ:return new TN(t,e);case I.MAP_KEY:case I.MAP_VALUE:case I.SEQ_ITEM:return new Rl(t,e);case I.COMMENT:case I.PLAIN:return new Ny(t,e);case I.QUOTE_DOUBLE:return new CN(t,e);case I.QUOTE_SINGLE:return new MN(t,e);default:return null}}let DN=class fi{static parseType(e,n,r){switch(e[n]){case"*":return I.ALIAS;case">":return I.BLOCK_FOLDED;case"|":return I.BLOCK_LITERAL;case"{":return I.FLOW_MAP;case"[":return I.FLOW_SEQ;case"?":return!r&&B.atBlank(e,n+1,!0)?I.MAP_KEY:I.PLAIN;case":":return!r&&B.atBlank(e,n+1,!0)?I.MAP_VALUE:I.PLAIN;case"-":return!r&&B.atBlank(e,n+1,!0)?I.SEQ_ITEM:I.PLAIN;case'"':return I.QUOTE_DOUBLE;case"'":return I.QUOTE_SINGLE;default:return I.PLAIN}}constructor(e={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){ze(this,"parseNode",(c,u)=>{if(B.atDocumentBoundary(this.src,u))return null;const l=new fi(this,c),{props:d,type:f,valueStart:g}=l.parseProps(u),p=LN(f,d);let y=u;try{y=p.parse(l,g)}catch(w){const h=w instanceof Error?w.message:String(w);p.error||(p.error=new Fe(p,h))}if(p.range=new be(u,y),y<=u&&(p.error||(p.error=new Error("Node#parse consumed no characters")),p.error.parseEnd=y,p.error.source=p,p.range.end=u+1),l.nodeStartsCollection(p)){!p.error&&!l.atLineStart&&l.parent.type===I.DOCUMENT&&(p.error=new Fe(p,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const w=new Oy(p);return y=w.parse(new fi(l),y),w.range=new be(u,y),w}return p}),this.atLineStart=n??(e.atLineStart||!1),this.inCollection=r??(e.inCollection||!1),this.inFlow=o??(e.inFlow||!1),this.indent=s??e.indent,this.lineStart=i??e.lineStart,this.parent=a??(e.parent||{}),this.root=e.root,this.src=e.src}nodeStartsCollection(e){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(e instanceof Rl)return!0;let s=e.range.end;return o[s]===`
117
- `||o[s-1]===`
118
- `?!1:(s=B.endOfWhiteSpace(o,s),o[s]===":")}parseProps(e){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;e=this.atLineStart?B.endOfIndent(o,e):B.endOfWhiteSpace(o,e);let a=o[e];for(;a===ke.ANCHOR||a===ke.COMMENT||a===ke.TAG||a===`
119
- `;){if(a===`
120
- `){let u=e,l;do l=u+1,u=B.endOfIndent(o,l);while(o[u]===`
121
- `);const d=u-(l+this.indent),f=r.type===I.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!B.nextNodeIsIndented(o[u],d,!f))break;this.atLineStart=!0,this.lineStart=l,i=!1,e=u}else if(a===ke.COMMENT){const u=B.endOfLine(o,e+1);s.push(new be(e,u)),e=u}else{let u=B.endOfIdentifier(o,e+1);a===ke.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(e+1,u+13))&&(u=B.endOfIdentifier(o,u+5)),s.push(new be(e,u)),i=!0,e=B.endOfWhiteSpace(o,u)}a=o[e]}i&&a===":"&&B.atBlank(o,e+1,!0)&&(e-=1);const c=fi.parseType(o,e,n);return{props:s,type:c,valueStart:e}}};function Tl(t){const e=[];t.indexOf("\r")!==-1&&(t=t.replace(/\r\n?/g,(o,s)=>(o.length>1&&e.push(s),`
122
- `)));const n=[];let r=0;do{const o=new PN,s=new DN({src:t});r=o.parse(s,r),n.push(o)}while(r<t.length);return n.setOrigRanges=()=>{if(e.length===0)return!1;for(let s=1;s<e.length;++s)e[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(e,o);return e.splice(0,e.length),!0},n.toString=()=>n.join(`...
123
- `),n}function UN(t,e,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${e}#`)}
124
- ${e}${t}`:t}function qr(t,e,n){return n?n.indexOf(`
125
- `)===-1?`${t} #${n}`:`${t}
126
- `+n.replace(/^/gm,`${e||""}#`):t}let nt=class{};function _t(t,e,n){if(Array.isArray(t))return t.map((r,o)=>_t(r,String(o),n));if(t&&typeof t.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(t);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=t.toJSON(e,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof t=="bigint"?Number(t):t}let me=class extends nt{constructor(e){super(),this.value=e}toJSON(e,n){return n&&n.keep?this.value:_t(this.value,e,n)}toString(){return String(this.value)}};function sh(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){const s=e[o];if(Number.isInteger(s)&&s>=0){const i=[];i[s]=r,r=i}else{const i={};Object.defineProperty(i,s,{value:r,writable:!0,enumerable:!0,configurable:!0}),r=i}}return t.createNode(r,!1)}const ko=t=>t==null||typeof t=="object"&&t[Symbol.iterator]().next().done;let Ue=class Jn extends nt{constructor(e){super(),ze(this,"items",[]),this.schema=e}addIn(e,n){if(ko(e))this.add(n);else{const[r,...o]=e,s=this.get(r,!0);if(s instanceof Jn)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,sh(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([e,...n]){if(n.length===0)return this.delete(e);const r=this.get(e,!0);if(r instanceof Jn)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${e}. Remaining path: ${n}`)}getIn([e,...n],r){const o=this.get(e,!0);return n.length===0?!r&&o instanceof me?o.value:o:o instanceof Jn?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(e=>{if(!e||e.type!=="PAIR")return!1;const n=e.value;return n==null||n instanceof me&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([e,...n]){if(n.length===0)return this.has(e);const r=this.get(e,!0);return r instanceof Jn?r.hasIn(n):!1}setIn([e,...n],r){if(n.length===0)this.set(e,r);else{const o=this.get(e,!0);if(o instanceof Jn)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(e,sh(this.schema,n,r));else throw new Error(`Expected YAML collection at ${e}. Remaining path: ${n}`)}}toJSON(){return null}toString(e,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=e,d=this.type===I.FLOW_MAP||this.type===I.FLOW_SEQ||e.inFlow;d&&(s+=u);const f=o&&this.hasAllNullValues();e=Object.assign({},e,{allNullValues:f,indent:s,inFlow:d,type:null});let g=!1,p=!1;const y=this.items.reduce((h,v,b)=>{let E;v&&(!g&&v.spaceBefore&&h.push({type:"comment",str:""}),v.commentBefore&&v.commentBefore.match(/^.*$/gm).forEach(j=>{h.push({type:"comment",str:`#${j}`})}),v.comment&&(E=v.comment),d&&(!g&&v.spaceBefore||v.commentBefore||v.comment||v.key&&(v.key.commentBefore||v.key.comment)||v.value&&(v.value.commentBefore||v.value.comment))&&(p=!0)),g=!1;let N=l(v,e,()=>E=null,()=>g=!0);return d&&!p&&N.includes(`
127
- `)&&(p=!0),d&&b<this.items.length-1&&(N+=","),N=qr(N,s,E),g&&(E||d)&&(g=!1),h.push({type:"item",str:N}),h},[]);let w;if(y.length===0)w=r.start+r.end;else if(d){const{start:h,end:v}=r,b=y.map(E=>E.str);if(p||b.reduce((E,N)=>E+N.length+2,2)>Jn.maxFlowStringSingleLineLength){w=h;for(const E of b)w+=E?`
128
- ${u}${c}${E}`:`
129
- `;w+=`
130
- ${c}${v}`}else w=`${h} ${b.join(" ")} ${v}`}else{const h=y.map(n);w=h.shift();for(const v of h)w+=v?`
131
- ${c}${v}`:`
132
- `}return this.comment?(w+=`
133
- `+this.comment.replace(/^/gm,`${c}#`),i&&i()):g&&a&&a(),w}};ze(Ue,"maxFlowStringSingleLineLength",60);function Ls(t){let e=t instanceof me?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),Number.isInteger(e)&&e>=0?e:null}let Dt=class extends Ue{add(e){this.items.push(e)}delete(e){const n=Ls(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){const r=Ls(e);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof me?o.value:o}has(e){const n=Ls(e);return typeof n=="number"&&n<this.items.length}set(e,n){const r=Ls(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);this.items[r]=n}toJSON(e,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(_t(s,String(o++),n));return r}toString(e,n,r){return e?super.toString(e,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(e.indent||"")+" "},n,r):JSON.stringify(this)}};const BN=(t,e,n)=>e===null?"":typeof e!="object"?String(e):t instanceof nt&&n&&n.doc?t.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(e);let le=class Ay extends nt{constructor(e,n=null){super(),this.key=e,this.value=n,this.type=Ay.Type.PAIR}get commentBefore(){return this.key instanceof nt?this.key.commentBefore:void 0}set commentBefore(e){if(this.key==null&&(this.key=new me(null)),this.key instanceof nt)this.key.commentBefore=e;else{const n="Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.";throw new Error(n)}}addToJSMap(e,n){const r=_t(this.key,"",e);if(n instanceof Map){const o=_t(this.value,r,e);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=BN(this.key,r,e),s=_t(this.value,o,e);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(e,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(e,n,r){if(!e||!e.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=e.doc.options;let{key:a,value:c}=this,u=a instanceof nt&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof Ue){const N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let l=!i&&(!a||u||(a instanceof nt?a instanceof Ue||a.type===I.BLOCK_FOLDED||a.type===I.BLOCK_LITERAL:typeof a=="object"));const{doc:d,indent:f,indentStep:g,stringify:p}=e;e=Object.assign({},e,{implicitKey:!l,indent:f+g});let y=!1,w=p(a,e,()=>u=null,()=>y=!0);if(w=qr(w,e.indent,u),!l&&w.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(e.allNullValues&&!i)return this.comment?(w=qr(w,e.indent,this.comment),n&&n()):y&&!u&&r&&r(),e.inFlow&&!l?w:`? ${w}`;w=l?`? ${w}
134
- ${f}:`:`${w}:`,this.comment&&(w=qr(w,e.indent,this.comment),n&&n());let h="",v=null;if(c instanceof nt){if(c.spaceBefore&&(h=`
135
- `),c.commentBefore){const N=c.commentBefore.replace(/^/gm,`${e.indent}#`);h+=`
136
- ${N}`}v=c.comment}else c&&typeof c=="object"&&(c=d.schema.createNode(c,!0));e.implicitKey=!1,!l&&!this.comment&&c instanceof me&&(e.indentAtStart=w.length+1),y=!1,!s&&o>=2&&!e.inFlow&&!l&&c instanceof Dt&&c.type!==I.FLOW_SEQ&&!c.tag&&!d.anchors.getName(c)&&(e.indent=e.indent.substr(2));const b=p(c,e,()=>v=null,()=>y=!0);let E=" ";return h||this.comment?E=`${h}
137
- ${e.indent}`:!l&&c instanceof Ue?(!(b[0]==="["||b[0]==="{")||b.includes(`
138
- `))&&(E=`
139
- ${e.indent}`):b[0]===`
140
- `&&(E=""),y&&!v&&r&&r(),qr(w+E+b,e.indent,v)}};ze(le,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const pi=(t,e)=>{if(t instanceof tn){const n=e.get(t.source);return n.count*n.aliasCount}else if(t instanceof Ue){let n=0;for(const r of t.items){const o=pi(r,e);o>n&&(n=o)}return n}else if(t instanceof le){const n=pi(t.key,e),r=pi(t.value,e);return Math.max(n,r)}return 1};let tn=class Iy extends nt{static stringify({range:e,source:n},{anchors:r,doc:o,implicitKey:s,inStringifyKey:i}){let a=Object.keys(r).find(u=>r[u]===n);if(!a&&i&&(a=o.anchors.getName(n)||o.anchors.newName()),a)return`*${a}${s?" ":""}`;const c=o.anchors.getName(n)?"Alias node must be after source node":"Source node not found for alias node";throw new Error(`${c} [${e}]`)}constructor(e){super(),this.source=e,this.type=I.ALIAS}set tag(e){throw new Error("Alias nodes cannot have tags")}toJSON(e,n){if(!n)return _t(this.source,e,n);const{anchors:r,maxAliasCount:o}=n,s=r.get(this.source);if(!s||s.res===void 0){const i="This should not happen: Alias anchor was not resolved?";throw this.cstNode?new os(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=pi(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new os(this.cstNode,i):new ReferenceError(i)}return s.res}toString(e){return Iy.stringify(this,e)}};ze(tn,"default",!0);function ar(t,e){const n=e instanceof me?e.value:e;for(const r of t)if(r instanceof le&&(r.key===e||r.key===n||r.key&&r.key.value===n))return r}let ot=class extends Ue{add(e,n){e?e instanceof le||(e=new le(e.key||e,e.value)):e=new le(e);const r=ar(this.items,e.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=e.value;else throw new Error(`Key ${e.key} already set`);else if(o){const s=this.items.findIndex(i=>o(e,i)<0);s===-1?this.items.push(e):this.items.splice(s,0,e)}else this.items.push(e)}delete(e){const n=ar(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){const r=ar(this.items,e),o=r&&r.value;return!n&&o instanceof me?o.value:o}has(e){return!!ar(this.items,e)}set(e,n){this.add(new le(e,n),!0)}toJSON(e,n,r){const o=r?new r:n&&n.mapAsMap?new Map:{};n&&n.onCreate&&n.onCreate(o);for(const s of this.items)s.addToJSMap(n,o);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof le))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(e,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:e.indent||""},n,r)}};const Py="<<";let xy=class extends le{constructor(e){if(e instanceof le){let n=e.value;n instanceof Dt||(n=new Dt,n.items.push(e.value),n.range=e.value.range),super(e.key,n),this.range=e.range}else super(new me(Py),new Dt);this.type=le.Type.MERGE_PAIR}addToJSMap(e,n){for(const{source:r}of this.value.items){if(!(r instanceof ot))throw new Error("Merge sources must be maps");const o=r.toJSON(null,e,Map);for(const[s,i]of o)n instanceof Map?n.has(s)||n.set(s,i):n instanceof Set?n.add(s):Object.prototype.hasOwnProperty.call(n,s)||Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return n}toString(e,n){const r=this.value;if(r.items.length>1)return super.toString(e,n);this.value=r.items[0];const o=super.toString(e,n);return this.value=r,o}};const Uo={defaultType:I.BLOCK_LITERAL,lineWidth:76},Wt={trueStr:"true",falseStr:"false"},Nn={asBigInt:!1},Xr={nullStr:"null"},nn={defaultType:I.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function Cl(t,e,n){for(const{format:r,test:o,resolve:s}of e)if(o){const i=t.match(o);if(i){let a=s.apply(null,i);return a instanceof me||(a=new me(a)),r&&(a.format=r),a}}return n&&(t=n(t)),new me(t)}const Ry="flow",su="block",hi="quoted",ih=(t,e)=>{let n=t[e+1];for(;n===" "||n===" ";){do n=t[e+=1];while(n&&n!==`
141
- `);n=t[e+1]}return e};function ma(t,e,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return t;const c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;const u=[],l={};let d=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):d=o-r);let f,g,p=!1,y=-1,w=-1,h=-1;n===su&&(y=ih(t,y),y!==-1&&(d=y+c));for(let b;b=t[y+=1];){if(n===hi&&b==="\\"){switch(w=y,t[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":y+=9;break;default:y+=1}h=y}if(b===`
142
- `)n===su&&(y=ih(t,y)),d=y+c,f=void 0;else{if(b===" "&&g&&g!==" "&&g!==`
143
- `&&g!==" "){const E=t[y+1];E&&E!==" "&&E!==`
144
- `&&E!==" "&&(f=y)}if(y>=d)if(f)u.push(f),d=f+c,f=void 0;else if(n===hi){for(;g===" "||g===" ";)g=b,b=t[y+=1],p=!0;const E=y>h+1?y-2:w-1;if(l[E])return t;u.push(E),l[E]=!0,d=E+c,f=void 0}else p=!0}g=b}if(p&&a&&a(),u.length===0)return t;i&&i();let v=t.slice(0,u[0]);for(let b=0;b<u.length;++b){const E=u[b],N=u[b+1]||t.length;E===0?v=`
145
- ${e}${t.slice(0,N)}`:(n===hi&&l[E]&&(v+=`${t[E]}\\`),v+=`
146
- ${e}${t.slice(E+1,N)}`)}return v}const Ml=({indentAtStart:t})=>t?Object.assign({indentAtStart:t},nn.fold):nn.fold,ga=t=>/^(%|---|\.\.\.)/m.test(t);function FN(t,e,n){if(!e||e<0)return!1;const r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`
147
- `){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function dr(t,e){const{implicitKey:n}=e,{jsonEncoding:r,minMultiLineLength:o}=nn.doubleQuoted,s=JSON.stringify(t);if(r)return s;const i=e.indent||(ga(t)?" ":"");let a="",c=0;for(let u=0,l=s[u];l;l=s[++u])if(l===" "&&s[u+1]==="\\"&&s[u+2]==="n"&&(a+=s.slice(c,u)+"\\ ",u+=1,c=u,l="\\"),l==="\\")switch(s[u+1]){case"u":{a+=s.slice(c,u);const d=s.substr(u+2,4);switch(d){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:d.substr(0,2)==="00"?a+="\\x"+d.substr(2):a+=s.substr(u,6)}u+=5,c=u+1}break;case"n":if(n||s[u+2]==='"'||s.length<o)u+=1;else{for(a+=s.slice(c,u)+`
148
-
149
- `;s[u+2]==="\\"&&s[u+3]==="n"&&s[u+4]!=='"';)a+=`
150
- `,u+=2;a+=i,s[u+2]===" "&&(a+="\\"),u+=1,c=u+1}break;default:u+=1}return a=c?a+s.slice(c):s,n?a:ma(a,i,hi,Ml(e))}function Ty(t,e){if(e.implicitKey){if(/\n/.test(t))return dr(t,e)}else if(/[ \t]\n|\n[ \t]/.test(t))return dr(t,e);const n=e.indent||(ga(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
151
- ${n}`)+"'";return e.implicitKey?r:ma(r,n,Ry,Ml(e))}function mi({comment:t,type:e,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return dr(n,r);const i=r.indent||(r.forceBlockIndent||ga(n)?" ":""),a=i?"2":"1",c=e===I.BLOCK_FOLDED?!1:e===I.BLOCK_LITERAL?!0:!FN(n,nn.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
152
- `;let l="",d="";if(n=n.replace(/[\n\t ]*$/,g=>{const p=g.indexOf(`
153
- `);return p===-1?u+="-":(n===g||p!==g.length-1)&&(u+="+",s&&s()),d=g.replace(/\n$/,""),""}).replace(/^[\n ]*/,g=>{g.indexOf(" ")!==-1&&(u+=a);const p=g.match(/ +$/);return p?(l=g.slice(0,-p[0].length),p[0]):(l=g,"")}),d&&(d=d.replace(/\n+(?!\n|$)/g,`$&${i}`)),l&&(l=l.replace(/\n+/g,`$&${i}`)),t&&(u+=" #"+t.replace(/ ?[\r\n]+/g," "),o&&o()),!n)return`${u}${a}
154
- ${i}${d}`;if(c)return n=n.replace(/\n+/g,`$&${i}`),`${u}
155
- ${i}${l}${n}${d}`;n=n.replace(/\n+/g,`
156
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const f=ma(`${l}${n}${d}`,i,su,nn.fold);return`${u}
157
- ${i}${f}`}function qN(t,e,n,r){const{comment:o,type:s,value:i}=t,{actualString:a,implicitKey:c,indent:u,inFlow:l}=e;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return dr(i,e);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
158
- `)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?Ty(i,e):dr(i,e):mi(t,e,n,r);if(!c&&!l&&s!==I.PLAIN&&i.indexOf(`
159
- `)!==-1)return mi(t,e,n,r);if(u===""&&ga(i))return e.forceBlockIndent=!0,mi(t,e,n,r);const d=i.replace(/\n+/g,`$&
160
- ${u}`);if(a){const{tags:g}=e.doc.schema;if(typeof Cl(d,g,g.scalarFallback).value!="string")return dr(i,e)}const f=c?d:ma(d,u,Ry,Ml(e));return o&&!l&&(f.indexOf(`
161
- `)!==-1||o.indexOf(`
162
- `)!==-1)?(n&&n(),UN(f,u,o)):f}function Ll(t,e,n,r){const{defaultType:o}=nn,{implicitKey:s,inFlow:i}=e;let{type:a,value:c}=t;typeof c!="string"&&(c=String(c),t=Object.assign({},t,{value:c}));const u=d=>{switch(d){case I.BLOCK_FOLDED:case I.BLOCK_LITERAL:return mi(t,e,n,r);case I.QUOTE_DOUBLE:return dr(c,e);case I.QUOTE_SINGLE:return Ty(c,e);case I.PLAIN:return qN(t,e,n,r);default:return null}};(a!==I.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===I.BLOCK_FOLDED||a===I.BLOCK_LITERAL))&&(a=I.QUOTE_DOUBLE);let l=u(a);if(l===null&&(l=u(o),l===null))throw new Error(`Unsupported default string type ${o}`);return l}function Ht({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=e-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function Cy(t,e){let n,r;switch(e.type){case I.FLOW_MAP:n="}",r="flow map";break;case I.FLOW_SEQ:n="]",r="flow sequence";break;default:t.push(new X(e,"Not a flow collection!?"));return}let o;for(let s=e.items.length-1;s>=0;--s){const i=e.items[s];if(!i||i.type!==I.COMMENT){o=i;break}}if(o&&o.char!==n){const s=`Expected ${r} to end with ${n}`;let i;typeof o.offset=="number"?(i=new X(e,s),i.offset=o.offset+1):(i=new X(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),t.push(i)}}function My(t,e){const n=e.context.src[e.range.start-1];if(n!==`
163
- `&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";t.push(new X(e,r))}}function Ly(t,e){const n=String(e),r=n.substr(0,8)+"..."+n.substr(-8);return new X(t,`The "${r}" key is too long`)}function Dy(t,e){for(const{afterKey:n,before:r,comment:o}of e){let s=t.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
164
- `+o:s.commentBefore=o):o!==void 0&&(t.comment?t.comment+=`
165
- `+o:t.comment=o)}}function Es(t,e){const n=e.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=e),t.errors.push(r)}),n.str):""}function KN(t,e){const{handle:n,suffix:r}=e.tag;let o=t.tagPrefixes.find(s=>s.handle===n);if(!o){const s=t.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new X(e,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new X(e,`The ${n} tag has no suffix.`);if(n==="!"&&(t.version||t.options.version)==="1.0"){if(r[0]==="^")return t.warnings.push(new co(e,"YAML 1.0 ^ tag expansion is not supported")),r;if(/[:/]/.test(r)){const s=r.match(/^([a-z0-9-]+)\/(.*)/i);return s?`tag:${s[1]}.yaml.org,2002:${s[2]}`:`tag:${r}`}}return o.prefix+decodeURIComponent(r)}function VN(t,e){const{tag:n,type:r}=e;let o=!1;if(n){const{handle:s,suffix:i,verbatim:a}=n;if(a){if(a!=="!"&&a!=="!!")return a;const c=`Verbatim tags aren't resolved, so ${a} is invalid.`;t.errors.push(new X(e,c))}else if(s==="!"&&!i)o=!0;else try{return KN(t,e)}catch(c){t.errors.push(c)}}switch(r){case I.BLOCK_FOLDED:case I.BLOCK_LITERAL:case I.QUOTE_DOUBLE:case I.QUOTE_SINGLE:return gn.STR;case I.FLOW_MAP:case I.MAP:return gn.MAP;case I.FLOW_SEQ:case I.SEQ:return gn.SEQ;case I.PLAIN:return o?gn.STR:null;default:return null}}function ah(t,e,n){const{tags:r}=t.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(t,e);return a instanceof Ue?a:new me(a)}const s=Es(t,e);return typeof s=="string"&&o.length>0?Cl(s,o,r.scalarFallback):null}function GN({type:t}){switch(t){case I.FLOW_MAP:case I.MAP:return gn.MAP;case I.FLOW_SEQ:case I.SEQ:return gn.SEQ;default:return gn.STR}}function zN(t,e,n){try{const r=ah(t,e,n);if(r)return n&&e.tag&&(r.tag=n),r}catch(r){if(r instanceof hr)r.source||(r.source=e),t.errors.push(r);else{const o=r instanceof Error?r.message:String(r);t.errors.push(new X(e,o))}return null}try{const r=GN(e);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;t.warnings.push(new co(e,o));const s=ah(t,e,r);return s.tag=n,s}catch(r){const o=new os(e,r.message);return o.stack=r.stack,t.errors.push(o),null}}const WN=t=>{if(!t)return!1;const{type:e}=t;return e===I.MAP_KEY||e===I.MAP_VALUE||e===I.SEQ_ITEM};function HN(t,e){const n={before:[],after:[]};let r=!1,o=!1;const s=WN(e.context.parent)?e.context.parent.props.concat(e.props):e.props;for(const{start:i,end:a}of s)switch(e.context.src[i]){case ke.COMMENT:{if(!e.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";t.push(new X(e,l))}const{header:c,valueRange:u}=e;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(e.context.src.slice(i+1,a));break}case ke.ANCHOR:if(r){const c="A node can have at most one anchor";t.push(new X(e,c))}r=!0;break;case ke.TAG:if(o){const c="A node can have at most one tag";t.push(new X(e,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function JN(t,e){const{anchors:n,errors:r,schema:o}=t;if(e.type===I.ALIAS){const i=e.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new os(e,u)),null}const c=new tn(a);return n._cstAliases.push(c),c}const s=VN(t,e);if(s)return zN(t,e,s);if(e.type!==I.PLAIN){const i=`Failed to resolve ${e.type} node here`;return r.push(new Fe(e,i)),null}try{const i=Es(t,e);return Cl(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=e),r.push(i),null}}function $n(t,e){if(!e)return null;e.error&&t.errors.push(e.error);const{comments:n,hasAnchor:r,hasTag:o}=HN(t.errors,e);if(r){const{anchors:i}=t,a=e.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=e}if(e.type===I.ALIAS&&(r||o)){const i="An alias node must not specify any properties";t.errors.push(new X(e,i))}const s=JN(t,e);if(s){s.range=[e.range.start,e.range.end],t.options.keepCstNodes&&(s.cstNode=e),t.options.keepNodeTypes&&(s.type=e.type);const i=n.before.join(`
166
- `);i&&(s.commentBefore=s.commentBefore?`${s.commentBefore}
167
- ${i}`:i);const a=n.after.join(`
168
- `);a&&(s.comment=s.comment?`${s.comment}
169
- ${a}`:a)}return e.resolved=s}function Uy(t,e){if(e.type!==I.MAP&&e.type!==I.FLOW_MAP){const i=`A ${e.type} node cannot be resolved as a mapping`;return t.errors.push(new Fe(e,i)),null}const{comments:n,items:r}=e.type===I.FLOW_MAP?XN(t,e):ZN(t,e),o=new ot;o.items=r,Dy(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof Ue&&(s=!0),t.schema.merge&&a&&a.value===Py){r[i]=new xy(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof tn){const{type:d}=l.source;return d===I.MAP||d===I.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&t.errors.push(new X(e,u))}else for(let c=i+1;c<r.length;++c){const{key:u}=r[c];if(a===u||a&&u&&Object.prototype.hasOwnProperty.call(a,"value")&&a.value===u.value){const l=`Map keys must be unique; "${a}" is repeated`;t.errors.push(new X(e,l));break}}}if(s&&!t.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";t.warnings.push(new co(e,i))}return e.resolved=o,o}const QN=({context:{lineStart:t,node:e,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(e&&o>e.valueRange.start||n[o]!==ke.COMMENT)return!1;for(let s=t;s<o;++s)if(n[s]===`
170
- `)return!1;return!0};function YN(t,e){if(!QN(t))return;const n=t.getPropValue(0,ke.COMMENT,!0);let r=!1;const o=e.value.commentBefore;if(o&&o.startsWith(n))e.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=e.value.comment;!t.node&&s&&s.startsWith(n)&&(e.value.comment=s.substr(n.length+1),r=!0)}r&&(e.comment=n)}function ZN(t,e){const n=[],r=[];let o,s=null;for(let i=0;i<e.items.length;++i){const a=e.items[i];switch(a.type){case I.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case I.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case I.MAP_KEY:o!==void 0&&r.push(new le(o)),a.error&&t.errors.push(a.error),o=$n(t,a.node),s=null;break;case I.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&t.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===I.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";t.errors.push(new X(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new Ny(I.PLAIN,[]),c.context={parent:a,src:a.context.src};const l=a.range.start+1;if(c.range={start:l,end:l},c.valueRange={start:l,end:l},typeof a.range.origStart=="number"){const d=a.range.origStart+1;c.range.origStart=c.range.origEnd=d,c.valueRange.origStart=c.valueRange.origEnd=d}}const u=new le(o,$n(t,c));YN(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&t.errors.push(Ly(e,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new le(o)),o=$n(t,a),s=a.range.start,a.error&&t.errors.push(a.error);e:for(let c=i+1;;++c){const u=e.items[c];switch(u&&u.type){case I.BLANK_LINE:case I.COMMENT:continue e;case I.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";t.errors.push(new X(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";t.errors.push(new X(a,c))}}}return o!==void 0&&r.push(new le(o)),{comments:n,items:r}}function XN(t,e){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<e.items.length;++a){const c=e.items[a];if(typeof c.char=="string"){const{char:u,offset:l}=c;if(u==="?"&&o===void 0&&!s){s=!0,i=":";continue}if(u===":"){if(o===void 0&&(o=null),i===":"){i=",";continue}}else if(s&&(o===void 0&&u!==","&&(o=null),s=!1),o!==void 0&&(r.push(new le(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===e.items.length-1)continue}else if(u===i){i=":";continue}const d=`Flow map contains an unexpected ${u}`,f=new Fe(e,d);f.offset=l,t.errors.push(f)}else c.type===I.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===I.COMMENT?(My(t.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&t.errors.push(new X(c,"Separator , missing in flow map")),o=$n(t,c)):(i!==","&&t.errors.push(new X(c,"Indicator : missing in flow map entry")),r.push(new le(o,$n(t,c))),o=void 0,s=!1)}return Cy(t.errors,e),o!==void 0&&r.push(new le(o)),{comments:n,items:r}}function By(t,e){if(e.type!==I.SEQ&&e.type!==I.FLOW_SEQ){const s=`A ${e.type} node cannot be resolved as a sequence`;return t.errors.push(new Fe(e,s)),null}const{comments:n,items:r}=e.type===I.FLOW_SEQ?tO(t,e):eO(t,e),o=new Dt;if(o.items=r,Dy(o,n),!t.options.mapAsMap&&r.some(s=>s instanceof le&&s.key instanceof Ue)){const s="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";t.warnings.push(new co(e,s))}return e.resolved=o,o}function eO(t,e){const n=[],r=[];for(let o=0;o<e.items.length;++o){const s=e.items[o];switch(s.type){case I.BLANK_LINE:n.push({before:r.length});break;case I.COMMENT:n.push({comment:s.comment,before:r.length});break;case I.SEQ_ITEM:if(s.error&&t.errors.push(s.error),r.push($n(t,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";t.errors.push(new X(s,i))}break;default:s.error&&t.errors.push(s.error),t.errors.push(new Fe(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function tO(t,e){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<e.items.length;++u){const l=e.items[u];if(typeof l.char=="string"){const{char:d,offset:f}=l;if(d!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new le(s)),o=!1,s=void 0,i=null),d===a)a=null;else if(!a&&d==="?")o=!0;else if(a!=="["&&d===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof le){const g="Chaining flow sequence pairs is invalid",p=new X(e,g);p.offset=f,t.errors.push(p)}if(!o&&typeof i=="number"){const g=l.range?l.range.start:l.offset;g>i+1024&&t.errors.push(Ly(e,s));const{src:p}=c.context;for(let y=i;y<g;++y)if(p[y]===`
171
- `){const w="Implicit keys of flow sequence pairs need to be on a single line";t.errors.push(new X(c,w));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||d!=="]"||u<e.items.length-1){const g=`Flow sequence contains an unexpected ${d}`,p=new Fe(e,g);p.offset=f,t.errors.push(p)}}else if(l.type===I.BLANK_LINE)n.push({before:r.length});else if(l.type===I.COMMENT)My(t.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const f=`Expected a ${a} in flow sequence`;t.errors.push(new X(l,f))}const d=$n(t,l);s===void 0?(r.push(d),c=l):(r.push(new le(s,d)),s=void 0),i=l.range.start,a=","}}return Cy(t.errors,e),s!==void 0&&r.push(new le(s)),{comments:n,items:r}}const Fy={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(t,e)=>{const n=Es(t,e);if(typeof Buffer=="function")return Buffer.from(n,"base64");if(typeof atob=="function"){const r=atob(n.replace(/[\n\r]/g,"")),o=new Uint8Array(r.length);for(let s=0;s<r.length;++s)o[s]=r.charCodeAt(s);return o}else{const r="This environment does not support reading binary tags; either Buffer or atob is required";return t.errors.push(new os(e,r)),null}},options:Uo,stringify:({comment:t,type:e,value:n},r,o,s)=>{let i;if(typeof Buffer=="function")i=n instanceof Buffer?n.toString("base64"):Buffer.from(n.buffer).toString("base64");else if(typeof btoa=="function"){let a="";for(let c=0;c<n.length;++c)a+=String.fromCharCode(n[c]);i=btoa(a)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e||(e=Uo.defaultType),e===I.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=Uo,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,d=0;l<c;++l,d+=a)u[l]=i.substr(d,a);n=u.join(e===I.BLOCK_LITERAL?`
172
- `:" ")}return Ll({comment:t,type:e,value:n},r,o,s)}};function qy(t,e){const n=By(t,e);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof le)){if(o instanceof ot){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new X(e,i)}const s=o.items[0]||new le;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
173
- ${s.commentBefore}`:o.commentBefore),o.comment&&(s.comment=s.comment?`${o.comment}
174
- ${s.comment}`:o.comment),o=s}n.items[r]=o instanceof le?o:new le(o)}}return n}function Ky(t,e,n){const r=new Dt(t);r.tag="tag:yaml.org,2002:pairs";for(const o of e){let s,i;if(Array.isArray(o))if(o.length===2)s=o[0],i=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const c=Object.keys(o);if(c.length===1)s=c[0],i=o[s];else throw new TypeError(`Expected { key: value } tuple: ${o}`)}else s=o;const a=t.createPair(s,i,n);r.items.push(a)}return r}const Vy={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:qy,createNode:Ky};let ya=class Gy extends Dt{constructor(){super(),ze(this,"add",ot.prototype.add.bind(this)),ze(this,"delete",ot.prototype.delete.bind(this)),ze(this,"get",ot.prototype.get.bind(this)),ze(this,"has",ot.prototype.has.bind(this)),ze(this,"set",ot.prototype.set.bind(this)),this.tag=Gy.tag}toJSON(e,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof le?(s=_t(o.key,"",n),i=_t(o.value,s,n)):s=_t(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};ze(ya,"tag","tag:yaml.org,2002:omap");function nO(t,e){const n=qy(t,e),r=[];for(const{key:o}of n.items)if(o instanceof me)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new X(e,s)}else r.push(o.value);return Object.assign(new ya,n)}function rO(t,e,n){const r=Ky(t,e,n),o=new ya;return o.items=r.items,o}const zy={identify:t=>t instanceof Map,nodeClass:ya,default:!1,tag:"tag:yaml.org,2002:omap",resolve:nO,createNode:rO};let wa=class Wy extends ot{constructor(){super(),this.tag=Wy.tag}add(e){const n=e instanceof le?e:new le(e);ar(this.items,n.key)||this.items.push(n)}get(e,n){const r=ar(this.items,e);return!n&&r instanceof le?r.key instanceof me?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=ar(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new le(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(e,n,r);throw new Error("Set items must all have null values")}};ze(wa,"tag","tag:yaml.org,2002:set");function oO(t,e){const n=Uy(t,e);if(!n.hasAllNullValues())throw new X(e,"Set items must all have null values");return Object.assign(new wa,n)}function sO(t,e,n){const r=new wa;for(const o of e)r.items.push(t.createPair(o,null,n));return r}const Hy={identify:t=>t instanceof Set,nodeClass:wa,default:!1,tag:"tag:yaml.org,2002:set",resolve:oO,createNode:sO},Dl=(t,e)=>{const n=e.split(":").reduce((r,o)=>r*60+Number(o),0);return t==="-"?-n:n},Jy=({value:t})=>{if(isNaN(t)||!isFinite(t))return Ht(t);let e="";t<0&&(e="-",t=Math.abs(t));const n=[t%60];return t<60?n.unshift(0):(t=Math.round((t-n[0])/60),n.unshift(t%60),t>=60&&(t=Math.round((t-n[0])/60),n.unshift(t))),e+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},Qy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(t,e,n)=>Dl(e,n.replace(/_/g,"")),stringify:Jy},Yy={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(t,e,n)=>Dl(e,n.replace(/_/g,"")),stringify:Jy},Zy={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^(?:([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?)$"),resolve:(t,e,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(e,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=Dl(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:t})=>t.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function Xy(t){const e=typeof process<"u"&&process.env||{};return t?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!e.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!e.YAML_SILENCE_WARNINGS}function ew(t,e){if(Xy(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(t,e):console.warn(e?`${e}: ${t}`:t)}}const ch={};function iO(t,e){if(!ch[t]&&Xy(!0)){ch[t]=!0;let n=`The option '${t}' will be removed in a future release`;n+=`, use '${e}' instead.`,ew(n,"DeprecationWarning")}}function aO(t,e,n){const r=new ot(t);if(e instanceof Map)for(const[o,s]of e)r.items.push(t.createPair(o,s,n));else if(e&&typeof e=="object")for(const o of Object.keys(e))r.items.push(t.createPair(o,e[o],n));return typeof t.sortMapEntries=="function"&&r.items.sort(t.sortMapEntries),r}const is={createNode:aO,default:!0,nodeClass:ot,tag:"tag:yaml.org,2002:map",resolve:Uy};function cO(t,e,n){const r=new Dt(t);if(e&&e[Symbol.iterator])for(const o of e){const s=t.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const va={createNode:cO,default:!0,nodeClass:Dt,tag:"tag:yaml.org,2002:seq",resolve:By},uO={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Es,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),Ll(t,e,n,r)},options:nn},Ul=[is,va,uO],$a=t=>typeof t=="bigint"||Number.isInteger(t),Bl=(t,e,n)=>Nn.asBigInt?BigInt(t):parseInt(e,n);function tw(t,e,n){const{value:r}=t;return $a(r)&&r>=0?n+r.toString(e):Ht(t)}const nw={identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new me(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Xr,stringify:()=>Xr.nullStr},rw={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>t[0]==="t"||t[0]==="T",options:Wt,stringify:({value:t})=>t?Wt.trueStr:Wt.falseStr},ow={identify:t=>$a(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(t,e)=>Bl(t,e,8),options:Nn,stringify:t=>tw(t,8,"0o")},sw={identify:$a,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:t=>Bl(t,t,10),options:Nn,stringify:Ht},iw={identify:t=>$a(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(t,e)=>Bl(t,e,16),options:Nn,stringify:t=>tw(t,16,"0x")},aw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(t,e)=>e?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ht},cw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify:({value:t})=>Number(t).toExponential()},uw={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(t,e,n){const r=e||n,o=new me(parseFloat(t));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:Ht},lO=Ul.concat([nw,rw,ow,sw,iw,aw,cw,uw]),uh=t=>typeof t=="bigint"||Number.isInteger(t),Ds=({value:t})=>JSON.stringify(t),lw=[is,va,{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Es,stringify:Ds},{identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new me(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Ds},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:t=>t==="true",stringify:Ds},{identify:uh,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:t=>Nn.asBigInt?BigInt(t):parseInt(t,10),stringify:({value:t})=>uh(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Ds}];lw.scalarFallback=t=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(t)}`)};const lh=({value:t})=>t?Wt.trueStr:Wt.falseStr,jo=t=>typeof t=="bigint"||Number.isInteger(t);function Us(t,e,n){let r=e.replace(/_/g,"");if(Nn.asBigInt){switch(n){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}const s=BigInt(r);return t==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return t==="-"?-1*o:o}function tc(t,e,n){const{value:r}=t;if(jo(r)){const o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return Ht(t)}const dO=Ul.concat([{identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new me(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Xr,stringify:()=>Xr.nullStr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:Wt,stringify:lh},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>!1,options:Wt,stringify:lh},{identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(t,e,n)=>Us(e,n,2),stringify:t=>tc(t,2,"0b")},{identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(t,e,n)=>Us(e,n,8),stringify:t=>tc(t,8,"0")},{identify:jo,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(t,e,n)=>Us(e,n,10),stringify:Ht},{identify:jo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(t,e,n)=>Us(e,n,16),stringify:t=>tc(t,16,"0x")},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(t,e)=>e?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ht},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify:({value:t})=>Number(t).toExponential()},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(t,e){const n=new me(parseFloat(t.replace(/_/g,"")));if(e){const r=e.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:Ht}],Fy,zy,Vy,Hy,Qy,Yy,Zy),fO={core:lO,failsafe:Ul,json:lw,yaml11:dO},pO={binary:Fy,bool:rw,float:uw,floatExp:cw,floatNaN:aw,floatTime:Yy,int:sw,intHex:iw,intOct:ow,intTime:Qy,map:is,null:nw,omap:zy,pairs:Vy,seq:va,set:Hy,timestamp:Zy};function hO(t,e,n){if(e){const r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>(r.identify&&r.identify(t)||r.class&&t instanceof r.class)&&!r.format)}function mO(t,e,n){if(t instanceof nt)return t;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;e&&e.startsWith("!!")&&(e=r+e.slice(2));let c=hO(t,e,i.tags);if(!c){if(typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object")return a?new me(t):t;c=t instanceof Map?is:t[Symbol.iterator]?va:is}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(t&&typeof t=="object"&&s){const l=s.get(t);if(l){const d=new tn(l);return n.aliasNodes.push(d),d}u.value=t,s.set(t,u)}return u.node=c.createNode?c.createNode(n.schema,t,n):a?new me(t):t,e&&u.node instanceof nt&&(u.node.tag=e),u.node}function gO(t,e,n,r){let o=t[r.replace(/\W/g,"")];if(!o){const s=Object.keys(t).map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${r}"; use one of ${s}`)}if(Array.isArray(n))for(const s of n)o=o.concat(s);else typeof n=="function"&&(o=n(o.slice()));for(let s=0;s<o.length;++s){const i=o[s];if(typeof i=="string"){const a=e[i];if(!a){const c=Object.keys(e).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const yO=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0;let as=class dw{constructor({customTags:e,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?yO:o||null,!e&&s&&iO("tags","customTags"),this.tags=gO(fO,pO,e||s,r)}createNode(e,n,r,o){const s={defaultPrefix:dw.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return mO(e,r,i)}createPair(e,n,r){r||(r={wrapScalars:!0});const o=this.createNode(e,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new le(o,s)}};ze(as,"defaultPrefix",di);ze(as,"defaultTags",gn);const Vi={anchorPrefix:"a",customTags:null,indent:2,indentSeq:!0,keepCstNodes:!1,keepNodeTypes:!0,keepBlobsInJSON:!0,mapAsMap:!1,maxAliasCount:100,prettyErrors:!1,simpleKeys:!1,version:"1.2"},wO={get binary(){return Uo},set binary(t){Object.assign(Uo,t)},get bool(){return Wt},set bool(t){Object.assign(Wt,t)},get int(){return Nn},set int(t){Object.assign(Nn,t)},get null(){return Xr},set null(t){Object.assign(Xr,t)},get str(){return nn},set str(t){Object.assign(nn,t)}},fw={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:di},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:di}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:di}]}};function dh(t,e){if((t.version||t.options.version)==="1.0"){const o=e.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=e.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${e.replace(/^tag:/,"")}`}let n=t.tagPrefixes.find(o=>e.indexOf(o.prefix)===0);if(!n){const o=t.getDefaults().tagPrefixes;n=o&&o.find(s=>e.indexOf(s.prefix)===0)}if(!n)return e[0]==="!"?e:`!<${e}>`;const r=e.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function vO(t,e){if(e instanceof tn)return tn;if(e.tag){const o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)||o[0]}let n,r;if(e instanceof me){r=e.value;const o=t.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===e.format)||o.find(s=>!s.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){const o=r&&r.constructor?r.constructor.name:typeof r;throw new Error(`Tag not resolved for ${o} value`)}return n}function $O(t,e,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(t);return s&&(n[s]=t,o.push(`&${s}`)),t.tag?o.push(dh(r,t.tag)):e.default||o.push(dh(r,e.tag)),o.join(" ")}function Bs(t,e,n,r){const{anchors:o,schema:s}=e.doc;let i;if(!(t instanceof nt)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};t=s.createNode(t,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let d=o.getName(l.source);d||(d=o.newName(),o.map[d]=l.source)}}if(t instanceof le)return t.toString(e,n,r);i||(i=vO(s.tags,t));const a=$O(t,i,e);a.length>0&&(e.indentAtStart=(e.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(t,e,n,r):t instanceof me?Ll(t,e,n,r):t.toString(e,n,r);return a?t instanceof me||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
175
- ${e.indent}${c}`:c}class Fl{static validAnchorNode(e){return e instanceof me||e instanceof Dt||e instanceof ot}constructor(e){ze(this,"map",Object.create(null)),this.prefix=e}createAlias(e,n){return this.setAnchor(e,n),new tn(e)}createMergePair(...e){const n=new xy;return n.value.items=e.map(r=>{if(r instanceof tn){if(r.source instanceof ot)return r}else if(r instanceof ot)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(e){const{map:n}=this;return Object.keys(n).find(r=>n[r]===e)}getNames(){return Object.keys(this.map)}getNode(e){return this.map[e]}newName(e){e||(e=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${e}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:e,_cstAliases:n}=this;Object.keys(e).forEach(r=>{e[r]=e[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(e,n){if(e!=null&&!Fl.validAnchorNode(e))throw new Error("Anchors may only be set for Scalar, Seq and Map nodes");if(n&&/[\x00-\x19\s,[\]{}]/.test(n))throw new Error("Anchor names must not contain whitespace or control characters");const{map:r}=this,o=e&&Object.keys(r).find(s=>r[s]===e);if(o)if(n)o!==n&&(delete r[o],r[n]=e);else return o;else{if(!n){if(!e)return null;n=this.newName()}r[n]=e}return n}}const gi=(t,e)=>{if(t&&typeof t=="object"){const{tag:n}=t;t instanceof Ue?(n&&(e[n]=!0),t.items.forEach(r=>gi(r,e))):t instanceof le?(gi(t.key,e),gi(t.value,e)):t instanceof me&&n&&(e[n]=!0)}return e},bO=t=>Object.keys(gi(t,{}));function EO(t,e){const n={before:[],after:[]};let r,o=!1;for(const s of e)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";t.errors.push(new Fe(s,a));break}const i=$n(t,s);o&&(i.spaceBefore=!0,o=!1),r=i}else s.comment!==null?(r===void 0?n.before:n.after).push(s.comment):s.type===I.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!t.commentBefore&&(t.commentBefore=n.before.join(`
176
- `),n.before=[]));if(t.contents=r||null,!r)t.comment=n.before.concat(n.after).join(`
177
- `)||null;else{const s=n.before.join(`
178
- `);if(s){const i=r instanceof Ue&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
179
- ${i.commentBefore}`:s}t.comment=n.after.join(`
180
- `)||null}}function SO({tagPrefixes:t},e){const[n,r]=e.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new X(e,o)}if(t.some(o=>o.handle===n)){const o="The %TAG directive must only be given at most once per handle in the same document.";throw new X(e,o)}return{handle:n,prefix:r}}function _O(t,e){let[n]=e.parameters;if(e.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new X(e,r)}if(!fw[n]){const r=`Document will be parsed as YAML ${t.version||t.options.version} rather than YAML ${n}`;t.warnings.push(new co(e,r))}return n}function NO(t,e,n){const r=[];let o=!1;for(const s of e){const{comment:i,name:a}=s;switch(a){case"TAG":try{t.tagPrefixes.push(SO(t,s))}catch(c){t.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(t.version){const c="The %YAML directive must only be given at most once per document.";t.errors.push(new X(s,c))}try{t.version=_O(t,s)}catch(c){t.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;t.warnings.push(new co(s,c))}}i&&r.push(i)}if(n&&!o&&(t.version||n.version||t.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});t.tagPrefixes=n.tagPrefixes.map(s),t.version=n.version}t.commentBefore=r.join(`
181
- `)||null}function Or(t){if(t instanceof Ue)return!0;throw new Error("Expected a YAML collection as document contents")}let ql=class iu{constructor(e){this.anchors=new Fl(e.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=e,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(e){return Or(this.contents),this.contents.add(e)}addIn(e,n){Or(this.contents),this.contents.addIn(e,n)}delete(e){return Or(this.contents),this.contents.delete(e)}deleteIn(e){return ko(e)?this.contents==null?!1:(this.contents=null,!0):(Or(this.contents),this.contents.deleteIn(e))}getDefaults(){return iu.defaults[this.version]||iu.defaults[this.options.version]||{}}get(e,n){return this.contents instanceof Ue?this.contents.get(e,n):void 0}getIn(e,n){return ko(e)?!n&&this.contents instanceof me?this.contents.value:this.contents:this.contents instanceof Ue?this.contents.getIn(e,n):void 0}has(e){return this.contents instanceof Ue?this.contents.has(e):!1}hasIn(e){return ko(e)?this.contents!==void 0:this.contents instanceof Ue?this.contents.hasIn(e):!1}set(e,n){Or(this.contents),this.contents.set(e,n)}setIn(e,n){ko(e)?this.contents=n:(Or(this.contents),this.contents.setIn(e,n))}setSchema(e,n){if(!e&&!n&&this.schema)return;typeof e=="number"&&(e=e.toFixed(1)),e==="1.0"||e==="1.1"||e==="1.2"?(this.version?this.version=e:this.options.version=e,delete this.options.schema):e&&typeof e=="string"&&(this.options.schema=e),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new as(r)}parse(e,n){this.options.keepCstNodes&&(this.cstNode=e),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=e;if(i&&(i.source||(i.source=this),this.errors.push(i)),NO(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],EO(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof hr&&c.makePretty();for(const c of this.warnings)c instanceof hr&&c.makePretty()}return this}listNonDefaultTags(){return bO(this.contents).filter(e=>e.indexOf(as.defaultPrefix)!==0)}setTagPrefix(e,n){if(e[0]!=="!"||e[e.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===e);r?r.prefix=n:this.tagPrefixes.push({handle:e,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==e)}toJSON(e,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof e!="string"||!(this.contents instanceof me)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Bs},c=Object.keys(this.anchors.map);c.length>0&&(a.anchors=new Map(c.map(l=>[this.anchors.map[l],{alias:[],aliasCount:0,count:1}])));const u=_t(this.contents,e,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:d}of a.anchors.values())n(d,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const e=this.options.indent;if(!Number.isInteger(e)||e<=0){const c=JSON.stringify(e);throw new Error(`"indent" option must be a positive integer, not ${c}`)}this.setSchema();const n=[];let r=!1;if(this.version){let c="%YAML 1.2";this.schema.name==="yaml-1.1"&&(this.version==="1.0"?c="%YAML:1.0":this.version==="1.1"&&(c="%YAML 1.1")),n.push(c),r=!0}const o=this.listNonDefaultTags();this.tagPrefixes.forEach(({handle:c,prefix:u})=>{o.some(l=>l.indexOf(u)===0)&&(n.push(`%TAG ${c} ${u}`),r=!0)}),(r||this.directivesEndMarker)&&n.push("---"),this.commentBefore&&((r||!this.directivesEndMarker)&&n.unshift(""),n.unshift(this.commentBefore.replace(/^/gm,"#")));const s={anchors:Object.create(null),doc:this,indent:"",indentStep:" ".repeat(e),stringify:Bs};let i=!1,a=null;if(this.contents){this.contents instanceof nt&&(this.contents.spaceBefore&&(r||this.directivesEndMarker)&&n.push(""),this.contents.commentBefore&&n.push(this.contents.commentBefore.replace(/^/gm,"#")),s.forceBlockIndent=!!this.comment,a=this.contents.comment);const c=a?null:()=>i=!0,u=Bs(this.contents,s,()=>a=null,c);n.push(qr(u,"",a))}else this.contents!==void 0&&n.push(Bs(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
182
- `)+`
183
- `}};ze(ql,"defaults",fw);function OO(t,e=!0,n){n===void 0&&typeof e=="string"&&(n=e,e=!0);const r=Object.assign({},ql.defaults[Vi.version],Vi);return new as(r).createNode(t,e,n)}let ba=class extends ql{constructor(e){super(Object.assign({},Vi,e))}};function kO(t,e){const n=[];let r;for(const o of Tl(t)){const s=new ba(e);s.parse(o,r),n.push(s),r=s}return n}function pw(t,e){const n=Tl(t),r=new ba(e).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new X(n[1],o))}return r}function jO(t,e){const n=pw(t,e);if(n.warnings.forEach(r=>ew(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function AO(t,e){const n=new ba(e);return n.contents=t,String(n)}const IO={createNode:OO,defaultOptions:Vi,Document:ba,parse:jO,parseAllDocuments:kO,parseCST:Tl,parseDocument:pw,scalarOptions:wO,stringify:AO},PO=Object.freeze(Object.defineProperty({__proto__:null,YAML:IO},Symbol.toStringTag,{value:"Module"})),xO=NN(PO);var RO=xO.YAML;const TO="1.0.0-redesign.1",CO="adhd",MO="default",LO="adhd-environment.json",nc="config.yaml",DO="config.local.yaml",UO={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};let fh=class extends Error{constructor(e,n){super(`contentHash: lone surrogate in ${e} (not well-formed Unicode)`),this.location=e,this.offending=n,this.name="LoneSurrogateError"}};function ph(t){for(let e=0;e<t.length;e++){const n=t.charCodeAt(e);if(n>=55296&&n<=56319){const r=e+1<t.length?t.charCodeAt(e+1):0;if(r<56320||r>57343)return!0;e++}else if(n>=56320&&n<=57343)return!0}return!1}function hw(t,e){const n=Array.from(t),r=Array.from(e),o=Math.min(n.length,r.length);for(let s=0;s<o;s++){const i=n[s].codePointAt(0)??0,a=r[s].codePointAt(0)??0;if(i!==a)return i<a?-1:1}return n.length===r.length?0:n.length<r.length?-1:1}function hh(t){return new TextEncoder().encode(t).length}function BO(t){const e=Object.keys(t).sort(hw);let n="";for(const r of e){const o=t[r];if(ph(r))throw new fh("key",r);if(ph(o))throw new fh("value",o);n+=`${hh(r)}:${r}=${hh(o)}:${o}
184
- `}return`sha256-${mw(n)}`}function FO(t){const e=[...t].sort((n,r)=>hw(n.name,r.name)).map(n=>`${n.name}:${n.kind}:${n.scope}`).join(`
185
- `);return`sha256-${mw(e)}`}function qO(t){return`ADHD_${t.toUpperCase().replace(/[.-]/g,"_")}`}function KO(t,e){return`${t}_${e.toUpperCase().replace(/[.-]/g,"_")}`}function VO(t){const e={type:"object",properties:{}},n=t;for(const r of Object.keys(n)){const o=n[r],s=r.split(".");let i=e;s.forEach((a,c)=>{if(c===s.length-1){i.properties[a]=GO(o);return}const u=i.properties[a];if(u===void 0){const l={type:"object",properties:{}};i.properties[a]=l,i=l}else i=u})}return e}function GO(t){const e={type:t.type};return t.default!==void 0&&t.secret!==!0&&(e.default=t.default),t.description!==void 0&&(e.description=t.description),t.minimum!==void 0&&(e.minimum=t.minimum),t.maximum!==void 0&&(e.maximum=t.maximum),t.enum!==void 0&&(e.enum=t.enum),t.pattern!==void 0&&(e.pattern=t.pattern),t.minLength!==void 0&&(e.minLength=t.minLength),t.maxLength!==void 0&&(e.maxLength=t.maxLength),t.items!==void 0&&(e.items=t.items),e}const zO="adhd-env-ref:";function WO(t){return`${zO}${t}`}const HO=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],JO=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Pt(t,e){return(t>>>e|t<<32-e)>>>0}function QO(t){const e=Uint32Array.from(JO),n=t.length*8;let r=t.length+1;for(;r%64!==56;)r++;r+=8;const o=new Uint8Array(r);o.set(t),o[t.length]=128;const s=Math.floor(n/4294967296),i=n>>>0,a=new DataView(o.buffer);a.setUint32(r-8,s,!1),a.setUint32(r-4,i,!1);const c=new Uint32Array(64);for(let d=0;d<r;d+=64){for(let E=0;E<16;E++)c[E]=a.getUint32(d+E*4,!1);for(let E=16;E<64;E++){const N=c[E-15],j=c[E-2],T=Pt(N,7)^Pt(N,18)^N>>>3,M=Pt(j,17)^Pt(j,19)^j>>>10;c[E]=c[E-16]+T+c[E-7]+M>>>0}let f=e[0],g=e[1],p=e[2],y=e[3],w=e[4],h=e[5],v=e[6],b=e[7];for(let E=0;E<64;E++){const N=Pt(w,6)^Pt(w,11)^Pt(w,25),j=w&h^~w&v,T=b+N+j+HO[E]+c[E]>>>0,M=Pt(f,2)^Pt(f,13)^Pt(f,22),C=f&g^f&p^g&p,G=M+C>>>0;b=v,v=h,h=w,w=y+T>>>0,y=p,p=g,g=f,f=T+G>>>0}e[0]=e[0]+f>>>0,e[1]=e[1]+g>>>0,e[2]=e[2]+p>>>0,e[3]=e[3]+y>>>0,e[4]=e[4]+w>>>0,e[5]=e[5]+h>>>0,e[6]=e[6]+v>>>0,e[7]=e[7]+b>>>0}const u=new Uint8Array(32),l=new DataView(u.buffer);for(let d=0;d<8;d++)l.setUint32(d*4,e[d],!1);return u}function YO(t){let e="";for(const n of t)e+=n.toString(16).padStart(2,"0");return e}function mw(t){const e=new TextEncoder().encode(t);return YO(QO(e))}function gw(t,e=""){const n={};if(t===null||typeof t!="object"||Array.isArray(t))return e&&(n[e]=t),n;for(const[r,o]of Object.entries(t)){const s=e?`${e}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,gw(o,s)):n[s]=o}return n}function Fs(t){if(J.existsSync(t))try{const e=J.readFileSync(t,"utf8"),n=RO.parse(e);return n===null||typeof n!="object"||Array.isArray(n)?void 0:gw(n)}catch{return}}function ZO(t){return{system:Fs(L.join(t.system,nc)),global:Fs(L.join(t.global,nc)),project:t.project?Fs(L.join(t.project,nc)):void 0,local:t.project?Fs(L.join(t.project,DO)):void 0}}function XO(t){const e={source:t.source,scope:t.scope};return t.source==="env"&&t.env!==void 0&&(e.env=t.env),e}function au(t,e){if(t===void 0)return t;switch(e){case"integer":{if(typeof t=="number")return t;const n=parseInt(String(t),10);return Number.isNaN(n)?t:n}case"number":{if(typeof t=="number")return t;const n=parseFloat(String(t));return Number.isNaN(n)?t:n}case"boolean":{if(typeof t=="boolean")return t;const n=String(t).toLowerCase();return n==="true"?!0:n==="false"?!1:t}case"array":return Array.isArray(t)?t:typeof t=="string"?t.length===0?[]:t.split(",").map(n=>n.trim()):t;case"string":return typeof t=="string"?t:String(t);default:return t}}function yw(t){const e={};for(const n of Object.keys(t)){const r=n.split(".");let o=e;r.forEach((s,i)=>{if(i===r.length-1){o[s]=t[n];return}const a=o[s];(typeof a!="object"||a===null||Array.isArray(a))&&(o[s]={}),o=o[s]})}return e}const ek=[["system","system"],["global","global"],["project","project"],["local","local"]];function tk(t,e,n,r){const o={},s={},i={},a={};for(const c of Object.keys(t)){const u=t[c],l=u.env&&u.env!==""?u.env:KO(r.prefix,c),d=u.at==="runtime"||u.secret===!0,f=u.scope??r.activeScope;let g=u.default,p="default";for(const[b,E]of ek){const N=e[b];N&&Object.prototype.hasOwnProperty.call(N,c)&&(g=au(N[c],u.type),p=E)}const y=n[l];let w,h,v;y!==void 0?(w=au(y,u.type),h="env",v=l):(w=g,h=p),o[c]=d?WO(l):w,s[c]=w,i[c]=XO(d?{source:"env",scope:f,env:l}:{source:h,scope:f,env:v}),a[c]={...u,env:l,live:d,fallbackValue:g}}return{raw:o,nested:yw(o),typedRaw:s,provenance:i,fields:a}}function nk(t,e){return t.replace(/\$\{HOME\}/g,mt.homedir()).replace(/\$HOME\b/g,mt.homedir()).replace(/\$\{PROJECT_ROOT\}/g,e.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,e.namespace)}function rk(t,e){const n={};for(const[r,o]of Object.entries(t??{})){const s=o.scope??e.activeScope,i=o.share??UO[o.kind],a=o.path?nk(o.path,e):L.join(Ey(e.roots,s),r),c=i==="per-instance"?L.join(a,e.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:s,share:i}}return n}function ok(t,e){const n={};for(const[r,o]of Object.entries(t??{})){const s=e[o.in];if(!s)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:L.join(s.path,o.name),share:o.share??"shared"}}return n}var cu={exports:{}},ww={},Nt={},eo={},Ss={},ae={},cs={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends e{constructor(v){if(super(),!t.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class r extends e{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((b,E)=>`${b}${E}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((b,E)=>(E instanceof n&&(b[E.str]=(b[E.str]||0)+1),b),{})}}t._Code=r,t.nil=new r("");function o(h,...v){const b=[h[0]];let E=0;for(;E<v.length;)a(b,v[E]),b.push(h[++E]);return new r(b)}t._=o;const s=new r("+");function i(h,...v){const b=[g(h[0])];let E=0;for(;E<v.length;)b.push(s),a(b,v[E]),b.push(s,g(h[++E]));return c(b),new r(b)}t.str=i;function a(h,v){v instanceof r?h.push(...v._items):v instanceof n?h.push(v):h.push(d(v))}t.addCodeArg=a;function c(h){let v=1;for(;v<h.length-1;){if(h[v]===s){const b=u(h[v-1],h[v+1]);if(b!==void 0){h.splice(v-1,3,b);continue}h[v++]="+"}v++}}function u(h,v){if(v==='""')return h;if(h==='""')return v;if(typeof h=="string")return v instanceof n||h[h.length-1]!=='"'?void 0:typeof v!="string"?`${h.slice(0,-1)}${v}"`:v[0]==='"'?h.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(h instanceof n))return`"${h}${v.slice(1)}`}function l(h,v){return v.emptyStr()?h:h.emptyStr()?v:i`${h}${v}`}t.strConcat=l;function d(h){return typeof h=="number"||typeof h=="boolean"||h===null?h:g(Array.isArray(h)?h.join(","):h)}function f(h){return new r(g(h))}t.stringify=f;function g(h){return JSON.stringify(h).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=g;function p(h){return typeof h=="string"&&t.IDENTIFIER.test(h)?new r(`.${h}`):o`[${h}]`}t.getProperty=p;function y(h){if(typeof h=="string"&&t.IDENTIFIER.test(h))return new r(`${h}`);throw new Error(`CodeGen: invalid export name: ${h}, use explicit $id name mapping`)}t.getEsmExportName=y;function w(h){return new r(h.toString())}t.regexpCode=w})(cs);var uu={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=cs;class n extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var r;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(r||(t.UsedValueState=r={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class o{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=o;class s extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=s;const i=(0,e._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:e.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const f=this.toName(u),{prefix:g}=f,p=(d=l.key)!==null&&d!==void 0?d:l.ref;let y=this._values[g];if(y){const v=y.get(p);if(v)return v}else y=this._values[g]=new Map;y.set(p,f);const w=this._scope[g]||(this._scope[g]=[]),h=w.length;return w[h]=l.ref,f.setValue(l,{property:g,itemIndex:h}),f}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},l,d)}_reduceValues(u,l,d={},f){let g=e.nil;for(const p in u){const y=u[p];if(!y)continue;const w=d[p]=d[p]||new Map;y.forEach(h=>{if(w.has(h))return;w.set(h,r.Started);let v=l(h);if(v){const b=this.opts.es5?t.varKinds.var:t.varKinds.const;g=(0,e._)`${g}${b} ${h} = ${v};${this.opts._n}`}else if(v=f==null?void 0:f(h))g=(0,e._)`${g}${v}${this.opts._n}`;else throw new n(h);w.set(h,r.Completed)})}return g}}t.ValueScope=a})(uu);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=cs,n=uu;var r=cs;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}});var o=uu;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(m,$){return this}}class i extends s{constructor(m,$,O){super(),this.varKind=m,this.name=$,this.rhs=O}render({es5:m,_n:$}){const O=m?n.varKinds.var:this.varKind,x=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${x};`+$}optimizeNames(m,$){if(m[this.name.str])return this.rhs&&(this.rhs=fe(this.rhs,m,$)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(m,$,O){super(),this.lhs=m,this.rhs=$,this.sideEffects=O}render({_n:m}){return`${this.lhs} = ${this.rhs};`+m}optimizeNames(m,$){if(!(this.lhs instanceof e.Name&&!m[this.lhs.str]&&!this.sideEffects))return this.rhs=fe(this.rhs,m,$),this}get names(){const m=this.lhs instanceof e.Name?{}:{...this.lhs.names};return ue(m,this.rhs)}}class c extends a{constructor(m,$,O,x){super(m,O,x),this.op=$}render({_n:m}){return`${this.lhs} ${this.op}= ${this.rhs};`+m}}class u extends s{constructor(m){super(),this.label=m,this.names={}}render({_n:m}){return`${this.label}:`+m}}class l extends s{constructor(m){super(),this.label=m,this.names={}}render({_n:m}){return`break${this.label?` ${this.label}`:""};`+m}}class d extends s{constructor(m){super(),this.error=m}render({_n:m}){return`throw ${this.error};`+m}get names(){return this.error.names}}class f extends s{constructor(m){super(),this.code=m}render({_n:m}){return`${this.code};`+m}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(m,$){return this.code=fe(this.code,m,$),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class g extends s{constructor(m=[]){super(),this.nodes=m}render(m){return this.nodes.reduce(($,O)=>$+O.render(m),"")}optimizeNodes(){const{nodes:m}=this;let $=m.length;for(;$--;){const O=m[$].optimizeNodes();Array.isArray(O)?m.splice($,1,...O):O?m[$]=O:m.splice($,1)}return m.length>0?this:void 0}optimizeNames(m,$){const{nodes:O}=this;let x=O.length;for(;x--;){const R=O[x];R.optimizeNames(m,$)||(he(m,R.names),O.splice(x,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((m,$)=>Z(m,$.names),{})}}class p extends g{render(m){return"{"+m._n+super.render(m)+"}"+m._n}}class y extends g{}class w extends p{}w.kind="else";class h extends p{constructor(m,$){super($),this.condition=m}render(m){let $=`if(${this.condition})`+super.render(m);return this.else&&($+="else "+this.else.render(m)),$}optimizeNodes(){super.optimizeNodes();const m=this.condition;if(m===!0)return this.nodes;let $=this.else;if($){const O=$.optimizeNodes();$=this.else=Array.isArray(O)?new w(O):O}if($)return m===!1?$ instanceof h?$:$.nodes:this.nodes.length?this:new h(pe(m),$ instanceof h?[$]:$.nodes);if(!(m===!1||!this.nodes.length))return this}optimizeNames(m,$){var O;if(this.else=(O=this.else)===null||O===void 0?void 0:O.optimizeNames(m,$),!!(super.optimizeNames(m,$)||this.else))return this.condition=fe(this.condition,m,$),this}get names(){const m=super.names;return ue(m,this.condition),this.else&&Z(m,this.else.names),m}}h.kind="if";class v extends p{}v.kind="for";class b extends v{constructor(m){super(),this.iteration=m}render(m){return`for(${this.iteration})`+super.render(m)}optimizeNames(m,$){if(super.optimizeNames(m,$))return this.iteration=fe(this.iteration,m,$),this}get names(){return Z(super.names,this.iteration.names)}}class E extends v{constructor(m,$,O,x){super(),this.varKind=m,this.name=$,this.from=O,this.to=x}render(m){const $=m.es5?n.varKinds.var:this.varKind,{name:O,from:x,to:R}=this;return`for(${$} ${O}=${x}; ${O}<${R}; ${O}++)`+super.render(m)}get names(){const m=ue(super.names,this.from);return ue(m,this.to)}}class N extends v{constructor(m,$,O,x){super(),this.loop=m,this.varKind=$,this.name=O,this.iterable=x}render(m){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(m)}optimizeNames(m,$){if(super.optimizeNames(m,$))return this.iterable=fe(this.iterable,m,$),this}get names(){return Z(super.names,this.iterable.names)}}class j extends p{constructor(m,$,O){super(),this.name=m,this.args=$,this.async=O}render(m){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(m)}}j.kind="func";class T extends g{render(m){return"return "+super.render(m)}}T.kind="return";class M extends p{render(m){let $="try"+super.render(m);return this.catch&&($+=this.catch.render(m)),this.finally&&($+=this.finally.render(m)),$}optimizeNodes(){var m,$;return super.optimizeNodes(),(m=this.catch)===null||m===void 0||m.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(m,$){var O,x;return super.optimizeNames(m,$),(O=this.catch)===null||O===void 0||O.optimizeNames(m,$),(x=this.finally)===null||x===void 0||x.optimizeNames(m,$),this}get names(){const m=super.names;return this.catch&&Z(m,this.catch.names),this.finally&&Z(m,this.finally.names),m}}class C extends p{constructor(m){super(),this.error=m}render(m){return`catch(${this.error})`+super.render(m)}}C.kind="catch";class G extends p{render(m){return"finally"+super.render(m)}}G.kind="finally";class H{constructor(m,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
186
- `:""},this._extScope=m,this._scope=new n.Scope({parent:m}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(m){return this._scope.name(m)}scopeName(m){return this._extScope.name(m)}scopeValue(m,$){const O=this._extScope.value(m,$);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(m,$){return this._extScope.getValue(m,$)}scopeRefs(m){return this._extScope.scopeRefs(m,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(m,$,O,x){const R=this._scope.toName($);return O!==void 0&&x&&(this._constants[R.str]=O),this._leafNode(new i(m,R,O)),R}const(m,$,O){return this._def(n.varKinds.const,m,$,O)}let(m,$,O){return this._def(n.varKinds.let,m,$,O)}var(m,$,O){return this._def(n.varKinds.var,m,$,O)}assign(m,$,O){return this._leafNode(new a(m,$,O))}add(m,$){return this._leafNode(new c(m,t.operators.ADD,$))}code(m){return typeof m=="function"?m():m!==e.nil&&this._leafNode(new f(m)),this}object(...m){const $=["{"];for(const[O,x]of m)$.length>1&&$.push(","),$.push(O),(O!==x||this.opts.es5)&&($.push(":"),(0,e.addCodeArg)($,x));return $.push("}"),new e._Code($)}if(m,$,O){if(this._blockNode(new h(m)),$&&O)this.code($).else().code(O).endIf();else if($)this.code($).endIf();else if(O)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(m){return this._elseNode(new h(m))}else(){return this._elseNode(new w)}endIf(){return this._endBlockNode(h,w)}_for(m,$){return this._blockNode(m),$&&this.code($).endFor(),this}for(m,$){return this._for(new b(m),$)}forRange(m,$,O,x,R=this.opts.es5?n.varKinds.var:n.varKinds.let){const U=this._scope.toName(m);return this._for(new E(R,U,$,O),()=>x(U))}forOf(m,$,O,x=n.varKinds.const){const R=this._scope.toName(m);if(this.opts.es5){const U=$ instanceof e.Name?$:this.var("_arr",$);return this.forRange("_i",0,(0,e._)`${U}.length`,q=>{this.var(R,(0,e._)`${U}[${q}]`),O(R)})}return this._for(new N("of",x,R,$),()=>O(R))}forIn(m,$,O,x=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(m,(0,e._)`Object.keys(${$})`,O);const R=this._scope.toName(m);return this._for(new N("in",x,R,$),()=>O(R))}endFor(){return this._endBlockNode(v)}label(m){return this._leafNode(new u(m))}break(m){return this._leafNode(new l(m))}return(m){const $=new T;if(this._blockNode($),this.code(m),$.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(m,$,O){if(!$&&!O)throw new Error('CodeGen: "try" without "catch" and "finally"');const x=new M;if(this._blockNode(x),this.code(m),$){const R=this.name("e");this._currNode=x.catch=new C(R),$(R)}return O&&(this._currNode=x.finally=new G,this.code(O)),this._endBlockNode(C,G)}throw(m){return this._leafNode(new d(m))}block(m,$){return this._blockStarts.push(this._nodes.length),m&&this.code(m).endBlock($),this}endBlock(m){const $=this._blockStarts.pop();if($===void 0)throw new Error("CodeGen: not in self-balancing block");const O=this._nodes.length-$;if(O<0||m!==void 0&&O!==m)throw new Error(`CodeGen: wrong number of nodes: ${O} vs ${m} expected`);return this._nodes.length=$,this}func(m,$=e.nil,O,x){return this._blockNode(new j(m,$,O)),x&&this.code(x).endFunc(),this}endFunc(){return this._endBlockNode(j)}optimize(m=1){for(;m-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(m){return this._currNode.nodes.push(m),this}_blockNode(m){this._currNode.nodes.push(m),this._nodes.push(m)}_endBlockNode(m,$){const O=this._currNode;if(O instanceof m||$&&O instanceof $)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${$?`${m.kind}/${$.kind}`:m.kind}"`)}_elseNode(m){const $=this._currNode;if(!($ instanceof h))throw new Error('CodeGen: "else" without "if"');return this._currNode=$.else=m,this}get _root(){return this._nodes[0]}get _currNode(){const m=this._nodes;return m[m.length-1]}set _currNode(m){const $=this._nodes;$[$.length-1]=m}}t.CodeGen=H;function Z(_,m){for(const $ in m)_[$]=(_[$]||0)+(m[$]||0);return _}function ue(_,m){return m instanceof e._CodeOrName?Z(_,m.names):_}function fe(_,m,$){if(_ instanceof e.Name)return O(_);if(!x(_))return _;return new e._Code(_._items.reduce((R,U)=>(U instanceof e.Name&&(U=O(U)),U instanceof e._Code?R.push(...U._items):R.push(U),R),[]));function O(R){const U=$[R.str];return U===void 0||m[R.str]!==1?R:(delete m[R.str],U)}function x(R){return R instanceof e._Code&&R._items.some(U=>U instanceof e.Name&&m[U.str]===1&&$[U.str]!==void 0)}}function he(_,m){for(const $ in m)_[$]=(_[$]||0)-(m[$]||0)}function pe(_){return typeof _=="boolean"||typeof _=="number"||_===null?!_:(0,e._)`!${k(_)}`}t.not=pe;const Oe=S(t.operators.AND);function gt(..._){return _.reduce(Oe)}t.and=gt;const ut=S(t.operators.OR);function A(..._){return _.reduce(ut)}t.or=A;function S(_){return(m,$)=>m===e.nil?$:$===e.nil?m:(0,e._)`${k(m)} ${_} ${k($)}`}function k(_){return _ instanceof e.Name?_:(0,e._)`(${_})`}})(ae);var K={};Object.defineProperty(K,"__esModule",{value:!0});K.checkStrictMode=K.getErrorPath=K.Type=K.useFunc=K.setEvaluated=K.evaluatedPropsToName=K.mergeEvaluated=K.eachItem=K.unescapeJsonPointer=K.escapeJsonPointer=K.escapeFragment=K.unescapeFragment=K.schemaRefOrVal=K.schemaHasRulesButRef=K.schemaHasRules=K.checkUnknownRules=K.alwaysValidSchema=K.toHash=void 0;const ye=ae,sk=cs;function ik(t){const e={};for(const n of t)e[n]=!0;return e}K.toHash=ik;function ak(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(vw(t,e),!$w(e,t.self.RULES.all))}K.alwaysValidSchema=ak;function vw(t,e=t.schema){const{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;const o=r.RULES.keywords;for(const s in e)o[s]||Sw(t,`unknown keyword: "${s}"`)}K.checkUnknownRules=vw;function $w(t,e){if(typeof t=="boolean")return!t;for(const n in t)if(e[n])return!0;return!1}K.schemaHasRules=$w;function ck(t,e){if(typeof t=="boolean")return!t;for(const n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}K.schemaHasRulesButRef=ck;function uk({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,ye._)`${n}`}return(0,ye._)`${t}${e}${(0,ye.getProperty)(r)}`}K.schemaRefOrVal=uk;function lk(t){return bw(decodeURIComponent(t))}K.unescapeFragment=lk;function dk(t){return encodeURIComponent(Kl(t))}K.escapeFragment=dk;function Kl(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}K.escapeJsonPointer=Kl;function bw(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}K.unescapeJsonPointer=bw;function fk(t,e){if(Array.isArray(t))for(const n of t)e(n);else e(t)}K.eachItem=fk;function mh({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof ye.Name?(s instanceof ye.Name?t(o,s,i):e(o,s,i),i):s instanceof ye.Name?(e(o,i,s),s):n(s,i);return a===ye.Name&&!(c instanceof ye.Name)?r(o,c):c}}K.mergeEvaluated={props:mh({mergeNames:(t,e,n)=>t.if((0,ye._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,ye._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,ye._)`${n} || {}`).code((0,ye._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,ye._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,ye._)`${n} || {}`),Vl(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Ew}),items:mh({mergeNames:(t,e,n)=>t.if((0,ye._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,ye._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,ye._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,ye._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Ew(t,e){if(e===!0)return t.var("props",!0);const n=t.var("props",(0,ye._)`{}`);return e!==void 0&&Vl(t,n,e),n}K.evaluatedPropsToName=Ew;function Vl(t,e,n){Object.keys(n).forEach(r=>t.assign((0,ye._)`${e}${(0,ye.getProperty)(r)}`,!0))}K.setEvaluated=Vl;const gh={};function pk(t,e){return t.scopeValue("func",{ref:e,code:gh[e.code]||(gh[e.code]=new sk._Code(e.code))})}K.useFunc=pk;var lu;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(lu||(K.Type=lu={}));function hk(t,e,n){if(t instanceof ye.Name){const r=e===lu.Num;return n?r?(0,ye._)`"[" + ${t} + "]"`:(0,ye._)`"['" + ${t} + "']"`:r?(0,ye._)`"/" + ${t}`:(0,ye._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,ye.getProperty)(t).toString():"/"+Kl(t)}K.getErrorPath=hk;function Sw(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}K.checkStrictMode=Sw;var Bt={};Object.defineProperty(Bt,"__esModule",{value:!0});const Ve=ae,mk={data:new Ve.Name("data"),valCxt:new Ve.Name("valCxt"),instancePath:new Ve.Name("instancePath"),parentData:new Ve.Name("parentData"),parentDataProperty:new Ve.Name("parentDataProperty"),rootData:new Ve.Name("rootData"),dynamicAnchors:new Ve.Name("dynamicAnchors"),vErrors:new Ve.Name("vErrors"),errors:new Ve.Name("errors"),this:new Ve.Name("this"),self:new Ve.Name("self"),scope:new Ve.Name("scope"),json:new Ve.Name("json"),jsonPos:new Ve.Name("jsonPos"),jsonLen:new Ve.Name("jsonLen"),jsonPart:new Ve.Name("jsonPart")};Bt.default=mk;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=ae,n=K,r=Bt;t.keywordError={message:({keyword:w})=>(0,e.str)`must pass "${w}" keyword validation`},t.keyword$DataError={message:({keyword:w,schemaType:h})=>h?(0,e.str)`"${w}" keyword must be ${h} ($data)`:(0,e.str)`"${w}" keyword is invalid ($data)`};function o(w,h=t.keywordError,v,b){const{it:E}=w,{gen:N,compositeRule:j,allErrors:T}=E,M=d(w,h,v);b??(j||T)?c(N,M):u(E,(0,e._)`[${M}]`)}t.reportError=o;function s(w,h=t.keywordError,v){const{it:b}=w,{gen:E,compositeRule:N,allErrors:j}=b,T=d(w,h,v);c(E,T),N||j||u(b,r.default.vErrors)}t.reportExtraError=s;function i(w,h){w.assign(r.default.errors,h),w.if((0,e._)`${r.default.vErrors} !== null`,()=>w.if(h,()=>w.assign((0,e._)`${r.default.vErrors}.length`,h),()=>w.assign(r.default.vErrors,null)))}t.resetErrorsCount=i;function a({gen:w,keyword:h,schemaValue:v,data:b,errsCount:E,it:N}){if(E===void 0)throw new Error("ajv implementation error");const j=w.name("err");w.forRange("i",E,r.default.errors,T=>{w.const(j,(0,e._)`${r.default.vErrors}[${T}]`),w.if((0,e._)`${j}.instancePath === undefined`,()=>w.assign((0,e._)`${j}.instancePath`,(0,e.strConcat)(r.default.instancePath,N.errorPath))),w.assign((0,e._)`${j}.schemaPath`,(0,e.str)`${N.errSchemaPath}/${h}`),N.opts.verbose&&(w.assign((0,e._)`${j}.schema`,v),w.assign((0,e._)`${j}.data`,b))})}t.extendErrors=a;function c(w,h){const v=w.const("err",h);w.if((0,e._)`${r.default.vErrors} === null`,()=>w.assign(r.default.vErrors,(0,e._)`[${v}]`),(0,e._)`${r.default.vErrors}.push(${v})`),w.code((0,e._)`${r.default.errors}++`)}function u(w,h){const{gen:v,validateName:b,schemaEnv:E}=w;E.$async?v.throw((0,e._)`new ${w.ValidationError}(${h})`):(v.assign((0,e._)`${b}.errors`,h),v.return(!1))}const l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(w,h,v){const{createErrors:b}=w.it;return b===!1?(0,e._)`{}`:f(w,h,v)}function f(w,h,v={}){const{gen:b,it:E}=w,N=[g(E,v),p(w,v)];return y(w,h,N),b.object(...N)}function g({errorPath:w},{instancePath:h}){const v=h?(0,e.str)`${w}${(0,n.getErrorPath)(h,n.Type.Str)}`:w;return[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,v)]}function p({keyword:w,it:{errSchemaPath:h}},{schemaPath:v,parentSchema:b}){let E=b?h:(0,e.str)`${h}/${w}`;return v&&(E=(0,e.str)`${E}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,E]}function y(w,{params:h,message:v},b){const{keyword:E,data:N,schemaValue:j,it:T}=w,{opts:M,propertyName:C,topSchemaRef:G,schemaPath:H}=T;b.push([l.keyword,E],[l.params,typeof h=="function"?h(w):h||(0,e._)`{}`]),M.messages&&b.push([l.message,typeof v=="function"?v(w):v]),M.verbose&&b.push([l.schema,j],[l.parentSchema,(0,e._)`${G}${H}`],[r.default.data,N]),C&&b.push([l.propertyName,C])}})(Ss);Object.defineProperty(eo,"__esModule",{value:!0});eo.boolOrEmptySchema=eo.topBoolOrEmptySchema=void 0;const gk=Ss,yk=ae,wk=Bt,vk={message:"boolean schema is false"};function $k(t){const{gen:e,schema:n,validateName:r}=t;n===!1?_w(t,!1):typeof n=="object"&&n.$async===!0?e.return(wk.default.data):(e.assign((0,yk._)`${r}.errors`,null),e.return(!0))}eo.topBoolOrEmptySchema=$k;function bk(t,e){const{gen:n,schema:r}=t;r===!1?(n.var(e,!1),_w(t)):n.var(e,!0)}eo.boolOrEmptySchema=bk;function _w(t,e){const{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,gk.reportError)(o,vk,void 0,e)}var Ae={},mr={};Object.defineProperty(mr,"__esModule",{value:!0});mr.getRules=mr.isJSONType=void 0;const Ek=["string","number","integer","boolean","null","object","array"],Sk=new Set(Ek);function _k(t){return typeof t=="string"&&Sk.has(t)}mr.isJSONType=_k;function Nk(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}mr.getRules=Nk;var Jt={};Object.defineProperty(Jt,"__esModule",{value:!0});Jt.shouldUseRule=Jt.shouldUseGroup=Jt.schemaHasRulesForType=void 0;function Ok({schema:t,self:e},n){const r=e.RULES.types[n];return r&&r!==!0&&Nw(t,r)}Jt.schemaHasRulesForType=Ok;function Nw(t,e){return e.rules.some(n=>Ow(t,n))}Jt.shouldUseGroup=Nw;function Ow(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Jt.shouldUseRule=Ow;Object.defineProperty(Ae,"__esModule",{value:!0});Ae.reportTypeError=Ae.checkDataTypes=Ae.checkDataType=Ae.coerceAndCheckDataType=Ae.getJSONTypes=Ae.getSchemaTypes=Ae.DataType=void 0;const kk=mr,jk=Jt,Ak=Ss,te=ae,kw=K;var zr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(zr||(Ae.DataType=zr={}));function Ik(t){const e=jw(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ae.getSchemaTypes=Ik;function jw(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(kk.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ae.getJSONTypes=jw;function Pk(t,e){const{gen:n,data:r,opts:o}=t,s=xk(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,jk.schemaHasRulesForType)(t,e[0]));if(i){const a=Gl(e,r,o.strictNumbers,zr.Wrong);n.if(a,()=>{s.length?Rk(t,e,s):zl(t)})}return i}Ae.coerceAndCheckDataType=Pk;const Aw=new Set(["string","number","integer","boolean","null"]);function xk(t,e){return e?t.filter(n=>Aw.has(n)||e==="array"&&n==="array"):[]}function Rk(t,e,n){const{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,te._)`typeof ${o}`),a=r.let("coerced",(0,te._)`undefined`);s.coerceTypes==="array"&&r.if((0,te._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,te._)`${o}[0]`).assign(i,(0,te._)`typeof ${o}`).if(Gl(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,te._)`${a} !== undefined`);for(const u of n)(Aw.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),zl(t),r.endIf(),r.if((0,te._)`${a} !== undefined`,()=>{r.assign(o,a),Tk(t,a)});function c(u){switch(u){case"string":r.elseIf((0,te._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,te._)`"" + ${o}`).elseIf((0,te._)`${o} === null`).assign(a,(0,te._)`""`);return;case"number":r.elseIf((0,te._)`${i} == "boolean" || ${o} === null
187
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,te._)`+${o}`);return;case"integer":r.elseIf((0,te._)`${i} === "boolean" || ${o} === null
188
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,te._)`+${o}`);return;case"boolean":r.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":r.elseIf((0,te._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,te._)`${i} === "string" || ${i} === "number"
189
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,te._)`[${o}]`)}}}function Tk({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,te._)`${e} !== undefined`,()=>t.assign((0,te._)`${e}[${n}]`,r))}function du(t,e,n,r=zr.Correct){const o=r===zr.Correct?te.operators.EQ:te.operators.NEQ;let s;switch(t){case"null":return(0,te._)`${e} ${o} null`;case"array":s=(0,te._)`Array.isArray(${e})`;break;case"object":s=(0,te._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,te._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,te._)`typeof ${e} ${o} ${t}`}return r===zr.Correct?s:(0,te.not)(s);function i(a=te.nil){return(0,te.and)((0,te._)`typeof ${e} == "number"`,a,n?(0,te._)`isFinite(${e})`:te.nil)}}Ae.checkDataType=du;function Gl(t,e,n,r){if(t.length===1)return du(t[0],e,n,r);let o;const s=(0,kw.toHash)(t);if(s.array&&s.object){const i=(0,te._)`typeof ${e} != "object"`;o=s.null?i:(0,te._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=te.nil;s.number&&delete s.integer;for(const i in s)o=(0,te.and)(o,du(i,e,n,r));return o}Ae.checkDataTypes=Gl;const Ck={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,te._)`{type: ${t}}`:(0,te._)`{type: ${e}}`};function zl(t){const e=Mk(t);(0,Ak.reportError)(e,Ck)}Ae.reportTypeError=zl;function Mk(t){const{gen:e,data:n,schema:r}=t,o=(0,kw.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}var Ea={};Object.defineProperty(Ea,"__esModule",{value:!0});Ea.assignDefaults=void 0;const kr=ae,Lk=K;function Dk(t,e){const{properties:n,items:r}=t.schema;if(e==="object"&&n)for(const o in n)yh(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>yh(t,s,o.default))}Ea.assignDefaults=Dk;function yh(t,e,n){const{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;const a=(0,kr._)`${s}${(0,kr.getProperty)(e)}`;if(o){(0,Lk.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,kr._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,kr._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,kr._)`${a} = ${(0,kr.stringify)(n)}`)}var Tt={},se={};Object.defineProperty(se,"__esModule",{value:!0});se.validateUnion=se.validateArray=se.usePattern=se.callValidateCode=se.schemaProperties=se.allSchemaProperties=se.noPropertyInData=se.propertyInData=se.isOwnProperty=se.hasPropFunc=se.reportMissingProp=se.checkMissingProp=se.checkReportMissingProp=void 0;const ve=ae,Wl=K,cn=Bt,Uk=K;function Bk(t,e){const{gen:n,data:r,it:o}=t;n.if(Jl(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ve._)`${e}`},!0),t.error()})}se.checkReportMissingProp=Bk;function Fk({gen:t,data:e,it:{opts:n}},r,o){return(0,ve.or)(...r.map(s=>(0,ve.and)(Jl(t,e,s,n.ownProperties),(0,ve._)`${o} = ${s}`)))}se.checkMissingProp=Fk;function qk(t,e){t.setParams({missingProperty:e},!0),t.error()}se.reportMissingProp=qk;function Iw(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ve._)`Object.prototype.hasOwnProperty`})}se.hasPropFunc=Iw;function Hl(t,e,n){return(0,ve._)`${Iw(t)}.call(${e}, ${n})`}se.isOwnProperty=Hl;function Kk(t,e,n,r){const o=(0,ve._)`${e}${(0,ve.getProperty)(n)} !== undefined`;return r?(0,ve._)`${o} && ${Hl(t,e,n)}`:o}se.propertyInData=Kk;function Jl(t,e,n,r){const o=(0,ve._)`${e}${(0,ve.getProperty)(n)} === undefined`;return r?(0,ve.or)(o,(0,ve.not)(Hl(t,e,n))):o}se.noPropertyInData=Jl;function Pw(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}se.allSchemaProperties=Pw;function Vk(t,e){return Pw(e).filter(n=>!(0,Wl.alwaysValidSchema)(t,e[n]))}se.schemaProperties=Vk;function Gk({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){const l=u?(0,ve._)`${t}, ${e}, ${r}${o}`:e,d=[[cn.default.instancePath,(0,ve.strConcat)(cn.default.instancePath,s)],[cn.default.parentData,i.parentData],[cn.default.parentDataProperty,i.parentDataProperty],[cn.default.rootData,cn.default.rootData]];i.opts.dynamicRef&&d.push([cn.default.dynamicAnchors,cn.default.dynamicAnchors]);const f=(0,ve._)`${l}, ${n.object(...d)}`;return c!==ve.nil?(0,ve._)`${a}.call(${c}, ${f})`:(0,ve._)`${a}(${f})`}se.callValidateCode=Gk;const zk=(0,ve._)`new RegExp`;function Wk({gen:t,it:{opts:e}},n){const r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ve._)`${o.code==="new RegExp"?zk:(0,Uk.useFunc)(t,o)}(${n}, ${r})`})}se.usePattern=Wk;function Hk(t){const{gen:e,data:n,keyword:r,it:o}=t,s=e.name("valid");if(o.allErrors){const a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){const c=e.const("len",(0,ve._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Wl.Type.Num},s),e.if((0,ve.not)(s),a)})}}se.validateArray=Hk;function Jk(t){const{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,Wl.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;const s=e.let("valid",!1),i=e.name("_valid");e.block(()=>n.forEach((a,c)=>{const u=t.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);e.assign(s,(0,ve._)`${s} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,ve.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}se.validateUnion=Jk;Object.defineProperty(Tt,"__esModule",{value:!0});Tt.validateKeywordUsage=Tt.validSchemaType=Tt.funcKeywordCode=Tt.macroKeywordCode=void 0;const Ye=ae,Zn=Bt,Qk=se,Yk=Ss;function Zk(t,e){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=xw(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");t.subschema({schema:a,schemaPath:Ye.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Tt.macroKeywordCode=Zk;function Xk(t,e){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;t1(c,e);const u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=xw(r,o,u),d=r.let("valid");t.block$data(d,f),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function f(){if(e.errors===!1)y(),e.modifying&&wh(t),w(()=>t.error());else{const h=e.async?g():p();e.modifying&&wh(t),w(()=>e1(t,h))}}function g(){const h=r.let("ruleErrs",null);return r.try(()=>y((0,Ye._)`await `),v=>r.assign(d,!1).if((0,Ye._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(h,(0,Ye._)`${v}.errors`),()=>r.throw(v))),h}function p(){const h=(0,Ye._)`${l}.errors`;return r.assign(h,null),y(Ye.nil),h}function y(h=e.async?(0,Ye._)`await `:Ye.nil){const v=c.opts.passContext?Zn.default.this:Zn.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,Ye._)`${h}${(0,Qk.callValidateCode)(t,l,v,b)}`,e.modifying)}function w(h){var v;r.if((0,Ye.not)((v=e.valid)!==null&&v!==void 0?v:d),h)}}Tt.funcKeywordCode=Xk;function wh(t){const{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Ye._)`${r.parentData}[${r.parentDataProperty}]`))}function e1(t,e){const{gen:n}=t;n.if((0,Ye._)`Array.isArray(${e})`,()=>{n.assign(Zn.default.vErrors,(0,Ye._)`${Zn.default.vErrors} === null ? ${e} : ${Zn.default.vErrors}.concat(${e})`).assign(Zn.default.errors,(0,Ye._)`${Zn.default.vErrors}.length`),(0,Yk.extendErrors)(t)},()=>t.error())}function t1({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function xw(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Ye.stringify)(n)})}function n1(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Tt.validSchemaType=n1;function r1({schema:t,opts:e,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const i=o.dependencies;if(i!=null&&i.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){const a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}Tt.validateKeywordUsage=r1;var bn={};Object.defineProperty(bn,"__esModule",{value:!0});bn.extendSubschemaMode=bn.extendSubschemaData=bn.getSubschema=void 0;const xt=ae,Rw=K;function o1(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,xt._)`${t.schemaPath}${(0,xt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,xt._)`${t.schemaPath}${(0,xt.getProperty)(e)}${(0,xt.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Rw.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}bn.getSubschema=o1;function s1(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=e;if(n!==void 0){const{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,xt._)`${e.data}${(0,xt.getProperty)(n)}`,!0);c(f),t.errorPath=(0,xt.str)`${u}${(0,Rw.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,xt._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){const u=o instanceof xt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}bn.extendSubschemaData=s1;function i1(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}bn.extendSubschemaMode=i1;var Le={},Tw=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n},Cw={exports:{}},yn=Cw.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};yi(e,r,o,t,"",t)};yn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};yn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};yn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};yn.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 yi(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in yn.arrayKeywords)for(var f=0;f<d.length;f++)yi(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in yn.propsKeywords){if(d&&typeof d=="object")for(var g in d)yi(t,e,n,d[g],o+"/"+l+"/"+a1(g),s,o,l,r,g)}else(l in yn.keywords||t.allKeys&&!(l in yn.skipKeywords))&&yi(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function a1(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var c1=Cw.exports;Object.defineProperty(Le,"__esModule",{value:!0});Le.getSchemaRefs=Le.resolveUrl=Le.normalizeId=Le._getFullPath=Le.getFullPath=Le.inlineRef=void 0;const u1=K,l1=Tw,d1=c1,f1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function p1(t,e=!0){return typeof t=="boolean"?!0:e===!0?!fu(t):e?Mw(t)<=e:!1}Le.inlineRef=p1;const h1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function fu(t){for(const e in t){if(h1.has(e))return!0;const n=t[e];if(Array.isArray(n)&&n.some(fu)||typeof n=="object"&&fu(n))return!0}return!1}function Mw(t){let e=0;for(const n in t)if(n==="$ref"||(e++,!f1.has(n)&&(typeof t[n]=="object"&&(0,u1.eachItem)(t[n],r=>e+=Mw(r)),e===1/0)))return 1/0;return e}function Lw(t,e="",n){n!==!1&&(e=Wr(e));const r=t.parse(e);return Dw(t,r)}Le.getFullPath=Lw;function Dw(t,e){return t.serialize(e).split("#")[0]+"#"}Le._getFullPath=Dw;const m1=/#\/?$/;function Wr(t){return t?t.replace(m1,""):""}Le.normalizeId=Wr;function g1(t,e,n){return n=Wr(n),t.resolve(e,n)}Le.resolveUrl=g1;const y1=/^[a-z_][-a-z0-9._]*$/i;function w1(t,e){if(typeof t=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Wr(t[n]||e),s={"":o},i=Lw(r,o,!1),a={},c=new Set;return d1(t,{allKeys:!0},(d,f,g,p)=>{if(p===void 0)return;const y=i+f;let w=s[p];typeof d[n]=="string"&&(w=h.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[f]=w;function h(b){const E=this.opts.uriResolver.resolve;if(b=Wr(w?E(w,b):b),c.has(b))throw l(b);c.add(b);let N=this.refs[b];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(d,N.schema,b):b!==Wr(y)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=y),b}function v(b){if(typeof b=="string"){if(!y1.test(b))throw new Error(`invalid anchor "${b}"`);h.call(this,`#${b}`)}}}),a;function u(d,f,g){if(f!==void 0&&!l1(d,f))throw l(g)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}Le.getSchemaRefs=w1;Object.defineProperty(Nt,"__esModule",{value:!0});Nt.getData=Nt.KeywordCxt=Nt.validateFunctionCode=void 0;const Uw=eo,vh=Ae,Ql=Jt,Gi=Ae,v1=Ea,Bo=Tt,rc=bn,z=ae,Q=Bt,$1=Le,Qt=K,$o=Ss;function b1(t){if(qw(t)&&(Kw(t),Fw(t))){_1(t);return}Bw(t,()=>(0,Uw.topBoolOrEmptySchema)(t))}Nt.validateFunctionCode=b1;function Bw({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,z._)`${Q.default.data}, ${Q.default.valCxt}`,r.$async,()=>{t.code((0,z._)`"use strict"; ${$h(n,o)}`),S1(t,o),t.code(s)}):t.func(e,(0,z._)`${Q.default.data}, ${E1(o)}`,r.$async,()=>t.code($h(n,o)).code(s))}function E1(t){return(0,z._)`{${Q.default.instancePath}="", ${Q.default.parentData}, ${Q.default.parentDataProperty}, ${Q.default.rootData}=${Q.default.data}${t.dynamicRef?(0,z._)`, ${Q.default.dynamicAnchors}={}`:z.nil}}={}`}function S1(t,e){t.if(Q.default.valCxt,()=>{t.var(Q.default.instancePath,(0,z._)`${Q.default.valCxt}.${Q.default.instancePath}`),t.var(Q.default.parentData,(0,z._)`${Q.default.valCxt}.${Q.default.parentData}`),t.var(Q.default.parentDataProperty,(0,z._)`${Q.default.valCxt}.${Q.default.parentDataProperty}`),t.var(Q.default.rootData,(0,z._)`${Q.default.valCxt}.${Q.default.rootData}`),e.dynamicRef&&t.var(Q.default.dynamicAnchors,(0,z._)`${Q.default.valCxt}.${Q.default.dynamicAnchors}`)},()=>{t.var(Q.default.instancePath,(0,z._)`""`),t.var(Q.default.parentData,(0,z._)`undefined`),t.var(Q.default.parentDataProperty,(0,z._)`undefined`),t.var(Q.default.rootData,Q.default.data),e.dynamicRef&&t.var(Q.default.dynamicAnchors,(0,z._)`{}`)})}function _1(t){const{schema:e,opts:n,gen:r}=t;Bw(t,()=>{n.$comment&&e.$comment&&Gw(t),A1(t),r.let(Q.default.vErrors,null),r.let(Q.default.errors,0),n.unevaluated&&N1(t),Vw(t),x1(t)})}function N1(t){const{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,z._)`${n}.evaluated`),e.if((0,z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,z._)`${t.evaluated}.props`,(0,z._)`undefined`)),e.if((0,z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,z._)`${t.evaluated}.items`,(0,z._)`undefined`))}function $h(t,e){const n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,z._)`/*# sourceURL=${n} */`:z.nil}function O1(t,e){if(qw(t)&&(Kw(t),Fw(t))){k1(t,e);return}(0,Uw.boolOrEmptySchema)(t,e)}function Fw({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const n in t)if(e.RULES.all[n])return!0;return!1}function qw(t){return typeof t.schema!="boolean"}function k1(t,e){const{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&Gw(t),I1(t),P1(t);const s=r.const("_errs",Q.default.errors);Vw(t,s),r.var(e,(0,z._)`${s} === ${Q.default.errors}`)}function Kw(t){(0,Qt.checkUnknownRules)(t),j1(t)}function Vw(t,e){if(t.opts.jtd)return bh(t,[],!1,e);const n=(0,vh.getSchemaTypes)(t.schema),r=(0,vh.coerceAndCheckDataType)(t,n);bh(t,n,!r,e)}function j1(t){const{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Qt.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function A1(t){const{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Qt.checkStrictMode)(t,"default is ignored in the schema root")}function I1(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,$1.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function P1(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Gw({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)t.code((0,z._)`${Q.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,z.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,z._)`${Q.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function x1(t){const{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,z._)`${Q.default.errors} === 0`,()=>e.return(Q.default.data),()=>e.throw((0,z._)`new ${o}(${Q.default.vErrors})`)):(e.assign((0,z._)`${r}.errors`,Q.default.vErrors),s.unevaluated&&R1(t),e.return((0,z._)`${Q.default.errors} === 0`))}function R1({gen:t,evaluated:e,props:n,items:r}){n instanceof z.Name&&t.assign((0,z._)`${e}.props`,n),r instanceof z.Name&&t.assign((0,z._)`${e}.items`,r)}function bh(t,e,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Qt.schemaHasRulesButRef)(s,l))){o.block(()=>Hw(t,"$ref",l.all.$ref.definition));return}c.jtd||T1(t,e),o.block(()=>{for(const f of l.rules)d(f);d(l.post)});function d(f){(0,Ql.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Gi.checkDataType)(f.type,i,c.strictNumbers)),Eh(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,Gi.reportTypeError)(t)),o.endIf()):Eh(t,f),a||o.if((0,z._)`${Q.default.errors} === ${r||0}`))}}function Eh(t,e){const{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,v1.assignDefaults)(t,e.type),n.block(()=>{for(const s of e.rules)(0,Ql.shouldUseRule)(r,s)&&Hw(t,s.keyword,s.definition,e.type)})}function T1(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(C1(t,e),t.opts.allowUnionTypes||M1(t,e),L1(t,t.dataTypes))}function C1(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{zw(t.dataTypes,n)||Yl(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),U1(t,e)}}function M1(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Yl(t,"use allowUnionTypes to allow union type keyword")}function L1(t,e){const n=t.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,Ql.shouldUseRule)(t.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>D1(e,i))&&Yl(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function D1(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function zw(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function U1(t,e){const n=[];for(const r of t.dataTypes)zw(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Yl(t,e){const n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Qt.checkStrictMode)(t,e,t.opts.strictTypes)}let Ww=class{constructor(e,n,r){if((0,Bo.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Qt.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",Jw(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Bo.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Q.default.errors))}result(e,n,r){this.failResult((0,z.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,z.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:n}=this;this.fail((0,z._)`${n} !== undefined && (${(0,z.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?$o.reportExtraError:$o.reportError)(this,this.def.error,n)}$dataError(){(0,$o.reportError)(this,this.def.$dataError||$o.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,$o.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=z.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=z.nil,n=z.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,z.or)((0,z._)`${o} === undefined`,n)),e!==z.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==z.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,z.or)(i(),a());function i(){if(r.length){if(!(n instanceof z.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,z._)`${(0,Gi.checkDataTypes)(c,n,s.opts.strictNumbers,Gi.DataType.Wrong)}`}return z.nil}function a(){if(o.validateSchema){const c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,z._)`!${c}(${n})`}return z.nil}}subschema(e,n){const r=(0,rc.getSubschema)(this.it,e);(0,rc.extendSubschemaData)(r,this.it,e),(0,rc.extendSubschemaMode)(r,e);const o={...this.it,...r,items:void 0,props:void 0};return O1(o,n),o}mergeEvaluated(e,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Qt.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Qt.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,z.Name)),!0}};Nt.KeywordCxt=Ww;function Hw(t,e,n,r){const o=new Ww(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Bo.funcKeywordCode)(o,n):"macro"in n?(0,Bo.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Bo.funcKeywordCode)(o,n)}const B1=/^\/(?:[^~]|~0|~1)*$/,F1=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Jw(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return Q.default.rootData;if(t[0]==="/"){if(!B1.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=Q.default.rootData}else{const u=F1.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);const l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,z._)`${s}${(0,z.getProperty)((0,Qt.unescapeJsonPointer)(u))}`,i=(0,z._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Nt.getData=Jw;var _s={};Object.defineProperty(_s,"__esModule",{value:!0});let q1=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};_s.default=q1;var uo={};Object.defineProperty(uo,"__esModule",{value:!0});const oc=Le;let K1=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,oc.resolveUrl)(e,n,r),this.missingSchema=(0,oc.normalizeId)((0,oc.getFullPath)(e,this.missingRef))}};uo.default=K1;var st={};Object.defineProperty(st,"__esModule",{value:!0});st.resolveSchema=st.getCompilingSchema=st.resolveRef=st.compileSchema=st.SchemaEnv=void 0;const wt=ae,V1=_s,Vn=Bt,Et=Le,Sh=K,G1=Nt;let Sa=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,Et.normalizeId)(r==null?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r==null?void 0:r.$async,this.refs={}}};st.SchemaEnv=Sa;function Zl(t){const e=Qw.call(this,t);if(e)return e;const n=(0,Et.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new wt.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;t.$async&&(a=i.scopeValue("Error",{ref:V1.default,code:(0,wt._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");t.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:Vn.default.data,parentData:Vn.default.parentData,parentDataProperty:Vn.default.parentDataProperty,dataNames:[Vn.default.data],dataPathArr:[wt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,wt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:wt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,wt._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(t),(0,G1.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const d=i.toString();l=`${i.scopeRefs(Vn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));const f=new Function(`${Vn.default.self}`,`${Vn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){const{props:g,items:p}=u;f.evaluated={props:g instanceof wt.Name?void 0:g,items:p instanceof wt.Name?void 0:p,dynamicProps:g instanceof wt.Name,dynamicItems:p instanceof wt.Name},f.source&&(f.source.evaluated=(0,wt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}st.compileSchema=Zl;function z1(t,e,n){var r;n=(0,Et.resolveUrl)(this.opts.uriResolver,e,n);const o=t.refs[n];if(o)return o;let s=J1.call(this,t,n);if(s===void 0){const i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Sa({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=W1.call(this,s)}st.resolveRef=z1;function W1(t){return(0,Et.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Zl.call(this,t)}function Qw(t){for(const e of this._compilations)if(H1(e,t))return e}st.getCompilingSchema=Qw;function H1(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function J1(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||_a.call(this,t,e)}function _a(t,e){const n=this.opts.uriResolver.parse(e),r=(0,Et._getFullPath)(this.opts.uriResolver,n);let o=(0,Et.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return sc.call(this,n,t);const s=(0,Et.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=_a.call(this,t,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:sc.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||Zl.call(this,i),s===(0,Et.normalizeId)(e)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Et.resolveUrl)(this.opts.uriResolver,o,u)),new Sa({schema:a,schemaId:c,root:t,baseId:o})}return sc.call(this,n,i)}}st.resolveSchema=_a;const Q1=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function sc(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,Sh.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!Q1.has(a)&&u&&(e=(0,Et.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Sh.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Et.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=_a.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Sa({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}const Y1="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",Z1="Meta-schema for $data reference (JSON AnySchema extension proposal)",X1="object",ej=["$data"],tj={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},nj=!1,rj={$id:Y1,description:Z1,type:X1,required:ej,properties:tj,additionalProperties:nj};var Xl={},Na={exports:{}};const oj=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Yw=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),ed=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Zw=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),sj=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Xw(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}const ij=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _h(t){return t.length=0,!0}function aj(t,e,n){if(t.length){const r=Xw(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function cj(t){let e=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=aj;for(let c=0;c<t.length;c++){const u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=_h}else{o.push(u);continue}}return o.length&&(a===_h?n.zone=o.join(""):i?r.push(o.join("")):r.push(Xw(o))),n.address=r.join(""),n}function ev(t){if(uj(t,":")<2)return{host:t,isIPV6:!1};const e=cj(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function uj(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function lj(t){let e=t;const n=[];let r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}const dj={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},fj=/[@/?#:]/g,pj=/[@/?#]/g;function tv(t,e){const n=e?pj:fj;return n.lastIndex=0,t.replace(n,r=>dj[r])}function hj(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){const o=t.slice(r+1,r+3);if(ed(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Zw(i)?n+=i:n+="%"+s,r+=2;continue}}n+=t[r]}return n}function mj(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){const r=t.slice(n+1,n+3);if(ed(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Zw(s)?e+=s:e+="%"+o,n+=2;continue}}sj(t[n])?e+=t[n]:e+=escape(t[n])}return e}function gj(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){const r=t.slice(n+1,n+3);if(ed(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function yj(t){const e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Yw(n)){const r=ev(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=tv(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}var nv={nonSimpleDomain:ij,recomposeAuthority:yj,reescapeHostDelimiters:tv,normalizePercentEncoding:hj,normalizePathEncoding:mj,escapePreservingEscapes:gj,removeDotSegments:lj,isIPv4:Yw,isUUID:oj,normalizeIPv6:ev};const{isUUID:wj}=nv,vj=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function rv(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function ov(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function sv(t){const e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function $j(t){return t.secure=rv(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function bj(t){if((t.port===(rv(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){const[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function Ej(t,e){if(!t.path)return t.error="URN can not be parsed",t;const n=t.path.match(vj);if(n){const r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];const o=`${r}:${e.nid||t.nid}`,s=td(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function Sj(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=td(o);s&&(t=s.serialize(t,e));const i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function _j(t,e){const n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!wj(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Nj(t){const e=t;return e.nss=(t.uuid||"").toLowerCase(),e}const iv={scheme:"http",domainHost:!0,parse:ov,serialize:sv},Oj={scheme:"https",domainHost:iv.domainHost,parse:ov,serialize:sv},wi={scheme:"ws",domainHost:!0,parse:$j,serialize:bj},kj={scheme:"wss",domainHost:wi.domainHost,parse:wi.parse,serialize:wi.serialize},jj={scheme:"urn",parse:Ej,serialize:Sj,skipNormalize:!0},Aj={scheme:"urn:uuid",parse:_j,serialize:Nj,skipNormalize:!0},zi={http:iv,https:Oj,ws:wi,wss:kj,urn:jj,"urn:uuid":Aj};Object.setPrototypeOf(zi,null);function td(t){return t&&(zi[t]||zi[t.toLowerCase()])||void 0}var Ij={SCHEMES:zi,getSchemeHandler:td};const{normalizeIPv6:Pj,removeDotSegments:Ao,recomposeAuthority:xj,normalizePercentEncoding:Rj,normalizePathEncoding:Tj,escapePreservingEscapes:Cj,reescapeHostDelimiters:Mj,isIPv4:Lj,nonSimpleDomain:Dj}=nv,{SCHEMES:Uj,getSchemeHandler:av}=Ij;function Bj(t,e){return typeof t=="string"?t=zj(t,e):typeof t=="object"&&(t=to(gr(t,e),e)),t}function Fj(t,e,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=cv(to(t,r),to(e,r),r,!0);return r.skipEscape=!0,gr(o,r)}function cv(t,e,n,r){const o={};return r||(t=to(gr(t,n),n),e=to(gr(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ao(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ao(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ao(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Ao(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function qj(t,e,n){const r=Nh(t,n),o=Nh(e,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function gr(t,e){const n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],s=av(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=Rj(n.path):(n.path=Cj(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=xj(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=Ao(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const Kj=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Vj=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function Gj(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function uv(t,e){const n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1,s=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);const i=t.match(Vj);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);const a=t.match(Kj);if(a){r.scheme=a[1],r.userinfo=a[3],r.host=a[4],r.port=parseInt(a[5],10),r.path=a[6]||"",r.query=a[7],r.fragment=a[8],isNaN(r.port)&&(r.port=a[5]);const c=Gj(r,a);if(c!==void 0&&(r.error=r.error||c,o=!0),r.host)if(Lj(r.host)===!1){const l=Pj(r.host);r.host=l.host.toLowerCase(),s=l.isIPV6}else s=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");const u=av(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&s===!1&&Dj(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(l){r.error=r.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Mj(unescape(r.host),s))),r.path&&(r.path=Tj(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}u&&u.parse&&u.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function to(t,e){return uv(t,e).parsed}function zj(t,e){return lv(t,e).normalized}function lv(t,e){const{parsed:n,malformedAuthorityOrPort:r}=uv(t,e);return{normalized:r?t:gr(n,e),malformedAuthorityOrPort:r}}function Nh(t,e){if(typeof t=="string"){const{normalized:n,malformedAuthorityOrPort:r}=lv(t,e);return r?void 0:n}if(typeof t=="object")return gr(t,e)}const nd={SCHEMES:Uj,normalize:Bj,resolve:Fj,resolveComponent:cv,equal:qj,serialize:gr,parse:to};Na.exports=nd;Na.exports.default=nd;Na.exports.fastUri=nd;var Wj=Na.exports;Object.defineProperty(Xl,"__esModule",{value:!0});const dv=Wj;dv.code='require("ajv/dist/runtime/uri").default';Xl.default=dv;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=Nt;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var n=ae;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=_s,o=uo,s=mr,i=st,a=ae,c=Le,u=Ae,l=K,d=rj,f=Xl,g=(A,S)=>new RegExp(A,S);g.code="new RegExp";const p=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),w={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."},h={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function b(A){var S,k,_,m,$,O,x,R,U,q,re,Qe,jn,An,In,Pn,xn,Rn,Tn,Cn,Mn,Ln,Dn,Un,Bn;const yt=A.strict,Fn=(S=A.code)===null||S===void 0?void 0:S.optimize,wo=Fn===!0||Fn===void 0?1:Fn||0,vo=(_=(k=A.code)===null||k===void 0?void 0:k.regExp)!==null&&_!==void 0?_:g,Ha=(m=A.uriResolver)!==null&&m!==void 0?m:f.default;return{strictSchema:(O=($=A.strictSchema)!==null&&$!==void 0?$:yt)!==null&&O!==void 0?O:!0,strictNumbers:(R=(x=A.strictNumbers)!==null&&x!==void 0?x:yt)!==null&&R!==void 0?R:!0,strictTypes:(q=(U=A.strictTypes)!==null&&U!==void 0?U:yt)!==null&&q!==void 0?q:"log",strictTuples:(Qe=(re=A.strictTuples)!==null&&re!==void 0?re:yt)!==null&&Qe!==void 0?Qe:"log",strictRequired:(An=(jn=A.strictRequired)!==null&&jn!==void 0?jn:yt)!==null&&An!==void 0?An:!1,code:A.code?{...A.code,optimize:wo,regExp:vo}:{optimize:wo,regExp:vo},loopRequired:(In=A.loopRequired)!==null&&In!==void 0?In:v,loopEnum:(Pn=A.loopEnum)!==null&&Pn!==void 0?Pn:v,meta:(xn=A.meta)!==null&&xn!==void 0?xn:!0,messages:(Rn=A.messages)!==null&&Rn!==void 0?Rn:!0,inlineRefs:(Tn=A.inlineRefs)!==null&&Tn!==void 0?Tn:!0,schemaId:(Cn=A.schemaId)!==null&&Cn!==void 0?Cn:"$id",addUsedSchema:(Mn=A.addUsedSchema)!==null&&Mn!==void 0?Mn:!0,validateSchema:(Ln=A.validateSchema)!==null&&Ln!==void 0?Ln:!0,validateFormats:(Dn=A.validateFormats)!==null&&Dn!==void 0?Dn:!0,unicodeRegExp:(Un=A.unicodeRegExp)!==null&&Un!==void 0?Un:!0,int32range:(Bn=A.int32range)!==null&&Bn!==void 0?Bn:!0,uriResolver:Ha}}class E{constructor(S={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,S=this.opts={...S,...b(S)};const{es5:k,lines:_}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:k,lines:_}),this.logger=Z(S.logger);const m=S.validateFormats;S.validateFormats=!1,this.RULES=(0,s.getRules)(),N.call(this,w,S,"NOT SUPPORTED"),N.call(this,h,S,"DEPRECATED","warn"),this._metaOpts=G.call(this),S.formats&&M.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&C.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),T.call(this),S.validateFormats=m}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:k,schemaId:_}=this.opts;let m=d;_==="id"&&(m={...d},m.id=m.$id,delete m.$id),k&&S&&this.addMetaSchema(m,m[_],!1)}defaultMeta(){const{meta:S,schemaId:k}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[k]||S:void 0}validate(S,k){let _;if(typeof S=="string"){if(_=this.getSchema(S),!_)throw new Error(`no schema with key or ref "${S}"`)}else _=this.compile(S);const m=_(k);return"$async"in _||(this.errors=_.errors),m}compile(S,k){const _=this._addSchema(S,k);return _.validate||this._compileSchemaEnv(_)}compileAsync(S,k){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:_}=this.opts;return m.call(this,S,k);async function m(q,re){await $.call(this,q.$schema);const Qe=this._addSchema(q,re);return Qe.validate||O.call(this,Qe)}async function $(q){q&&!this.getSchema(q)&&await m.call(this,{$ref:q},!0)}async function O(q){try{return this._compileSchemaEnv(q)}catch(re){if(!(re instanceof o.default))throw re;return x.call(this,re),await R.call(this,re.missingSchema),O.call(this,q)}}function x({missingSchema:q,missingRef:re}){if(this.refs[q])throw new Error(`AnySchema ${q} is loaded but ${re} cannot be resolved`)}async function R(q){const re=await U.call(this,q);this.refs[q]||await $.call(this,re.$schema),this.refs[q]||this.addSchema(re,q,k)}async function U(q){const re=this._loading[q];if(re)return re;try{return await(this._loading[q]=_(q))}finally{delete this._loading[q]}}}addSchema(S,k,_,m=this.opts.validateSchema){if(Array.isArray(S)){for(const O of S)this.addSchema(O,void 0,_,m);return this}let $;if(typeof S=="object"){const{schemaId:O}=this.opts;if($=S[O],$!==void 0&&typeof $!="string")throw new Error(`schema ${O} must be string`)}return k=(0,c.normalizeId)(k||$),this._checkUnique(k),this.schemas[k]=this._addSchema(S,_,k,m,!0),this}addMetaSchema(S,k,_=this.opts.validateSchema){return this.addSchema(S,k,!0,_),this}validateSchema(S,k){if(typeof S=="boolean")return!0;let _;if(_=S.$schema,_!==void 0&&typeof _!="string")throw new Error("$schema must be a string");if(_=_||this.opts.defaultMeta||this.defaultMeta(),!_)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const m=this.validate(_,S);if(!m&&k){const $="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error($);else throw new Error($)}return m}getSchema(S){let k;for(;typeof(k=j.call(this,S))=="string";)S=k;if(k===void 0){const{schemaId:_}=this.opts,m=new i.SchemaEnv({schema:{},schemaId:_});if(k=i.resolveSchema.call(this,m,S),!k)return;this.refs[S]=k}return k.validate||this._compileSchemaEnv(k)}removeSchema(S){if(S instanceof RegExp)return this._removeAllSchemas(this.schemas,S),this._removeAllSchemas(this.refs,S),this;switch(typeof S){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const k=j.call(this,S);return typeof k=="object"&&this._cache.delete(k.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const k=S;this._cache.delete(k);let _=S[this.opts.schemaId];return _&&(_=(0,c.normalizeId)(_),delete this.schemas[_],delete this.refs[_]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const k of S)this.addKeyword(k);return this}addKeyword(S,k){let _;if(typeof S=="string")_=S,typeof k=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),k.keyword=_);else if(typeof S=="object"&&k===void 0){if(k=S,_=k.keyword,Array.isArray(_)&&!_.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(fe.call(this,_,k),!k)return(0,l.eachItem)(_,$=>he.call(this,$)),this;Oe.call(this,k);const m={...k,type:(0,u.getJSONTypes)(k.type),schemaType:(0,u.getJSONTypes)(k.schemaType)};return(0,l.eachItem)(_,m.type.length===0?$=>he.call(this,$,m):$=>m.type.forEach(O=>he.call(this,$,m,O))),this}getKeyword(S){const k=this.RULES.all[S];return typeof k=="object"?k.definition:!!k}removeKeyword(S){const{RULES:k}=this;delete k.keywords[S],delete k.all[S];for(const _ of k.rules){const m=_.rules.findIndex($=>$.keyword===S);m>=0&&_.rules.splice(m,1)}return this}addFormat(S,k){return typeof k=="string"&&(k=new RegExp(k)),this.formats[S]=k,this}errorsText(S=this.errors,{separator:k=", ",dataVar:_="data"}={}){return!S||S.length===0?"No errors":S.map(m=>`${_}${m.instancePath} ${m.message}`).reduce((m,$)=>m+k+$)}$dataMetaSchema(S,k){const _=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const m of k){const $=m.split("/").slice(1);let O=S;for(const x of $)O=O[x];for(const x in _){const R=_[x];if(typeof R!="object")continue;const{$data:U}=R.definition,q=O[x];U&&q&&(O[x]=ut(q))}}return S}_removeAllSchemas(S,k){for(const _ in S){const m=S[_];(!k||k.test(_))&&(typeof m=="string"?delete S[_]:m&&!m.meta&&(this._cache.delete(m.schema),delete S[_]))}}_addSchema(S,k,_,m=this.opts.validateSchema,$=this.opts.addUsedSchema){let O;const{schemaId:x}=this.opts;if(typeof S=="object")O=S[x];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof S!="boolean")throw new Error("schema must be object or boolean")}let R=this._cache.get(S);if(R!==void 0)return R;_=(0,c.normalizeId)(O||_);const U=c.getSchemaRefs.call(this,S,_);return R=new i.SchemaEnv({schema:S,schemaId:x,meta:k,baseId:_,localRefs:U}),this._cache.set(R.schema,R),$&&!_.startsWith("#")&&(_&&this._checkUnique(_),this.refs[_]=R),m&&this.validateSchema(S,!0),R}_checkUnique(S){if(this.schemas[S]||this.refs[S])throw new Error(`schema with key or id "${S}" already exists`)}_compileSchemaEnv(S){if(S.meta?this._compileMetaSchema(S):i.compileSchema.call(this,S),!S.validate)throw new Error("ajv implementation error");return S.validate}_compileMetaSchema(S){const k=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,S)}finally{this.opts=k}}}E.ValidationError=r.default,E.MissingRefError=o.default,t.default=E;function N(A,S,k,_="error"){for(const m in A){const $=m;$ in S&&this.logger[_](`${k}: option ${m}. ${A[$]}`)}}function j(A){return A=(0,c.normalizeId)(A),this.schemas[A]||this.refs[A]}function T(){const A=this.opts.schemas;if(A)if(Array.isArray(A))this.addSchema(A);else for(const S in A)this.addSchema(A[S],S)}function M(){for(const A in this.opts.formats){const S=this.opts.formats[A];S&&this.addFormat(A,S)}}function C(A){if(Array.isArray(A)){this.addVocabulary(A);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in A){const k=A[S];k.keyword||(k.keyword=S),this.addKeyword(k)}}function G(){const A={...this.opts};for(const S of p)delete A[S];return A}const H={log(){},warn(){},error(){}};function Z(A){if(A===!1)return H;if(A===void 0)return console;if(A.log&&A.warn&&A.error)return A;throw new Error("logger must implement log, warn and error methods")}const ue=/^[a-z_$][a-z0-9_$:-]*$/i;function fe(A,S){const{RULES:k}=this;if((0,l.eachItem)(A,_=>{if(k.keywords[_])throw new Error(`Keyword ${_} is already defined`);if(!ue.test(_))throw new Error(`Keyword ${_} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function he(A,S,k){var _;const m=S==null?void 0:S.post;if(k&&m)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:$}=this;let O=m?$.post:$.rules.find(({type:R})=>R===k);if(O||(O={type:k,rules:[]},$.rules.push(O)),$.keywords[A]=!0,!S)return;const x={keyword:A,definition:{...S,type:(0,u.getJSONTypes)(S.type),schemaType:(0,u.getJSONTypes)(S.schemaType)}};S.before?pe.call(this,O,x,S.before):O.rules.push(x),$.all[A]=x,(_=S.implements)===null||_===void 0||_.forEach(R=>this.addKeyword(R))}function pe(A,S,k){const _=A.rules.findIndex(m=>m.keyword===k);_>=0?A.rules.splice(_,0,S):(A.rules.push(S),this.logger.warn(`rule ${k} is not defined`))}function Oe(A){let{metaSchema:S}=A;S!==void 0&&(A.$data&&this.opts.$data&&(S=ut(S)),A.validateSchema=this.compile(S,!0))}const gt={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ut(A){return{anyOf:[A,gt]}}})(ww);var rd={},od={},sd={};Object.defineProperty(sd,"__esModule",{value:!0});const Hj={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};sd.default=Hj;var yr={};Object.defineProperty(yr,"__esModule",{value:!0});yr.callRef=yr.getValidate=void 0;const Jj=uo,Oh=se,et=ae,jr=Bt,kh=st,qs=K,Qj={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();const l=kh.resolveRef.call(c,u,o,n);if(l===void 0)throw new Jj.default(r.opts.uriResolver,o,n);if(l instanceof kh.SchemaEnv)return f(l);return g(l);function d(){if(s===u)return vi(t,i,s,s.$async);const p=e.scopeValue("root",{ref:u});return vi(t,(0,et._)`${p}.validate`,u,u.$async)}function f(p){const y=fv(t,p);vi(t,y,p,p.$async)}function g(p){const y=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,et.stringify)(p)}:{ref:p}),w=e.name("valid"),h=t.subschema({schema:p,dataTypes:[],schemaPath:et.nil,topSchemaRef:y,errSchemaPath:n},w);t.mergeEvaluated(h),t.ok(w)}}};function fv(t,e){const{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,et._)`${n.scopeValue("wrapper",{ref:e})}.validate`}yr.getValidate=fv;function vi(t,e,n,r){const{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?jr.default.this:et.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const p=o.let("valid");o.try(()=>{o.code((0,et._)`await ${(0,Oh.callValidateCode)(t,e,u)}`),g(e),i||o.assign(p,!0)},y=>{o.if((0,et._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),f(y),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,Oh.callValidateCode)(t,e,u),()=>g(e),()=>f(e))}function f(p){const y=(0,et._)`${p}.errors`;o.assign(jr.default.vErrors,(0,et._)`${jr.default.vErrors} === null ? ${y} : ${jr.default.vErrors}.concat(${y})`),o.assign(jr.default.errors,(0,et._)`${jr.default.vErrors}.length`)}function g(p){var y;if(!s.opts.unevaluated)return;const w=(y=n==null?void 0:n.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(s.props=qs.mergeEvaluated.props(o,w.props,s.props));else{const h=o.var("props",(0,et._)`${p}.evaluated.props`);s.props=qs.mergeEvaluated.props(o,h,s.props,et.Name)}if(s.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(s.items=qs.mergeEvaluated.items(o,w.items,s.items));else{const h=o.var("items",(0,et._)`${p}.evaluated.items`);s.items=qs.mergeEvaluated.items(o,h,s.items,et.Name)}}}yr.callRef=vi;yr.default=Qj;Object.defineProperty(od,"__esModule",{value:!0});const Yj=sd,Zj=yr,Xj=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Yj.default,Zj.default];od.default=Xj;var id={},ad={};Object.defineProperty(ad,"__esModule",{value:!0});const Wi=ae,un=Wi.operators,Hi={maximum:{okStr:"<=",ok:un.LTE,fail:un.GT},minimum:{okStr:">=",ok:un.GTE,fail:un.LT},exclusiveMaximum:{okStr:"<",ok:un.LT,fail:un.GTE},exclusiveMinimum:{okStr:">",ok:un.GT,fail:un.LTE}},eA={message:({keyword:t,schemaCode:e})=>(0,Wi.str)`must be ${Hi[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Wi._)`{comparison: ${Hi[t].okStr}, limit: ${e}}`},tA={keyword:Object.keys(Hi),type:"number",schemaType:"number",$data:!0,error:eA,code(t){const{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Wi._)`${n} ${Hi[e].fail} ${r} || isNaN(${n})`)}};ad.default=tA;var cd={};Object.defineProperty(cd,"__esModule",{value:!0});const Fo=ae,nA={message:({schemaCode:t})=>(0,Fo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Fo._)`{multipleOf: ${t}}`},rA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:nA,code(t){const{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Fo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Fo._)`${i} !== parseInt(${i})`;t.fail$data((0,Fo._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};cd.default=rA;var ud={},ld={};Object.defineProperty(ld,"__esModule",{value:!0});function pv(t){const e=t.length;let n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}ld.default=pv;pv.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(ud,"__esModule",{value:!0});const Xn=ae,oA=K,sA=ld,iA={message({keyword:t,schemaCode:e}){const n=t==="maxLength"?"more":"fewer";return(0,Xn.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Xn._)`{limit: ${t}}`},aA={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:iA,code(t){const{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Xn.operators.GT:Xn.operators.LT,i=o.opts.unicode===!1?(0,Xn._)`${n}.length`:(0,Xn._)`${(0,oA.useFunc)(t.gen,sA.default)}(${n})`;t.fail$data((0,Xn._)`${i} ${s} ${r}`)}};ud.default=aA;var dd={};Object.defineProperty(dd,"__esModule",{value:!0});const cA=se,uA=K,Kr=ae,lA={message:({schemaCode:t})=>(0,Kr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Kr._)`{pattern: ${t}}`},dA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:lA,code(t){const{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Kr._)`new RegExp`:(0,uA.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Kr._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,Kr._)`!${l}`)}else{const c=(0,cA.usePattern)(t,o);t.fail$data((0,Kr._)`!${c}.test(${n})`)}}};dd.default=dA;var fd={};Object.defineProperty(fd,"__esModule",{value:!0});const qo=ae,fA={message({keyword:t,schemaCode:e}){const n=t==="maxProperties"?"more":"fewer";return(0,qo.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,qo._)`{limit: ${t}}`},pA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:fA,code(t){const{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?qo.operators.GT:qo.operators.LT;t.fail$data((0,qo._)`Object.keys(${n}).length ${o} ${r}`)}};fd.default=pA;var pd={};Object.defineProperty(pd,"__esModule",{value:!0});const bo=se,Ko=ae,hA=K,mA={message:({params:{missingProperty:t}})=>(0,Ko.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ko._)`{missingProperty: ${t}}`},gA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:mA,code(t){const{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const g=t.parentSchema.properties,{definedProperties:p}=t.it;for(const y of n)if((g==null?void 0:g[y])===void 0&&!p.has(y)){const w=i.schemaEnv.baseId+i.errSchemaPath,h=`required property "${y}" is not defined at "${w}" (strictRequired)`;(0,hA.checkStrictMode)(i,h,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Ko.nil,d);else for(const g of n)(0,bo.checkReportMissingProp)(t,g)}function l(){const g=e.let("missing");if(c||s){const p=e.let("valid",!0);t.block$data(p,()=>f(g,p)),t.ok(p)}else e.if((0,bo.checkMissingProp)(t,n,g)),(0,bo.reportMissingProp)(t,g),e.else()}function d(){e.forOf("prop",r,g=>{t.setParams({missingProperty:g}),e.if((0,bo.noPropertyInData)(e,o,g,a.ownProperties),()=>t.error())})}function f(g,p){t.setParams({missingProperty:g}),e.forOf(g,r,()=>{e.assign(p,(0,bo.propertyInData)(e,o,g,a.ownProperties)),e.if((0,Ko.not)(p),()=>{t.error(),e.break()})},Ko.nil)}}};pd.default=gA;var hd={};Object.defineProperty(hd,"__esModule",{value:!0});const Vo=ae,yA={message({keyword:t,schemaCode:e}){const n=t==="maxItems"?"more":"fewer";return(0,Vo.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Vo._)`{limit: ${t}}`},wA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:yA,code(t){const{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Vo.operators.GT:Vo.operators.LT;t.fail$data((0,Vo._)`${n}.length ${o} ${r}`)}};hd.default=wA;var md={},Ns={};Object.defineProperty(Ns,"__esModule",{value:!0});const hv=Tw;hv.code='require("ajv/dist/runtime/equal").default';Ns.default=hv;Object.defineProperty(md,"__esModule",{value:!0});const ic=Ae,Ce=ae,vA=K,$A=Ns,bA={message:({params:{i:t,j:e}})=>(0,Ce.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ce._)`{i: ${t}, j: ${e}}`},EA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:bA,code(t){const{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;const c=e.let("valid"),u=s.items?(0,ic.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ce._)`${i} === false`),t.ok(c);function l(){const p=e.let("i",(0,Ce._)`${n}.length`),y=e.let("j");t.setParams({i:p,j:y}),e.assign(c,!0),e.if((0,Ce._)`${p} > 1`,()=>(d()?f:g)(p,y))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,y){const w=e.name("item"),h=(0,ic.checkDataTypes)(u,w,a.opts.strictNumbers,ic.DataType.Wrong),v=e.const("indices",(0,Ce._)`{}`);e.for((0,Ce._)`;${p}--;`,()=>{e.let(w,(0,Ce._)`${n}[${p}]`),e.if(h,(0,Ce._)`continue`),u.length>1&&e.if((0,Ce._)`typeof ${w} == "string"`,(0,Ce._)`${w} += "_"`),e.if((0,Ce._)`typeof ${v}[${w}] == "number"`,()=>{e.assign(y,(0,Ce._)`${v}[${w}]`),t.error(),e.assign(c,!1).break()}).code((0,Ce._)`${v}[${w}] = ${p}`)})}function g(p,y){const w=(0,vA.useFunc)(e,$A.default),h=e.name("outer");e.label(h).for((0,Ce._)`;${p}--;`,()=>e.for((0,Ce._)`${y} = ${p}; ${y}--;`,()=>e.if((0,Ce._)`${w}(${n}[${p}], ${n}[${y}])`,()=>{t.error(),e.assign(c,!1).break(h)})))}}};md.default=EA;var gd={};Object.defineProperty(gd,"__esModule",{value:!0});const pu=ae,SA=K,_A=Ns,NA={message:"must be equal to constant",params:({schemaCode:t})=>(0,pu._)`{allowedValue: ${t}}`},OA={keyword:"const",$data:!0,error:NA,code(t){const{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,pu._)`!${(0,SA.useFunc)(e,_A.default)}(${n}, ${o})`):t.fail((0,pu._)`${s} !== ${n}`)}};gd.default=OA;var yd={};Object.defineProperty(yd,"__esModule",{value:!0});const Io=ae,kA=K,jA=Ns,AA={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Io._)`{allowedValues: ${t}}`},IA={keyword:"enum",schemaType:"array",$data:!0,error:AA,code(t){const{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");const a=o.length>=i.opts.loopEnum;let c;const u=()=>c??(c=(0,kA.useFunc)(e,jA.default));let l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const g=e.const("vSchema",s);l=(0,Io.or)(...o.map((p,y)=>f(g,y)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,g=>e.if((0,Io._)`${u()}(${n}, ${g})`,()=>e.assign(l,!0).break()))}function f(g,p){const y=o[p];return typeof y=="object"&&y!==null?(0,Io._)`${u()}(${n}, ${g}[${p}])`:(0,Io._)`${n} === ${y}`}}};yd.default=IA;Object.defineProperty(id,"__esModule",{value:!0});const PA=ad,xA=cd,RA=ud,TA=dd,CA=fd,MA=pd,LA=hd,DA=md,UA=gd,BA=yd,FA=[PA.default,xA.default,RA.default,TA.default,CA.default,MA.default,LA.default,DA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},UA.default,BA.default];id.default=FA;var wd={},lo={};Object.defineProperty(lo,"__esModule",{value:!0});lo.validateAdditionalItems=void 0;const er=ae,hu=K,qA={message:({params:{len:t}})=>(0,er.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,er._)`{limit: ${t}}`},KA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:qA,code(t){const{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,hu.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}mv(t,r)}};function mv(t,e){const{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;const a=n.const("len",(0,er._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,er._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,hu.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,er._)`${a} <= ${e.length}`);n.if((0,er.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:hu.Type.Num},u),i.allErrors||n.if((0,er.not)(u),()=>n.break())})}}lo.validateAdditionalItems=mv;lo.default=KA;var vd={},fo={};Object.defineProperty(fo,"__esModule",{value:!0});fo.validateTuple=void 0;const jh=ae,$i=K,VA=se,GA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:n}=t;if(Array.isArray(e))return gv(t,"additionalItems",e);n.items=!0,!(0,$i.alwaysValidSchema)(n,e)&&t.ok((0,VA.validateArray)(t))}};function gv(t,e,n=t.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=$i.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,jh._)`${s}.length`);n.forEach((d,f)=>{(0,$i.alwaysValidSchema)(a,d)||(r.if((0,jh._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){const{opts:f,errSchemaPath:g}=a,p=n.length,y=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!y){const w=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0,$i.checkStrictMode)(a,w,f.strictTuples)}}}fo.validateTuple=gv;fo.default=GA;Object.defineProperty(vd,"__esModule",{value:!0});const zA=fo,WA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,zA.validateTuple)(t,"items")};vd.default=WA;var $d={};Object.defineProperty($d,"__esModule",{value:!0});const Ah=ae,HA=K,JA=se,QA=lo,YA={message:({params:{len:t}})=>(0,Ah.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ah._)`{limit: ${t}}`},ZA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:YA,code(t){const{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,HA.alwaysValidSchema)(r,e)&&(o?(0,QA.validateAdditionalItems)(t,o):t.ok((0,JA.validateArray)(t)))}};$d.default=ZA;var bd={};Object.defineProperty(bd,"__esModule",{value:!0});const dt=ae,Ks=K,XA={message:({params:{min:t,max:e}})=>e===void 0?(0,dt.str)`must contain at least ${t} valid item(s)`:(0,dt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,dt._)`{minContains: ${t}}`:(0,dt._)`{minContains: ${t}, maxContains: ${e}}`},eI={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:XA,code(t){const{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=e.const("len",(0,dt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ks.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ks.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ks.alwaysValidSchema)(s,n)){let y=(0,dt._)`${l} >= ${i}`;a!==void 0&&(y=(0,dt._)`${y} && ${l} <= ${a}`),t.pass(y);return}s.items=!0;const d=e.name("valid");a===void 0&&i===1?g(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,dt._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){const y=e.name("_valid"),w=e.let("count",0);g(y,()=>e.if(y,()=>p(w)))}function g(y,w){e.forRange("i",0,l,h=>{t.subschema({keyword:"contains",dataProp:h,dataPropType:Ks.Type.Num,compositeRule:!0},y),w()})}function p(y){e.code((0,dt._)`${y}++`),a===void 0?e.if((0,dt._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,dt._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,dt._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};bd.default=eI;var yv={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=ae,n=K,r=se;t.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const d=u===1?"property":"properties";return(0,e.str)`must have ${d} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:d}})=>(0,e._)`{property: ${c},
190
- missingProperty: ${d},
191
- depsCount: ${u},
192
- deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const d in c){if(d==="__proto__")continue;const f=Array.isArray(c[d])?u:l;f[d]=c[d]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:d,it:f}=c;if(Object.keys(u).length===0)return;const g=l.let("missing");for(const p in u){const y=u[p];if(y.length===0)continue;const w=(0,r.propertyInData)(l,d,p,f.opts.ownProperties);c.setParams({property:p,depsCount:y.length,deps:y.join(", ")}),f.allErrors?l.if(w,()=>{for(const h of y)(0,r.checkReportMissingProp)(c,h)}):(l.if((0,e._)`${w} && (${(0,r.checkMissingProp)(c,y,g)})`),(0,r.reportMissingProp)(c,g),l.else())}}t.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:d,keyword:f,it:g}=c,p=l.name("valid");for(const y in u)(0,n.alwaysValidSchema)(g,u[y])||(l.if((0,r.propertyInData)(l,d,y,g.opts.ownProperties),()=>{const w=c.subschema({keyword:f,schemaProp:y},p);c.mergeValidEvaluated(w,p)},()=>l.var(p,!0)),c.ok(p))}t.validateSchemaDeps=a,t.default=o})(yv);var Ed={};Object.defineProperty(Ed,"__esModule",{value:!0});const wv=ae,tI=K,nI={message:"property name must be valid",params:({params:t})=>(0,wv._)`{propertyName: ${t.propertyName}}`},rI={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:nI,code(t){const{gen:e,schema:n,data:r,it:o}=t;if((0,tI.alwaysValidSchema)(o,n))return;const s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,wv.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Ed.default=rI;var Oa={};Object.defineProperty(Oa,"__esModule",{value:!0});const Vs=se,$t=ae,oI=Bt,Gs=K,sI={message:"must NOT have additional properties",params:({params:t})=>(0,$t._)`{additionalProperty: ${t.additionalProperty}}`},iI={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:sI,code(t){const{gen:e,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Gs.alwaysValidSchema)(i,n))return;const u=(0,Vs.allSchemaProperties)(r.properties),l=(0,Vs.allSchemaProperties)(r.patternProperties);d(),t.ok((0,$t._)`${s} === ${oI.default.errors}`);function d(){e.forIn("key",o,w=>{!u.length&&!l.length?p(w):e.if(f(w),()=>p(w))})}function f(w){let h;if(u.length>8){const v=(0,Gs.schemaRefOrVal)(i,r.properties,"properties");h=(0,Vs.isOwnProperty)(e,v,w)}else u.length?h=(0,$t.or)(...u.map(v=>(0,$t._)`${w} === ${v}`)):h=$t.nil;return l.length&&(h=(0,$t.or)(h,...l.map(v=>(0,$t._)`${(0,Vs.usePattern)(t,v)}.test(${w})`))),(0,$t.not)(h)}function g(w){e.code((0,$t._)`delete ${o}[${w}]`)}function p(w){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){g(w);return}if(n===!1){t.setParams({additionalProperty:w}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Gs.alwaysValidSchema)(i,n)){const h=e.name("valid");c.removeAdditional==="failing"?(y(w,h,!1),e.if((0,$t.not)(h),()=>{t.reset(),g(w)})):(y(w,h),a||e.if((0,$t.not)(h),()=>e.break()))}}function y(w,h,v){const b={keyword:"additionalProperties",dataProp:w,dataPropType:Gs.Type.Str};v===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,h)}}};Oa.default=iI;var Sd={};Object.defineProperty(Sd,"__esModule",{value:!0});const aI=Nt,Ih=se,ac=K,Ph=Oa,cI={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Ph.default.code(new aI.KeywordCxt(s,Ph.default,"additionalProperties"));const i=(0,Ih.allSchemaProperties)(n);for(const d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=ac.mergeEvaluated.props(e,(0,ac.toHash)(i),s.props));const a=i.filter(d=>!(0,ac.alwaysValidSchema)(s,n[d]));if(a.length===0)return;const c=e.name("valid");for(const d of a)u(d)?l(d):(e.if((0,Ih.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Sd.default=cI;var _d={};Object.defineProperty(_d,"__esModule",{value:!0});const xh=se,zs=ae,Rh=K,Th=K,uI={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,xh.allSchemaProperties)(n),c=a.filter(y=>(0,Rh.alwaysValidSchema)(s,n[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof zs.Name)&&(s.props=(0,Th.evaluatedPropsToName)(e,s.props));const{props:d}=s;f();function f(){for(const y of a)u&&g(y),s.allErrors?p(y):(e.var(l,!0),p(y),e.if(l))}function g(y){for(const w in u)new RegExp(y).test(w)&&(0,Rh.checkStrictMode)(s,`property ${w} matches pattern ${y} (use allowMatchingProperties)`)}function p(y){e.forIn("key",r,w=>{e.if((0,zs._)`${(0,xh.usePattern)(t,y)}.test(${w})`,()=>{const h=c.includes(y);h||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:w,dataPropType:Th.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,zs._)`${d}[${w}]`,!0):!h&&!s.allErrors&&e.if((0,zs.not)(l),()=>e.break())})})}}};_d.default=uI;var Nd={};Object.defineProperty(Nd,"__esModule",{value:!0});const lI=K,dI={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:n,it:r}=t;if((0,lI.alwaysValidSchema)(r,n)){t.fail();return}const o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Nd.default=dI;var Od={};Object.defineProperty(Od,"__esModule",{value:!0});const fI=se,pI={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:fI.validateUnion,error:{message:"must match a schema in anyOf"}};Od.default=pI;var kd={};Object.defineProperty(kd,"__esModule",{value:!0});const bi=ae,hI=K,mI={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,bi._)`{passingSchemas: ${t.passing}}`},gI={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:mI,code(t){const{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let f;(0,hI.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,bi._)`${c} && ${i}`).assign(i,!1).assign(a,(0,bi._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,bi.Name)})})}}};kd.default=gI;var jd={};Object.defineProperty(jd,"__esModule",{value:!0});const yI=K,wI={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=e.name("valid");n.forEach((s,i)=>{if((0,yI.alwaysValidSchema)(r,s))return;const a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};jd.default=wI;var Ad={};Object.defineProperty(Ad,"__esModule",{value:!0});const Ji=ae,vv=K,vI={message:({params:t})=>(0,Ji.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ji._)`{failingKeyword: ${t.ifClause}}`},$I={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:vI,code(t){const{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,vv.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=Ch(r,"then"),s=Ch(r,"else");if(!o&&!s)return;const i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){const l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Ji.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){const l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{const f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,Ji._)`${l}`):t.setParams({ifClause:l})}}}};function Ch(t,e){const n=t.schema[e];return n!==void 0&&!(0,vv.alwaysValidSchema)(t,n)}Ad.default=$I;var Id={};Object.defineProperty(Id,"__esModule",{value:!0});const bI=K,EI={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,bI.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Id.default=EI;Object.defineProperty(wd,"__esModule",{value:!0});const SI=lo,_I=vd,NI=fo,OI=$d,kI=bd,jI=yv,AI=Ed,II=Oa,PI=Sd,xI=_d,RI=Nd,TI=Od,CI=kd,MI=jd,LI=Ad,DI=Id;function UI(t=!1){const e=[RI.default,TI.default,CI.default,MI.default,LI.default,DI.default,AI.default,II.default,jI.default,PI.default,xI.default];return t?e.push(_I.default,OI.default):e.push(SI.default,NI.default),e.push(kI.default),e}wd.default=UI;var Pd={},xd={};Object.defineProperty(xd,"__esModule",{value:!0});const Se=ae,BI={message:({schemaCode:t})=>(0,Se.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Se._)`{format: ${t}}`},FI={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:BI,code(t,e){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?f():g();function f(){const p=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=n.const("fDef",(0,Se._)`${p}[${i}]`),w=n.let("fType"),h=n.let("format");n.if((0,Se._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>n.assign(w,(0,Se._)`${y}.type || "string"`).assign(h,(0,Se._)`${y}.validate`),()=>n.assign(w,(0,Se._)`"string"`).assign(h,y)),t.fail$data((0,Se.or)(v(),b()));function v(){return c.strictSchema===!1?Se.nil:(0,Se._)`${i} && !${h}`}function b(){const E=l.$async?(0,Se._)`(${y}.async ? await ${h}(${r}) : ${h}(${r}))`:(0,Se._)`${h}(${r})`,N=(0,Se._)`(typeof ${h} == "function" ? ${E} : ${h}.test(${r}))`;return(0,Se._)`${h} && ${h} !== true && ${w} === ${e} && !${N}`}}function g(){const p=d.formats[s];if(!p){v();return}if(p===!0)return;const[y,w,h]=b(p);y===e&&t.pass(E());function v(){if(c.strictSchema===!1){d.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(N){const j=N instanceof RegExp?(0,Se.regexpCode)(N):c.code.formats?(0,Se._)`${c.code.formats}${(0,Se.getProperty)(s)}`:void 0,T=n.scopeValue("formats",{key:s,ref:N,code:j});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,Se._)`${T}.validate`]:["string",N,T]}function E(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Se._)`await ${h}(${r})`}return typeof w=="function"?(0,Se._)`${h}(${r})`:(0,Se._)`${h}.test(${r})`}}}};xd.default=FI;Object.defineProperty(Pd,"__esModule",{value:!0});const qI=xd,KI=[qI.default];Pd.default=KI;var no={};Object.defineProperty(no,"__esModule",{value:!0});no.contentVocabulary=no.metadataVocabulary=void 0;no.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];no.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(rd,"__esModule",{value:!0});const VI=od,GI=id,zI=wd,WI=Pd,Mh=no,HI=[VI.default,GI.default,(0,zI.default)(),WI.default,Mh.metadataVocabulary,Mh.contentVocabulary];rd.default=HI;var Rd={},ka={};Object.defineProperty(ka,"__esModule",{value:!0});ka.DiscrError=void 0;var Lh;(function(t){t.Tag="tag",t.Mapping="mapping"})(Lh||(ka.DiscrError=Lh={}));Object.defineProperty(Rd,"__esModule",{value:!0});const Mr=ae,mu=ka,Dh=st,JI=uo,QI=K,YI={message:({params:{discrError:t,tagName:e}})=>t===mu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Mr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},ZI={keyword:"discriminator",type:"object",schemaType:"object",error:YI,code(t){const{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");const c=e.let("valid",!1),u=e.const("tag",(0,Mr._)`${n}${(0,Mr.getProperty)(a)}`);e.if((0,Mr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:mu.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){const g=f();e.if(!1);for(const p in g)e.elseIf((0,Mr._)`${u} === ${p}`),e.assign(c,d(g[p]));e.else(),t.error(!1,{discrError:mu.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(g){const p=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:g},p);return t.mergeEvaluated(y,Mr.Name),p}function f(){var g;const p={},y=h(o);let w=!0;for(let E=0;E<i.length;E++){let N=i[E];if(N!=null&&N.$ref&&!(0,QI.schemaHasRulesButRef)(N,s.self.RULES)){const T=N.$ref;if(N=Dh.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,T),N instanceof Dh.SchemaEnv&&(N=N.schema),N===void 0)throw new JI.default(s.opts.uriResolver,s.baseId,T)}const j=(g=N==null?void 0:N.properties)===null||g===void 0?void 0:g[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);w=w&&(y||h(N)),v(j,E)}if(!w)throw new Error(`discriminator: "${a}" must be required`);return p;function h({required:E}){return Array.isArray(E)&&E.includes(a)}function v(E,N){if(E.const)b(E.const,N);else if(E.enum)for(const j of E.enum)b(j,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(E,N){if(typeof E!="string"||E in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[E]=N}}}};Rd.default=ZI;const XI="http://json-schema.org/draft-07/schema#",eP="http://json-schema.org/draft-07/schema#",tP="Core schema meta-schema",nP={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:[]}},rP=["object","boolean"],oP={$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:"#"}},sP={$schema:XI,$id:eP,title:tP,definitions:nP,type:rP,properties:oP,default:!0};(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const n=ww,r=rd,o=Rd,s=sP,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(p=>this.addVocabulary(p)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const p=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(p,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var u=Nt;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=ae;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=_s;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=uo;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})(cu,cu.exports);var iP=cu.exports;const aP=_N(iP);let $v=class extends Error{constructor(e){super(e.length>0?`Config validation failed: ${e.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=e,this.name="ValidationError"}};function cP(t,e){if(!e)return;const n=e,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new aP({allErrors:!0,strict:!1}).compile(n);if(!o(t))throw new $v(uP(o.errors??[]))}function uP(t){return t.map(e=>({field:lP(e),message:e.message??"is invalid",keyword:e.keyword}))}function lP(t){var e;return(t.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((e=t.params)==null?void 0:e.missingProperty)??"(root)")}function dP(t,e){return L.join(Ey(t,e),LO)}const fP=384,pP=448;function hP(t,e,n={}){const r=n.mode??fP,o=n.dirMode??pP,s=L.dirname(t);J.mkdirSync(s,{recursive:!0,mode:o}),J.chmodSync(s,o);const i=`${t}.tmp`,a=typeof e=="string"?e:JSON.stringify(e,null,2);try{J.writeFileSync(i,a,{encoding:"utf8",mode:r}),J.chmodSync(i,r),J.renameSync(i,t),J.chmodSync(t,r)}catch(c){try{J.existsSync(i)&&J.unlinkSync(i)}catch{}throw c}}const mP="0.1.0";function Uh(t,e){if(!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new Error(`${e} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(t)}`)}function gP(){return`${process.pid}-${kn.randomBytes(3).toString("hex")}`}function bv(t,e,n={}){if(!t)throw new Error("Environment requires a non-empty 'project' name");Uh(t,"project");const r=e.orgNamespace??CO,o=e.envPrefixOverride??qO(t),s=e.namespaces&&e.namespaces.length>0?e.namespaces:[MO],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${t}" (declared: ${s.join(", ")})`);Uh(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=bN({scope:n.scope,cwd:n.cwd},a),l=SN({project:t,namespace:i,orgNamespace:r,projectRoot:u,adhdRoot:n.adhdRoot});return{project:t,namespace:i,orgNamespace:r,envPrefix:o,scope:c,projectRoot:u,roots:l}}function yP(t,e,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=bv(t,e,n),u=n.processEnv??process.env,l=ZO(c),d=n.instanceId??gP(),{raw:f,nested:g,typedRaw:p,provenance:y,fields:w}=tk(e.config,l,u,{prefix:s,activeScope:i}),h={};for(const N of Object.keys(w)){const j=w[N];j.live&&(h[N]={env:j.env,type:j.type,fallback:j.secret===!0?void 0:j.fallbackValue})}const v=VO(e.config);cP(yw(p),v);const b=rk(e.dirs,{roots:c,activeScope:i,instanceId:d,projectRoot:a,namespace:r}),E=ok(e.files,b);return{version:TO,libraryVersion:mP,generatedAt:new Date().toISOString(),project:t,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:d,config:g,raw:f,liveFields:h,fieldSchema:v,configHash:BO(Object.fromEntries(Object.entries(p).map(([N,j])=>[N,String(j)]))),structureHash:FO(Object.values(b).map(N=>({name:N.name,kind:N.kind,scope:N.scope}))),dirs:Object.values(b),files:Object.values(E),provenance:y}}let us=class extends Error{constructor(e){super(e),this.name="EnvironmentError"}},wP=class extends us{constructor(e){super(`adhd-environment snapshot not found: ${e}`),this.snapshotPath=e,this.name="SnapshotNotFoundError"}},vP=class extends us{constructor(e,n){super(`lock "${e}" is already held (${n})`),this.lockName=e,this.lockPath=n,this.name="LockHeldError"}};function $P(t,e){let n=t;for(const r of e.split("."))if(n!==null&&typeof n=="object"&&r in n)n=n[r];else return;return n}function gu(t){if(t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>gu(n));const e={};for(const[n,r]of Object.entries(t))e[n]=gu(r);return e}function bP(t,e){const n=gu(t);for(const r of Object.keys(e)){const o=e[r],s=r.split(".");let i=n;for(let c=0;c<s.length-1;c++){const u=s[c],l=i[u];(typeof l!="object"||l===null||Array.isArray(l))&&(i[u]={}),i=i[u]}const a=s[s.length-1];Object.defineProperty(i,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?au(c,o.type):o.fallback}})}return n}function EP(t){if(!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("\0"))throw new us(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(t)}`)}let Ev=class Sv{constructor(e,n,r={}){let o,s;try{o=yP(e,n,r);const i=bv(e,n,r);s=dP(i.roots,o.scope)}catch(i){throw i instanceof $v||i instanceof us?i:new us(i instanceof Error?i.message:String(i))}return Bh(this,o,s)}static fromSnapshot(e){if(!J.existsSync(e))throw new wP(e);const n=JSON.parse(J.readFileSync(e,"utf8")),r=Object.create(Sv.prototype);return Bh(r,n,e)}get(e){const n=e.indexOf(".");if(n===-1)return;const r=e.slice(0,n),o=e.slice(n+1);switch(r){case"config":return $P(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(e){return e.startsWith(this.prefix)}resolveEnvName(e){if(this.isEnvNameAllowed(e))return process.env[e]}lock(e="singleton"){EP(e);const n=this.paths.run??this._runDirFallback();J.mkdirSync(n,{recursive:!0});const r=L.join(n,`${e}.lock`);let o;try{o=J.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new vP(e,r):i}J.writeSync(o,`${process.pid}
36
+ LIMIT 1`,[o.uid,t.locType,t.value]);if(i)return{uid:i.uid,created:!1,location:{uid:i.uid,locType:t.locType,value:t.value,componentUid:o.uid}};const s={componentUid:o.uid,locType:t.locType,value:t.value},a=await J(n,{kind:"location",name:t.value,metadata:s,at:r}),c=await F(n,"has_location");return await M(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"component",dstRowid:a.rowid,dstUid:a.uid,dstKind:"location",rel:"has_location",rule:c,typePolicy:e.typePolicy}),await U({tx:n,typePolicy:e.typePolicy,subjectRowid:a.rowid,subjectUid:a.uid,subjectKind:"location",actor:t.by,action:"created",at:r}),{uid:a.uid,created:!0,location:{uid:a.uid,locType:t.locType,value:t.value,componentUid:o.uid}}})}async function Kl(e,t){return oe("uid",t.uid),oe("by",t.by),Q("by",t.by),z(e,async n=>{var c;const r=V(),o=await nt(n,"location",t.uid),i={...o.metadata??{},...t.reason!==void 0?{invalidatedReason:t.reason}:{},invalidatedAt:r},s=await n.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ? AND t_invalid IS NULL",[r,JSON.stringify(i),o.rowid]);if(s.rowsAffected!==1)throw new Error(`rmLocation: invalidate UPDATE affected ${s.rowsAffected} rows for uid="${t.uid}", expected exactly 1.`);const a=typeof((c=o.metadata)==null?void 0:c.componentUid)=="string"?o.metadata.componentUid:void 0;if(a!==void 0){const d=await Bt(n,a);(d==null?void 0:d.tInvalid)===null&&await _e(n,{srcRowid:d.rowid,dstRowid:o.rowid,rel:"has_location",reason:t.reason,at:r})}return await U({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"location",actor:t.by,action:"deleted",note:t.reason,at:r}),{uid:o.uid,invalidated:!0}})}async function U(e){const t=e.at??V(),n={actor:e.actor,action:e.action,target_uid:e.subjectUid,from:e.from??null,to:e.to??null,note:e.note??null,at:t},r=so(Wi(n)),o={...n,sha:r},i=await J(e.tx,{at:t,kind:"audit",name:e.action,content:e.note??e.action,metadata:o}),s=await F(e.tx,"audits");return await M(e.tx,{at:t,srcRowid:e.subjectRowid,srcUid:e.subjectUid,srcKind:e.subjectKind,dstRowid:i.rowid,dstUid:i.uid,dstKind:"audit",rel:"audits",rule:s,typePolicy:e.typePolicy}),{rowid:i.rowid,uid:i.uid,sha:r}}const Hl="embed did not settle before store close — recorded by the close-time drain (RAG-SPEC.md §2.2)";function lo(e,t){return`${e}
37
+ ${t}`.trim()}function Ot(e,t){const n=e.embedding;if(!n)return Promise.resolve();const r=Vl(e,n,t),o={subjectRowid:t.subjectRowid,subjectUid:t.subjectUid,actor:t.actor,action:t.action,settled:r,outcome:"pending"},i=Ui(e.adapter).register(o);return r.then(s=>{o.outcome=s,s!=="unrecorded"&&i()},()=>{o.outcome="unrecorded"}),r.then(()=>{})}async function Vl(e,t,n){let r,o;try{if(n.action==="upsert"){const i=await t.embedDocument(n.content);await t.upsertVector(n.subjectRowid,i),r="embedding_upserted"}else await t.deleteVector(n.subjectRowid),r="embedding_deleted"}catch(i){r="embedding_failed",o=i instanceof Error?i.message:String(i),console.error(`scheduleIssueEmbedding: embed round-trip failed for issue uid="${n.subjectUid}" (action="${n.action}") — degrading to an "embedding_failed" audit row.`,i)}try{await z(e,async i=>{await U({tx:i,typePolicy:e.typePolicy,subjectRowid:n.subjectRowid,subjectUid:n.subjectUid,subjectKind:"issue",actor:n.actor,action:r,note:o})})}catch(i){return console.error(`scheduleIssueEmbedding: failed to persist "${r}" audit row for issue uid="${n.subjectUid}" — the embedding outcome itself is unrecorded.`,i),"unrecorded"}switch(r){case"embedding_upserted":return"upserted";case"embedding_deleted":return"deleted";case"embedding_failed":return"failed"}}async function Gl(e,t){const n=[],r=[];for(const o of t)try{await z(e,async i=>{await U({tx:i,typePolicy:e.typePolicy,subjectRowid:o.subjectRowid,subjectUid:o.subjectUid,subjectKind:"issue",actor:o.actor,action:"embedding_failed",note:Hl})}),o.outcome="failed",n.push(o)}catch(i){o.outcome="unrecorded",r.push(o),console.error(`recordUnsettledEmbedsAsFailed: could not persist the "embedding_failed" audit row for issue uid="${o.subjectUid}" — this embed outcome is UNRECORDED.`,i)}return{recorded:n,unrecorded:r}}async function Rt(e,t=5e3){if(e!==":memory:"&&O.mkdirSync(k.dirname(e),{recursive:!0}),!Number.isInteger(t)||t<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${t}`);const n=await pe.createStoreAdapter({dbPath:e});await n.pragmaSet("busy_timeout",t);const r=Aa.createGraphBackend(n,{typePolicy:ur});await wl(()=>r.applySchema());try{await oo(n)}catch(i){throw await n.close().catch(()=>{}),i}return{adapter:n,graph:r,typePolicy:ur,flushEmbeds:i=>Ui(n).drain(i)}}async function Xi(e,t){const n=await e.flushEmbeds(t);let r=0,o=[...n.unrecorded];try{if(n.stillPending.length>0){const i=await Gl(e,n.stillPending);r=i.recorded.length,o=[...o,...i.unrecorded]}}finally{await e.adapter.close()}return{drained:n.drained,stillPending:n.stillPending,recordedAsFailed:r,unrecorded:o}}async function In(e){if(!e)return;let t;try{t=await Xi(e)}catch(n){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${n instanceof Error?n.message:String(n)}`);return}t.unrecorded.length>0?(console.error(`backlog: ${t.unrecorded.length} scheduled embed(s) died UNRECORDED — the store closed before they settled and the embedding_failed audit row could not be written. The subject write(s) are durable; the vector(s) are missing. Re-run the embedding backfill.`),process.exitCode||(process.exitCode=1)):t.stillPending.length>0&&console.error(`backlog: ${t.stillPending.length} scheduled embed(s) did not settle before close — recorded as embedding_failed. The subject write(s) are durable.`)}const Tn=["SIGINT","SIGTERM"];function Qi(e,t=n=>process.exit(n)){let n=!1;const r=i=>{n||(n=!0,e().catch(s=>{console.error(`backlog: signal cleanup failed (${i}): ${s instanceof Error?s.message:String(s)}`)}).finally(()=>{o(),t(128+W.constants.signals[i])}))},o=()=>{for(const i of Tn)process.removeListener(i,r)};for(const i of Tn)process.on(i,r);return{dispose:o}}function Jl(){return Tn.some(e=>process.listenerCount(e)>0)}const Wl=[".git",".adhd","adhd.environment.yaml"];function nn(e){let t=k.resolve(e);const{root:n}=k.parse(t);for(;;){for(const o of Wl)if(O.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=k.dirname(t);if(r===t)return;t=r}}const zl=new Set(["system","global","project"]);function Yl(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:nn(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&zl.has(r)){const i=r;return i==="project"?{scope:"project",projectRoot:nn(n)??n}:{scope:i}}const o=nn(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function hr(e){return`.${e}`}function Xl(e){const t=W.homedir();if(process.platform==="darwin")return k.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??k.join(t,"AppData","Roaming");return k.join(r,e)}const n=process.env.XDG_DATA_HOME??k.join(t,".local","share");return k.join(n,e)}function Ql(e){const t=e.orgNamespace,n=e.adhdRoot??k.join(W.homedir(),hr(t)),r=e.adhdRoot??Xl(t),o={system:k.join(r,e.project,e.namespace),global:k.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=k.join(e.projectRoot,hr(t),e.project,e.namespace)),o}function Zi(e,t){return t==="project"?e.project??e.global:e[t]}const Zl="1.0.0-redesign.1",eu="adhd",tu="default",nu="adhd-environment.json",Te="config.yaml",es="config.local.yaml",ou={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class yr extends Error{constructor(t,n){super(`contentHash: lone surrogate in ${t} (not well-formed Unicode)`),this.location=t,this.offending=n,this.name="LoneSurrogateError"}}function wr(e){for(let t=0;t<e.length;t++){const n=e.charCodeAt(t);if(n>=55296&&n<=56319){const r=t+1<e.length?e.charCodeAt(t+1):0;if(r<56320||r>57343)return!0;t++}else if(n>=56320&&n<=57343)return!0}return!1}function ts(e,t){const n=Array.from(e),r=Array.from(t),o=Math.min(n.length,r.length);for(let i=0;i<o;i++){const s=n[i].codePointAt(0)??0,a=r[i].codePointAt(0)??0;if(s!==a)return s<a?-1:1}return n.length===r.length?0:n.length<r.length?-1:1}function vr(e){return new TextEncoder().encode(e).length}function ru(e){const t=Object.keys(e).sort(ts);let n="";for(const o of t){const i=e[o];if(wr(o))throw new yr("key",o);if(wr(i))throw new yr("value",i);n+=`${vr(o)}:${o}=${vr(i)}:${i}
38
+ `}return`sha256-${ns(n)}`}function iu(e){const n=[...e].sort((r,o)=>ts(r.name,o.name)).map(r=>`${r.name}:${r.kind}:${r.scope}`).join(`
39
+ `);return`sha256-${ns(n)}`}function su(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function au(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function cu(e){const t={type:"object",properties:{}},n=e;for(const r of Object.keys(n)){const o=n[r],i=r.split(".");let s=t;i.forEach((a,c)=>{if(c===i.length-1){s.properties[a]=du(o);return}const l=s.properties[a];if(l===void 0){const u={type:"object",properties:{}};s.properties[a]=u,s=u}else s=l})}return t}function du(e){const t={type:e.type};return e.default!==void 0&&e.secret!==!0&&(t.default=e.default),e.description!==void 0&&(t.description=e.description),e.minimum!==void 0&&(t.minimum=e.minimum),e.maximum!==void 0&&(t.maximum=e.maximum),e.enum!==void 0&&(t.enum=e.enum),e.pattern!==void 0&&(t.pattern=e.pattern),e.minLength!==void 0&&(t.minLength=e.minLength),e.maxLength!==void 0&&(t.maxLength=e.maxLength),e.items!==void 0&&(t.items=e.items),t}const lu="adhd-env-ref:";function uu(e){return`${lu}${e}`}const fu=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],pu=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function te(e,t){return(e>>>t|e<<32-t)>>>0}function mu(e){const t=Uint32Array.from(pu),n=e.length*8;let r=e.length+1;for(;r%64!==56;)r++;r+=8;const o=new Uint8Array(r);o.set(e),o[e.length]=128;const i=Math.floor(n/4294967296),s=n>>>0,a=new DataView(o.buffer);a.setUint32(r-8,i,!1),a.setUint32(r-4,s,!1);const c=new Uint32Array(64);for(let u=0;u<r;u+=64){for(let b=0;b<16;b++)c[b]=a.getUint32(u+b*4,!1);for(let b=16;b<64;b++){const S=c[b-15],E=c[b-2],A=te(S,7)^te(S,18)^S>>>3,j=te(E,17)^te(E,19)^E>>>10;c[b]=c[b-16]+A+c[b-7]+j>>>0}let f=t[0],g=t[1],p=t[2],m=t[3],v=t[4],h=t[5],y=t[6],w=t[7];for(let b=0;b<64;b++){const S=te(v,6)^te(v,11)^te(v,25),E=v&h^~v&y,A=w+S+E+fu[b]+c[b]>>>0,j=te(f,2)^te(f,13)^te(f,22),N=f&g^f&p^g&p,_=j+N>>>0;w=y,y=h,h=v,v=m+A>>>0,m=p,p=g,g=f,f=A+_>>>0}t[0]=t[0]+f>>>0,t[1]=t[1]+g>>>0,t[2]=t[2]+p>>>0,t[3]=t[3]+m>>>0,t[4]=t[4]+v>>>0,t[5]=t[5]+h>>>0,t[6]=t[6]+y>>>0,t[7]=t[7]+w>>>0}const d=new Uint8Array(32),l=new DataView(d.buffer);for(let u=0;u<8;u++)l.setUint32(u*4,t[u],!1);return d}function gu(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function ns(e){const t=new TextEncoder().encode(e);return gu(mu(t))}const{parse:hu}=Ta;function os(e,t=""){const n={};if(e===null||typeof e!="object"||Array.isArray(e))return t&&(n[t]=e),n;for(const[r,o]of Object.entries(e)){const i=t?`${t}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,os(o,i)):n[i]=o}return n}function gt(e){if(O.existsSync(e))try{const t=O.readFileSync(e,"utf8"),n=hu(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:os(n)}catch{return}}function yu(e){return{system:gt(k.join(e.system,Te)),global:gt(k.join(e.global,Te)),project:e.project?gt(k.join(e.project,Te)):void 0,local:e.project?gt(k.join(e.project,es)):void 0}}function br(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function $n(e,t){if(e===void 0)return e;switch(t){case"integer":{if(typeof e=="number")return e;const n=parseInt(String(e),10);return Number.isNaN(n)?e:n}case"number":{if(typeof e=="number")return e;const n=parseFloat(String(e));return Number.isNaN(n)?e:n}case"boolean":{if(typeof e=="boolean")return e;const n=String(e).toLowerCase();return n==="true"?!0:n==="false"?!1:e}case"array":return Array.isArray(e)?e:typeof e=="string"?e.length===0?[]:e.split(",").map(n=>n.trim()):e;case"string":return typeof e=="string"?e:String(e);default:return e}}function rs(e){const t={};for(const n of Object.keys(e)){const r=n.split(".");let o=t;r.forEach((i,s)=>{if(s===r.length-1){o[i]=e[n];return}const a=o[i];(typeof a!="object"||a===null||Array.isArray(a))&&(o[i]={}),o=o[i]})}return t}const wu=[["system","system"],["global","global"],["project","project"],["local","local"]];function vu(e,t,n,r){const o={},i={},s={},a={};for(const c of Object.keys(e)){const d=e[c],l=d.env&&d.env!==""?d.env:au(r.prefix,c),u=d.at==="runtime"||d.secret===!0,f=d.scope??r.activeScope;let g=d.default,p="default";for(const[w,b]of wu){const S=t[w];S&&Object.prototype.hasOwnProperty.call(S,c)&&(g=$n(S[c],d.type),p=b)}const m=n[l];let v,h,y;m!==void 0?(v=$n(m,d.type),h="env",y=l):(v=g,h=p),o[c]=u?uu(l):v,i[c]=v,s[c]=br(u?{source:"env",scope:f,env:l}:{source:h,scope:f,env:y}),a[c]={...d,env:l,live:u,fallbackValue:g}}return{raw:o,nested:rs(o),typedRaw:i,provenance:s,fields:a}}function bu(e,t){return e.replace(/\$\{HOME\}/g,W.homedir()).replace(/\$HOME\b/g,W.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function Su(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const i=o.scope??t.activeScope,s=o.share??ou[o.kind],a=o.path?bu(o.path,t):k.join(Zi(t.roots,i),r),c=s==="per-instance"?k.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:i,share:s}}return n}function Eu(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const i=t[o.in];if(!i)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:k.join(i.path,o.name),share:o.share??"shared"}}return n}class is extends Error{constructor(t){super(t.length>0?`Config validation failed: ${t.map(n=>`${n.field} ${n.message}`).join("; ")}`:"Config validation failed"),this.fieldErrors=t,this.name="ValidationError"}}function ku(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const i=new Zr({allErrors:!0,strict:!1}).compile(n);if(!i(e))throw new is(Au(i.errors??[]))}function Au(e){return e.map(t=>({field:ju(t),message:t.message??"is invalid",keyword:t.keyword}))}function ju(e){var r;const t=(e.instancePath??"").replace(/^\//,"").replace(/\//g,".");return t||(((r=e.params)==null?void 0:r.missingProperty)??"(root)")}function _u(e,t){return k.join(Zi(e,t),nu)}const Nu=384,Ou=448;function Ru(e,t,n={}){const r=n.mode??Nu,o=n.dirMode??Ou,i=k.dirname(e);O.mkdirSync(i,{recursive:!0,mode:o}),O.chmodSync(i,o);const s=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{O.writeFileSync(s,a,{encoding:"utf8",mode:r}),O.chmodSync(s,r),O.renameSync(s,e),O.chmodSync(e,r)}catch(c){try{O.existsSync(s)&&O.unlinkSync(s)}catch{}throw c}}const Iu="0.1.0";function Sr(e,t){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Error(`${t} must be a non-empty path segment with no '.', '..', path separators, or NUL: ${JSON.stringify(e)}`)}function Tu(){return`${process.pid}-${ue.randomBytes(3).toString("hex")}`}function uo(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");Sr(e,"project");const r=t.orgNamespace??eu,o=t.envPrefixOverride??su(e),i=t.namespaces&&t.namespaces.length>0?t.namespaces:[tu],s=n.namespace??i[0];if(!i.includes(s))throw new Error(`Namespace "${s}" is not declared for project "${e}" (declared: ${i.join(", ")})`);Sr(s,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:d}=Yl({scope:n.scope,cwd:n.cwd},a),l=Ql({project:e,namespace:s,orgNamespace:r,projectRoot:d,adhdRoot:n.adhdRoot});return{project:e,namespace:s,orgNamespace:r,envPrefix:o,scope:c,projectRoot:d,roots:l}}function $u(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:i,scope:s,projectRoot:a,roots:c}=uo(e,t,n),d=n.processEnv??process.env,l=yu(c),u=n.instanceId??Tu(),{raw:f,nested:g,typedRaw:p,provenance:m,fields:v}=vu(t.config,l,d,{prefix:i,activeScope:s}),h={};for(const E of Object.keys(v)){const A=v[E];A.live&&(h[E]={env:A.env,type:A.type,fallback:A.secret===!0?void 0:A.fallbackValue})}const y=cu(t.config);ku(rs(p),y);const w=Su(t.dirs,{roots:c,activeScope:s,instanceId:u,projectRoot:a,namespace:r}),b=Eu(t.files,w);return{version:Zl,libraryVersion:Iu,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:i,scope:s,instanceId:u,config:g,raw:f,liveFields:h,fieldSchema:y,configHash:ru(Object.fromEntries(Object.entries(p).map(([E,A])=>[E,String(A)]))),structureHash:iu(Object.values(w).map(E=>({name:E.name,kind:E.kind,scope:E.scope}))),dirs:Object.values(w),files:Object.values(b),provenance:m}}class Xe extends Error{constructor(t){super(t),this.name="EnvironmentError"}}class Cu extends Xe{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class Pu extends Xe{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function xu(e,t){let n=e;for(const r of t.split("."))if(n!==null&&typeof n=="object"&&r in n)n=n[r];else return;return n}function Cn(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>Cn(n));const t={};for(const[n,r]of Object.entries(e))t[n]=Cn(r);return t}function Lu(e,t){const n=Cn(e);for(const r of Object.keys(t)){const o=t[r],i=r.split(".");let s=n;for(let c=0;c<i.length-1;c++){const d=i[c],l=s[d];(typeof l!="object"||l===null||Array.isArray(l))&&(s[d]={}),s=s[d]}const a=i[i.length-1];Object.defineProperty(s,a,{enumerable:!0,configurable:!0,get(){const c=process.env[o.env];return c!==void 0?$n(c,o.type):o.fallback}})}return n}function Uu(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new Xe(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class Kt{constructor(t,n,r={}){let o,i;try{o=$u(t,n,r);const s=uo(t,n,r);i=_u(s.roots,o.scope)}catch(s){throw s instanceof is||s instanceof Xe?s:new Xe(s instanceof Error?s.message:String(s))}return Er(this,o,i)}static fromSnapshot(t){if(!O.existsSync(t))throw new Cu(t);const n=JSON.parse(O.readFileSync(t,"utf8")),r=Object.create(Kt.prototype);return Er(r,n,t)}get(t){const n=t.indexOf(".");if(n===-1)return;const r=t.slice(0,n),o=t.slice(n+1);switch(r){case"config":return xu(this.config,o);case"path":return this.paths[o];case"env":return this.resolveEnvName(o);case"provenance":return this._data.provenance[o];default:return}}isEnvNameAllowed(t){return t.startsWith(this.prefix)}resolveEnvName(t){if(this.isEnvNameAllowed(t))return process.env[t]}lock(t="singleton"){Uu(t);const n=this.paths.run??this._runDirFallback();O.mkdirSync(n,{recursive:!0});const r=k.join(n,`${t}.lock`);let o;try{o=O.openSync(r,"wx")}catch(s){throw(s==null?void 0:s.code)==="EEXIST"?new Pu(t,r):s}O.writeSync(o,`${process.pid}
193
40
  ${this.instanceId}
194
- `),J.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{J.unlinkSync(r)}catch{}}}}_runDirFallback(){return L.join(L.dirname(this.snapshotPath),"run")}ensureDirs(){for(const e of Object.values(this.paths))J.mkdirSync(e,{recursive:!0})}write(){return hP(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}};function Bh(t,e,n){const r={};for(const i of e.dirs)r[i.name]=i.path;const o={};for(const i of e.files)o[i.name]=i.path;const s=bP(e.config,e.liveFields??{});return Object.defineProperties(t,{project:{value:e.project,enumerable:!0},namespace:{value:e.namespace,enumerable:!0},orgNamespace:{value:e.orgNamespace,enumerable:!0},scope:{value:e.scope,enumerable:!0},prefix:{value:e.envPrefix,enumerable:!0},instanceId:{value:e.instanceId,enumerable:!0},hash:{value:e.configHash,enumerable:!0},version:{value:{configHash:e.configHash,structureHash:e.structureHash,generatedAt:e.generatedAt,libraryVersion:e.libraryVersion},enumerable:!0},provenance:{value:e.provenance,enumerable:!0},dirs:{value:e.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:s,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:e,enumerable:!1}}),new Proxy(t,{get(i,a,c){return typeof a=="string"&&!(a in i)?i.get(a):Reflect.get(i,a,c)}})}const ls={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production","test","sandbox"],dirs:{data:{kind:"data"},cache:{kind:"cache"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"Backlog graph DB path. Unset ⇒ falls back to env.files.db under the resolved scope root."},"db.busyTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_DATABASE_BUSY_TIMEOUT_MS",default:5e3,description:"The store adapter's `busy_timeout` (ms) each write waits for a contended lock before retrying (DEBT-BACKLOG-CONCURRENCY-BUSY-RETRY-001). Raise this when scaling toward more concurrent agents writing the same global-scope store."},"logging.level":{type:"string",env:"ADHD_BACKLOG_LOG_LEVEL",default:"info",enum:["trace","debug","info","warn","error","fatal","silent"]},"embedding.enabled":{type:"boolean",env:"ADHD_BACKLOG_EMBEDDING_ENABLED",default:!1,description:'RAG-SPEC.md §1.6 — opt IN to the semantic/RAG stack. Default FALSE: semantic inputs (filter.semantic, filter.anchor, view:"similar", sort:"relevance", fields:["_vector"]) answer RagNotConfiguredError (§5a) until this is set. Requires the optionalDependencies @adhd/sox-embedding-provider + @adhd/sox-vector-store to be installed, and a store whose adapter reports capabilities.nativeVectors (turso). Enabling it with any of those missing logs a typed reason and leaves RAG unconfigured — it never crashes startup.'},"embedding.provider":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_PROVIDER",default:"fastembed",description:"Embedding provider type, forwarded verbatim to @adhd/sox-embedding-provider's createEmbeddingProvider ('fastembed' | 'remote')."},"embedding.model":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_MODEL",default:"bge-base-en-v1.5",description:"Embedding model id (768-dim bge-base-en-v1.5 by default). RAG-SPEC.md §2.5: the dimensional contract is STRUCTURAL — changing this after items are embedded orphans existing vectors under the old model id rather than silently truncating; re-embed via admin(embedding_backfill)."}}};function _v(t){if(t)return t;const e=process.env.ADHD_BACKLOG_SCOPE;if(e)return e;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function Go(t={}){const e={namespace:t.namespace??"production",scope:_v(t.scope)};return t.adhdRoot!==void 0&&(e.adhdRoot=t.adhdRoot),t.cwd!==void 0&&(e.cwd=t.cwd),t.instanceId!==void 0&&(e.instanceId=t.instanceId),new Ev("backlog",ls,e)}function zo(t){return t.config.db.path??t.files.db}function SP(t,e){return`${t}:${e}`}function _P(t={}){const e=process.env.APIGEN_IR_CACHE_FILE;if(e)return e;const n={namespace:"production",scope:"global"};t.adhdRoot!==void 0&&(n.adhdRoot=t.adhdRoot),t.instanceId!==void 0&&(n.instanceId=t.instanceId);const r=new Ev("backlog",ls,n);return L.join(r.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}const zt=Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);let cc;function NP(){return cc||(cc=zt("ts-morph").Project,cc)}const Nv=Symbol.for("adhd.apigen.extraction-session");function Ov(t,e){const n=[...t.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...t.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!e.has(o)){e.add(o);try{r.refreshFromFileSystemSync()}catch{}Ov(r,e)}}}function kv(t){try{const e=J.statSync(t);return`${e.mtimeMs}:${e.size}`}catch{return"nostat"}}const Ei=new Map,Fh=new Map;function OP(t,e,n){const r=e??"",o=Ei.get(r);let s=n;if(o&&o.fileVersions.size>0){const c=[n],u=[...o.fileVersions.entries()].sort(([l],[d])=>l.localeCompare(d));for(const[l,d]of u)l!==t&&c.push(`${l}:${d}`);s=c.join("|")}const i=`${t}\0${e??""}`;let a=Fh.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},Fh.set(i,a)),a.schemas}function kP(){const t={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},e=new Map;let n=!1;return{[Nv]:!0,stats:t,schemaCache:new Map,aliasCache:new WeakMap,zodImportCache:new WeakMap,generatorCache:new Map,projectFor(r){if(n)throw new Error("apigen-core: ExtractionSession used after dispose()");const o=r??"",s=r?this.statVersion(r):"";let i=Ei.get(o);if(i&&i.tsconfigVersion!==s&&(i=void 0),!i){const a=NP();i={project:r?new a({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new a({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},Ei.set(o,i),t.projectsBuilt++}return i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=Ei.get(o??""),a=this.statVersion(r);let c=s.getSourceFile(r);if(c===void 0?c=s.addSourceFileAtPath(r):i&&i.fileVersions.get(r)!==a&&c.refreshFromFileSystemSync(),i==null||i.fileVersions.set(r,a),i){const u=new Set([r]);Ov(c,u);for(const l of u)l!==r&&i.fileVersions.set(l,this.statVersion(l))}return c},statVersion(r){let o=e.get(r);return o===void 0&&(o=kv(r),e.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),e.clear()}}}function jP(t){const e=t;if(e[Nv]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return e}const Qi="x-apigen-logical";function qh(t,e){const n=new Set,r=[t];for(;r.length>0;){const o=r.pop();if(!o||n.has(o))continue;n.add(o);const s=o.$ref;if(typeof s=="string"){if(e){const d=e[s];if(!d){const f=Object.keys(e).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${s}" cannot be resolved. Available $defs: ${f}`)}r.push(d)}continue}const i=o.oneOf;if(Array.isArray(i))for(const d of i)typeof d=="object"&&d!==null&&r.push(d);const a=o.properties;if(a)for(const d of Object.values(a))r.push(d);const c=o.items;if(Array.isArray(c))for(const d of c)typeof d=="object"&&d!==null&&r.push(d);else typeof c=="object"&&c!==null&&r.push(c);const u=o.additionalProperties;typeof u=="object"&&u!==null&&r.push(u);const l=o.propertyNames;typeof l=="object"&&l!==null&&r.push(l)}}const Kh=new Set(["string","number","boolean","integer"]);function AP(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Kh.has(n):Array.isArray(n)?n.every(r=>Kh.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function IP(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(AP)}function PP(t){const e={},n=r=>{for(const o of["definitions","$defs"]){const s=r[o];if(s)for(const[i,a]of Object.entries(s)){const c=i.startsWith("#/")?i:`#/${o}/${i}`;e[c]=a}}};for(const r of Object.values(t.schemas))n(r.input),n(r.output);if(Object.keys(e).length!==0)for(const[r,o]of Object.entries(t.schemas))try{qh(o.input,e),qh(o.output,e)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function xP(t,e){const n=['apigen calling convention: all domain parameters go inside a "data" envelope — e.g. { "data": { ... } }'+(e?".":" (an empty object for this zero-parameter tool).")];return t.length>0&&n.push(`Field(s) ${t.map(r=>`"${r}"`).join(", ")} are transport-level envelope metadata, NOT domain data — do not nest them under "data". Over MCP they are read from arguments._meta["x-<pluginId>-<field>"] (default pluginId "adhd"); see @adhd/apigen-engine-naming's envelopeMetaKey/envelopeCliFlag/envelopeEnvVar for the HTTP-header / CLI-flag / env-var equivalents.`),n.join(" ")}function RP(t,e,n){PP(t);const r={};for(const[o,s]of Object.entries(t.schemas)){const i={},a=s.input.properties??{},c=s.input.required??[],u={},l=[],d={};for(const w of e)if(w.envelope&&i[w.id]!==!1)for(const[h,v]of Object.entries(w.envelope))u[h]=v,d[h]=w.id,l.includes(h)||l.push(h);const f={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},g=s.safe===!0||IP(s.input),p=s.input.definitions,y=s.input.$defs;r[o]={input:{type:"object",properties:{...u,data:f},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:xP(Object.keys(u),Object.keys(a).length>0),...p?{definitions:p}:{},...y?{$defs:y}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":g,...Object.keys(d).length>0?{"x-apigen-envelope":d}:{}}}return r}const TP=8;function CP(t,e){try{return e?t.getText(e):t.getText()}catch{try{return t.getText()}catch{return}}}let MP=0;async function LP(t,e,n,r){const o=`__ApigenProbe_${process.pid}_${MP++}`;let s;try{s=e.addTypeAlias({name:o,type:n});const i=s.getType();return await r(i)}catch{return}finally{try{s==null||s.remove()}catch{}}}async function jv(t,e,n){if(n>TP)return{};if(t.isString()||t.isStringLiteral())return t.isStringLiteral()?{type:"string",enum:[t.getLiteralValue()]}:{type:"string"};if(t.isNumber()||t.isNumberLiteral())return t.isNumberLiteral()?{type:"number",enum:[t.getLiteralValue()]}:{type:"number"};if(t.isBoolean())return{type:"boolean"};if(t.isBooleanLiteral())return{type:"boolean"};if(t.isNull()||t.isUndefined()||t.isVoid())return{type:"null"};if(t.isUnion()){const r=t.getUnionTypes();if(r.every(i=>i.isStringLiteral())&&r.length>0)return{type:"string",enum:r.map(i=>i.getLiteralValue())};if(r.every(i=>i.isNumberLiteral())&&r.length>0)return{type:"number",enum:r.map(i=>i.getLiteralValue())};const o=await Promise.all(r.map(i=>jv(i,e,n+1))),s=Td(o);return{oneOf:o,...s?{discriminator:s}:{},[Qi]:"union"}}if(t.isArray()){const r=t.getArrayElementType();return{type:"array",items:r?await e(r.getText()):{}}}if(t.isTuple()){const r=t.getTupleElements(),o=await Promise.all(r.map(s=>e(s.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(t.isObject()){const r=t.getStringIndexType(),o=t.getNumberIndexType(),s=r??o,i=t.getProperties();if(s&&i.length===0)return{type:"object",additionalProperties:await e(s.getText())};const a={},c=[];for(const u of i){const l=u.getName(),d=u.getDeclarations()[0];let f;if(d)try{f=u.getTypeAtLocation(d)}catch{f=void 0}if(f!==void 0&&f.getCallSignatures().length>0)continue;const g=f!==void 0?CP(f,d):void 0;a[l]=g!==void 0?await e(g):{},u.isOptional()||c.push(l)}if(Object.keys(a).length>0){const u=s?await e(s.getText()):!1;return{type:"object",properties:a,...c.length>0?{required:c}:{},additionalProperties:u}}return{}}return{}}function Td(t){if(t.length<2)return;const e=[];for(const r of t){if(r.type!=="object")return;const o=r.properties;if(!o||typeof o!="object")return;e.push(o)}const n=Object.keys(e[0]).filter(r=>e.every(o=>Object.prototype.hasOwnProperty.call(o,r)));for(const r of n){const o=[];let s=!0;for(const a of e){const c=a[r],u=c&&(c.type==="string"||c.type==="number"),l=c==null?void 0:c.enum;if(!u||!Array.isArray(l)||l.length!==1){s=!1;break}o.push(String(l[0]))}if(!s||new Set(o).size!==o.length)continue;const i={};return o.forEach((a,c)=>{i[a]=`#/oneOf/${c}`}),{propertyName:r,mapping:i}}}function Si(t,e,n){if(e>6)return{};const r=t.trim();if(r==="string")return{type:"string"};if(r==="number")return{type:"number"};if(r==="boolean")return{type:"boolean"};if(r==="null")return{type:"null"};if(r==="undefined")return{type:"null"};const o=yu[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=yu[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:Si(r.slice(0,-2),e+1,n)};if(r.includes("|")){const s=r.split("|").map(c=>c.trim());if(s.every(c=>c.startsWith("'")))return{type:"string",enum:s.map(c=>c.replace(/'/g,""))};const i=s.map(c=>Si(c,e+1,n)),a=Td(i);return{oneOf:i,...a?{discriminator:a}:{},[Qi]:"union"}}if(r.startsWith("{")&&r.endsWith("}")){const s=r.slice(1,-1).trim(),i={};for(const a of s.split(";").filter(Boolean)){const[c,u]=a.split(":").map(l=>l.trim());c&&u&&(i[c.replace("?","")]=Si(u,e+1,n))}return{type:"object",properties:i}}return{}}function Av(t){const e=[];let n=0,r=0;for(let s=0;s<t.length;s++){const i=t[s];i==="<"||i==="["||i==="{"||i==="("?n++:i===">"||i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(e.push(t.slice(r,s).trim()),r=s+1)}const o=t.slice(r).trim();return o.length>0&&e.push(o),e}function DP(t){const e=/^(?:Readonly)?Map<(.+)>$/.exec(t);return e?e[1]:void 0}function UP(t){const e=/^(?:Readonly)?Set<(.+)>$/.exec(t);return e?e[1]:void 0}function BP(t){let e=t.trim();if(e.startsWith("readonly ")&&(e=e.slice(9).trim()),!e.startsWith("[")||!e.endsWith("]"))return;const n=e.slice(1,-1).trim();if(n.length!==0)return Av(n)}async function FP(t,e){const n=t.trim(),r=DP(n);if(r!==void 0){const i=Av(r);if(i.length===2){const[a,c]=await Promise.all([e(i[0]),e(i[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=UP(n);if(o!==void 0)return{type:"array",items:await e(o),uniqueItems:!0};const s=BP(n);if(s!==void 0){const i=await Promise.all(s.map(a=>e(a)));return{type:"array",items:i,minItems:i.length,maxItems:i.length}}}const Iv={"decimal.js":"Decimal"},yu={Date:{type:"string",format:"date-time"},bigint:{type:"string",format:"int64"},Uint8Array:{type:"string",format:"byte"},Buffer:{type:"string",format:"byte"},URL:{type:"string",format:"uri"},RegExp:{type:"string",format:"regex"},Decimal:{type:"string",format:"decimal"}},Vh={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function Gh(t){var e;const n=new Map;for(const r of t.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=Iv[o];if(!s)continue;const i=r.getDefaultImport();if(i){const a=i.getText();a!==s&&n.set(a,s)}for(const a of r.getNamedImports()){const c=((e=a.getAliasNode())==null?void 0:e.getText())??a.getName();c!==s&&n.set(c,s)}}return n}function qP(t,e){return n=>{n.addNodeParser({supportsNode(r){var o,s,i;if(r.kind!==e)return!1;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText);return a!==void 0&&Object.prototype.hasOwnProperty.call(Vh,a)},createType(r){var o,s,i;const a=((o=r.typeName)==null?void 0:o.escapedText)??((i=(s=r.typeName)==null?void 0:s.right)==null?void 0:i.escapedText),{AnnotatedType:c,StringType:u}=wu();return new c(new u,{format:Vh[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===t},createType(){const{AnnotatedType:r,StringType:o}=wu();return new r(new o,{format:"int64"},!1)}})}}let uc;function wu(){return uc||(uc=zt("ts-json-schema-generator"),uc)}let Eo;function KP(){if(Eo)return Eo;try{const t=L.dirname(zt.resolve("ts-json-schema-generator/package.json"));Eo=zt(zt.resolve("typescript",{paths:[t]}))}catch{Eo=zt("typescript")}return Eo}const hn=new Map;function VP(){const t=process.env.APIGEN_PROGRAM_CACHE,e=t===void 0?NaN:Number(t);return Number.isFinite(e)&&e>=0?e:8}function GP(t){const e=hn.get(t);return e&&(hn.delete(t),hn.set(t,e)),e}function zP(t,e){const n=VP();if(n!==0)for(hn.delete(t),hn.set(t,e);hn.size>n;){const r=hn.keys().next().value;hn.delete(r)}}function WP(t,e){return`${t}\0${e??""}`}const HP=new Set(["zod",/^zod\/./]);function JP(t){for(const e of t.getImportDeclarations()){const n=e.getModuleSpecifierValue();for(const r of HP)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function QP(t){for(const e of["$defs","definitions"]){const n=t[e];if(!n||typeof n!="object")continue;const r=Object.keys(n);if(r.length===0)continue;const o=new Set(r.filter(s=>/zod/i.test(s)));for(const[s,i]of Object.entries(n)){if(o.has(s)||typeof i!="object"||i===null)continue;const a=i,c=typeof a.$ref=="string"?a.$ref:"";if(c){for(const u of o)if(c.includes(u)){o.add(s);break}}}for(const s of o)delete n[s]}vu(t)}function vu(t,e){if(!t||typeof t!="object")return;const n=e??new WeakSet;if(!n.has(t)){n.add(t);for(const r of Object.keys(t))if(r==="$ref"&&typeof t[r]=="string"){const o=t[r];/zod/i.test(o)&&delete t[r]}for(const[,r]of Object.entries(t))if(typeof r=="object"&&r!==null)if(Array.isArray(r))for(const o of r)typeof o=="object"&&o!==null&&vu(o,n);else vu(r,n)}}function YP(t){const e=new Set;for(const r of["$defs","definitions"]){const o=t[r];if(o&&typeof o=="object")for(const s of Object.keys(o))e.add(s)}const n=$u(t,e);if(n.length>0)throw new Error(`[apigen-core-client] Generated schema contains ${n.length} unresolvable $ref(s): ${n.join(", ")}. This usually means zod-internal definitions were stripped but $ref references to them remain. Check the source file's imports or the ts-json-schema-generator output.`)}function $u(t,e){if(!t||typeof t!="object")return[];const n=[];for(const[r,o]of Object.entries(t))if(r==="$ref"&&typeof o=="string"){const s=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);s&&!e.has(s[1])&&n.push(o)}else if(typeof o=="object"&&o!==null)if(Array.isArray(o))for(const s of o)typeof s=="object"&&s!==null&&n.push(...$u(s,e));else n.push(...$u(o,e));return n}function ZP(t){const e=t.anyOf;if(!Array.isArray(e)||e.length<2)return t;const n=e,r=Td(n),o={...t};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[Qi]:o[Qi]??"union"}}function XP(t,e,n){const{DEFAULT_CONFIG:r}=zt("ts-json-schema-generator/dist/src/Config.js"),o={...r,...t},s=o.path,i=WP(s,o.tsconfig);let a;a=n?n.statVersion(s):kv(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??GP(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=zt("ts-json-schema-generator/dist/factory/program.js"),{createParser:d,createFormatter:f,SchemaGenerator:g}=wu(),p=KP(),y=qP(p.SyntaxKind.BigIntKeyword,p.SyntaxKind.TypeReference),w=l(o),h=d(w,o,y),v=f(o);if(c=new g(w,h,v,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const b={version:a,gen:c};zP(i,b),n==null||n.generatorCache.set(i,b)}}const u=c.createSchema(o.type);return QP(u),YP(u),u}function ex(t,e){let n=t.trim();if(n=xv(n),e!=null&&e.size){const o=e.get(n);if(o!==void 0)return o}const r=n.match(/^ReadonlyArray<(.+)>$/);for(r&&(n=`${r[1].trim()}[]`);n.startsWith("readonly ");)n=n.slice(9).trim();return n}function Pv(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const tx=Object.entries(Iv).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${Pv(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function xv(t){let e=t;for(const{pattern:n,key:r}of tx)e=e.replace(n,r);return e}function nx(t,e){let n=xv(t);for(const[r,o]of e)n=n.replace(new RegExp(`\\b${Pv(r)}\\b`,"g"),o);return n}async function ds(t,e,n,r,o,s){const i=e.getFilePath(),a=`${i}\0${r??""}\0${n}`,c=s??new Set;if(c.has(a))return{};if(!o){const p=new Set(c);return p.add(a),zh(t,e,n,r,void 0,p)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=OP(i,r,o.statVersion(i)),d=l.get(n);if(d!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(d)),d;o.stats.schemaCacheMisses++;const f=new Set(c);f.add(a);const g=zh(t,e,n,r,o,f).then(p=>(l.set(n,p),p)).catch(p=>{throw o.schemaCache.delete(a),p});return o.schemaCache.set(a,g),g}async function zh(t,e,n,r,o,s){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let i;if(o){const f=o.aliasCache.get(e);i=f??Gh(e),f||o.aliasCache.set(e,i)}else i=Gh(e);const a=ex(n,i),c=yu[a];if(c!==void 0)return c;const u=await FP(a,f=>ds(t,e,f,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(e))??JP(e);if(o&&o.zodImportCache.set(e,l),!l)try{const f={path:e.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},g=XP(f,!0,o);return ZP(g)}catch{}try{const f=await LP(t,e,a,g=>jv(g,p=>ds(t,e,p,r,o,s),0));if(f!==void 0)return f}catch{}const d=nx(a,i);return Si(d,0,i)}function Cd(t,e,n){if(t!=null&&t.hasInitializer()){const r=t.getInitializer();if(r)return r.getText()}return rx(n,e)}function rx(t,e){var n;const r=t,o=((n=r==null?void 0:r.getJsDocs)==null?void 0:n.call(r))??[],s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=new RegExp(`\\[\\s*${s}\\s*=\\s*([^\\]]+)\\]`);for(const a of o)for(const c of a.getTags()){if(c.getTagName()!=="param")continue;const u=c.getText().match(i);if(u)return u[1].trim()}}function ox(t){const e=t.trim(),n=e.match(/^(['"`])([\s\S]*)\1$/);if(n)return n[2];if(e==="true")return!0;if(e==="false")return!1;if(e==="null")return null;if(e!=="undefined"){if(/^-?\d+(\.\d+)?$/.test(e))return Number(e);try{return JSON.parse(e)}catch{return e}}}function sx(t,e){const n=ox(e);if(n===void 0)return;t.default=n;const r=typeof n=="string"?n:JSON.stringify(n),o=typeof t.description=="string"?t.description:void 0;t.description=o?`${o} (default: ${r})`:`(default: ${r})`}let lc;function ix(){return lc||(lc=zt("ts-morph").SyntaxKind,lc)}function ja(t){try{if(!t)return;const e=ix();if(t.getKind()!==e.TypeReference)return;const n=t;if(n.getTypeArguments().length>0)return;const r=n.getTypeName();if(r.getKind()!==e.Identifier)return;const o=r.getSymbol();if(!o)return;const s=o.getDeclarations().find(u=>u.getKindName()==="TypeAliasDeclaration");if(!s)return;const i=s,a=i.getType();if(!(a.isString()||a.isNumber()||a.isBoolean()))return;const c=i.getJsDocs();for(const u of c)for(const l of u.getTags())if(l.getTagName()==="format"){const d=l.getCommentText();if(d!==void 0)return d.trim()}return}catch{return}}const ax=new Set(["AsyncGenerator","AsyncIterableIterator","AsyncIterable","Generator","IterableIterator","Iterable","ApiStream"]);function cx(t){const e=[];let n=0,r="";for(const o of t)o==="<"||o==="("||o==="["||o==="{"?n++:(o===">"||o===")"||o==="]"||o==="}")&&n--,o===","&&n===0?(e.push(r.trim()),r=""):r+=o;return r.trim().length>0&&e.push(r.trim()),e}function ux(t){const e=t.trim(),n=e.indexOf("<");if(n===-1||!e.endsWith(">"))return null;const r=e.slice(0,n),o=r.includes(".")?r.slice(r.lastIndexOf(".")+1):r;if(!ax.has(o))return null;let s=0;for(let c=n;c<e.length;c++){const u=e[c];if(u==="<")s++;else if(u===">"&&(s--,s===0&&c!==e.length-1))return null}if(s!==0)return null;const i=e.slice(n+1,-1),a=cx(i);return a.length>0?a[0]:null}async function lx(t){const e=t.session===void 0,n=jP(t.session??kP());try{return await dx(t,n)}finally{e&&n.dispose()}}async function dx(t,e){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:s}=t,i=e.projectFor(s),a=e.sourceFileFor(n,s),c=L.basename(n),u=Gt(hx(c)),l=o?null:u,d=Gt(r),f=[];for(const[y,w]of a.getExportedDeclarations()){if(y==="default"||Hs(y))continue;const h=gx(w);if(h){const N=h.getSignature(),j=Jh(N,h),T=N.getReturnType().getText(),M=Gn(N);f.push(await Ws(i,a,d,l,y,j,T,h.isAsync(),s,e,M));continue}const v=w.find(N=>N.getKindName()==="VariableDeclaration");if(!v)continue;const b=v.getInitializer(),E=b==null?void 0:b.getKindName();if(b&&["ArrowFunction","FunctionExpression"].includes(E??"")){const N=v.getType().getCallSignatures();if(N.length===0)continue;const j=N[0],T=Qh(j,v,v.getVariableStatement()),M=j.getReturnType().getText(),C=Gn(j),G=b.isAsync();f.push(await Ws(i,a,d,l,y,T,M,G,s,e,C))}else if(E==="ObjectLiteralExpression"){const N=v.getType();for(const j of N.getProperties()){const T=j.getName();if(Hs(T))continue;const M=j.getTypeAtLocation(v).getCallSignatures();if(M.length===0)continue;const C=M[0],G=Qh(C,v,v.getVariableStatement()),H=C.getReturnType().getText(),Z=Gn(C),ue=[...l?[l]:[],Gt(y),Gt(T)];f.push(await _i(i,a,d,ue,T,G,H,!1,s,e,Z))}}else{const N=v.getType(),j=N.getText();if(Qn(N,v)){const T=await ds(i,a,j,s,e);f.push(fx(d,l,y,T))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${y}`)}}const g=a.getDefaultExportSymbol();if(g){const y=a.getExportAssignment(w=>!w.isExportEquals());if(y){const w=y.getExpression(),h=w.getKindName();if(["ArrowFunction","FunctionExpression"].includes(h)){const v=w.getType().getCallSignatures();if(v.length>0){const b=v[0],E=dc(b,y),N=b.getReturnType().getText(),j=Gn(b),T=w.isAsync();f.push(await Ws(i,a,d,l,"default",E,N,T,s,e,j))}}else{const v=w.getType();for(const b of v.getProperties()){const E=b.getName();if(Hs(E))continue;const N=b.getTypeAtLocation(y).getCallSignatures();if(N.length===0)continue;const j=N[0],T=dc(j,y),M=j.getReturnType().getText(),C=Gn(j),G=[...l?[l]:[],Gt("default"),Gt(E)];f.push(await _i(i,a,d,G,E,T,M,!1,s,e,C))}}}else{const w=g.getDeclarations();for(const h of w){if(h.getKindName()!=="FunctionDeclaration")continue;const v=h,b=v.getName(),E=b&&b.length>0?b:"default",N=v.getSignature(),j=Jh(N,v),T=N.getReturnType().getText(),M=Gn(N);f.push(await Ws(i,a,d,l,E,j,T,v.isAsync(),s,e,M))}}}const p=mx(a);if(p.length>0)for(const{name:y,sig:w}of p){if(Hs(y))continue;const h=dc(w),v=w.getReturnType().getText(),b=Gn(w),E=[...l?[l]:[],Gt(y)];f.push(await _i(i,a,d,E,y,h,v,!1,s,e,b))}return f}function Wh(t,e,n,r){const o=new Set,s=i=>{if(Array.isArray(i))return i.map(s);if(!i||typeof i!="object"||o.has(i))return i;o.add(i);try{const a=i,c={};for(const[u,l]of Object.entries(a)){if(u==="definitions"||u==="$defs"){const d=u,f=e[d];for(const[g,p]of Object.entries(l)){const y=s(p),w=f[g];if(w!==void 0&&JSON.stringify(w)!==JSON.stringify(y))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${d}.${g}" definition that conflicts with an identically-named definition already hoisted from another param/output in the same function. Two structurally different types share the same generated definition key, so apigen cannot safely merge them into one function-level schema.`);f[g]=y}continue}c[u]=s(l)}return c}finally{o.delete(i)}};return s(t)}function Hh(t,e){if(!e||t.format!==void 0||"$ref"in t||"properties"in t||"items"in t)return;const n=t.type;(n==="string"||n==="number"||n==="integer"||n==="boolean")&&(t.format=e)}function Gn(t){var e;try{return ja((e=t.getDeclaration())==null?void 0:e.getReturnTypeNode())}catch{return}}async function Ws(t,e,n,r,o,s,i,a,c,u,l){const d=Gt(o);return _i(t,e,n,r?[r,d]:[d],o,s,i,a,c,u,l)}async function _i(t,e,n,r,o,s,i,a,c,u,l){const d=s.length>0&&s[0].name==="ctx",f=s.filter(C=>C.name!=="ctx"),g=f.filter(C=>!C.optional).map(C=>C.name),p={},y={definitions:{},$defs:{}};for(const C of f){const G=await ds(t,e,C.type,c,u),H=Wh(G,y,o,C.name);C.defaultValue!==void 0&&sx(H,C.defaultValue),Hh(H,C.format),p[C.name]=H}const w=i.replace(/^Promise<(.+)>$/,"$1").trim(),h=ux(w),v=h!==null,b=v?h:w,E=await ds(t,e,b,c,u),N={definitions:{},$defs:{}},j=Wh(E,N,o,"<return>"),T=l?{...j}:j;Hh(T,l),Object.keys(N.definitions).length>0&&(T.definitions={...T.definitions,...N.definitions}),Object.keys(N.$defs).length>0&&(T.$defs={...T.$defs,...N.$defs});const M={type:"object",properties:p,required:g,...Object.keys(y.definitions).length>0?{definitions:y.definitions}:{},...Object.keys(y.$defs).length>0?{$defs:y.$defs}:{}};return{id:Rv(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:v,safe:!1,input:M,output:T,envelope:{},typeText:{lang:"ts",input:yx(s),output:b},...d?{hasCtx:!0}:{}}}function fx(t,e,n,r){const o=Gt(n),s=e?[e,o]:[o];return{id:Rv(t,s),host:"ts",namespace:t,path:s,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function Rv(t,e){return(t.raw?[t,...e]:e).map(n=>n.words.join("-")).join("/")}function px(t){return t.split(/[-_.]+/).flatMap(e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(e=>e.toLowerCase()).filter(Boolean)}function Gt(t){return{raw:t,words:px(t)}}function hx(t){return t.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function mx(t){const e=[];for(const n of t.getStatements()){if(n.getKindName()!=="ExpressionStatement")continue;const r=n.getExpression();if(r.getKindName()!=="BinaryExpression")continue;const o=r;if(o.getLeft().getText().trim()!=="module.exports"||o.getOperatorToken().getKindName()!=="EqualsToken")continue;const s=o.getRight(),i=s.getType();for(const a of i.getProperties()){const c=a.getTypeAtLocation(s).getCallSignatures();c.length!==0&&e.push({name:a.getName(),sig:c[0]})}}return e}function gx(t){let e;for(const n of t){if(n.getKindName()!=="FunctionDeclaration")continue;const r=n;if(e||(e=r),r.getBody())return r}return e}function Jh(t,e){return t.getParameters().map(n=>{var r;const o=n.getDeclarations(),s=o.length>0&&o[0].getKindName()==="Parameter"?o[0]:null,i=n.isOptional()||((s==null?void 0:s.hasInitializer())??!1)||(((r=s==null?void 0:s.hasQuestionToken)==null?void 0:r.call(s))??!1);return{name:n.getName(),type:n.getTypeAtLocation(t.getDeclaration()).getText(),optional:i,defaultValue:Cd(s,n.getName(),e),format:ja(s==null?void 0:s.getTypeNode())}})}function Qh(t,e,n){return t.getParameters().map(r=>{var o;const s=r.getDeclarations(),i=s.length>0&&s[0].getKindName()==="Parameter"?s[0]:null,a=r.isOptional()||((i==null?void 0:i.hasInitializer())??!1)||(((o=i==null?void 0:i.hasQuestionToken)==null?void 0:o.call(i))??!1);return{name:r.getName(),type:r.getTypeAtLocation(e).getText(),optional:a,defaultValue:Cd(i,r.getName(),n??e),format:ja(i==null?void 0:i.getTypeNode())}})}function dc(t,e){return t.getParameters().map(n=>{var r,o,s;const i=n.getDeclarations(),a=i.length>0&&i[0].getKindName()==="Parameter"?i[0]:null,c=n.isOptional()||((a==null?void 0:a.hasInitializer())??!1)||(((r=a==null?void 0:a.hasQuestionToken)==null?void 0:r.call(a))??!1);return{name:n.getName(),type:a?a.getType().getText():((s=(o=n.getValueDeclaration())==null?void 0:o.getType())==null?void 0:s.getText())??"unknown",optional:c,defaultValue:Cd(a,n.getName(),e),format:ja(a==null?void 0:a.getTypeNode())}})}function yx(t){const e=t.filter(n=>n.name!=="ctx");return e.length===0?"()":"("+e.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function Hs(t){return!!(t==="__samples__"||t.startsWith("__"))}function Qn(t,e,n=new Set){if(t.getCallSignatures().length>0||t.getConstructSignatures().length>0)return!1;if(t.isString()||t.isNumber()||t.isBoolean()||t.isNull()||t.isUndefined()||t.isStringLiteral()||t.isNumberLiteral()||t.isBooleanLiteral()||t.isEnumLiteral())return!0;if(t.isArray()||t.isReadonlyArray()){const r=t.getArrayElementType();return r?Qn(r,e,n):!1}if(t.isTuple())return t.getTupleElements().every(r=>Qn(r,e,n));if(t.isUnion())return t.getUnionTypes().every(r=>Qn(r,e,n));if(t.isIntersection())return t.getIntersectionTypes().every(r=>Qn(r,e,n));if(t.isObject()){const r=t.getText(e);if(n.has(r))return!0;n.add(r);const o=t.getStringIndexType(),s=t.getNumberIndexType();if(o||s)return[o,s].every(a=>!a||Qn(a,e,n));const i=t.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(e);return Qn(c,e,n)})}return!1}function wx(t,e){return async n=>{let r=()=>e(n);for(let o=t.length-1;o>=0;o--){const s=t[o],i=r;r=()=>s(n,i)}return r()}}function vx(t,e){return wx(t,e)}function $x(t,e,n={}){const r=t.map(o=>o.capabilities.extractLayer).filter(o=>!!o).map(o=>o.createLayer?o.createLayer(n):o.layer).filter(o=>!!o);return vx(r,e)}const bx=Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);let fc;function Ex(){return fc||(fc=bx("ts-morph").Project,fc)}function Tv(t,e){const n=[...t.getImportDeclarations().map(r=>r.getModuleSpecifierSourceFile()),...t.getExportDeclarations().map(r=>r.getModuleSpecifierSourceFile())];for(const r of n){if(!r)continue;const o=r.getFilePath();if(!o.includes("/node_modules/")&&!e.has(o)){e.add(o);try{r.refreshFromFileSystemSync()}catch{}Tv(r,e)}}}let pc;function Sx(){if(!pc){const t=Ex();pc=new t({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})}return pc}function Cv(t){const e=Sx(),n=e.getSourceFile(t),r=n??e.addSourceFileAtPath(t);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([t]);return Tv(r,o),[...o].sort()}const _x={"decimal.js":"Decimal"};function Nx(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(_x).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${Nx(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));async function Ox(t,e){await or.mkdir(L.dirname(t),{recursive:!0});const n=`${t}.${process.pid}.${kn.randomUUID()}.tmp`;try{await or.writeFile(n,JSON.stringify(e),"utf8"),await or.rename(n,t)}catch(r){throw await or.unlink(n).catch(()=>{}),r}}function kx(t){return{async get(){try{const e=await or.readFile(t,"utf8");return JSON.parse(e)}catch{return}},async put(e,n){await Ox(t,n)}}}const bu=1;function jx(t){return kn.createHash("sha256").update(t).digest("hex")}async function Yh(t){return jx(await or.readFile(t,"utf8"))}async function Yi(t){try{return(await or.stat(t)).mtimeMs}catch{return}}async function Zh(t,e){const n=await Yh(t.source),r=kn.createHash("sha256");r.update(`formatVersion:${bu}
195
- `),r.update(`extractorVersion:${e}
196
- `),r.update(`host:${t.host}
197
- `),r.update(`namespace:${t.namespace??""}
198
- `),r.update(`source:${n}
199
- `);for(const o of Cv(t.source))o!==t.source&&r.update(`dep:${o}:${await Yh(o)}
200
- `);return r.digest("hex")}async function Xh(t,e){const n=await Yi(t.source)??0,r=[];for(const o of Cv(t.source)){if(o===t.source)continue;const s=await Yi(o);s!==void 0&&r.push({path:o,mtimeMs:s})}return{contentKey:e,source:{path:t.source,mtimeMs:n},deps:r}}async function Ax(t,e){if(e.source.path!==t.source)return!1;const n=await Yi(e.source.path);if(n===void 0||n!==e.source.mtimeMs)return!1;for(const r of e.deps){const o=await Yi(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function Ix(t){if(t.cache==="artifact")throw new Error("apigen-plugin-ir-cache: createIrCacheLayer() (the RUNTIME CACHE 'extractLayer' capability) received cache: 'artifact'. That value selects the ARTIFACT-mode 'target' capability instead (--type ir-cache --opt cache=artifact) — a file path is required here. See docs/apigen/design-notes/extract-stage-onion-and-ir-cache.md Revision 2 (R2.2).");const e=kx(t.cache),n=t.extractorVersion;async function r(o,s,i){const a=i??await Zh(o,n),c=await Xh(o,a);await e.put(t.cache,{formatVersion:bu,operations:s,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,s)=>{const i=await e.get(t.cache);if(!i||i.formatVersion!==bu||i.extractorVersion!==n||!i.staleness){const u=await s();return r(o,u).catch(()=>{}),u}if(await Ax(o,i.staleness))return i.operations;const a=await Zh(o,n);if(a===i.staleness.contentKey)return Xh(o,a).then(u=>e.put(t.cache,{...i,staleness:u})).catch(()=>{}),i.operations;const c=await s();return r(o,c,a).catch(()=>{}),c}}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);function Px(t){if(t.__esModule)return t;var e=t.default;if(typeof e=="function"){var n=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var o=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return t[r]}})}),n}const je={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},P={ALIAS:"ALIAS",BLANK_LINE:"BLANK_LINE",BLOCK_FOLDED:"BLOCK_FOLDED",BLOCK_LITERAL:"BLOCK_LITERAL",COMMENT:"COMMENT",DIRECTIVE:"DIRECTIVE",DOCUMENT:"DOCUMENT",FLOW_MAP:"FLOW_MAP",FLOW_SEQ:"FLOW_SEQ",MAP:"MAP",MAP_KEY:"MAP_KEY",MAP_VALUE:"MAP_VALUE",PLAIN:"PLAIN",QUOTE_DOUBLE:"QUOTE_DOUBLE",QUOTE_SINGLE:"QUOTE_SINGLE",SEQ:"SEQ",SEQ_ITEM:"SEQ_ITEM"},Ni="tag:yaml.org,2002:",wn={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function em(t){const e=[0];let n=t.indexOf(`
201
- `);for(;n!==-1;)n+=1,e.push(n),n=t.indexOf(`
202
- `,n);return e}function Mv(t){let e,n;return typeof t=="string"?(e=em(t),n=t):(Array.isArray(t)&&(t=t[0]),t&&t.context&&(t.lineStarts||(t.lineStarts=em(t.context.src)),e=t.lineStarts,n=t.context.src)),{lineStarts:e,src:n}}function Eu(t,e){if(typeof t!="number"||t<0)return null;const{lineStarts:n,src:r}=Mv(e);if(!n||!r||t>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(t<i)return{line:s,col:t-n[s-1]+1};if(t===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:t-n[o-1]+1}}function xx(t,e){const{lineStarts:n,src:r}=Mv(e);if(!n||!(t>=1)||t>n.length)return null;const o=n[t-1];let s=n[t];for(;s&&s>o&&r[s-1]===`
203
- `;)--s;return r.slice(o,s)}function Rx({start:t,end:e},n,r=80){let o=xx(t.line,n);if(!o)return null;let{col:s}=t;if(o.length>r)if(s<=r-10)o=o.substr(0,r-1)+"…";else{const l=Math.round(r/2);o.length>s+l&&(o=o.substr(0,s+l-1)+"…"),s-=o.length-r,o="…"+o.substr(1-r)}let i=1,a="";e&&(e.line===t.line&&s+(e.col-t.col)<=r+1?i=e.col-t.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
204
- ${c}${u}${a}`}let Ee=class Lv{static copy(e){return new Lv(e.start,e.end)}constructor(e,n){this.start=e,this.end=n||e}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(e,n){const{start:r,end:o}=this;if(e.length===0||o<=e[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<e.length&&!(e[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<e.length&&!(e[s]>=o);)++s;return this.origEnd=o+s,i}},F=class Vt{static addStringTerminator(e,n,r){if(r[r.length-1]===`
205
- `)return r;const o=Vt.endOfWhiteSpace(e,n);return o>=e.length||e[o]===`
206
- `?r+`
207
- `:r}static atDocumentBoundary(e,n,r){const o=e[n];if(!o)return!0;const s=e[n-1];if(s&&s!==`
208
- `)return!1;if(r){if(o!==r)return!1}else if(o!==je.DIRECTIVES_END&&o!==je.DOCUMENT_END)return!1;const i=e[n+1],a=e[n+2];if(i!==o||a!==o)return!1;const c=e[n+3];return!c||c===`
209
- `||c===" "||c===" "}static endOfIdentifier(e,n){let r=e[n];const o=r==="<",s=o?[`
210
- `," "," ",">"]:[`
211
- `," "," ","[","]","{","}",","];for(;r&&s.indexOf(r)===-1;)r=e[n+=1];return o&&r===">"&&(n+=1),n}static endOfIndent(e,n){let r=e[n];for(;r===" ";)r=e[n+=1];return n}static endOfLine(e,n){let r=e[n];for(;r&&r!==`
212
- `;)r=e[n+=1];return n}static endOfWhiteSpace(e,n){let r=e[n];for(;r===" "||r===" ";)r=e[n+=1];return n}static startOfLine(e,n){let r=e[n-1];if(r===`
213
- `)return n;for(;r&&r!==`
214
- `;)r=e[n-=1];return n+1}static endOfBlockIndent(e,n,r){const o=Vt.endOfIndent(e,r);if(o>r+n)return o;{const s=Vt.endOfWhiteSpace(e,o),i=e[s];if(!i||i===`
215
- `)return s}return null}static atBlank(e,n,r){const o=e[n];return o===`
216
- `||o===" "||o===" "||r&&!o}static nextNodeIsIndented(e,n,r){return!e||n<0?!1:n>0?!0:r&&e==="-"}static normalizeOffset(e,n){const r=e[n];return r?r!==`
217
- `&&e[n-1]===`
218
- `?n-1:Vt.endOfWhiteSpace(e,n):n}static foldNewline(e,n,r){let o=0,s=!1,i="",a=e[n+1];for(;a===" "||a===" "||a===`
219
- `;){switch(a){case`
220
- `:o=0,n+=1,i+=`
221
- `;break;case" ":o<=r&&(s=!0),n=Vt.endOfWhiteSpace(e,n+2)-1;break;case" ":o+=1,n+=1;break}a=e[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(e,n,r){Object.defineProperty(this,"context",{value:r||null,writable:!0}),this.error=null,this.range=null,this.valueRange=null,this.props=n||[],this.type=e,this.value=null}getPropValue(e,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[e];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let e=0;e<this.props.length;++e){const n=this.getPropValue(e,je.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const e=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,je.COMMENT,!0);r!=null&&e.push(r)}return e.length>0?e.join(`
222
- `):null}commentHasRequiredWhitespace(e){const{src:n}=this.context;if(this.header&&e===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return e!==r||Vt.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:e}=this.context;for(let n=0;n<this.props.length;++n)if(e[this.props[n].start]===je.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:e}=this.context;for(let n=0;n<this.props.length;++n)if(e[this.props[n].start]!==je.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[P.FLOW_MAP,P.FLOW_SEQ,P.QUOTE_DOUBLE,P.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const e=Eu(this.range.start,this.context.root);if(!e)return;const n=Eu(this.range.end,this.context.root);return{start:e,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:e,end:n}=this.valueRange;return this.context.src.slice(e,n)}get tag(){for(let e=0;e<this.props.length;++e){const n=this.getPropValue(e,je.TAG,!1);if(n!=null){if(n[1]==="<")return{verbatim:n.slice(2,-1)};{const[r,o,s]=n.match(/^(.*!)([^!]*)$/);return{handle:o,suffix:s}}}}return null}get valueRangeContainsNewline(){if(!this.valueRange||!this.context)return!1;const{start:e,end:n}=this.valueRange,{src:r}=this.context;for(let o=e;o<n;++o)if(r[o]===`
223
- `)return!0;return!1}parseComment(e){const{src:n}=this.context;if(n[e]===je.COMMENT){const r=Vt.endOfLine(n,e+1),o=new Ee(e,r);return this.props.push(o),r}return e}setOrigRanges(e,n){return this.range&&(n=this.range.setOrigRange(e,n)),this.valueRange&&this.valueRange.setOrigRange(e,n),this.props.forEach(r=>r.setOrigRange(e,n)),n}toString(){const{context:{src:e},range:n,value:r}=this;if(r!=null)return r;const o=e.slice(n.start,n.end);return Vt.addStringTerminator(e,n.end,o)}},wr=class extends Error{constructor(e,n,r){if(!r||!(n instanceof F))throw new Error(`Invalid arguments for new ${e}`);super(),this.name=e,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const e=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new Ee(this.offset,this.offset+1);const n=e&&Eu(this.offset,e);if(n){const r={line:n.line,col:n.col+1};this.linePos={start:n,end:r}}delete this.offset}else this.range=this.source.range,this.linePos=this.source.rangeAsLinePos;if(this.linePos){const{line:n,col:r}=this.linePos.start;this.message+=` at line ${n}, column ${r}`;const o=e&&Rx(this.linePos,e);o&&(this.message+=`:
41
+ `),O.closeSync(o);let i=!1;return()=>{if(!i){i=!0;try{O.unlinkSync(r)}catch{}}}}_runDirFallback(){return k.join(k.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))O.mkdirSync(t,{recursive:!0})}write(){return Ru(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function Er(e,t,n){const r={};for(const s of t.dirs)r[s.name]=s.path;const o={};for(const s of t.files)o[s.name]=s.path;const i=Lu(t.config,t.liveFields??{});return Object.defineProperties(e,{project:{value:t.project,enumerable:!0},namespace:{value:t.namespace,enumerable:!0},orgNamespace:{value:t.orgNamespace,enumerable:!0},scope:{value:t.scope,enumerable:!0},prefix:{value:t.envPrefix,enumerable:!0},instanceId:{value:t.instanceId,enumerable:!0},hash:{value:t.configHash,enumerable:!0},version:{value:{configHash:t.configHash,structureHash:t.structureHash,generatedAt:t.generatedAt,libraryVersion:t.libraryVersion},enumerable:!0},provenance:{value:t.provenance,enumerable:!0},dirs:{value:t.dirs,enumerable:!0},snapshotPath:{value:n,enumerable:!0},config:{value:i,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:t,enumerable:!1}}),new Proxy(e,{get(s,a,c){return typeof a=="string"&&!(a in s)?s.get(a):Reflect.get(s,a,c)}})}const Ue={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production","test","sandbox"],dirs:{data:{kind:"data"},cache:{kind:"cache"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"Backlog graph DB path. Unset ⇒ falls back to env.files.db under the resolved scope root."},"db.busyTimeoutMs":{type:"integer",env:"ADHD_BACKLOG_DATABASE_BUSY_TIMEOUT_MS",default:5e3,description:"The store adapter's `busy_timeout` (ms) each write waits for a contended lock before retrying (DEBT-BACKLOG-CONCURRENCY-BUSY-RETRY-001). Raise this when scaling toward more concurrent agents writing the same global-scope store."},"logging.level":{type:"string",env:"ADHD_BACKLOG_LOG_LEVEL",default:"info",enum:["trace","debug","info","warn","error","fatal","silent"]},"embedding.enabled":{type:"boolean",env:"ADHD_BACKLOG_EMBEDDING_ENABLED",default:!1,description:'RAG-SPEC.md §1.6 — opt IN to the semantic/RAG stack. Default FALSE: semantic inputs (filter.semantic, filter.anchor, view:"similar", sort:"relevance", fields:["_vector"]) answer RagNotConfiguredError (§5a) until this is set. Requires the optionalDependencies @adhd/sox-embedding-provider + @adhd/sox-vector-store to be installed, and a store whose adapter reports capabilities.nativeVectors (turso). Enabling it with any of those missing logs a typed reason and leaves RAG unconfigured — it never crashes startup.'},"embedding.provider":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_PROVIDER",default:"fastembed",description:"Embedding provider type, forwarded verbatim to @adhd/sox-embedding-provider's createEmbeddingProvider ('fastembed' | 'remote')."},"embedding.model":{type:"string",env:"ADHD_BACKLOG_EMBEDDING_MODEL",default:"bge-base-en-v1.5",description:"Embedding model id (768-dim bge-base-en-v1.5 by default). RAG-SPEC.md §2.5: the dimensional contract is STRUCTURAL — changing this after items are embedded orphans existing vectors under the old model id rather than silently truncating; re-embed via admin(embedding_backfill)."}}};function fo(e){if(e)return e;const t=process.env.ADHD_BACKLOG_SCOPE;if(t)return t;const n=process.env.ADHD_ENV_SCOPE;return n||"global"}function $e(e={}){const t={namespace:e.namespace??"production",scope:fo(e.scope)};return e.adhdRoot!==void 0&&(t.adhdRoot=e.adhdRoot),e.cwd!==void 0&&(t.cwd=e.cwd),e.instanceId!==void 0&&(t.instanceId=e.instanceId),new Kt("backlog",Ue,t)}function Ge(e){return e.config.db.path??e.files.db}function Du(e,t){return`${e}:${t}`}function Mu(e={}){const t=process.env.APIGEN_IR_CACHE_FILE;if(t)return t;const n={namespace:"production",scope:"global"};e.adhdRoot!==void 0&&(n.adhdRoot=e.adhdRoot),e.instanceId!==void 0&&(n.instanceId=e.instanceId);const r=new Kt("backlog",Ue,n);return k.join(r.paths.cache,"apigen","ir-cache","backlog-client.ir.json")}function kr(e){return{raw:e,words:ze(e)}}function ss(e,t,n,r){for(const o of r??[]){const i=o.path[o.path.length-1];if(o.namespace.raw===e&&(i==null?void 0:i.raw)===t)return o}return{id:`${ze(e).join("-")}/${ze(t).join("-")}`,host:"ts",namespace:kr(e),path:[kr(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function Fu(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},n=e["x-apigen-envelope"],r={};for(const i of Object.keys(t)){if(i==="data")continue;const s=(n==null?void 0:n[i])??"adhd";r[i]=Ai(s,i)}return r}function Bu(e){const t=Id(e.options.port),n=e.options.routePrefix??"",r=e.options.projection??{},o=Od(e.packages.map(s=>s.id)),i=["// Auto-generated by @adhd/apigen-cli — do not edit","import Fastify from 'fastify'","import { dispatch, buildFnTable, coerceQueryParams } from '@adhd/apigen-engine-runtime'"];for(const[s,a]of e.packages.entries()){const c=o[s];i.push(`import * as ${c}_ns from ${se(a.importPath)}`),i.push(`const ${c}_fns = buildFnTable(${c}_ns as Record<string, unknown>)`)}i.push(""),i.push(`const schemas: Record<string, unknown> = ${Ni(JSON.stringify(Object.fromEntries(e.packages.flatMap(s=>Object.entries(s.schemas).map(([a,c])=>[`${s.id}:${a}`,{schema:c,pkgId:s.id}]))),null,2))}`),i.push(""),i.push("const app = Fastify()"),i.push("");for(const[s,a]of e.packages.entries()){const c=o[s];for(const[d,l]of Object.entries(a.schemas)){const u=ss(a.id,d,l,e.operations),f=ye({op:u,schema:l,transport:"http",projection:r}),g=n+f.http.route,p=f.http.verb,m=Fu(l),v=Object.entries(m),h=se(`${a.id}:${d}`),y=se(d);if(p==="GET"){if(i.push(`app.get(${se(g)}, async (req) => {`),i.push(` const query = coerceQueryParams(req.query as Record<string, unknown>, schemas[${h}]['schema'] as any)`),v.length>0){const w=v.map(([b,S])=>`${se(b)}: (req.headers as Record<string, unknown>)[${se(S)}]`).join(", ");i.push(` const envelope: Record<string, unknown> = { ${w} }`)}else i.push(" const envelope: Record<string, unknown> = {}");i.push(` return dispatch(${c}_fns as any, undefined, schemas[${h}]['schema'] as any, ${y}, envelope, query as any)`),i.push("})")}else{if(i.push(`app.post(${se(g)}, async (req) => {`),i.push(" const { data = {} } = req.body as Record<string, unknown>"),v.length>0){const w=v.map(([b,S])=>`${se(b)}: (req.headers as Record<string, unknown>)[${se(S)}]`).join(", ");i.push(` const envelope: Record<string, unknown> = { ${w} }`)}else i.push(" const envelope: Record<string, unknown> = {}");i.push(` return dispatch(${c}_fns as any, undefined, schemas[${h}]['schema'] as any, ${y}, envelope, data as any)`),i.push("})")}}}return i.push(""),i.push("app.setErrorHandler((err, _req, reply) => {"),i.push(" reply.status(500).send({"),i.push(" code: 'internal',"),i.push(" message: err instanceof Error ? err.message : 'Internal error',"),i.push(" })"),i.push("})"),i.push(""),i.push("async function main(): Promise<void> {"),i.push(" try {"),i.push(` await app.listen({ port: ${t} })`),i.push(" } catch (err) {"),i.push(" app.log.error(err)"),i.push(" process.exit(1)"),i.push(" }"),i.push("}"),i.push(""),i.push("main()"),{files:[{path:"routes.ts",content:i.join(`
42
+ `)}]}}function qu(e){return`data: ${e}
224
43
 
225
- ${o}
226
- `)}delete this.source}};class fs extends wr{constructor(e,n){super("YAMLReferenceError",e,n)}}let ee=class extends wr{constructor(e,n){super("YAMLSemanticError",e,n)}},qe=class extends wr{constructor(e,n){super("YAMLSyntaxError",e,n)}},po=class extends wr{constructor(e,n){super("YAMLWarning",e,n)}};function We(t,e,n){return(e=Cx(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function Tx(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Cx(t){var e=Tx(t,"string");return typeof e=="symbol"?e:e+""}let Dv=class Su extends F{static endOfLine(e,n,r){let o=e[n],s=n;for(;o&&o!==`
227
- `&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=e[s+1];if(o===":"&&(!i||i===`
228
- `||i===" "||i===" "||r&&i===",")||(o===" "||o===" ")&&i==="#")break;s+=1,o=i}return s}get strValue(){if(!this.valueRange||!this.context)return null;let{start:e,end:n}=this.valueRange;const{src:r}=this.context;let o=r[n-1];for(;e<n&&(o===`
229
- `||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=e;a<n;++a){const c=r[a];if(c===`
230
- `){const{fold:u,offset:l}=F.foldNewline(r,a,-1);s+=u,a=l}else if(c===" "||c===" "){const u=a;let l=r[a+1];for(;a<n&&(l===" "||l===" ");)a+=1,l=r[a+1];l!==`
231
- `&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[e];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new ee(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new ee(this,a)],str:s}}default:return s}}parseBlockValue(e){const{indent:n,inFlow:r,src:o}=this.context;let s=e,i=e;for(let a=o[s];a===`
232
- `&&!F.atDocumentBoundary(o,s+1);a=o[s]){const c=F.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
233
- `?s=c:(i=Su.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=e),this.valueRange.end=i,i}parse(e,n){this.context=e;const{inFlow:r,src:o}=e;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
234
- `&&(s=Su.endOfLine(o,n,r)),this.valueRange=new Ee(n,s),s=F.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}};class ps extends F{constructor(){super(P.BLANK_LINE)}get includesTrailingLines(){return!0}parse(e,n){return this.context=e,this.range=new Ee(n,n+1),n+1}}let Md=class extends F{constructor(e,n){super(e,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let{atLineStart:s,lineStart:i}=e;!s&&this.type===P.SEQ_ITEM&&(this.error=new ee(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:e.indent;let c=F.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",d=[];let f=null;for(;u===`
235
- `||u==="#";){if(u==="#"){const p=F.endOfLine(o,c+1);d.push(new Ee(c,p)),c=p}else{s=!0,i=c+1;const p=F.endOfWhiteSpace(o,i);o[p]===`
236
- `&&d.length===0&&(f=new ps,i=f.parse({src:o},i)),c=F.endOfIndent(o,i)}u=o[c]}if(F.nextNodeIsIndented(u,c-(i+a),this.type!==P.SEQ_ITEM)?this.node=r({atLineStart:s,inCollection:!1,indent:a,lineStart:i,parent:this},c):u&&i>n+1&&(c=i-1),this.node){if(f){const p=e.parent.items||e.parent.contents;p&&p.push(f)}d.length&&Array.prototype.push.apply(this.props,d),c=this.node.range.end}else if(l){const p=d[0];this.props.push(p),c=p.end}else c=F.endOfLine(o,n+1);const g=this.node?this.node.valueRange.end:c;return this.valueRange=new Ee(n,g),c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.node?this.node.setOrigRanges(e,n):n}toString(){const{context:{src:e},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?e.slice(r.start,n.range.start)+String(n):e.slice(r.start,r.end);return F.addStringTerminator(e,r.end,s)}},Wo=class extends F{constructor(){super(P.COMMENT)}parse(e,n){this.context=e;const r=this.parseComment(n);return this.range=new Ee(n,r),r}};function _u(t){let e=t;for(;e instanceof Md;)e=e.node;if(!(e instanceof Uv))return null;const n=e.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=e.items[i];if(a.type===P.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===P.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=e.items.splice(r,n-r),s=o[0].range.start;for(;e.range.end=s,e.valueRange&&e.valueRange.end>s&&(e.valueRange.end=s),e!==t;)e=e.context.parent;return o}let Uv=class Nu extends F{static nextContentHasIndent(e,n,r){const o=F.endOfLine(e,n)+1;n=F.endOfWhiteSpace(e,o);const s=e[n];return s?n>=o+r?!0:s!=="#"&&s!==`
237
- `?!1:Nu.nextContentHasIndent(e,n,r):!1}constructor(e){super(e.type===P.SEQ_ITEM?P.SEQ:P.MAP);for(let r=e.props.length-1;r>=0;--r)if(e.props[r].start<e.context.lineStart){this.props=e.props.slice(0,r+1),e.props=e.props.slice(r+1);const o=e.props[0]||e.valueRange;e.range.start=o.start;break}this.items=[e];const n=_u(e);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let s=F.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=Ee.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=F.normalizeOffset(o,c);let u=o[c],l=F.endOfWhiteSpace(o,s)===c,d=!1;for(;u;){for(;u===`
238
- `||u==="#";){if(l&&u===`
239
- `&&!d){const p=new ps;if(c=p.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(p),c-=1}else if(u==="#"){if(c<s+a&&!Nu.nextContentHasIndent(o,c,a))return c;const p=new Wo;if(c=p.parse({indent:a,lineStart:s,src:o},c),this.items.push(p),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=F.endOfIndent(o,s),F.atBlank(o,c)){const p=F.endOfWhiteSpace(o,c),y=o[p];(!y||y===`
240
- `||y==="#")&&(c=p)}u=o[c],l=!0}if(!u)break;if(c!==s+a&&(l||u!==":")){if(c<s+a){s>n&&(c=s);break}else if(!this.error){const p="All collection items must start at the same column";this.error=new qe(this,p)}}if(i.type===P.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const p=o[c+1];if(!p||p===`
241
- `||p===" "||p===" "){const y="A collection cannot be both a mapping and a sequence";this.error=new qe(this,y)}}const f=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!f)return c;if(this.items.push(f),this.valueRange.end=f.valueRange.end,c=F.normalizeOffset(o,f.range.end),u=o[c],l=!1,d=f.includesTrailingLines,u){let p=c-1,y=o[p];for(;y===" "||y===" ";)y=o[--p];y===`
242
- `&&(s=p+1,l=!0)}const g=_u(f);g&&Array.prototype.push.apply(this.items,g)}return c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.items.forEach(r=>{n=r.setOrigRanges(e,n)}),n}toString(){const{context:{src:e},items:n,range:r,value:o}=this;if(o!=null)return o;let s=e.slice(r.start,n[0].range.start)+String(n[0]);for(let i=1;i<n.length;++i){const a=n[i],{atLineStart:c,indent:u}=a.context;if(c)for(let l=0;l<u;++l)s+=" ";s+=String(a)}return F.addStringTerminator(e,r.end,s)}};class Mx extends F{constructor(){super(P.DIRECTIVE),this.name=null}get parameters(){const e=this.rawValue;return e?e.trim().split(/[ \t]+/):[]}parseName(e){const{src:n}=this.context;let r=e,o=n[r];for(;o&&o!==`
243
- `&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(e,r),r}parseParameters(e){const{src:n}=this.context;let r=e,o=n[r];for(;o&&o!==`
244
- `&&o!=="#";)o=n[r+=1];return this.valueRange=new Ee(e,r),r}parse(e,n){this.context=e;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new Ee(n,r),r}}let Lx=class Ou extends F{static startCommentOrEndBlankLine(e,n){const r=F.endOfWhiteSpace(e,n),o=e[r];return o==="#"||o===`
245
- `?r:n}constructor(){super(P.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(e){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=e;for(;!F.atDocumentBoundary(n,s,je.DIRECTIVES_END);)switch(s=Ou.startCommentOrEndBlankLine(n,s),n[s]){case`
246
- `:if(r){const i=new ps;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new Wo;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new Mx;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new ee(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new Ee(s,s+3),s+3):(o?this.error=new ee(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(e){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=e;for(;r[o-1]==="-";)o-=1;let s=F.endOfWhiteSpace(r,e),i=o===e;for(this.valueRange=new Ee(s);!F.atDocumentBoundary(r,s,je.DOCUMENT_END);){switch(r[s]){case`
247
- `:if(i){const a=new ps;s=a.parse({src:r},s),s<r.length&&this.contents.push(a)}else s+=1,i=!0;o=s;break;case"#":{const a=new Wo;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=F.endOfIndent(r,s),c=n({atLineStart:i,indent:-1,inFlow:!1,inCollection:!1,lineStart:o,parent:this},a);if(!c)return this.valueRange.end=a;this.contents.push(c),s=c.range.end,i=!1;const u=_u(c);u&&Array.prototype.push.apply(this.contents,u)}}s=Ou.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new Ee(s,s+3),s+=3,r[s])){if(s=F.endOfWhiteSpace(r,s),r[s]==="#"){const a=new Wo;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
248
- `:s+=1;break;case void 0:break;default:this.error=new qe(this,"Document end marker line cannot have a non-comment suffix")}}return s}parse(e,n){e.root=this,this.context=e;const{src:r}=e;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.directives.forEach(r=>{n=r.setOrigRanges(e,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(e,n)),this.contents.forEach(r=>{n=r.setOrigRanges(e,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(e,n)),n}toString(){const{contents:e,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return e.length>0&&((n.length>0||e[0].type===P.COMMENT)&&(o+=`---
249
- `),o+=e.join("")),o[o.length-1]!==`
250
- `&&(o+=`
251
- `),o}},Dx=class extends F{parse(t,e){this.context=t;const{src:n}=t;let r=F.endOfIdentifier(n,e+1);return this.valueRange=new Ee(e+1,r),r=F.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const ln={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class Ux extends F{constructor(e,n){super(e,n),this.blockIndent=null,this.chomping=ln.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===ln.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:e,end:n}=this.valueRange;const{indent:r,src:o}=this.context;if(this.valueRange.isEmpty())return"";let s=null,i=o[n-1];for(;i===`
252
- `||i===" "||i===" ";){if(n-=1,n<=e){if(this.chomping===ln.KEEP)break;return""}i===`
253
- `&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===ln.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===P.BLOCK_FOLDED;let l=!0,d="",f="",g=!1;for(let p=e;p<n;++p){for(let w=0;w<c&&o[p]===" ";++w)p+=1;const y=o[p];if(y===`
254
- `)f===`
255
- `?d+=`
256
- `:f=`
257
- `;else{const w=F.endOfLine(o,p),h=o.slice(p,w);p=w,u&&(y===" "||y===" ")&&p<a?(f===" "?f=`
258
- `:!g&&!l&&f===`
259
- `&&(f=`
44
+ `}function Ku(e){return`event: error
45
+ data: ${e}
260
46
 
261
- `),d+=f+h,f=w<n&&o[w]||"",g=!0):(d+=f+h,f=u&&p<a?" ":`
262
- `,g=!1),l&&h!==""&&(l=!1)}}return this.chomping===ln.STRIP?d:d+`
263
- `}parseBlockHeader(e){const{src:n}=this.context;let r=e+1,o="";for(;;){const s=n[r];switch(s){case"-":this.chomping=ln.STRIP;break;case"+":this.chomping=ln.KEEP;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":o+=s;break;default:return this.blockIndent=Number(o)||null,this.header=new Ee(e,r),r}r+=1}}parseBlockValue(e){const{indent:n,src:r}=this.context,o=!!this.blockIndent;let s=e,i=e,a=1;for(let c=r[s];c===`
264
- `&&(s+=1,!F.atDocumentBoundary(r,s));c=r[s]){const u=F.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],d=u-(s+n);if(this.blockIndent){if(l&&l!==`
265
- `&&d<this.blockIndent){if(r[u]==="#")break;if(!this.error){const f=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new ee(this,f)}}}else if(r[u]!==`
266
- `){if(d<a){const f="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new ee(this,f)}this.blockIndent=d}else d>a&&(a=d);r[u]===`
267
- `?s=u:s=i=F.endOfLine(r,u)}return this.chomping!==ln.KEEP&&(s=r[i]?i+1:i),this.valueRange=new Ee(e+1,s),s}parse(e,n){this.context=e;const{src:r}=e;let o=this.parseBlockHeader(n);return o=F.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.header?this.header.setOrigRange(e,n):n}}class Bx extends F{constructor(e,n){super(e,n),this.items=null}prevNodeIsJsonLike(e=this.items.length){const n=this.items[e-1];return!!n&&(n.jsonLike||n.type===P.COMMENT&&this.prevNodeIsJsonLike(e-1))}parse(e,n){this.context=e;const{parseNode:r,src:o}=e;let{indent:s,lineStart:i}=e,a=o[n];this.items=[{char:a,offset:n}];let c=F.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
268
- `:{i=c+1;const u=F.endOfWhiteSpace(o,i);if(o[u]===`
269
- `){const l=new ps;i=l.parse({src:o},i),this.items.push(l)}if(c=F.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new ee(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new Wo;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
270
- `||u===" "||u===" "||u===","||a===":"&&this.prevNodeIsJsonLike()){this.items.push({char:a,offset:c}),c+=1;break}}default:{const u=r({atLineStart:!1,inCollection:!1,inFlow:!0,indent:-1,lineStart:i,parent:this},c);if(!u)return this.valueRange=new Ee(n,c),c;this.items.push(u),c=F.normalizeOffset(o,u.range.end)}}c=F.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new Ee(n,c+1),a&&(this.items.push({char:a,offset:c}),c=F.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(e,n){return n=super.setOrigRanges(e,n),this.items.forEach(r=>{if(r instanceof F)n=r.setOrigRanges(e,n);else if(e.length===0)r.origOffset=r.offset;else{let o=n;for(;o<e.length&&!(e[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:e},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof F);let i="",a=r.start;return s.forEach(c=>{const u=e.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
271
- `&&e[a-1]!==`
272
- `&&e[a]===`
273
- `&&(a+=1)}),i+=e.slice(a,r.end),F.addStringTerminator(e,r.end,i)}}let Fx=class Bv extends F{static endOfQuote(e,n){let r=e[n];for(;r&&r!=='"';)n+=r==="\\"?2:1,r=e[n];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const e=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=='"'&&e.push(new qe(this,'Missing closing "quote'));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
274
- `){F.atDocumentBoundary(s,a+1)&&e.push(new ee(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:d}=F.foldNewline(s,a,o);i+=u,a=l,d&&e.push(new ee(this,"Multi-line double-quoted string needs to be sufficiently indented"))}else if(c==="\\")switch(a+=1,s[a]){case"0":i+="\0";break;case"a":i+="\x07";break;case"b":i+="\b";break;case"e":i+="\x1B";break;case"f":i+="\f";break;case"n":i+=`
275
- `;break;case"r":i+="\r";break;case"t":i+=" ";break;case"v":i+="\v";break;case"N":i+="…";break;case"_":i+=" ";break;case"L":i+="\u2028";break;case"P":i+="\u2029";break;case" ":i+=" ";break;case'"':i+='"';break;case"/":i+="/";break;case"\\":i+="\\";break;case" ":i+=" ";break;case"x":i+=this.parseCharCode(a+1,2,e),a+=2;break;case"u":i+=this.parseCharCode(a+1,4,e),a+=4;break;case"U":i+=this.parseCharCode(a+1,8,e),a+=8;break;case`
276
- `:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:e.push(new qe(this,`Invalid escape sequence ${s.substr(a-1,2)}`)),i+="\\"+s[a]}else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
277
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return e.length>0?{errors:e,str:i}:i}parseCharCode(e,n,r){const{src:o}=this.context,s=o.substr(e,n),i=s.length===n&&/^[0-9a-fA-F]+$/.test(s)?parseInt(s,16):NaN;return isNaN(i)?(r.push(new qe(this,`Invalid escape sequence ${o.substr(e-2,n+2)}`)),o.substr(e-2,n+2)):String.fromCodePoint(i)}parse(e,n){this.context=e;const{src:r}=e;let o=Bv.endOfQuote(r,n+1);return this.valueRange=new Ee(n,o),o=F.endOfWhiteSpace(r,o),o=this.parseComment(o),o}};class Ld extends F{static endOfQuote(e,n){let r=e[n];for(;r;)if(r==="'"){if(e[n+1]!=="'")break;r=e[n+=2]}else r=e[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const e=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&e.push(new qe(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
278
- `){F.atDocumentBoundary(s,a+1)&&e.push(new ee(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:d}=F.foldNewline(s,a,o);i+=u,a=l,d&&e.push(new ee(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&e.push(new qe(this,"Unescaped single quote? This should not happen."));else if(c===" "||c===" "){const u=a;let l=s[a+1];for(;l===" "||l===" ";)a+=1,l=s[a+1];l!==`
279
- `&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return e.length>0?{errors:e,str:i}:i}parse(e,n){this.context=e;const{src:r}=e;let o=Ld.endOfQuote(r,n+1);return this.valueRange=new Ee(n,o),o=F.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}function qx(t,e){switch(t){case P.ALIAS:return new Dx(t,e);case P.BLOCK_FOLDED:case P.BLOCK_LITERAL:return new Ux(t,e);case P.FLOW_MAP:case P.FLOW_SEQ:return new Bx(t,e);case P.MAP_KEY:case P.MAP_VALUE:case P.SEQ_ITEM:return new Md(t,e);case P.COMMENT:case P.PLAIN:return new Dv(t,e);case P.QUOTE_DOUBLE:return new Fx(t,e);case P.QUOTE_SINGLE:return new Ld(t,e);default:return null}}let Kx=class Oi{static parseType(e,n,r){switch(e[n]){case"*":return P.ALIAS;case">":return P.BLOCK_FOLDED;case"|":return P.BLOCK_LITERAL;case"{":return P.FLOW_MAP;case"[":return P.FLOW_SEQ;case"?":return!r&&F.atBlank(e,n+1,!0)?P.MAP_KEY:P.PLAIN;case":":return!r&&F.atBlank(e,n+1,!0)?P.MAP_VALUE:P.PLAIN;case"-":return!r&&F.atBlank(e,n+1,!0)?P.SEQ_ITEM:P.PLAIN;case'"':return P.QUOTE_DOUBLE;case"'":return P.QUOTE_SINGLE;default:return P.PLAIN}}constructor(e={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){We(this,"parseNode",(c,u)=>{if(F.atDocumentBoundary(this.src,u))return null;const l=new Oi(this,c),{props:d,type:f,valueStart:g}=l.parseProps(u),p=qx(f,d);let y=u;try{y=p.parse(l,g)}catch(w){const h=w instanceof Error?w.message:String(w);p.error||(p.error=new qe(p,h))}if(p.range=new Ee(u,y),y<=u&&(p.error||(p.error=new Error("Node#parse consumed no characters")),p.error.parseEnd=y,p.error.source=p,p.range.end=u+1),l.nodeStartsCollection(p)){!p.error&&!l.atLineStart&&l.parent.type===P.DOCUMENT&&(p.error=new qe(p,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const w=new Uv(p);return y=w.parse(new Oi(l),y),w.range=new Ee(u,y),w}return p}),this.atLineStart=n??(e.atLineStart||!1),this.inCollection=r??(e.inCollection||!1),this.inFlow=o??(e.inFlow||!1),this.indent=s??e.indent,this.lineStart=i??e.lineStart,this.parent=a??(e.parent||{}),this.root=e.root,this.src=e.src}nodeStartsCollection(e){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(e instanceof Md)return!0;let s=e.range.end;return o[s]===`
280
- `||o[s-1]===`
281
- `?!1:(s=F.endOfWhiteSpace(o,s),o[s]===":")}parseProps(e){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;e=this.atLineStart?F.endOfIndent(o,e):F.endOfWhiteSpace(o,e);let a=o[e];for(;a===je.ANCHOR||a===je.COMMENT||a===je.TAG||a===`
282
- `;){if(a===`
283
- `){let u=e,l;do l=u+1,u=F.endOfIndent(o,l);while(o[u]===`
284
- `);const d=u-(l+this.indent),f=r.type===P.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!F.nextNodeIsIndented(o[u],d,!f))break;this.atLineStart=!0,this.lineStart=l,i=!1,e=u}else if(a===je.COMMENT){const u=F.endOfLine(o,e+1);s.push(new Ee(e,u)),e=u}else{let u=F.endOfIdentifier(o,e+1);a===je.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(e+1,u+13))&&(u=F.endOfIdentifier(o,u+5)),s.push(new Ee(e,u)),i=!0,e=F.endOfWhiteSpace(o,u)}a=o[e]}i&&a===":"&&F.atBlank(o,e+1,!0)&&(e-=1);const c=Oi.parseType(o,e,n);return{props:s,type:c,valueStart:e}}};function Dd(t){const e=[];t.indexOf("\r")!==-1&&(t=t.replace(/\r\n?/g,(o,s)=>(o.length>1&&e.push(s),`
285
- `)));const n=[];let r=0;do{const o=new Lx,s=new Kx({src:t});r=o.parse(s,r),n.push(o)}while(r<t.length);return n.setOrigRanges=()=>{if(e.length===0)return!1;for(let s=1;s<e.length;++s)e[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(e,o);return e.splice(0,e.length),!0},n.toString=()=>n.join(`...
286
- `),n}function Vx(t,e,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${e}#`)}
287
- ${e}${t}`:t}function Vr(t,e,n){return n?n.indexOf(`
288
- `)===-1?`${t} #${n}`:`${t}
289
- `+n.replace(/^/gm,`${e||""}#`):t}let rt=class{};function Ot(t,e,n){if(Array.isArray(t))return t.map((r,o)=>Ot(r,String(o),n));if(t&&typeof t.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(t);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=t.toJSON(e,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof t=="bigint"?Number(t):t}let ge=class extends rt{constructor(e){super(),this.value=e}toJSON(e,n){return n&&n.keep?this.value:Ot(this.value,e,n)}toString(){return String(this.value)}};function tm(t,e,n){let r=n;for(let o=e.length-1;o>=0;--o){const s=e[o];if(Number.isInteger(s)&&s>=0){const i=[];i[s]=r,r=i}else{const i={};Object.defineProperty(i,s,{value:r,writable:!0,enumerable:!0,configurable:!0}),r=i}}return t.createNode(r,!1)}const Po=t=>t==null||typeof t=="object"&&t[Symbol.iterator]().next().done;let Be=class Yn extends rt{constructor(e){super(),We(this,"items",[]),this.schema=e}addIn(e,n){if(Po(e))this.add(n);else{const[r,...o]=e,s=this.get(r,!0);if(s instanceof Yn)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,tm(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([e,...n]){if(n.length===0)return this.delete(e);const r=this.get(e,!0);if(r instanceof Yn)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${e}. Remaining path: ${n}`)}getIn([e,...n],r){const o=this.get(e,!0);return n.length===0?!r&&o instanceof ge?o.value:o:o instanceof Yn?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(e=>{if(!e||e.type!=="PAIR")return!1;const n=e.value;return n==null||n instanceof ge&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([e,...n]){if(n.length===0)return this.has(e);const r=this.get(e,!0);return r instanceof Yn?r.hasIn(n):!1}setIn([e,...n],r){if(n.length===0)this.set(e,r);else{const o=this.get(e,!0);if(o instanceof Yn)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(e,tm(this.schema,n,r));else throw new Error(`Expected YAML collection at ${e}. Remaining path: ${n}`)}}toJSON(){return null}toString(e,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=e,d=this.type===P.FLOW_MAP||this.type===P.FLOW_SEQ||e.inFlow;d&&(s+=u);const f=o&&this.hasAllNullValues();e=Object.assign({},e,{allNullValues:f,indent:s,inFlow:d,type:null});let g=!1,p=!1;const y=this.items.reduce((h,v,b)=>{let E;v&&(!g&&v.spaceBefore&&h.push({type:"comment",str:""}),v.commentBefore&&v.commentBefore.match(/^.*$/gm).forEach(j=>{h.push({type:"comment",str:`#${j}`})}),v.comment&&(E=v.comment),d&&(!g&&v.spaceBefore||v.commentBefore||v.comment||v.key&&(v.key.commentBefore||v.key.comment)||v.value&&(v.value.commentBefore||v.value.comment))&&(p=!0)),g=!1;let N=l(v,e,()=>E=null,()=>g=!0);return d&&!p&&N.includes(`
290
- `)&&(p=!0),d&&b<this.items.length-1&&(N+=","),N=Vr(N,s,E),g&&(E||d)&&(g=!1),h.push({type:"item",str:N}),h},[]);let w;if(y.length===0)w=r.start+r.end;else if(d){const{start:h,end:v}=r,b=y.map(E=>E.str);if(p||b.reduce((E,N)=>E+N.length+2,2)>Yn.maxFlowStringSingleLineLength){w=h;for(const E of b)w+=E?`
291
- ${u}${c}${E}`:`
292
- `;w+=`
293
- ${c}${v}`}else w=`${h} ${b.join(" ")} ${v}`}else{const h=y.map(n);w=h.shift();for(const v of h)w+=v?`
294
- ${c}${v}`:`
295
- `}return this.comment?(w+=`
296
- `+this.comment.replace(/^/gm,`${c}#`),i&&i()):g&&a&&a(),w}};We(Be,"maxFlowStringSingleLineLength",60);function Js(t){let e=t instanceof ge?t.value:t;return e&&typeof e=="string"&&(e=Number(e)),Number.isInteger(e)&&e>=0?e:null}let Ut=class extends Be{add(e){this.items.push(e)}delete(e){const n=Js(e);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(e,n){const r=Js(e);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof ge?o.value:o}has(e){const n=Js(e);return typeof n=="number"&&n<this.items.length}set(e,n){const r=Js(e);if(typeof r!="number")throw new Error(`Expected a valid index, not ${e}.`);this.items[r]=n}toJSON(e,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(Ot(s,String(o++),n));return r}toString(e,n,r){return e?super.toString(e,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(e.indent||"")+" "},n,r):JSON.stringify(this)}};const Gx=(t,e,n)=>e===null?"":typeof e!="object"?String(e):t instanceof rt&&n&&n.doc?t.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(e);let de=class Fv extends rt{constructor(e,n=null){super(),this.key=e,this.value=n,this.type=Fv.Type.PAIR}get commentBefore(){return this.key instanceof rt?this.key.commentBefore:void 0}set commentBefore(e){if(this.key==null&&(this.key=new ge(null)),this.key instanceof rt)this.key.commentBefore=e;else{const n="Pair.commentBefore is an alias for Pair.key.commentBefore. To set it, the key must be a Node.";throw new Error(n)}}addToJSMap(e,n){const r=Ot(this.key,"",e);if(n instanceof Map){const o=Ot(this.value,r,e);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=Gx(this.key,r,e),s=Ot(this.value,o,e);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(e,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(e,n,r){if(!e||!e.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=e.doc.options;let{key:a,value:c}=this,u=a instanceof rt&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof Be){const N="With simple keys, collection cannot be used as a key value";throw new Error(N)}}let l=!i&&(!a||u||(a instanceof rt?a instanceof Be||a.type===P.BLOCK_FOLDED||a.type===P.BLOCK_LITERAL:typeof a=="object"));const{doc:d,indent:f,indentStep:g,stringify:p}=e;e=Object.assign({},e,{implicitKey:!l,indent:f+g});let y=!1,w=p(a,e,()=>u=null,()=>y=!0);if(w=Vr(w,e.indent,u),!l&&w.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(e.allNullValues&&!i)return this.comment?(w=Vr(w,e.indent,this.comment),n&&n()):y&&!u&&r&&r(),e.inFlow&&!l?w:`? ${w}`;w=l?`? ${w}
297
- ${f}:`:`${w}:`,this.comment&&(w=Vr(w,e.indent,this.comment),n&&n());let h="",v=null;if(c instanceof rt){if(c.spaceBefore&&(h=`
298
- `),c.commentBefore){const N=c.commentBefore.replace(/^/gm,`${e.indent}#`);h+=`
299
- ${N}`}v=c.comment}else c&&typeof c=="object"&&(c=d.schema.createNode(c,!0));e.implicitKey=!1,!l&&!this.comment&&c instanceof ge&&(e.indentAtStart=w.length+1),y=!1,!s&&o>=2&&!e.inFlow&&!l&&c instanceof Ut&&c.type!==P.FLOW_SEQ&&!c.tag&&!d.anchors.getName(c)&&(e.indent=e.indent.substr(2));const b=p(c,e,()=>v=null,()=>y=!0);let E=" ";return h||this.comment?E=`${h}
300
- ${e.indent}`:!l&&c instanceof Be?(!(b[0]==="["||b[0]==="{")||b.includes(`
301
- `))&&(E=`
302
- ${e.indent}`):b[0]===`
303
- `&&(E=""),y&&!v&&r&&r(),Vr(w+E+b,e.indent,v)}};We(de,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const ki=(t,e)=>{if(t instanceof rn){const n=e.get(t.source);return n.count*n.aliasCount}else if(t instanceof Be){let n=0;for(const r of t.items){const o=ki(r,e);o>n&&(n=o)}return n}else if(t instanceof de){const n=ki(t.key,e),r=ki(t.value,e);return Math.max(n,r)}return 1};let rn=class qv extends rt{static stringify({range:e,source:n},{anchors:r,doc:o,implicitKey:s,inStringifyKey:i}){let a=Object.keys(r).find(u=>r[u]===n);if(!a&&i&&(a=o.anchors.getName(n)||o.anchors.newName()),a)return`*${a}${s?" ":""}`;const c=o.anchors.getName(n)?"Alias node must be after source node":"Source node not found for alias node";throw new Error(`${c} [${e}]`)}constructor(e){super(),this.source=e,this.type=P.ALIAS}set tag(e){throw new Error("Alias nodes cannot have tags")}toJSON(e,n){if(!n)return Ot(this.source,e,n);const{anchors:r,maxAliasCount:o}=n,s=r.get(this.source);if(!s||s.res===void 0){const i="This should not happen: Alias anchor was not resolved?";throw this.cstNode?new fs(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ki(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new fs(this.cstNode,i):new ReferenceError(i)}return s.res}toString(e){return qv.stringify(this,e)}};We(rn,"default",!0);function cr(t,e){const n=e instanceof ge?e.value:e;for(const r of t)if(r instanceof de&&(r.key===e||r.key===n||r.key&&r.key.value===n))return r}let it=class extends Be{add(e,n){e?e instanceof de||(e=new de(e.key||e,e.value)):e=new de(e);const r=cr(this.items,e.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=e.value;else throw new Error(`Key ${e.key} already set`);else if(o){const s=this.items.findIndex(i=>o(e,i)<0);s===-1?this.items.push(e):this.items.splice(s,0,e)}else this.items.push(e)}delete(e){const n=cr(this.items,e);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(e,n){const r=cr(this.items,e),o=r&&r.value;return!n&&o instanceof ge?o.value:o}has(e){return!!cr(this.items,e)}set(e,n){this.add(new de(e,n),!0)}toJSON(e,n,r){const o=r?new r:n&&n.mapAsMap?new Map:{};n&&n.onCreate&&n.onCreate(o);for(const s of this.items)s.addToJSMap(n,o);return o}toString(e,n,r){if(!e)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof de))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(e,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:e.indent||""},n,r)}};const Kv="<<";class Vv extends de{constructor(e){if(e instanceof de){let n=e.value;n instanceof Ut||(n=new Ut,n.items.push(e.value),n.range=e.value.range),super(e.key,n),this.range=e.range}else super(new ge(Kv),new Ut);this.type=de.Type.MERGE_PAIR}addToJSMap(e,n){for(const{source:r}of this.value.items){if(!(r instanceof it))throw new Error("Merge sources must be maps");const o=r.toJSON(null,e,Map);for(const[s,i]of o)n instanceof Map?n.has(s)||n.set(s,i):n instanceof Set?n.add(s):Object.prototype.hasOwnProperty.call(n,s)||Object.defineProperty(n,s,{value:i,writable:!0,enumerable:!0,configurable:!0})}return n}toString(e,n){const r=this.value;if(r.items.length>1)return super.toString(e,n);this.value=r.items[0];const o=super.toString(e,n);return this.value=r,o}}const Ho={defaultType:P.BLOCK_LITERAL,lineWidth:76},Yt={trueStr:"true",falseStr:"false"},On={asBigInt:!1},ro={nullStr:"null"},on={defaultType:P.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function Ud(t,e,n){for(const{format:r,test:o,resolve:s}of e)if(o){const i=t.match(o);if(i){let a=s.apply(null,i);return a instanceof ge||(a=new ge(a)),r&&(a.format=r),a}}return n&&(t=n(t)),new ge(t)}const Gv="flow",ku="block",ji="quoted",nm=(t,e)=>{let n=t[e+1];for(;n===" "||n===" ";){do n=t[e+=1];while(n&&n!==`
304
- `);n=t[e+1]}return e};function Aa(t,e,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return t;const c=Math.max(1+s,1+o-e.length);if(t.length<=c)return t;const u=[],l={};let d=o-e.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):d=o-r);let f,g,p=!1,y=-1,w=-1,h=-1;n===ku&&(y=nm(t,y),y!==-1&&(d=y+c));for(let b;b=t[y+=1];){if(n===ji&&b==="\\"){switch(w=y,t[y+1]){case"x":y+=3;break;case"u":y+=5;break;case"U":y+=9;break;default:y+=1}h=y}if(b===`
305
- `)n===ku&&(y=nm(t,y)),d=y+c,f=void 0;else{if(b===" "&&g&&g!==" "&&g!==`
306
- `&&g!==" "){const E=t[y+1];E&&E!==" "&&E!==`
307
- `&&E!==" "&&(f=y)}if(y>=d)if(f)u.push(f),d=f+c,f=void 0;else if(n===ji){for(;g===" "||g===" ";)g=b,b=t[y+=1],p=!0;const E=y>h+1?y-2:w-1;if(l[E])return t;u.push(E),l[E]=!0,d=E+c,f=void 0}else p=!0}g=b}if(p&&a&&a(),u.length===0)return t;i&&i();let v=t.slice(0,u[0]);for(let b=0;b<u.length;++b){const E=u[b],N=u[b+1]||t.length;E===0?v=`
308
- ${e}${t.slice(0,N)}`:(n===ji&&l[E]&&(v+=`${t[E]}\\`),v+=`
309
- ${e}${t.slice(E+1,N)}`)}return v}const Bd=({indentAtStart:t})=>t?Object.assign({indentAtStart:t},on.fold):on.fold,Ia=t=>/^(%|---|\.\.\.)/m.test(t);function zx(t,e,n){if(!e||e<0)return!1;const r=e-n,o=t.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(t[s]===`
310
- `){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function fr(t,e){const{implicitKey:n}=e,{jsonEncoding:r,minMultiLineLength:o}=on.doubleQuoted,s=JSON.stringify(t);if(r)return s;const i=e.indent||(Ia(t)?" ":"");let a="",c=0;for(let u=0,l=s[u];l;l=s[++u])if(l===" "&&s[u+1]==="\\"&&s[u+2]==="n"&&(a+=s.slice(c,u)+"\\ ",u+=1,c=u,l="\\"),l==="\\")switch(s[u+1]){case"u":{a+=s.slice(c,u);const d=s.substr(u+2,4);switch(d){case"0000":a+="\\0";break;case"0007":a+="\\a";break;case"000b":a+="\\v";break;case"001b":a+="\\e";break;case"0085":a+="\\N";break;case"00a0":a+="\\_";break;case"2028":a+="\\L";break;case"2029":a+="\\P";break;default:d.substr(0,2)==="00"?a+="\\x"+d.substr(2):a+=s.substr(u,6)}u+=5,c=u+1}break;case"n":if(n||s[u+2]==='"'||s.length<o)u+=1;else{for(a+=s.slice(c,u)+`
311
-
312
- `;s[u+2]==="\\"&&s[u+3]==="n"&&s[u+4]!=='"';)a+=`
313
- `,u+=2;a+=i,s[u+2]===" "&&(a+="\\"),u+=1,c=u+1}break;default:u+=1}return a=c?a+s.slice(c):s,n?a:Aa(a,i,ji,Bd(e))}function zv(t,e){if(e.implicitKey){if(/\n/.test(t))return fr(t,e)}else if(/[ \t]\n|\n[ \t]/.test(t))return fr(t,e);const n=e.indent||(Ia(t)?" ":""),r="'"+t.replace(/'/g,"''").replace(/\n+/g,`$&
314
- ${n}`)+"'";return e.implicitKey?r:Aa(r,n,Gv,Bd(e))}function Ai({comment:t,type:e,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return fr(n,r);const i=r.indent||(r.forceBlockIndent||Ia(n)?" ":""),a=i?"2":"1",c=e===P.BLOCK_FOLDED?!1:e===P.BLOCK_LITERAL?!0:!zx(n,on.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
315
- `;let l="",d="";if(n=n.replace(/[\n\t ]*$/,g=>{const p=g.indexOf(`
316
- `);return p===-1?u+="-":(n===g||p!==g.length-1)&&(u+="+",s&&s()),d=g.replace(/\n$/,""),""}).replace(/^[\n ]*/,g=>{g.indexOf(" ")!==-1&&(u+=a);const p=g.match(/ +$/);return p?(l=g.slice(0,-p[0].length),p[0]):(l=g,"")}),d&&(d=d.replace(/\n+(?!\n|$)/g,`$&${i}`)),l&&(l=l.replace(/\n+/g,`$&${i}`)),t&&(u+=" #"+t.replace(/ ?[\r\n]+/g," "),o&&o()),!n)return`${u}${a}
317
- ${i}${d}`;if(c)return n=n.replace(/\n+/g,`$&${i}`),`${u}
318
- ${i}${l}${n}${d}`;n=n.replace(/\n+/g,`
319
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const f=Aa(`${l}${n}${d}`,i,ku,on.fold);return`${u}
320
- ${i}${f}`}function Wx(t,e,n,r){const{comment:o,type:s,value:i}=t,{actualString:a,implicitKey:c,indent:u,inFlow:l}=e;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return fr(i,e);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
321
- `)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?zv(i,e):fr(i,e):Ai(t,e,n,r);if(!c&&!l&&s!==P.PLAIN&&i.indexOf(`
322
- `)!==-1)return Ai(t,e,n,r);if(u===""&&Ia(i))return e.forceBlockIndent=!0,Ai(t,e,n,r);const d=i.replace(/\n+/g,`$&
323
- ${u}`);if(a){const{tags:g}=e.doc.schema;if(typeof Ud(d,g,g.scalarFallback).value!="string")return fr(i,e)}const f=c?d:Aa(d,u,Gv,Bd(e));return o&&!l&&(f.indexOf(`
324
- `)!==-1||o.indexOf(`
325
- `)!==-1)?(n&&n(),Vx(f,u,o)):f}function Fd(t,e,n,r){const{defaultType:o}=on,{implicitKey:s,inFlow:i}=e;let{type:a,value:c}=t;typeof c!="string"&&(c=String(c),t=Object.assign({},t,{value:c}));const u=d=>{switch(d){case P.BLOCK_FOLDED:case P.BLOCK_LITERAL:return Ai(t,e,n,r);case P.QUOTE_DOUBLE:return fr(c,e);case P.QUOTE_SINGLE:return zv(c,e);case P.PLAIN:return Wx(t,e,n,r);default:return null}};(a!==P.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===P.BLOCK_FOLDED||a===P.BLOCK_LITERAL))&&(a=P.QUOTE_DOUBLE);let l=u(a);if(l===null&&(l=u(o),l===null))throw new Error(`Unsupported default string type ${o}`);return l}function Zt({format:t,minFractionDigits:e,tag:n,value:r}){if(typeof r=="bigint")return String(r);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=JSON.stringify(r);if(!t&&e&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=e-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function Wv(t,e){let n,r;switch(e.type){case P.FLOW_MAP:n="}",r="flow map";break;case P.FLOW_SEQ:n="]",r="flow sequence";break;default:t.push(new ee(e,"Not a flow collection!?"));return}let o;for(let s=e.items.length-1;s>=0;--s){const i=e.items[s];if(!i||i.type!==P.COMMENT){o=i;break}}if(o&&o.char!==n){const s=`Expected ${r} to end with ${n}`;let i;typeof o.offset=="number"?(i=new ee(e,s),i.offset=o.offset+1):(i=new ee(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),t.push(i)}}function Hv(t,e){const n=e.context.src[e.range.start-1];if(n!==`
326
- `&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";t.push(new ee(e,r))}}function Jv(t,e){const n=String(e),r=n.substr(0,8)+"..."+n.substr(-8);return new ee(t,`The "${r}" key is too long`)}function Qv(t,e){for(const{afterKey:n,before:r,comment:o}of e){let s=t.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
327
- `+o:s.commentBefore=o):o!==void 0&&(t.comment?t.comment+=`
328
- `+o:t.comment=o)}}function Os(t,e){const n=e.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=e),t.errors.push(r)}),n.str):""}function Hx(t,e){const{handle:n,suffix:r}=e.tag;let o=t.tagPrefixes.find(s=>s.handle===n);if(!o){const s=t.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new ee(e,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new ee(e,`The ${n} tag has no suffix.`);if(n==="!"&&(t.version||t.options.version)==="1.0"){if(r[0]==="^")return t.warnings.push(new po(e,"YAML 1.0 ^ tag expansion is not supported")),r;if(/[:/]/.test(r)){const s=r.match(/^([a-z0-9-]+)\/(.*)/i);return s?`tag:${s[1]}.yaml.org,2002:${s[2]}`:`tag:${r}`}}return o.prefix+decodeURIComponent(r)}function Jx(t,e){const{tag:n,type:r}=e;let o=!1;if(n){const{handle:s,suffix:i,verbatim:a}=n;if(a){if(a!=="!"&&a!=="!!")return a;const c=`Verbatim tags aren't resolved, so ${a} is invalid.`;t.errors.push(new ee(e,c))}else if(s==="!"&&!i)o=!0;else try{return Hx(t,e)}catch(c){t.errors.push(c)}}switch(r){case P.BLOCK_FOLDED:case P.BLOCK_LITERAL:case P.QUOTE_DOUBLE:case P.QUOTE_SINGLE:return wn.STR;case P.FLOW_MAP:case P.MAP:return wn.MAP;case P.FLOW_SEQ:case P.SEQ:return wn.SEQ;case P.PLAIN:return o?wn.STR:null;default:return null}}function rm(t,e,n){const{tags:r}=t.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(t,e);return a instanceof Be?a:new ge(a)}const s=Os(t,e);return typeof s=="string"&&o.length>0?Ud(s,o,r.scalarFallback):null}function Qx({type:t}){switch(t){case P.FLOW_MAP:case P.MAP:return wn.MAP;case P.FLOW_SEQ:case P.SEQ:return wn.SEQ;default:return wn.STR}}function Yx(t,e,n){try{const r=rm(t,e,n);if(r)return n&&e.tag&&(r.tag=n),r}catch(r){if(r instanceof wr)r.source||(r.source=e),t.errors.push(r);else{const o=r instanceof Error?r.message:String(r);t.errors.push(new ee(e,o))}return null}try{const r=Qx(e);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;t.warnings.push(new po(e,o));const s=rm(t,e,r);return s.tag=n,s}catch(r){const o=new fs(e,r.message);return o.stack=r.stack,t.errors.push(o),null}}const Zx=t=>{if(!t)return!1;const{type:e}=t;return e===P.MAP_KEY||e===P.MAP_VALUE||e===P.SEQ_ITEM};function Xx(t,e){const n={before:[],after:[]};let r=!1,o=!1;const s=Zx(e.context.parent)?e.context.parent.props.concat(e.props):e.props;for(const{start:i,end:a}of s)switch(e.context.src[i]){case je.COMMENT:{if(!e.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";t.push(new ee(e,l))}const{header:c,valueRange:u}=e;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(e.context.src.slice(i+1,a));break}case je.ANCHOR:if(r){const c="A node can have at most one anchor";t.push(new ee(e,c))}r=!0;break;case je.TAG:if(o){const c="A node can have at most one tag";t.push(new ee(e,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function eR(t,e){const{anchors:n,errors:r,schema:o}=t;if(e.type===P.ALIAS){const i=e.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new fs(e,u)),null}const c=new rn(a);return n._cstAliases.push(c),c}const s=Jx(t,e);if(s)return Yx(t,e,s);if(e.type!==P.PLAIN){const i=`Failed to resolve ${e.type} node here`;return r.push(new qe(e,i)),null}try{const i=Os(t,e);return Ud(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=e),r.push(i),null}}function En(t,e){if(!e)return null;e.error&&t.errors.push(e.error);const{comments:n,hasAnchor:r,hasTag:o}=Xx(t.errors,e);if(r){const{anchors:i}=t,a=e.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=e}if(e.type===P.ALIAS&&(r||o)){const i="An alias node must not specify any properties";t.errors.push(new ee(e,i))}const s=eR(t,e);if(s){s.range=[e.range.start,e.range.end],t.options.keepCstNodes&&(s.cstNode=e),t.options.keepNodeTypes&&(s.type=e.type);const i=n.before.join(`
329
- `);i&&(s.commentBefore=s.commentBefore?`${s.commentBefore}
330
- ${i}`:i);const a=n.after.join(`
331
- `);a&&(s.comment=s.comment?`${s.comment}
332
- ${a}`:a)}return e.resolved=s}function Yv(t,e){if(e.type!==P.MAP&&e.type!==P.FLOW_MAP){const i=`A ${e.type} node cannot be resolved as a mapping`;return t.errors.push(new qe(e,i)),null}const{comments:n,items:r}=e.type===P.FLOW_MAP?oR(t,e):rR(t,e),o=new it;o.items=r,Qv(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof Be&&(s=!0),t.schema.merge&&a&&a.value===Kv){r[i]=new Vv(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof rn){const{type:d}=l.source;return d===P.MAP||d===P.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&t.errors.push(new ee(e,u))}else for(let c=i+1;c<r.length;++c){const{key:u}=r[c];if(a===u||a&&u&&Object.prototype.hasOwnProperty.call(a,"value")&&a.value===u.value){const l=`Map keys must be unique; "${a}" is repeated`;t.errors.push(new ee(e,l));break}}}if(s&&!t.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";t.warnings.push(new po(e,i))}return e.resolved=o,o}const tR=({context:{lineStart:t,node:e,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(e&&o>e.valueRange.start||n[o]!==je.COMMENT)return!1;for(let s=t;s<o;++s)if(n[s]===`
333
- `)return!1;return!0};function nR(t,e){if(!tR(t))return;const n=t.getPropValue(0,je.COMMENT,!0);let r=!1;const o=e.value.commentBefore;if(o&&o.startsWith(n))e.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=e.value.comment;!t.node&&s&&s.startsWith(n)&&(e.value.comment=s.substr(n.length+1),r=!0)}r&&(e.comment=n)}function rR(t,e){const n=[],r=[];let o,s=null;for(let i=0;i<e.items.length;++i){const a=e.items[i];switch(a.type){case P.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case P.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case P.MAP_KEY:o!==void 0&&r.push(new de(o)),a.error&&t.errors.push(a.error),o=En(t,a.node),s=null;break;case P.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&t.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===P.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";t.errors.push(new ee(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new Dv(P.PLAIN,[]),c.context={parent:a,src:a.context.src};const l=a.range.start+1;if(c.range={start:l,end:l},c.valueRange={start:l,end:l},typeof a.range.origStart=="number"){const d=a.range.origStart+1;c.range.origStart=c.range.origEnd=d,c.valueRange.origStart=c.valueRange.origEnd=d}}const u=new de(o,En(t,c));nR(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&t.errors.push(Jv(e,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new de(o)),o=En(t,a),s=a.range.start,a.error&&t.errors.push(a.error);e:for(let c=i+1;;++c){const u=e.items[c];switch(u&&u.type){case P.BLANK_LINE:case P.COMMENT:continue e;case P.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";t.errors.push(new ee(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";t.errors.push(new ee(a,c))}}}return o!==void 0&&r.push(new de(o)),{comments:n,items:r}}function oR(t,e){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<e.items.length;++a){const c=e.items[a];if(typeof c.char=="string"){const{char:u,offset:l}=c;if(u==="?"&&o===void 0&&!s){s=!0,i=":";continue}if(u===":"){if(o===void 0&&(o=null),i===":"){i=",";continue}}else if(s&&(o===void 0&&u!==","&&(o=null),s=!1),o!==void 0&&(r.push(new de(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===e.items.length-1)continue}else if(u===i){i=":";continue}const d=`Flow map contains an unexpected ${u}`,f=new qe(e,d);f.offset=l,t.errors.push(f)}else c.type===P.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===P.COMMENT?(Hv(t.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&t.errors.push(new ee(c,"Separator , missing in flow map")),o=En(t,c)):(i!==","&&t.errors.push(new ee(c,"Indicator : missing in flow map entry")),r.push(new de(o,En(t,c))),o=void 0,s=!1)}return Wv(t.errors,e),o!==void 0&&r.push(new de(o)),{comments:n,items:r}}function Zv(t,e){if(e.type!==P.SEQ&&e.type!==P.FLOW_SEQ){const s=`A ${e.type} node cannot be resolved as a sequence`;return t.errors.push(new qe(e,s)),null}const{comments:n,items:r}=e.type===P.FLOW_SEQ?iR(t,e):sR(t,e),o=new Ut;if(o.items=r,Qv(o,n),!t.options.mapAsMap&&r.some(s=>s instanceof de&&s.key instanceof Be)){const s="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";t.warnings.push(new po(e,s))}return e.resolved=o,o}function sR(t,e){const n=[],r=[];for(let o=0;o<e.items.length;++o){const s=e.items[o];switch(s.type){case P.BLANK_LINE:n.push({before:r.length});break;case P.COMMENT:n.push({comment:s.comment,before:r.length});break;case P.SEQ_ITEM:if(s.error&&t.errors.push(s.error),r.push(En(t,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";t.errors.push(new ee(s,i))}break;default:s.error&&t.errors.push(s.error),t.errors.push(new qe(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function iR(t,e){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<e.items.length;++u){const l=e.items[u];if(typeof l.char=="string"){const{char:d,offset:f}=l;if(d!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new de(s)),o=!1,s=void 0,i=null),d===a)a=null;else if(!a&&d==="?")o=!0;else if(a!=="["&&d===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof de){const g="Chaining flow sequence pairs is invalid",p=new ee(e,g);p.offset=f,t.errors.push(p)}if(!o&&typeof i=="number"){const g=l.range?l.range.start:l.offset;g>i+1024&&t.errors.push(Jv(e,s));const{src:p}=c.context;for(let y=i;y<g;++y)if(p[y]===`
334
- `){const w="Implicit keys of flow sequence pairs need to be on a single line";t.errors.push(new ee(c,w));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||d!=="]"||u<e.items.length-1){const g=`Flow sequence contains an unexpected ${d}`,p=new qe(e,g);p.offset=f,t.errors.push(p)}}else if(l.type===P.BLANK_LINE)n.push({before:r.length});else if(l.type===P.COMMENT)Hv(t.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const f=`Expected a ${a} in flow sequence`;t.errors.push(new ee(l,f))}const d=En(t,l);s===void 0?(r.push(d),c=l):(r.push(new de(s,d)),s=void 0),i=l.range.start,a=","}}return Wv(t.errors,e),s!==void 0&&r.push(new de(s)),{comments:n,items:r}}const Xv={identify:t=>t instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(t,e)=>{const n=Os(t,e);if(typeof Buffer=="function")return Buffer.from(n,"base64");if(typeof atob=="function"){const r=atob(n.replace(/[\n\r]/g,"")),o=new Uint8Array(r.length);for(let s=0;s<r.length;++s)o[s]=r.charCodeAt(s);return o}else{const r="This environment does not support reading binary tags; either Buffer or atob is required";return t.errors.push(new fs(e,r)),null}},options:Ho,stringify:({comment:t,type:e,value:n},r,o,s)=>{let i;if(typeof Buffer=="function")i=n instanceof Buffer?n.toString("base64"):Buffer.from(n.buffer).toString("base64");else if(typeof btoa=="function"){let a="";for(let c=0;c<n.length;++c)a+=String.fromCharCode(n[c]);i=btoa(a)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e||(e=Ho.defaultType),e===P.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=Ho,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,d=0;l<c;++l,d+=a)u[l]=i.substr(d,a);n=u.join(e===P.BLOCK_LITERAL?`
335
- `:" ")}return Fd({comment:t,type:e,value:n},r,o,s)}};function e$(t,e){const n=Zv(t,e);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof de)){if(o instanceof it){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new ee(e,i)}const s=o.items[0]||new de;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
336
- ${s.commentBefore}`:o.commentBefore),o.comment&&(s.comment=s.comment?`${o.comment}
337
- ${s.comment}`:o.comment),o=s}n.items[r]=o instanceof de?o:new de(o)}}return n}function t$(t,e,n){const r=new Ut(t);r.tag="tag:yaml.org,2002:pairs";for(const o of e){let s,i;if(Array.isArray(o))if(o.length===2)s=o[0],i=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){const c=Object.keys(o);if(c.length===1)s=c[0],i=o[s];else throw new TypeError(`Expected { key: value } tuple: ${o}`)}else s=o;const a=t.createPair(s,i,n);r.items.push(a)}return r}const n$={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:e$,createNode:t$};let Pa=class r$ extends Ut{constructor(){super(),We(this,"add",it.prototype.add.bind(this)),We(this,"delete",it.prototype.delete.bind(this)),We(this,"get",it.prototype.get.bind(this)),We(this,"has",it.prototype.has.bind(this)),We(this,"set",it.prototype.set.bind(this)),this.tag=r$.tag}toJSON(e,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof de?(s=Ot(o.key,"",n),i=Ot(o.value,s,n)):s=Ot(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};We(Pa,"tag","tag:yaml.org,2002:omap");function aR(t,e){const n=e$(t,e),r=[];for(const{key:o}of n.items)if(o instanceof ge)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new ee(e,s)}else r.push(o.value);return Object.assign(new Pa,n)}function cR(t,e,n){const r=t$(t,e,n),o=new Pa;return o.items=r.items,o}const o$={identify:t=>t instanceof Map,nodeClass:Pa,default:!1,tag:"tag:yaml.org,2002:omap",resolve:aR,createNode:cR};let xa=class s$ extends it{constructor(){super(),this.tag=s$.tag}add(e){const n=e instanceof de?e:new de(e);cr(this.items,n.key)||this.items.push(n)}get(e,n){const r=cr(this.items,e);return!n&&r instanceof de?r.key instanceof ge?r.key.value:r.key:r}set(e,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=cr(this.items,e);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new de(e))}toJSON(e,n){return super.toJSON(e,n,Set)}toString(e,n,r){if(!e)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(e,n,r);throw new Error("Set items must all have null values")}};We(xa,"tag","tag:yaml.org,2002:set");function uR(t,e){const n=Yv(t,e);if(!n.hasAllNullValues())throw new ee(e,"Set items must all have null values");return Object.assign(new xa,n)}function lR(t,e,n){const r=new xa;for(const o of e)r.items.push(t.createPair(o,null,n));return r}const i$={identify:t=>t instanceof Set,nodeClass:xa,default:!1,tag:"tag:yaml.org,2002:set",resolve:uR,createNode:lR},qd=(t,e)=>{const n=e.split(":").reduce((r,o)=>r*60+Number(o),0);return t==="-"?-n:n},a$=({value:t})=>{if(isNaN(t)||!isFinite(t))return Zt(t);let e="";t<0&&(e="-",t=Math.abs(t));const n=[t%60];return t<60?n.unshift(0):(t=Math.round((t-n[0])/60),n.unshift(t%60),t>=60&&(t=Math.round((t-n[0])/60),n.unshift(t))),e+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},c$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(t,e,n)=>qd(e,n.replace(/_/g,"")),stringify:a$},u$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(t,e,n)=>qd(e,n.replace(/_/g,"")),stringify:a$},l$={identify:t=>t instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^(?:([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?)$"),resolve:(t,e,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(e,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=qd(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:t})=>t.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function d$(t){const e=typeof process<"u"&&process.env||{};return t?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!e.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!e.YAML_SILENCE_WARNINGS}function f$(t,e){if(d$(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(t,e):console.warn(e?`${e}: ${t}`:t)}}const om={};function dR(t,e){if(!om[t]&&d$(!0)){om[t]=!0;let n=`The option '${t}' will be removed in a future release`;n+=`, use '${e}' instead.`,f$(n,"DeprecationWarning")}}function fR(t,e,n){const r=new it(t);if(e instanceof Map)for(const[o,s]of e)r.items.push(t.createPair(o,s,n));else if(e&&typeof e=="object")for(const o of Object.keys(e))r.items.push(t.createPair(o,e[o],n));return typeof t.sortMapEntries=="function"&&r.items.sort(t.sortMapEntries),r}const hs={createNode:fR,default:!0,nodeClass:it,tag:"tag:yaml.org,2002:map",resolve:Yv};function pR(t,e,n){const r=new Ut(t);if(e&&e[Symbol.iterator])for(const o of e){const s=t.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const Ra={createNode:pR,default:!0,nodeClass:Ut,tag:"tag:yaml.org,2002:seq",resolve:Zv},hR={identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Os,stringify(t,e,n,r){return e=Object.assign({actualString:!0},e),Fd(t,e,n,r)},options:on},Kd=[hs,Ra,hR],Ta=t=>typeof t=="bigint"||Number.isInteger(t),Vd=(t,e,n)=>On.asBigInt?BigInt(t):parseInt(e,n);function p$(t,e,n){const{value:r}=t;return Ta(r)&&r>=0?n+r.toString(e):Zt(t)}const h$={identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new ge(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:ro,stringify:()=>ro.nullStr},m$={identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:t=>t[0]==="t"||t[0]==="T",options:Yt,stringify:({value:t})=>t?Yt.trueStr:Yt.falseStr},g$={identify:t=>Ta(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(t,e)=>Vd(t,e,8),options:On,stringify:t=>p$(t,8,"0o")},y$={identify:Ta,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:t=>Vd(t,t,10),options:On,stringify:Zt},w$={identify:t=>Ta(t)&&t>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(t,e)=>Vd(t,e,16),options:On,stringify:t=>p$(t,16,"0x")},v$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(t,e)=>e?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Zt},$$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t),stringify:({value:t})=>Number(t).toExponential()},b$={identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(t,e,n){const r=e||n,o=new ge(parseFloat(t));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:Zt},mR=Kd.concat([h$,m$,g$,y$,w$,v$,$$,b$]),sm=t=>typeof t=="bigint"||Number.isInteger(t),Qs=({value:t})=>JSON.stringify(t),E$=[hs,Ra,{identify:t=>typeof t=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Os,stringify:Qs},{identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new ge(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Qs},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:t=>t==="true",stringify:Qs},{identify:sm,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:t=>On.asBigInt?BigInt(t):parseInt(t,10),stringify:({value:t})=>sm(t)?t.toString():JSON.stringify(t)},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:t=>parseFloat(t),stringify:Qs}];E$.scalarFallback=t=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(t)}`)};const im=({value:t})=>t?Yt.trueStr:Yt.falseStr,xo=t=>typeof t=="bigint"||Number.isInteger(t);function Ys(t,e,n){let r=e.replace(/_/g,"");if(On.asBigInt){switch(n){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}const s=BigInt(r);return t==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return t==="-"?-1*o:o}function hc(t,e,n){const{value:r}=t;if(xo(r)){const o=r.toString(e);return r<0?"-"+n+o.substr(1):n+o}return Zt(t)}const gR=Kd.concat([{identify:t=>t==null,createNode:(t,e,n)=>n.wrapScalars?new ge(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:ro,stringify:()=>ro.nullStr},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:Yt,stringify:im},{identify:t=>typeof t=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/i,resolve:()=>!1,options:Yt,stringify:im},{identify:xo,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(t,e,n)=>Ys(e,n,2),stringify:t=>hc(t,2,"0b")},{identify:xo,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(t,e,n)=>Ys(e,n,8),stringify:t=>hc(t,8,"0")},{identify:xo,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(t,e,n)=>Ys(e,n,10),stringify:Zt},{identify:xo,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(t,e,n)=>Ys(e,n,16),stringify:t=>hc(t,16,"0x")},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(t,e)=>e?NaN:t[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Zt},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:t=>parseFloat(t.replace(/_/g,"")),stringify:({value:t})=>Number(t).toExponential()},{identify:t=>typeof t=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(t,e){const n=new ge(parseFloat(t.replace(/_/g,"")));if(e){const r=e.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:Zt}],Xv,o$,n$,i$,c$,u$,l$),yR={core:mR,failsafe:Kd,json:E$,yaml11:gR},wR={binary:Xv,bool:m$,float:b$,floatExp:$$,floatNaN:v$,floatTime:u$,int:y$,intHex:w$,intOct:g$,intTime:c$,map:hs,null:h$,omap:o$,pairs:n$,seq:Ra,set:i$,timestamp:l$};function vR(t,e,n){if(e){const r=n.filter(s=>s.tag===e),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${e} not found`);return o}return n.find(r=>(r.identify&&r.identify(t)||r.class&&t instanceof r.class)&&!r.format)}function $R(t,e,n){if(t instanceof rt)return t;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;e&&e.startsWith("!!")&&(e=r+e.slice(2));let c=vR(t,e,i.tags);if(!c){if(typeof t.toJSON=="function"&&(t=t.toJSON()),!t||typeof t!="object")return a?new ge(t):t;c=t instanceof Map?hs:t[Symbol.iterator]?Ra:hs}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(t&&typeof t=="object"&&s){const l=s.get(t);if(l){const d=new rn(l);return n.aliasNodes.push(d),d}u.value=t,s.set(t,u)}return u.node=c.createNode?c.createNode(n.schema,t,n):a?new ge(t):t,e&&u.node instanceof rt&&(u.node.tag=e),u.node}function bR(t,e,n,r){let o=t[r.replace(/\W/g,"")];if(!o){const s=Object.keys(t).map(i=>JSON.stringify(i)).join(", ");throw new Error(`Unknown schema "${r}"; use one of ${s}`)}if(Array.isArray(n))for(const s of n)o=o.concat(s);else typeof n=="function"&&(o=n(o.slice()));for(let s=0;s<o.length;++s){const i=o[s];if(typeof i=="string"){const a=e[i];if(!a){const c=Object.keys(e).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const ER=(t,e)=>t.key<e.key?-1:t.key>e.key?1:0;let ms=class S${constructor({customTags:e,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?ER:o||null,!e&&s&&dR("tags","customTags"),this.tags=bR(yR,wR,e||s,r)}createNode(e,n,r,o){const s={defaultPrefix:S$.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return $R(e,r,i)}createPair(e,n,r){r||(r={wrapScalars:!0});const o=this.createNode(e,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new de(o,s)}};We(ms,"defaultPrefix",Ni);We(ms,"defaultTags",wn);const Zi={anchorPrefix:"a",customTags:null,indent:2,indentSeq:!0,keepCstNodes:!1,keepNodeTypes:!0,keepBlobsInJSON:!0,mapAsMap:!1,maxAliasCount:100,prettyErrors:!1,simpleKeys:!1,version:"1.2"},SR={get binary(){return Ho},set binary(t){Object.assign(Ho,t)},get bool(){return Yt},set bool(t){Object.assign(Yt,t)},get int(){return On},set int(t){Object.assign(On,t)},get null(){return ro},set null(t){Object.assign(ro,t)},get str(){return on},set str(t){Object.assign(on,t)}},_$={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:Ni},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Ni}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:Ni}]}};function am(t,e){if((t.version||t.options.version)==="1.0"){const o=e.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=e.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${e.replace(/^tag:/,"")}`}let n=t.tagPrefixes.find(o=>e.indexOf(o.prefix)===0);if(!n){const o=t.getDefaults().tagPrefixes;n=o&&o.find(s=>e.indexOf(s.prefix)===0)}if(!n)return e[0]==="!"?e:`!<${e}>`;const r=e.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function _R(t,e){if(e instanceof rn)return rn;if(e.tag){const o=t.filter(s=>s.tag===e.tag);if(o.length>0)return o.find(s=>s.format===e.format)||o[0]}let n,r;if(e instanceof ge){r=e.value;const o=t.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===e.format)||o.find(s=>!s.format)}else r=e,n=t.find(o=>o.nodeClass&&r instanceof o.nodeClass);if(!n){const o=r&&r.constructor?r.constructor.name:typeof r;throw new Error(`Tag not resolved for ${o} value`)}return n}function NR(t,e,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(t);return s&&(n[s]=t,o.push(`&${s}`)),t.tag?o.push(am(r,t.tag)):e.default||o.push(am(r,e.tag)),o.join(" ")}function Zs(t,e,n,r){const{anchors:o,schema:s}=e.doc;let i;if(!(t instanceof rt)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};t=s.createNode(t,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let d=o.getName(l.source);d||(d=o.newName(),o.map[d]=l.source)}}if(t instanceof de)return t.toString(e,n,r);i||(i=_R(s.tags,t));const a=NR(t,i,e);a.length>0&&(e.indentAtStart=(e.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(t,e,n,r):t instanceof ge?Fd(t,e,n,r):t.toString(e,n,r);return a?t instanceof ge||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
338
- ${e.indent}${c}`:c}class Gd{static validAnchorNode(e){return e instanceof ge||e instanceof Ut||e instanceof it}constructor(e){We(this,"map",Object.create(null)),this.prefix=e}createAlias(e,n){return this.setAnchor(e,n),new rn(e)}createMergePair(...e){const n=new Vv;return n.value.items=e.map(r=>{if(r instanceof rn){if(r.source instanceof it)return r}else if(r instanceof it)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(e){const{map:n}=this;return Object.keys(n).find(r=>n[r]===e)}getNames(){return Object.keys(this.map)}getNode(e){return this.map[e]}newName(e){e||(e=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${e}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:e,_cstAliases:n}=this;Object.keys(e).forEach(r=>{e[r]=e[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(e,n){if(e!=null&&!Gd.validAnchorNode(e))throw new Error("Anchors may only be set for Scalar, Seq and Map nodes");if(n&&/[\x00-\x19\s,[\]{}]/.test(n))throw new Error("Anchor names must not contain whitespace or control characters");const{map:r}=this,o=e&&Object.keys(r).find(s=>r[s]===e);if(o)if(n)o!==n&&(delete r[o],r[n]=e);else return o;else{if(!n){if(!e)return null;n=this.newName()}r[n]=e}return n}}const Ii=(t,e)=>{if(t&&typeof t=="object"){const{tag:n}=t;t instanceof Be?(n&&(e[n]=!0),t.items.forEach(r=>Ii(r,e))):t instanceof de?(Ii(t.key,e),Ii(t.value,e)):t instanceof ge&&n&&(e[n]=!0)}return e},OR=t=>Object.keys(Ii(t,{}));function kR(t,e){const n={before:[],after:[]};let r,o=!1;for(const s of e)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";t.errors.push(new qe(s,a));break}const i=En(t,s);o&&(i.spaceBefore=!0,o=!1),r=i}else s.comment!==null?(r===void 0?n.before:n.after).push(s.comment):s.type===P.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!t.commentBefore&&(t.commentBefore=n.before.join(`
339
- `),n.before=[]));if(t.contents=r||null,!r)t.comment=n.before.concat(n.after).join(`
340
- `)||null;else{const s=n.before.join(`
341
- `);if(s){const i=r instanceof Be&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
342
- ${i.commentBefore}`:s}t.comment=n.after.join(`
343
- `)||null}}function jR({tagPrefixes:t},e){const[n,r]=e.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new ee(e,o)}if(t.some(o=>o.handle===n)){const o="The %TAG directive must only be given at most once per handle in the same document.";throw new ee(e,o)}return{handle:n,prefix:r}}function AR(t,e){let[n]=e.parameters;if(e.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new ee(e,r)}if(!_$[n]){const r=`Document will be parsed as YAML ${t.version||t.options.version} rather than YAML ${n}`;t.warnings.push(new po(e,r))}return n}function IR(t,e,n){const r=[];let o=!1;for(const s of e){const{comment:i,name:a}=s;switch(a){case"TAG":try{t.tagPrefixes.push(jR(t,s))}catch(c){t.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(t.version){const c="The %YAML directive must only be given at most once per document.";t.errors.push(new ee(s,c))}try{t.version=AR(t,s)}catch(c){t.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;t.warnings.push(new po(s,c))}}i&&r.push(i)}if(n&&!o&&(t.version||n.version||t.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});t.tagPrefixes=n.tagPrefixes.map(s),t.version=n.version}t.commentBefore=r.join(`
344
- `)||null}function Ar(t){if(t instanceof Be)return!0;throw new Error("Expected a YAML collection as document contents")}let zd=class ju{constructor(e){this.anchors=new Gd(e.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=e,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(e){return Ar(this.contents),this.contents.add(e)}addIn(e,n){Ar(this.contents),this.contents.addIn(e,n)}delete(e){return Ar(this.contents),this.contents.delete(e)}deleteIn(e){return Po(e)?this.contents==null?!1:(this.contents=null,!0):(Ar(this.contents),this.contents.deleteIn(e))}getDefaults(){return ju.defaults[this.version]||ju.defaults[this.options.version]||{}}get(e,n){return this.contents instanceof Be?this.contents.get(e,n):void 0}getIn(e,n){return Po(e)?!n&&this.contents instanceof ge?this.contents.value:this.contents:this.contents instanceof Be?this.contents.getIn(e,n):void 0}has(e){return this.contents instanceof Be?this.contents.has(e):!1}hasIn(e){return Po(e)?this.contents!==void 0:this.contents instanceof Be?this.contents.hasIn(e):!1}set(e,n){Ar(this.contents),this.contents.set(e,n)}setIn(e,n){Po(e)?this.contents=n:(Ar(this.contents),this.contents.setIn(e,n))}setSchema(e,n){if(!e&&!n&&this.schema)return;typeof e=="number"&&(e=e.toFixed(1)),e==="1.0"||e==="1.1"||e==="1.2"?(this.version?this.version=e:this.options.version=e,delete this.options.schema):e&&typeof e=="string"&&(this.options.schema=e),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new ms(r)}parse(e,n){this.options.keepCstNodes&&(this.cstNode=e),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=e;if(i&&(i.source||(i.source=this),this.errors.push(i)),IR(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],kR(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof wr&&c.makePretty();for(const c of this.warnings)c instanceof wr&&c.makePretty()}return this}listNonDefaultTags(){return OR(this.contents).filter(e=>e.indexOf(ms.defaultPrefix)!==0)}setTagPrefix(e,n){if(e[0]!=="!"||e[e.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===e);r?r.prefix=n:this.tagPrefixes.push({handle:e,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==e)}toJSON(e,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof e!="string"||!(this.contents instanceof ge)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Zs},c=Object.keys(this.anchors.map);c.length>0&&(a.anchors=new Map(c.map(l=>[this.anchors.map[l],{alias:[],aliasCount:0,count:1}])));const u=Ot(this.contents,e,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:d}of a.anchors.values())n(d,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const e=this.options.indent;if(!Number.isInteger(e)||e<=0){const c=JSON.stringify(e);throw new Error(`"indent" option must be a positive integer, not ${c}`)}this.setSchema();const n=[];let r=!1;if(this.version){let c="%YAML 1.2";this.schema.name==="yaml-1.1"&&(this.version==="1.0"?c="%YAML:1.0":this.version==="1.1"&&(c="%YAML 1.1")),n.push(c),r=!0}const o=this.listNonDefaultTags();this.tagPrefixes.forEach(({handle:c,prefix:u})=>{o.some(l=>l.indexOf(u)===0)&&(n.push(`%TAG ${c} ${u}`),r=!0)}),(r||this.directivesEndMarker)&&n.push("---"),this.commentBefore&&((r||!this.directivesEndMarker)&&n.unshift(""),n.unshift(this.commentBefore.replace(/^/gm,"#")));const s={anchors:Object.create(null),doc:this,indent:"",indentStep:" ".repeat(e),stringify:Zs};let i=!1,a=null;if(this.contents){this.contents instanceof rt&&(this.contents.spaceBefore&&(r||this.directivesEndMarker)&&n.push(""),this.contents.commentBefore&&n.push(this.contents.commentBefore.replace(/^/gm,"#")),s.forceBlockIndent=!!this.comment,a=this.contents.comment);const c=a?null:()=>i=!0,u=Zs(this.contents,s,()=>a=null,c);n.push(Vr(u,"",a))}else this.contents!==void 0&&n.push(Zs(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
345
- `)+`
346
- `}};We(zd,"defaults",_$);function PR(t,e=!0,n){n===void 0&&typeof e=="string"&&(n=e,e=!0);const r=Object.assign({},zd.defaults[Zi.version],Zi);return new ms(r).createNode(t,e,n)}class Ca extends zd{constructor(e){super(Object.assign({},Zi,e))}}function xR(t,e){const n=[];let r;for(const o of Dd(t)){const s=new Ca(e);s.parse(o,r),n.push(s),r=s}return n}function N$(t,e){const n=Dd(t),r=new Ca(e).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new ee(n[1],o))}return r}function RR(t,e){const n=N$(t,e);if(n.warnings.forEach(r=>f$(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function TR(t,e){const n=new Ca(e);return n.contents=t,String(n)}const CR={createNode:PR,defaultOptions:Zi,Document:Ca,parse:RR,parseAllDocuments:xR,parseCST:Dd,parseDocument:N$,scalarOptions:SR,stringify:TR},MR=Object.freeze(Object.defineProperty({__proto__:null,YAML:CR},Symbol.toStringTag,{value:"Module"})),LR=Px(MR);LR.YAML;var cm={exports:{}},O$={},kt={},oo={},ks={},ce={},gs={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.regexpCode=t.getEsmExportName=t.getProperty=t.safeStringify=t.stringify=t.strConcat=t.addCodeArg=t.str=t._=t.nil=t._Code=t.Name=t.IDENTIFIER=t._CodeOrName=void 0;class e{}t._CodeOrName=e,t.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends e{constructor(v){if(super(),!t.IDENTIFIER.test(v))throw new Error("CodeGen: name must be a valid identifier");this.str=v}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}t.Name=n;class r extends e{constructor(v){super(),this._items=typeof v=="string"?[v]:v}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;const v=this._items[0];return v===""||v==='""'}get str(){var v;return(v=this._str)!==null&&v!==void 0?v:this._str=this._items.reduce((b,E)=>`${b}${E}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((b,E)=>(E instanceof n&&(b[E.str]=(b[E.str]||0)+1),b),{})}}t._Code=r,t.nil=new r("");function o(h,...v){const b=[h[0]];let E=0;for(;E<v.length;)a(b,v[E]),b.push(h[++E]);return new r(b)}t._=o;const s=new r("+");function i(h,...v){const b=[g(h[0])];let E=0;for(;E<v.length;)b.push(s),a(b,v[E]),b.push(s,g(h[++E]));return c(b),new r(b)}t.str=i;function a(h,v){v instanceof r?h.push(...v._items):v instanceof n?h.push(v):h.push(d(v))}t.addCodeArg=a;function c(h){let v=1;for(;v<h.length-1;){if(h[v]===s){const b=u(h[v-1],h[v+1]);if(b!==void 0){h.splice(v-1,3,b);continue}h[v++]="+"}v++}}function u(h,v){if(v==='""')return h;if(h==='""')return v;if(typeof h=="string")return v instanceof n||h[h.length-1]!=='"'?void 0:typeof v!="string"?`${h.slice(0,-1)}${v}"`:v[0]==='"'?h.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!(h instanceof n))return`"${h}${v.slice(1)}`}function l(h,v){return v.emptyStr()?h:h.emptyStr()?v:i`${h}${v}`}t.strConcat=l;function d(h){return typeof h=="number"||typeof h=="boolean"||h===null?h:g(Array.isArray(h)?h.join(","):h)}function f(h){return new r(g(h))}t.stringify=f;function g(h){return JSON.stringify(h).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}t.safeStringify=g;function p(h){return typeof h=="string"&&t.IDENTIFIER.test(h)?new r(`.${h}`):o`[${h}]`}t.getProperty=p;function y(h){if(typeof h=="string"&&t.IDENTIFIER.test(h))return new r(`${h}`);throw new Error(`CodeGen: invalid export name: ${h}, use explicit $id name mapping`)}t.getEsmExportName=y;function w(h){return new r(h.toString())}t.regexpCode=w})(gs);var Au={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ValueScope=t.ValueScopeName=t.Scope=t.varKinds=t.UsedValueState=void 0;const e=gs;class n extends Error{constructor(u){super(`CodeGen: "code" for ${u} not defined`),this.value=u.value}}var r;(function(c){c[c.Started=0]="Started",c[c.Completed=1]="Completed"})(r||(t.UsedValueState=r={})),t.varKinds={const:new e.Name("const"),let:new e.Name("let"),var:new e.Name("var")};class o{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof e.Name?u:this.name(u)}name(u){return new e.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,d;if(!((d=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||d===void 0)&&d.has(u)||this._prefixes&&!this._prefixes.has(u))throw new Error(`CodeGen: prefix "${u}" is not allowed in this scope`);return this._names[u]={prefix:u,index:0}}}t.Scope=o;class s extends e.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:d}){this.value=u,this.scopePath=(0,e._)`.${new e.Name(l)}[${d}]`}}t.ValueScopeName=s;const i=(0,e._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:e.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var d;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const f=this.toName(u),{prefix:g}=f,p=(d=l.key)!==null&&d!==void 0?d:l.ref;let y=this._values[g];if(y){const v=y.get(p);if(v)return v}else y=this._values[g]=new Map;y.set(p,f);const w=this._scope[g]||(this._scope[g]=[]),h=w.length;return w[h]=l.ref,f.setValue(l,{property:g,itemIndex:h}),f}getValue(u,l){const d=this._values[u];if(d)return d.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,d=>{if(d.scopePath===void 0)throw new Error(`CodeGen: name "${d}" has no value`);return(0,e._)`${u}${d.scopePath}`})}scopeCode(u=this._values,l,d){return this._reduceValues(u,f=>{if(f.value===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return f.value.code},l,d)}_reduceValues(u,l,d={},f){let g=e.nil;for(const p in u){const y=u[p];if(!y)continue;const w=d[p]=d[p]||new Map;y.forEach(h=>{if(w.has(h))return;w.set(h,r.Started);let v=l(h);if(v){const b=this.opts.es5?t.varKinds.var:t.varKinds.const;g=(0,e._)`${g}${b} ${h} = ${v};${this.opts._n}`}else if(v=f==null?void 0:f(h))g=(0,e._)`${g}${v}${this.opts._n}`;else throw new n(h);w.set(h,r.Completed)})}return g}}t.ValueScope=a})(Au);(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.or=t.and=t.not=t.CodeGen=t.operators=t.varKinds=t.ValueScopeName=t.ValueScope=t.Scope=t.Name=t.regexpCode=t.stringify=t.getProperty=t.nil=t.strConcat=t.str=t._=void 0;const e=gs,n=Au;var r=gs;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(t,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(t,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(t,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return r.Name}});var o=Au;Object.defineProperty(t,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(t,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(t,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(t,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),t.operators={GT:new e._Code(">"),GTE:new e._Code(">="),LT:new e._Code("<"),LTE:new e._Code("<="),EQ:new e._Code("==="),NEQ:new e._Code("!=="),NOT:new e._Code("!"),OR:new e._Code("||"),AND:new e._Code("&&"),ADD:new e._Code("+")};class s{optimizeNodes(){return this}optimizeNames(m,$){return this}}class i extends s{constructor(m,$,O){super(),this.varKind=m,this.name=$,this.rhs=O}render({es5:m,_n:$}){const O=m?n.varKinds.var:this.varKind,x=this.rhs===void 0?"":` = ${this.rhs}`;return`${O} ${this.name}${x};`+$}optimizeNames(m,$){if(m[this.name.str])return this.rhs&&(this.rhs=fe(this.rhs,m,$)),this}get names(){return this.rhs instanceof e._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(m,$,O){super(),this.lhs=m,this.rhs=$,this.sideEffects=O}render({_n:m}){return`${this.lhs} = ${this.rhs};`+m}optimizeNames(m,$){if(!(this.lhs instanceof e.Name&&!m[this.lhs.str]&&!this.sideEffects))return this.rhs=fe(this.rhs,m,$),this}get names(){const m=this.lhs instanceof e.Name?{}:{...this.lhs.names};return ue(m,this.rhs)}}class c extends a{constructor(m,$,O,x){super(m,O,x),this.op=$}render({_n:m}){return`${this.lhs} ${this.op}= ${this.rhs};`+m}}class u extends s{constructor(m){super(),this.label=m,this.names={}}render({_n:m}){return`${this.label}:`+m}}class l extends s{constructor(m){super(),this.label=m,this.names={}}render({_n:m}){return`break${this.label?` ${this.label}`:""};`+m}}class d extends s{constructor(m){super(),this.error=m}render({_n:m}){return`throw ${this.error};`+m}get names(){return this.error.names}}class f extends s{constructor(m){super(),this.code=m}render({_n:m}){return`${this.code};`+m}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(m,$){return this.code=fe(this.code,m,$),this}get names(){return this.code instanceof e._CodeOrName?this.code.names:{}}}class g extends s{constructor(m=[]){super(),this.nodes=m}render(m){return this.nodes.reduce(($,O)=>$+O.render(m),"")}optimizeNodes(){const{nodes:m}=this;let $=m.length;for(;$--;){const O=m[$].optimizeNodes();Array.isArray(O)?m.splice($,1,...O):O?m[$]=O:m.splice($,1)}return m.length>0?this:void 0}optimizeNames(m,$){const{nodes:O}=this;let x=O.length;for(;x--;){const R=O[x];R.optimizeNames(m,$)||(he(m,R.names),O.splice(x,1))}return O.length>0?this:void 0}get names(){return this.nodes.reduce((m,$)=>Z(m,$.names),{})}}class p extends g{render(m){return"{"+m._n+super.render(m)+"}"+m._n}}class y extends g{}class w extends p{}w.kind="else";class h extends p{constructor(m,$){super($),this.condition=m}render(m){let $=`if(${this.condition})`+super.render(m);return this.else&&($+="else "+this.else.render(m)),$}optimizeNodes(){super.optimizeNodes();const m=this.condition;if(m===!0)return this.nodes;let $=this.else;if($){const O=$.optimizeNodes();$=this.else=Array.isArray(O)?new w(O):O}if($)return m===!1?$ instanceof h?$:$.nodes:this.nodes.length?this:new h(pe(m),$ instanceof h?[$]:$.nodes);if(!(m===!1||!this.nodes.length))return this}optimizeNames(m,$){var O;if(this.else=(O=this.else)===null||O===void 0?void 0:O.optimizeNames(m,$),!!(super.optimizeNames(m,$)||this.else))return this.condition=fe(this.condition,m,$),this}get names(){const m=super.names;return ue(m,this.condition),this.else&&Z(m,this.else.names),m}}h.kind="if";class v extends p{}v.kind="for";class b extends v{constructor(m){super(),this.iteration=m}render(m){return`for(${this.iteration})`+super.render(m)}optimizeNames(m,$){if(super.optimizeNames(m,$))return this.iteration=fe(this.iteration,m,$),this}get names(){return Z(super.names,this.iteration.names)}}class E extends v{constructor(m,$,O,x){super(),this.varKind=m,this.name=$,this.from=O,this.to=x}render(m){const $=m.es5?n.varKinds.var:this.varKind,{name:O,from:x,to:R}=this;return`for(${$} ${O}=${x}; ${O}<${R}; ${O}++)`+super.render(m)}get names(){const m=ue(super.names,this.from);return ue(m,this.to)}}class N extends v{constructor(m,$,O,x){super(),this.loop=m,this.varKind=$,this.name=O,this.iterable=x}render(m){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(m)}optimizeNames(m,$){if(super.optimizeNames(m,$))return this.iterable=fe(this.iterable,m,$),this}get names(){return Z(super.names,this.iterable.names)}}class j extends p{constructor(m,$,O){super(),this.name=m,this.args=$,this.async=O}render(m){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(m)}}j.kind="func";class T extends g{render(m){return"return "+super.render(m)}}T.kind="return";class M extends p{render(m){let $="try"+super.render(m);return this.catch&&($+=this.catch.render(m)),this.finally&&($+=this.finally.render(m)),$}optimizeNodes(){var m,$;return super.optimizeNodes(),(m=this.catch)===null||m===void 0||m.optimizeNodes(),($=this.finally)===null||$===void 0||$.optimizeNodes(),this}optimizeNames(m,$){var O,x;return super.optimizeNames(m,$),(O=this.catch)===null||O===void 0||O.optimizeNames(m,$),(x=this.finally)===null||x===void 0||x.optimizeNames(m,$),this}get names(){const m=super.names;return this.catch&&Z(m,this.catch.names),this.finally&&Z(m,this.finally.names),m}}class C extends p{constructor(m){super(),this.error=m}render(m){return`catch(${this.error})`+super.render(m)}}C.kind="catch";class G extends p{render(m){return"finally"+super.render(m)}}G.kind="finally";class H{constructor(m,$={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...$,_n:$.lines?`
347
- `:""},this._extScope=m,this._scope=new n.Scope({parent:m}),this._nodes=[new y]}toString(){return this._root.render(this.opts)}name(m){return this._scope.name(m)}scopeName(m){return this._extScope.name(m)}scopeValue(m,$){const O=this._extScope.value(m,$);return(this._values[O.prefix]||(this._values[O.prefix]=new Set)).add(O),O}getScopeValue(m,$){return this._extScope.getValue(m,$)}scopeRefs(m){return this._extScope.scopeRefs(m,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(m,$,O,x){const R=this._scope.toName($);return O!==void 0&&x&&(this._constants[R.str]=O),this._leafNode(new i(m,R,O)),R}const(m,$,O){return this._def(n.varKinds.const,m,$,O)}let(m,$,O){return this._def(n.varKinds.let,m,$,O)}var(m,$,O){return this._def(n.varKinds.var,m,$,O)}assign(m,$,O){return this._leafNode(new a(m,$,O))}add(m,$){return this._leafNode(new c(m,t.operators.ADD,$))}code(m){return typeof m=="function"?m():m!==e.nil&&this._leafNode(new f(m)),this}object(...m){const $=["{"];for(const[O,x]of m)$.length>1&&$.push(","),$.push(O),(O!==x||this.opts.es5)&&($.push(":"),(0,e.addCodeArg)($,x));return $.push("}"),new e._Code($)}if(m,$,O){if(this._blockNode(new h(m)),$&&O)this.code($).else().code(O).endIf();else if($)this.code($).endIf();else if(O)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(m){return this._elseNode(new h(m))}else(){return this._elseNode(new w)}endIf(){return this._endBlockNode(h,w)}_for(m,$){return this._blockNode(m),$&&this.code($).endFor(),this}for(m,$){return this._for(new b(m),$)}forRange(m,$,O,x,R=this.opts.es5?n.varKinds.var:n.varKinds.let){const U=this._scope.toName(m);return this._for(new E(R,U,$,O),()=>x(U))}forOf(m,$,O,x=n.varKinds.const){const R=this._scope.toName(m);if(this.opts.es5){const U=$ instanceof e.Name?$:this.var("_arr",$);return this.forRange("_i",0,(0,e._)`${U}.length`,q=>{this.var(R,(0,e._)`${U}[${q}]`),O(R)})}return this._for(new N("of",x,R,$),()=>O(R))}forIn(m,$,O,x=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(m,(0,e._)`Object.keys(${$})`,O);const R=this._scope.toName(m);return this._for(new N("in",x,R,$),()=>O(R))}endFor(){return this._endBlockNode(v)}label(m){return this._leafNode(new u(m))}break(m){return this._leafNode(new l(m))}return(m){const $=new T;if(this._blockNode($),this.code(m),$.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(T)}try(m,$,O){if(!$&&!O)throw new Error('CodeGen: "try" without "catch" and "finally"');const x=new M;if(this._blockNode(x),this.code(m),$){const R=this.name("e");this._currNode=x.catch=new C(R),$(R)}return O&&(this._currNode=x.finally=new G,this.code(O)),this._endBlockNode(C,G)}throw(m){return this._leafNode(new d(m))}block(m,$){return this._blockStarts.push(this._nodes.length),m&&this.code(m).endBlock($),this}endBlock(m){const $=this._blockStarts.pop();if($===void 0)throw new Error("CodeGen: not in self-balancing block");const O=this._nodes.length-$;if(O<0||m!==void 0&&O!==m)throw new Error(`CodeGen: wrong number of nodes: ${O} vs ${m} expected`);return this._nodes.length=$,this}func(m,$=e.nil,O,x){return this._blockNode(new j(m,$,O)),x&&this.code(x).endFunc(),this}endFunc(){return this._endBlockNode(j)}optimize(m=1){for(;m-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(m){return this._currNode.nodes.push(m),this}_blockNode(m){this._currNode.nodes.push(m),this._nodes.push(m)}_endBlockNode(m,$){const O=this._currNode;if(O instanceof m||$&&O instanceof $)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${$?`${m.kind}/${$.kind}`:m.kind}"`)}_elseNode(m){const $=this._currNode;if(!($ instanceof h))throw new Error('CodeGen: "else" without "if"');return this._currNode=$.else=m,this}get _root(){return this._nodes[0]}get _currNode(){const m=this._nodes;return m[m.length-1]}set _currNode(m){const $=this._nodes;$[$.length-1]=m}}t.CodeGen=H;function Z(_,m){for(const $ in m)_[$]=(_[$]||0)+(m[$]||0);return _}function ue(_,m){return m instanceof e._CodeOrName?Z(_,m.names):_}function fe(_,m,$){if(_ instanceof e.Name)return O(_);if(!x(_))return _;return new e._Code(_._items.reduce((R,U)=>(U instanceof e.Name&&(U=O(U)),U instanceof e._Code?R.push(...U._items):R.push(U),R),[]));function O(R){const U=$[R.str];return U===void 0||m[R.str]!==1?R:(delete m[R.str],U)}function x(R){return R instanceof e._Code&&R._items.some(U=>U instanceof e.Name&&m[U.str]===1&&$[U.str]!==void 0)}}function he(_,m){for(const $ in m)_[$]=(_[$]||0)-(m[$]||0)}function pe(_){return typeof _=="boolean"||typeof _=="number"||_===null?!_:(0,e._)`!${k(_)}`}t.not=pe;const Oe=S(t.operators.AND);function gt(..._){return _.reduce(Oe)}t.and=gt;const ut=S(t.operators.OR);function A(..._){return _.reduce(ut)}t.or=A;function S(_){return(m,$)=>m===e.nil?$:$===e.nil?m:(0,e._)`${k(m)} ${_} ${k($)}`}function k(_){return _ instanceof e.Name?_:(0,e._)`(${_})`}})(ce);var V={};Object.defineProperty(V,"__esModule",{value:!0});V.checkStrictMode=V.getErrorPath=V.Type=V.useFunc=V.setEvaluated=V.evaluatedPropsToName=V.mergeEvaluated=V.eachItem=V.unescapeJsonPointer=V.escapeJsonPointer=V.escapeFragment=V.unescapeFragment=V.schemaRefOrVal=V.schemaHasRulesButRef=V.schemaHasRules=V.checkUnknownRules=V.alwaysValidSchema=V.toHash=void 0;const we=ce,DR=gs;function UR(t){const e={};for(const n of t)e[n]=!0;return e}V.toHash=UR;function BR(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(k$(t,e),!j$(e,t.self.RULES.all))}V.alwaysValidSchema=BR;function k$(t,e=t.schema){const{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;const o=r.RULES.keywords;for(const s in e)o[s]||P$(t,`unknown keyword: "${s}"`)}V.checkUnknownRules=k$;function j$(t,e){if(typeof t=="boolean")return!t;for(const n in t)if(e[n])return!0;return!1}V.schemaHasRules=j$;function FR(t,e){if(typeof t=="boolean")return!t;for(const n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}V.schemaHasRulesButRef=FR;function qR({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,we._)`${n}`}return(0,we._)`${t}${e}${(0,we.getProperty)(r)}`}V.schemaRefOrVal=qR;function KR(t){return A$(decodeURIComponent(t))}V.unescapeFragment=KR;function VR(t){return encodeURIComponent(Wd(t))}V.escapeFragment=VR;function Wd(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}V.escapeJsonPointer=Wd;function A$(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}V.unescapeJsonPointer=A$;function GR(t,e){if(Array.isArray(t))for(const n of t)e(n);else e(t)}V.eachItem=GR;function um({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof we.Name?(s instanceof we.Name?t(o,s,i):e(o,s,i),i):s instanceof we.Name?(e(o,i,s),s):n(s,i);return a===we.Name&&!(c instanceof we.Name)?r(o,c):c}}V.mergeEvaluated={props:um({mergeNames:(t,e,n)=>t.if((0,we._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,we._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,we._)`${n} || {}`).code((0,we._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,we._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,we._)`${n} || {}`),Hd(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:I$}),items:um({mergeNames:(t,e,n)=>t.if((0,we._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,we._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,we._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,we._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function I$(t,e){if(e===!0)return t.var("props",!0);const n=t.var("props",(0,we._)`{}`);return e!==void 0&&Hd(t,n,e),n}V.evaluatedPropsToName=I$;function Hd(t,e,n){Object.keys(n).forEach(r=>t.assign((0,we._)`${e}${(0,we.getProperty)(r)}`,!0))}V.setEvaluated=Hd;const lm={};function zR(t,e){return t.scopeValue("func",{ref:e,code:lm[e.code]||(lm[e.code]=new DR._Code(e.code))})}V.useFunc=zR;var Iu;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Iu||(V.Type=Iu={}));function WR(t,e,n){if(t instanceof we.Name){const r=e===Iu.Num;return n?r?(0,we._)`"[" + ${t} + "]"`:(0,we._)`"['" + ${t} + "']"`:r?(0,we._)`"/" + ${t}`:(0,we._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,we.getProperty)(t).toString():"/"+Wd(t)}V.getErrorPath=WR;function P$(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}V.checkStrictMode=P$;var Ft={};Object.defineProperty(Ft,"__esModule",{value:!0});const Ge=ce,HR={data:new Ge.Name("data"),valCxt:new Ge.Name("valCxt"),instancePath:new Ge.Name("instancePath"),parentData:new Ge.Name("parentData"),parentDataProperty:new Ge.Name("parentDataProperty"),rootData:new Ge.Name("rootData"),dynamicAnchors:new Ge.Name("dynamicAnchors"),vErrors:new Ge.Name("vErrors"),errors:new Ge.Name("errors"),this:new Ge.Name("this"),self:new Ge.Name("self"),scope:new Ge.Name("scope"),json:new Ge.Name("json"),jsonPos:new Ge.Name("jsonPos"),jsonLen:new Ge.Name("jsonLen"),jsonPart:new Ge.Name("jsonPart")};Ft.default=HR;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.extendErrors=t.resetErrorsCount=t.reportExtraError=t.reportError=t.keyword$DataError=t.keywordError=void 0;const e=ce,n=V,r=Ft;t.keywordError={message:({keyword:w})=>(0,e.str)`must pass "${w}" keyword validation`},t.keyword$DataError={message:({keyword:w,schemaType:h})=>h?(0,e.str)`"${w}" keyword must be ${h} ($data)`:(0,e.str)`"${w}" keyword is invalid ($data)`};function o(w,h=t.keywordError,v,b){const{it:E}=w,{gen:N,compositeRule:j,allErrors:T}=E,M=d(w,h,v);b??(j||T)?c(N,M):u(E,(0,e._)`[${M}]`)}t.reportError=o;function s(w,h=t.keywordError,v){const{it:b}=w,{gen:E,compositeRule:N,allErrors:j}=b,T=d(w,h,v);c(E,T),N||j||u(b,r.default.vErrors)}t.reportExtraError=s;function i(w,h){w.assign(r.default.errors,h),w.if((0,e._)`${r.default.vErrors} !== null`,()=>w.if(h,()=>w.assign((0,e._)`${r.default.vErrors}.length`,h),()=>w.assign(r.default.vErrors,null)))}t.resetErrorsCount=i;function a({gen:w,keyword:h,schemaValue:v,data:b,errsCount:E,it:N}){if(E===void 0)throw new Error("ajv implementation error");const j=w.name("err");w.forRange("i",E,r.default.errors,T=>{w.const(j,(0,e._)`${r.default.vErrors}[${T}]`),w.if((0,e._)`${j}.instancePath === undefined`,()=>w.assign((0,e._)`${j}.instancePath`,(0,e.strConcat)(r.default.instancePath,N.errorPath))),w.assign((0,e._)`${j}.schemaPath`,(0,e.str)`${N.errSchemaPath}/${h}`),N.opts.verbose&&(w.assign((0,e._)`${j}.schema`,v),w.assign((0,e._)`${j}.data`,b))})}t.extendErrors=a;function c(w,h){const v=w.const("err",h);w.if((0,e._)`${r.default.vErrors} === null`,()=>w.assign(r.default.vErrors,(0,e._)`[${v}]`),(0,e._)`${r.default.vErrors}.push(${v})`),w.code((0,e._)`${r.default.errors}++`)}function u(w,h){const{gen:v,validateName:b,schemaEnv:E}=w;E.$async?v.throw((0,e._)`new ${w.ValidationError}(${h})`):(v.assign((0,e._)`${b}.errors`,h),v.return(!1))}const l={keyword:new e.Name("keyword"),schemaPath:new e.Name("schemaPath"),params:new e.Name("params"),propertyName:new e.Name("propertyName"),message:new e.Name("message"),schema:new e.Name("schema"),parentSchema:new e.Name("parentSchema")};function d(w,h,v){const{createErrors:b}=w.it;return b===!1?(0,e._)`{}`:f(w,h,v)}function f(w,h,v={}){const{gen:b,it:E}=w,N=[g(E,v),p(w,v)];return y(w,h,N),b.object(...N)}function g({errorPath:w},{instancePath:h}){const v=h?(0,e.str)`${w}${(0,n.getErrorPath)(h,n.Type.Str)}`:w;return[r.default.instancePath,(0,e.strConcat)(r.default.instancePath,v)]}function p({keyword:w,it:{errSchemaPath:h}},{schemaPath:v,parentSchema:b}){let E=b?h:(0,e.str)`${h}/${w}`;return v&&(E=(0,e.str)`${E}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,E]}function y(w,{params:h,message:v},b){const{keyword:E,data:N,schemaValue:j,it:T}=w,{opts:M,propertyName:C,topSchemaRef:G,schemaPath:H}=T;b.push([l.keyword,E],[l.params,typeof h=="function"?h(w):h||(0,e._)`{}`]),M.messages&&b.push([l.message,typeof v=="function"?v(w):v]),M.verbose&&b.push([l.schema,j],[l.parentSchema,(0,e._)`${G}${H}`],[r.default.data,N]),C&&b.push([l.propertyName,C])}})(ks);Object.defineProperty(oo,"__esModule",{value:!0});oo.boolOrEmptySchema=oo.topBoolOrEmptySchema=void 0;const JR=ks,QR=ce,YR=Ft,ZR={message:"boolean schema is false"};function XR(t){const{gen:e,schema:n,validateName:r}=t;n===!1?x$(t,!1):typeof n=="object"&&n.$async===!0?e.return(YR.default.data):(e.assign((0,QR._)`${r}.errors`,null),e.return(!0))}oo.topBoolOrEmptySchema=XR;function eT(t,e){const{gen:n,schema:r}=t;r===!1?(n.var(e,!1),x$(t)):n.var(e,!0)}oo.boolOrEmptySchema=eT;function x$(t,e){const{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,JR.reportError)(o,ZR,void 0,e)}var Ie={},vr={};Object.defineProperty(vr,"__esModule",{value:!0});vr.getRules=vr.isJSONType=void 0;const tT=["string","number","integer","boolean","null","object","array"],nT=new Set(tT);function rT(t){return typeof t=="string"&&nT.has(t)}vr.isJSONType=rT;function oT(){const t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}vr.getRules=oT;var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.shouldUseRule=Xt.shouldUseGroup=Xt.schemaHasRulesForType=void 0;function sT({schema:t,self:e},n){const r=e.RULES.types[n];return r&&r!==!0&&R$(t,r)}Xt.schemaHasRulesForType=sT;function R$(t,e){return e.rules.some(n=>T$(t,n))}Xt.shouldUseGroup=R$;function T$(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}Xt.shouldUseRule=T$;Object.defineProperty(Ie,"__esModule",{value:!0});Ie.reportTypeError=Ie.checkDataTypes=Ie.checkDataType=Ie.coerceAndCheckDataType=Ie.getJSONTypes=Ie.getSchemaTypes=Ie.DataType=void 0;const iT=vr,aT=Xt,cT=ks,ne=ce,C$=V;var Hr;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Hr||(Ie.DataType=Hr={}));function uT(t){const e=M$(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Ie.getSchemaTypes=uT;function M$(t){const e=Array.isArray(t)?t:t?[t]:[];if(e.every(iT.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Ie.getJSONTypes=M$;function lT(t,e){const{gen:n,data:r,opts:o}=t,s=dT(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,aT.schemaHasRulesForType)(t,e[0]));if(i){const a=Jd(e,r,o.strictNumbers,Hr.Wrong);n.if(a,()=>{s.length?fT(t,e,s):Qd(t)})}return i}Ie.coerceAndCheckDataType=lT;const L$=new Set(["string","number","integer","boolean","null"]);function dT(t,e){return e?t.filter(n=>L$.has(n)||e==="array"&&n==="array"):[]}function fT(t,e,n){const{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,ne._)`typeof ${o}`),a=r.let("coerced",(0,ne._)`undefined`);s.coerceTypes==="array"&&r.if((0,ne._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,ne._)`${o}[0]`).assign(i,(0,ne._)`typeof ${o}`).if(Jd(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,ne._)`${a} !== undefined`);for(const u of n)(L$.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Qd(t),r.endIf(),r.if((0,ne._)`${a} !== undefined`,()=>{r.assign(o,a),pT(t,a)});function c(u){switch(u){case"string":r.elseIf((0,ne._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ne._)`"" + ${o}`).elseIf((0,ne._)`${o} === null`).assign(a,(0,ne._)`""`);return;case"number":r.elseIf((0,ne._)`${i} == "boolean" || ${o} === null
348
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ne._)`+${o}`);return;case"integer":r.elseIf((0,ne._)`${i} === "boolean" || ${o} === null
349
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ne._)`+${o}`);return;case"boolean":r.elseIf((0,ne._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ne._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,ne._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,ne._)`${i} === "string" || ${i} === "number"
350
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,ne._)`[${o}]`)}}}function pT({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,ne._)`${e} !== undefined`,()=>t.assign((0,ne._)`${e}[${n}]`,r))}function Pu(t,e,n,r=Hr.Correct){const o=r===Hr.Correct?ne.operators.EQ:ne.operators.NEQ;let s;switch(t){case"null":return(0,ne._)`${e} ${o} null`;case"array":s=(0,ne._)`Array.isArray(${e})`;break;case"object":s=(0,ne._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ne._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ne._)`typeof ${e} ${o} ${t}`}return r===Hr.Correct?s:(0,ne.not)(s);function i(a=ne.nil){return(0,ne.and)((0,ne._)`typeof ${e} == "number"`,a,n?(0,ne._)`isFinite(${e})`:ne.nil)}}Ie.checkDataType=Pu;function Jd(t,e,n,r){if(t.length===1)return Pu(t[0],e,n,r);let o;const s=(0,C$.toHash)(t);if(s.array&&s.object){const i=(0,ne._)`typeof ${e} != "object"`;o=s.null?i:(0,ne._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ne.nil;s.number&&delete s.integer;for(const i in s)o=(0,ne.and)(o,Pu(i,e,n,r));return o}Ie.checkDataTypes=Jd;const hT={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ne._)`{type: ${t}}`:(0,ne._)`{type: ${e}}`};function Qd(t){const e=mT(t);(0,cT.reportError)(e,hT)}Ie.reportTypeError=Qd;function mT(t){const{gen:e,data:n,schema:r}=t,o=(0,C$.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}var Ma={};Object.defineProperty(Ma,"__esModule",{value:!0});Ma.assignDefaults=void 0;const Ir=ce,gT=V;function yT(t,e){const{properties:n,items:r}=t.schema;if(e==="object"&&n)for(const o in n)dm(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>dm(t,s,o.default))}Ma.assignDefaults=yT;function dm(t,e,n){const{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;const a=(0,Ir._)`${s}${(0,Ir.getProperty)(e)}`;if(o){(0,gT.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Ir._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ir._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Ir._)`${a} = ${(0,Ir.stringify)(n)}`)}var Ct={},ie={};Object.defineProperty(ie,"__esModule",{value:!0});ie.validateUnion=ie.validateArray=ie.usePattern=ie.callValidateCode=ie.schemaProperties=ie.allSchemaProperties=ie.noPropertyInData=ie.propertyInData=ie.isOwnProperty=ie.hasPropFunc=ie.reportMissingProp=ie.checkMissingProp=ie.checkReportMissingProp=void 0;const $e=ce,Yd=V,dn=Ft,wT=V;function vT(t,e){const{gen:n,data:r,it:o}=t;n.if(Xd(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,$e._)`${e}`},!0),t.error()})}ie.checkReportMissingProp=vT;function $T({gen:t,data:e,it:{opts:n}},r,o){return(0,$e.or)(...r.map(s=>(0,$e.and)(Xd(t,e,s,n.ownProperties),(0,$e._)`${o} = ${s}`)))}ie.checkMissingProp=$T;function bT(t,e){t.setParams({missingProperty:e},!0),t.error()}ie.reportMissingProp=bT;function D$(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,$e._)`Object.prototype.hasOwnProperty`})}ie.hasPropFunc=D$;function Zd(t,e,n){return(0,$e._)`${D$(t)}.call(${e}, ${n})`}ie.isOwnProperty=Zd;function ET(t,e,n,r){const o=(0,$e._)`${e}${(0,$e.getProperty)(n)} !== undefined`;return r?(0,$e._)`${o} && ${Zd(t,e,n)}`:o}ie.propertyInData=ET;function Xd(t,e,n,r){const o=(0,$e._)`${e}${(0,$e.getProperty)(n)} === undefined`;return r?(0,$e.or)(o,(0,$e.not)(Zd(t,e,n))):o}ie.noPropertyInData=Xd;function U$(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ie.allSchemaProperties=U$;function ST(t,e){return U$(e).filter(n=>!(0,Yd.alwaysValidSchema)(t,e[n]))}ie.schemaProperties=ST;function _T({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){const l=u?(0,$e._)`${t}, ${e}, ${r}${o}`:e,d=[[dn.default.instancePath,(0,$e.strConcat)(dn.default.instancePath,s)],[dn.default.parentData,i.parentData],[dn.default.parentDataProperty,i.parentDataProperty],[dn.default.rootData,dn.default.rootData]];i.opts.dynamicRef&&d.push([dn.default.dynamicAnchors,dn.default.dynamicAnchors]);const f=(0,$e._)`${l}, ${n.object(...d)}`;return c!==$e.nil?(0,$e._)`${a}.call(${c}, ${f})`:(0,$e._)`${a}(${f})`}ie.callValidateCode=_T;const NT=(0,$e._)`new RegExp`;function OT({gen:t,it:{opts:e}},n){const r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,$e._)`${o.code==="new RegExp"?NT:(0,wT.useFunc)(t,o)}(${n}, ${r})`})}ie.usePattern=OT;function kT(t){const{gen:e,data:n,keyword:r,it:o}=t,s=e.name("valid");if(o.allErrors){const a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){const c=e.const("len",(0,$e._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Yd.Type.Num},s),e.if((0,$e.not)(s),a)})}}ie.validateArray=kT;function jT(t){const{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,Yd.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;const s=e.let("valid",!1),i=e.name("_valid");e.block(()=>n.forEach((a,c)=>{const u=t.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);e.assign(s,(0,$e._)`${s} || ${i}`),t.mergeValidEvaluated(u,i)||e.if((0,$e.not)(s))})),t.result(s,()=>t.reset(),()=>t.error(!0))}ie.validateUnion=jT;Object.defineProperty(Ct,"__esModule",{value:!0});Ct.validateKeywordUsage=Ct.validSchemaType=Ct.funcKeywordCode=Ct.macroKeywordCode=void 0;const Ze=ce,tr=Ft,AT=ie,IT=ks;function PT(t,e){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=B$(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");t.subschema({schema:a,schemaPath:Ze.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Ct.macroKeywordCode=PT;function xT(t,e){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;TT(c,e);const u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=B$(r,o,u),d=r.let("valid");t.block$data(d,f),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function f(){if(e.errors===!1)y(),e.modifying&&fm(t),w(()=>t.error());else{const h=e.async?g():p();e.modifying&&fm(t),w(()=>RT(t,h))}}function g(){const h=r.let("ruleErrs",null);return r.try(()=>y((0,Ze._)`await `),v=>r.assign(d,!1).if((0,Ze._)`${v} instanceof ${c.ValidationError}`,()=>r.assign(h,(0,Ze._)`${v}.errors`),()=>r.throw(v))),h}function p(){const h=(0,Ze._)`${l}.errors`;return r.assign(h,null),y(Ze.nil),h}function y(h=e.async?(0,Ze._)`await `:Ze.nil){const v=c.opts.passContext?tr.default.this:tr.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,Ze._)`${h}${(0,AT.callValidateCode)(t,l,v,b)}`,e.modifying)}function w(h){var v;r.if((0,Ze.not)((v=e.valid)!==null&&v!==void 0?v:d),h)}}Ct.funcKeywordCode=xT;function fm(t){const{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,Ze._)`${r.parentData}[${r.parentDataProperty}]`))}function RT(t,e){const{gen:n}=t;n.if((0,Ze._)`Array.isArray(${e})`,()=>{n.assign(tr.default.vErrors,(0,Ze._)`${tr.default.vErrors} === null ? ${e} : ${tr.default.vErrors}.concat(${e})`).assign(tr.default.errors,(0,Ze._)`${tr.default.vErrors}.length`),(0,IT.extendErrors)(t)},()=>t.error())}function TT({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function B$(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,Ze.stringify)(n)})}function CT(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Ct.validSchemaType=CT;function MT({schema:t,opts:e,self:n,errSchemaPath:r},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");const i=o.dependencies;if(i!=null&&i.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){const a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}Ct.validateKeywordUsage=MT;var Sn={};Object.defineProperty(Sn,"__esModule",{value:!0});Sn.extendSubschemaMode=Sn.extendSubschemaData=Sn.getSubschema=void 0;const Rt=ce,F$=V;function LT(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){const a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Rt._)`${t.schemaPath}${(0,Rt.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Rt._)`${t.schemaPath}${(0,Rt.getProperty)(e)}${(0,Rt.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,F$.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Sn.getSubschema=LT;function DT(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');const{gen:a}=e;if(n!==void 0){const{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,Rt._)`${e.data}${(0,Rt.getProperty)(n)}`,!0);c(f),t.errorPath=(0,Rt.str)`${u}${(0,F$.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Rt._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){const u=o instanceof Rt.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}Sn.extendSubschemaData=DT;function UT(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}Sn.extendSubschemaMode=UT;var De={},q$=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n},K$={exports:{}},vn=K$.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};Pi(e,r,o,t,"",t)};vn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};vn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};vn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};vn.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 Pi(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in vn.arrayKeywords)for(var f=0;f<d.length;f++)Pi(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in vn.propsKeywords){if(d&&typeof d=="object")for(var g in d)Pi(t,e,n,d[g],o+"/"+l+"/"+BT(g),s,o,l,r,g)}else(l in vn.keywords||t.allKeys&&!(l in vn.skipKeywords))&&Pi(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function BT(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}var FT=K$.exports;Object.defineProperty(De,"__esModule",{value:!0});De.getSchemaRefs=De.resolveUrl=De.normalizeId=De._getFullPath=De.getFullPath=De.inlineRef=void 0;const qT=V,KT=q$,VT=FT,GT=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function zT(t,e=!0){return typeof t=="boolean"?!0:e===!0?!xu(t):e?V$(t)<=e:!1}De.inlineRef=zT;const WT=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function xu(t){for(const e in t){if(WT.has(e))return!0;const n=t[e];if(Array.isArray(n)&&n.some(xu)||typeof n=="object"&&xu(n))return!0}return!1}function V$(t){let e=0;for(const n in t)if(n==="$ref"||(e++,!GT.has(n)&&(typeof t[n]=="object"&&(0,qT.eachItem)(t[n],r=>e+=V$(r)),e===1/0)))return 1/0;return e}function G$(t,e="",n){n!==!1&&(e=Jr(e));const r=t.parse(e);return z$(t,r)}De.getFullPath=G$;function z$(t,e){return t.serialize(e).split("#")[0]+"#"}De._getFullPath=z$;const HT=/#\/?$/;function Jr(t){return t?t.replace(HT,""):""}De.normalizeId=Jr;function JT(t,e,n){return n=Jr(n),t.resolve(e,n)}De.resolveUrl=JT;const QT=/^[a-z_][-a-z0-9._]*$/i;function YT(t,e){if(typeof t=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Jr(t[n]||e),s={"":o},i=G$(r,o,!1),a={},c=new Set;return VT(t,{allKeys:!0},(d,f,g,p)=>{if(p===void 0)return;const y=i+f;let w=s[p];typeof d[n]=="string"&&(w=h.call(this,d[n])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[f]=w;function h(b){const E=this.opts.uriResolver.resolve;if(b=Jr(w?E(w,b):b),c.has(b))throw l(b);c.add(b);let N=this.refs[b];return typeof N=="string"&&(N=this.refs[N]),typeof N=="object"?u(d,N.schema,b):b!==Jr(y)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=y),b}function v(b){if(typeof b=="string"){if(!QT.test(b))throw new Error(`invalid anchor "${b}"`);h.call(this,`#${b}`)}}}),a;function u(d,f,g){if(f!==void 0&&!KT(d,f))throw l(g)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}De.getSchemaRefs=YT;Object.defineProperty(kt,"__esModule",{value:!0});kt.getData=kt.KeywordCxt=kt.validateFunctionCode=void 0;const W$=oo,pm=Ie,ef=Xt,Xi=Ie,ZT=Ma,Jo=Ct,mc=Sn,W=ce,Y=Ft,XT=De,en=V,So=ks;function eC(t){if(Q$(t)&&(Y$(t),J$(t))){rC(t);return}H$(t,()=>(0,W$.topBoolOrEmptySchema)(t))}kt.validateFunctionCode=eC;function H$({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,W._)`${Y.default.data}, ${Y.default.valCxt}`,r.$async,()=>{t.code((0,W._)`"use strict"; ${hm(n,o)}`),nC(t,o),t.code(s)}):t.func(e,(0,W._)`${Y.default.data}, ${tC(o)}`,r.$async,()=>t.code(hm(n,o)).code(s))}function tC(t){return(0,W._)`{${Y.default.instancePath}="", ${Y.default.parentData}, ${Y.default.parentDataProperty}, ${Y.default.rootData}=${Y.default.data}${t.dynamicRef?(0,W._)`, ${Y.default.dynamicAnchors}={}`:W.nil}}={}`}function nC(t,e){t.if(Y.default.valCxt,()=>{t.var(Y.default.instancePath,(0,W._)`${Y.default.valCxt}.${Y.default.instancePath}`),t.var(Y.default.parentData,(0,W._)`${Y.default.valCxt}.${Y.default.parentData}`),t.var(Y.default.parentDataProperty,(0,W._)`${Y.default.valCxt}.${Y.default.parentDataProperty}`),t.var(Y.default.rootData,(0,W._)`${Y.default.valCxt}.${Y.default.rootData}`),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,W._)`${Y.default.valCxt}.${Y.default.dynamicAnchors}`)},()=>{t.var(Y.default.instancePath,(0,W._)`""`),t.var(Y.default.parentData,(0,W._)`undefined`),t.var(Y.default.parentDataProperty,(0,W._)`undefined`),t.var(Y.default.rootData,Y.default.data),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,W._)`{}`)})}function rC(t){const{schema:e,opts:n,gen:r}=t;H$(t,()=>{n.$comment&&e.$comment&&X$(t),cC(t),r.let(Y.default.vErrors,null),r.let(Y.default.errors,0),n.unevaluated&&oC(t),Z$(t),dC(t)})}function oC(t){const{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,W._)`${n}.evaluated`),e.if((0,W._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,W._)`${t.evaluated}.props`,(0,W._)`undefined`)),e.if((0,W._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,W._)`${t.evaluated}.items`,(0,W._)`undefined`))}function hm(t,e){const n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,W._)`/*# sourceURL=${n} */`:W.nil}function sC(t,e){if(Q$(t)&&(Y$(t),J$(t))){iC(t,e);return}(0,W$.boolOrEmptySchema)(t,e)}function J$({schema:t,self:e}){if(typeof t=="boolean")return!t;for(const n in t)if(e.RULES.all[n])return!0;return!1}function Q$(t){return typeof t.schema!="boolean"}function iC(t,e){const{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&X$(t),uC(t),lC(t);const s=r.const("_errs",Y.default.errors);Z$(t,s),r.var(e,(0,W._)`${s} === ${Y.default.errors}`)}function Y$(t){(0,en.checkUnknownRules)(t),aC(t)}function Z$(t,e){if(t.opts.jtd)return mm(t,[],!1,e);const n=(0,pm.getSchemaTypes)(t.schema),r=(0,pm.coerceAndCheckDataType)(t,n);mm(t,n,!r,e)}function aC(t){const{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,en.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function cC(t){const{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,en.checkStrictMode)(t,"default is ignored in the schema root")}function uC(t){const e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,XT.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function lC(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function X$({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)t.code((0,W._)`${Y.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,W.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,W._)`${Y.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function dC(t){const{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,W._)`${Y.default.errors} === 0`,()=>e.return(Y.default.data),()=>e.throw((0,W._)`new ${o}(${Y.default.vErrors})`)):(e.assign((0,W._)`${r}.errors`,Y.default.vErrors),s.unevaluated&&fC(t),e.return((0,W._)`${Y.default.errors} === 0`))}function fC({gen:t,evaluated:e,props:n,items:r}){n instanceof W.Name&&t.assign((0,W._)`${e}.props`,n),r instanceof W.Name&&t.assign((0,W._)`${e}.items`,r)}function mm(t,e,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,en.schemaHasRulesButRef)(s,l))){o.block(()=>n0(t,"$ref",l.all.$ref.definition));return}c.jtd||pC(t,e),o.block(()=>{for(const f of l.rules)d(f);d(l.post)});function d(f){(0,ef.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Xi.checkDataType)(f.type,i,c.strictNumbers)),gm(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,Xi.reportTypeError)(t)),o.endIf()):gm(t,f),a||o.if((0,W._)`${Y.default.errors} === ${r||0}`))}}function gm(t,e){const{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,ZT.assignDefaults)(t,e.type),n.block(()=>{for(const s of e.rules)(0,ef.shouldUseRule)(r,s)&&n0(t,s.keyword,s.definition,e.type)})}function pC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(hC(t,e),t.opts.allowUnionTypes||mC(t,e),gC(t,t.dataTypes))}function hC(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{e0(t.dataTypes,n)||tf(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),wC(t,e)}}function mC(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&tf(t,"use allowUnionTypes to allow union type keyword")}function gC(t,e){const n=t.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,ef.shouldUseRule)(t.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>yC(e,i))&&tf(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function yC(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function e0(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function wC(t,e){const n=[];for(const r of t.dataTypes)e0(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function tf(t,e){const n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,en.checkStrictMode)(t,e,t.opts.strictTypes)}class t0{constructor(e,n,r){if((0,Jo.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,en.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",r0(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Jo.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",Y.default.errors))}result(e,n,r){this.failResult((0,W.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,W.not)(e),void 0,n)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);const{schemaCode:n}=this;this.fail((0,W._)`${n} !== undefined && (${(0,W.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?So.reportExtraError:So.reportError)(this,this.def.error,n)}$dataError(){(0,So.reportError)(this,this.def.$dataError||So.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,So.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=W.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=W.nil,n=W.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,W.or)((0,W._)`${o} === undefined`,n)),e!==W.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==W.nil&&r.assign(e,!1)),r.else()}invalid$data(){const{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,W.or)(i(),a());function i(){if(r.length){if(!(n instanceof W.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,W._)`${(0,Xi.checkDataTypes)(c,n,s.opts.strictNumbers,Xi.DataType.Wrong)}`}return W.nil}function a(){if(o.validateSchema){const c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,W._)`!${c}(${n})`}return W.nil}}subschema(e,n){const r=(0,mc.getSubschema)(this.it,e);(0,mc.extendSubschemaData)(r,this.it,e),(0,mc.extendSubschemaMode)(r,e);const o={...this.it,...r,items:void 0,props:void 0};return sC(o,n),o}mergeEvaluated(e,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=en.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=en.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,W.Name)),!0}}kt.KeywordCxt=t0;function n0(t,e,n,r){const o=new t0(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,Jo.funcKeywordCode)(o,n):"macro"in n?(0,Jo.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,Jo.funcKeywordCode)(o,n)}const vC=/^\/(?:[^~]|~0|~1)*$/,$C=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function r0(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!vC.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=Y.default.rootData}else{const u=$C.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);const l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,W._)`${s}${(0,W.getProperty)((0,en.unescapeJsonPointer)(u))}`,i=(0,W._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}kt.getData=r0;var js={};Object.defineProperty(js,"__esModule",{value:!0});let bC=class extends Error{constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};js.default=bC;var ho={};Object.defineProperty(ho,"__esModule",{value:!0});const gc=De;class EC extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,gc.resolveUrl)(e,n,r),this.missingSchema=(0,gc.normalizeId)((0,gc.getFullPath)(e,this.missingRef))}}ho.default=EC;var at={};Object.defineProperty(at,"__esModule",{value:!0});at.resolveSchema=at.getCompilingSchema=at.resolveRef=at.compileSchema=at.SchemaEnv=void 0;const vt=ce,SC=js,zn=Ft,St=De,ym=V,_C=kt;class La{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,St.normalizeId)(r==null?void 0:r[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}at.SchemaEnv=La;function nf(t){const e=o0.call(this,t);if(e)return e;const n=(0,St.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new vt.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;t.$async&&(a=i.scopeValue("Error",{ref:SC.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");t.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:zn.default.data,parentData:zn.default.parentData,parentDataProperty:zn.default.parentDataProperty,dataNames:[zn.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,vt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:vt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(t),(0,_C.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const d=i.toString();l=`${i.scopeRefs(zn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));const f=new Function(`${zn.default.self}`,`${zn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){const{props:g,items:p}=u;f.evaluated={props:g instanceof vt.Name?void 0:g,items:p instanceof vt.Name?void 0:p,dynamicProps:g instanceof vt.Name,dynamicItems:p instanceof vt.Name},f.source&&(f.source.evaluated=(0,vt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}at.compileSchema=nf;function NC(t,e,n){var r;n=(0,St.resolveUrl)(this.opts.uriResolver,e,n);const o=t.refs[n];if(o)return o;let s=jC.call(this,t,n);if(s===void 0){const i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new La({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=OC.call(this,s)}at.resolveRef=NC;function OC(t){return(0,St.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:nf.call(this,t)}function o0(t){for(const e of this._compilations)if(kC(e,t))return e}at.getCompilingSchema=o0;function kC(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function jC(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Da.call(this,t,e)}function Da(t,e){const n=this.opts.uriResolver.parse(e),r=(0,St._getFullPath)(this.opts.uriResolver,n);let o=(0,St.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return yc.call(this,n,t);const s=(0,St.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Da.call(this,t,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:yc.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||nf.call(this,i),s===(0,St.normalizeId)(e)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,St.resolveUrl)(this.opts.uriResolver,o,u)),new La({schema:a,schemaId:c,root:t,baseId:o})}return yc.call(this,n,i)}}at.resolveSchema=Da;const AC=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function yc(t,{baseId:e,schema:n,root:r}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of t.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,ym.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!AC.has(a)&&u&&(e=(0,St.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,ym.schemaHasRulesButRef)(n,this.RULES)){const a=(0,St.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=Da.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new La({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}const IC="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",PC="Meta-schema for $data reference (JSON AnySchema extension proposal)",xC="object",RC=["$data"],TC={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},CC=!1,MC={$id:IC,description:PC,type:xC,required:RC,properties:TC,additionalProperties:CC};var rf={},Ua={exports:{}};const LC=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),s0=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),of=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),i0=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),DC=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function a0(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}const UC=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function wm(t){return t.length=0,!0}function BC(t,e,n){if(t.length){const r=a0(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function FC(t){let e=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=BC;for(let c=0;c<t.length;c++){const u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=wm}else{o.push(u);continue}}return o.length&&(a===wm?n.zone=o.join(""):i?r.push(o.join("")):r.push(a0(o))),n.address=r.join(""),n}function c0(t){if(qC(t,":")<2)return{host:t,isIPV6:!1};const e=FC(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function qC(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function KC(t){let e=t;const n=[];let r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}const VC={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},GC=/[@/?#:]/g,zC=/[@/?#]/g;function u0(t,e){const n=e?zC:GC;return n.lastIndex=0,t.replace(n,r=>VC[r])}function WC(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){const o=t.slice(r+1,r+3);if(of(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&i0(i)?n+=i:n+="%"+s,r+=2;continue}}n+=t[r]}return n}function HC(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){const r=t.slice(n+1,n+3);if(of(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&i0(s)?e+=s:e+="%"+o,n+=2;continue}}DC(t[n])?e+=t[n]:e+=escape(t[n])}return e}function JC(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){const r=t.slice(n+1,n+3);if(of(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function QC(t){const e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!s0(n)){const r=c0(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=u0(n,!1)}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}var l0={nonSimpleDomain:UC,recomposeAuthority:QC,reescapeHostDelimiters:u0,normalizePercentEncoding:WC,normalizePathEncoding:HC,escapePreservingEscapes:JC,removeDotSegments:KC,isIPv4:s0,isUUID:LC,normalizeIPv6:c0};const{isUUID:YC}=l0,ZC=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function d0(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function f0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function p0(t){const e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function XC(t){return t.secure=d0(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function eM(t){if((t.port===(d0(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){const[e,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function tM(t,e){if(!t.path)return t.error="URN can not be parsed",t;const n=t.path.match(ZC);if(n){const r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];const o=`${r}:${e.nid||t.nid}`,s=sf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function nM(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=sf(o);s&&(t=s.serialize(t,e));const i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function rM(t,e){const n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!YC(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function oM(t){const e=t;return e.nss=(t.uuid||"").toLowerCase(),e}const h0={scheme:"http",domainHost:!0,parse:f0,serialize:p0},sM={scheme:"https",domainHost:h0.domainHost,parse:f0,serialize:p0},xi={scheme:"ws",domainHost:!0,parse:XC,serialize:eM},iM={scheme:"wss",domainHost:xi.domainHost,parse:xi.parse,serialize:xi.serialize},aM={scheme:"urn",parse:tM,serialize:nM,skipNormalize:!0},cM={scheme:"urn:uuid",parse:rM,serialize:oM,skipNormalize:!0},ea={http:h0,https:sM,ws:xi,wss:iM,urn:aM,"urn:uuid":cM};Object.setPrototypeOf(ea,null);function sf(t){return t&&(ea[t]||ea[t.toLowerCase()])||void 0}var uM={SCHEMES:ea,getSchemeHandler:sf};const{normalizeIPv6:lM,removeDotSegments:Ro,recomposeAuthority:dM,normalizePercentEncoding:fM,normalizePathEncoding:pM,escapePreservingEscapes:hM,reescapeHostDelimiters:mM,isIPv4:gM,nonSimpleDomain:yM}=l0,{SCHEMES:wM,getSchemeHandler:m0}=uM;function vM(t,e){return typeof t=="string"?t=NM(t,e):typeof t=="object"&&(t=so($r(t,e),e)),t}function $M(t,e,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=g0(so(t,r),so(e,r),r,!0);return r.skipEscape=!0,$r(o,r)}function g0(t,e,n,r){const o={};return r||(t=so($r(t,n),n),e=so($r(e,n),n)),n=n||{},!n.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ro(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ro(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ro(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Ro(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function bM(t,e,n){const r=vm(t,n),o=vm(e,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function $r(t,e){const n={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},r=Object.assign({},e),o=[],s=m0(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=fM(n.path):(n.path=hM(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=dM(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=Ro(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}const EM=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,SM=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function _M(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function y0(t,e){const n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0};let o=!1,s=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);const i=t.match(SM);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);const a=t.match(EM);if(a){r.scheme=a[1],r.userinfo=a[3],r.host=a[4],r.port=parseInt(a[5],10),r.path=a[6]||"",r.query=a[7],r.fragment=a[8],isNaN(r.port)&&(r.port=a[5]);const c=_M(r,a);if(c!==void 0&&(r.error=r.error||c,o=!0),r.host)if(gM(r.host)===!1){const l=lM(r.host);r.host=l.host.toLowerCase(),s=l.isIPV6}else s=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");const u=m0(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&s===!1&&yM(r.host))try{r.host=new URL("http://"+r.host).hostname}catch(l){r.error=r.error||"Host's domain name can not be converted to ASCII: "+l}if((!u||u&&!u.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=mM(unescape(r.host),s))),r.path&&(r.path=pM(r.path)),r.fragment))try{r.fragment=encodeURI(decodeURIComponent(r.fragment))}catch{r.error=r.error||"URI malformed"}u&&u.parse&&u.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o}}function so(t,e){return y0(t,e).parsed}function NM(t,e){return w0(t,e).normalized}function w0(t,e){const{parsed:n,malformedAuthorityOrPort:r}=y0(t,e);return{normalized:r?t:$r(n,e),malformedAuthorityOrPort:r}}function vm(t,e){if(typeof t=="string"){const{normalized:n,malformedAuthorityOrPort:r}=w0(t,e);return r?void 0:n}if(typeof t=="object")return $r(t,e)}const af={SCHEMES:wM,normalize:vM,resolve:$M,resolveComponent:g0,equal:bM,serialize:$r,parse:so};Ua.exports=af;Ua.exports.default=af;Ua.exports.fastUri=af;var OM=Ua.exports;Object.defineProperty(rf,"__esModule",{value:!0});const v0=OM;v0.code='require("ajv/dist/runtime/uri").default';rf.default=v0;(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=void 0;var e=kt;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return e.KeywordCxt}});var n=ce;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=js,o=ho,s=vr,i=at,a=ce,c=De,u=Ie,l=V,d=MC,f=rf,g=(A,S)=>new RegExp(A,S);g.code="new RegExp";const p=["removeAdditional","useDefaults","coerceTypes"],y=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),w={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."},h={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function b(A){var S,k,_,m,$,O,x,R,U,q,re,Qe,jn,An,In,Pn,xn,Rn,Tn,Cn,Mn,Ln,Dn,Un,Bn;const yt=A.strict,Fn=(S=A.code)===null||S===void 0?void 0:S.optimize,wo=Fn===!0||Fn===void 0?1:Fn||0,vo=(_=(k=A.code)===null||k===void 0?void 0:k.regExp)!==null&&_!==void 0?_:g,Ha=(m=A.uriResolver)!==null&&m!==void 0?m:f.default;return{strictSchema:(O=($=A.strictSchema)!==null&&$!==void 0?$:yt)!==null&&O!==void 0?O:!0,strictNumbers:(R=(x=A.strictNumbers)!==null&&x!==void 0?x:yt)!==null&&R!==void 0?R:!0,strictTypes:(q=(U=A.strictTypes)!==null&&U!==void 0?U:yt)!==null&&q!==void 0?q:"log",strictTuples:(Qe=(re=A.strictTuples)!==null&&re!==void 0?re:yt)!==null&&Qe!==void 0?Qe:"log",strictRequired:(An=(jn=A.strictRequired)!==null&&jn!==void 0?jn:yt)!==null&&An!==void 0?An:!1,code:A.code?{...A.code,optimize:wo,regExp:vo}:{optimize:wo,regExp:vo},loopRequired:(In=A.loopRequired)!==null&&In!==void 0?In:v,loopEnum:(Pn=A.loopEnum)!==null&&Pn!==void 0?Pn:v,meta:(xn=A.meta)!==null&&xn!==void 0?xn:!0,messages:(Rn=A.messages)!==null&&Rn!==void 0?Rn:!0,inlineRefs:(Tn=A.inlineRefs)!==null&&Tn!==void 0?Tn:!0,schemaId:(Cn=A.schemaId)!==null&&Cn!==void 0?Cn:"$id",addUsedSchema:(Mn=A.addUsedSchema)!==null&&Mn!==void 0?Mn:!0,validateSchema:(Ln=A.validateSchema)!==null&&Ln!==void 0?Ln:!0,validateFormats:(Dn=A.validateFormats)!==null&&Dn!==void 0?Dn:!0,unicodeRegExp:(Un=A.unicodeRegExp)!==null&&Un!==void 0?Un:!0,int32range:(Bn=A.int32range)!==null&&Bn!==void 0?Bn:!0,uriResolver:Ha}}class E{constructor(S={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,S=this.opts={...S,...b(S)};const{es5:k,lines:_}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:y,es5:k,lines:_}),this.logger=Z(S.logger);const m=S.validateFormats;S.validateFormats=!1,this.RULES=(0,s.getRules)(),N.call(this,w,S,"NOT SUPPORTED"),N.call(this,h,S,"DEPRECATED","warn"),this._metaOpts=G.call(this),S.formats&&M.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&C.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),T.call(this),S.validateFormats=m}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:k,schemaId:_}=this.opts;let m=d;_==="id"&&(m={...d},m.id=m.$id,delete m.$id),k&&S&&this.addMetaSchema(m,m[_],!1)}defaultMeta(){const{meta:S,schemaId:k}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[k]||S:void 0}validate(S,k){let _;if(typeof S=="string"){if(_=this.getSchema(S),!_)throw new Error(`no schema with key or ref "${S}"`)}else _=this.compile(S);const m=_(k);return"$async"in _||(this.errors=_.errors),m}compile(S,k){const _=this._addSchema(S,k);return _.validate||this._compileSchemaEnv(_)}compileAsync(S,k){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:_}=this.opts;return m.call(this,S,k);async function m(q,re){await $.call(this,q.$schema);const Qe=this._addSchema(q,re);return Qe.validate||O.call(this,Qe)}async function $(q){q&&!this.getSchema(q)&&await m.call(this,{$ref:q},!0)}async function O(q){try{return this._compileSchemaEnv(q)}catch(re){if(!(re instanceof o.default))throw re;return x.call(this,re),await R.call(this,re.missingSchema),O.call(this,q)}}function x({missingSchema:q,missingRef:re}){if(this.refs[q])throw new Error(`AnySchema ${q} is loaded but ${re} cannot be resolved`)}async function R(q){const re=await U.call(this,q);this.refs[q]||await $.call(this,re.$schema),this.refs[q]||this.addSchema(re,q,k)}async function U(q){const re=this._loading[q];if(re)return re;try{return await(this._loading[q]=_(q))}finally{delete this._loading[q]}}}addSchema(S,k,_,m=this.opts.validateSchema){if(Array.isArray(S)){for(const O of S)this.addSchema(O,void 0,_,m);return this}let $;if(typeof S=="object"){const{schemaId:O}=this.opts;if($=S[O],$!==void 0&&typeof $!="string")throw new Error(`schema ${O} must be string`)}return k=(0,c.normalizeId)(k||$),this._checkUnique(k),this.schemas[k]=this._addSchema(S,_,k,m,!0),this}addMetaSchema(S,k,_=this.opts.validateSchema){return this.addSchema(S,k,!0,_),this}validateSchema(S,k){if(typeof S=="boolean")return!0;let _;if(_=S.$schema,_!==void 0&&typeof _!="string")throw new Error("$schema must be a string");if(_=_||this.opts.defaultMeta||this.defaultMeta(),!_)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const m=this.validate(_,S);if(!m&&k){const $="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error($);else throw new Error($)}return m}getSchema(S){let k;for(;typeof(k=j.call(this,S))=="string";)S=k;if(k===void 0){const{schemaId:_}=this.opts,m=new i.SchemaEnv({schema:{},schemaId:_});if(k=i.resolveSchema.call(this,m,S),!k)return;this.refs[S]=k}return k.validate||this._compileSchemaEnv(k)}removeSchema(S){if(S instanceof RegExp)return this._removeAllSchemas(this.schemas,S),this._removeAllSchemas(this.refs,S),this;switch(typeof S){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{const k=j.call(this,S);return typeof k=="object"&&this._cache.delete(k.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const k=S;this._cache.delete(k);let _=S[this.opts.schemaId];return _&&(_=(0,c.normalizeId)(_),delete this.schemas[_],delete this.refs[_]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const k of S)this.addKeyword(k);return this}addKeyword(S,k){let _;if(typeof S=="string")_=S,typeof k=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),k.keyword=_);else if(typeof S=="object"&&k===void 0){if(k=S,_=k.keyword,Array.isArray(_)&&!_.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(fe.call(this,_,k),!k)return(0,l.eachItem)(_,$=>he.call(this,$)),this;Oe.call(this,k);const m={...k,type:(0,u.getJSONTypes)(k.type),schemaType:(0,u.getJSONTypes)(k.schemaType)};return(0,l.eachItem)(_,m.type.length===0?$=>he.call(this,$,m):$=>m.type.forEach(O=>he.call(this,$,m,O))),this}getKeyword(S){const k=this.RULES.all[S];return typeof k=="object"?k.definition:!!k}removeKeyword(S){const{RULES:k}=this;delete k.keywords[S],delete k.all[S];for(const _ of k.rules){const m=_.rules.findIndex($=>$.keyword===S);m>=0&&_.rules.splice(m,1)}return this}addFormat(S,k){return typeof k=="string"&&(k=new RegExp(k)),this.formats[S]=k,this}errorsText(S=this.errors,{separator:k=", ",dataVar:_="data"}={}){return!S||S.length===0?"No errors":S.map(m=>`${_}${m.instancePath} ${m.message}`).reduce((m,$)=>m+k+$)}$dataMetaSchema(S,k){const _=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const m of k){const $=m.split("/").slice(1);let O=S;for(const x of $)O=O[x];for(const x in _){const R=_[x];if(typeof R!="object")continue;const{$data:U}=R.definition,q=O[x];U&&q&&(O[x]=ut(q))}}return S}_removeAllSchemas(S,k){for(const _ in S){const m=S[_];(!k||k.test(_))&&(typeof m=="string"?delete S[_]:m&&!m.meta&&(this._cache.delete(m.schema),delete S[_]))}}_addSchema(S,k,_,m=this.opts.validateSchema,$=this.opts.addUsedSchema){let O;const{schemaId:x}=this.opts;if(typeof S=="object")O=S[x];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof S!="boolean")throw new Error("schema must be object or boolean")}let R=this._cache.get(S);if(R!==void 0)return R;_=(0,c.normalizeId)(O||_);const U=c.getSchemaRefs.call(this,S,_);return R=new i.SchemaEnv({schema:S,schemaId:x,meta:k,baseId:_,localRefs:U}),this._cache.set(R.schema,R),$&&!_.startsWith("#")&&(_&&this._checkUnique(_),this.refs[_]=R),m&&this.validateSchema(S,!0),R}_checkUnique(S){if(this.schemas[S]||this.refs[S])throw new Error(`schema with key or id "${S}" already exists`)}_compileSchemaEnv(S){if(S.meta?this._compileMetaSchema(S):i.compileSchema.call(this,S),!S.validate)throw new Error("ajv implementation error");return S.validate}_compileMetaSchema(S){const k=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,S)}finally{this.opts=k}}}E.ValidationError=r.default,E.MissingRefError=o.default,t.default=E;function N(A,S,k,_="error"){for(const m in A){const $=m;$ in S&&this.logger[_](`${k}: option ${m}. ${A[$]}`)}}function j(A){return A=(0,c.normalizeId)(A),this.schemas[A]||this.refs[A]}function T(){const A=this.opts.schemas;if(A)if(Array.isArray(A))this.addSchema(A);else for(const S in A)this.addSchema(A[S],S)}function M(){for(const A in this.opts.formats){const S=this.opts.formats[A];S&&this.addFormat(A,S)}}function C(A){if(Array.isArray(A)){this.addVocabulary(A);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in A){const k=A[S];k.keyword||(k.keyword=S),this.addKeyword(k)}}function G(){const A={...this.opts};for(const S of p)delete A[S];return A}const H={log(){},warn(){},error(){}};function Z(A){if(A===!1)return H;if(A===void 0)return console;if(A.log&&A.warn&&A.error)return A;throw new Error("logger must implement log, warn and error methods")}const ue=/^[a-z_$][a-z0-9_$:-]*$/i;function fe(A,S){const{RULES:k}=this;if((0,l.eachItem)(A,_=>{if(k.keywords[_])throw new Error(`Keyword ${_} is already defined`);if(!ue.test(_))throw new Error(`Keyword ${_} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function he(A,S,k){var _;const m=S==null?void 0:S.post;if(k&&m)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:$}=this;let O=m?$.post:$.rules.find(({type:R})=>R===k);if(O||(O={type:k,rules:[]},$.rules.push(O)),$.keywords[A]=!0,!S)return;const x={keyword:A,definition:{...S,type:(0,u.getJSONTypes)(S.type),schemaType:(0,u.getJSONTypes)(S.schemaType)}};S.before?pe.call(this,O,x,S.before):O.rules.push(x),$.all[A]=x,(_=S.implements)===null||_===void 0||_.forEach(R=>this.addKeyword(R))}function pe(A,S,k){const _=A.rules.findIndex(m=>m.keyword===k);_>=0?A.rules.splice(_,0,S):(A.rules.push(S),this.logger.warn(`rule ${k} is not defined`))}function Oe(A){let{metaSchema:S}=A;S!==void 0&&(A.$data&&this.opts.$data&&(S=ut(S)),A.validateSchema=this.compile(S,!0))}const gt={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function ut(A){return{anyOf:[A,gt]}}})(O$);var cf={},uf={},lf={};Object.defineProperty(lf,"__esModule",{value:!0});const kM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};lf.default=kM;var br={};Object.defineProperty(br,"__esModule",{value:!0});br.callRef=br.getValidate=void 0;const jM=ho,$m=ie,tt=ce,Pr=Ft,bm=at,Xs=V,AM={keyword:"$ref",schemaType:"string",code(t){const{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();const l=bm.resolveRef.call(c,u,o,n);if(l===void 0)throw new jM.default(r.opts.uriResolver,o,n);if(l instanceof bm.SchemaEnv)return f(l);return g(l);function d(){if(s===u)return Ri(t,i,s,s.$async);const p=e.scopeValue("root",{ref:u});return Ri(t,(0,tt._)`${p}.validate`,u,u.$async)}function f(p){const y=$0(t,p);Ri(t,y,p,p.$async)}function g(p){const y=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,tt.stringify)(p)}:{ref:p}),w=e.name("valid"),h=t.subschema({schema:p,dataTypes:[],schemaPath:tt.nil,topSchemaRef:y,errSchemaPath:n},w);t.mergeEvaluated(h),t.ok(w)}}};function $0(t,e){const{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,tt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}br.getValidate=$0;function Ri(t,e,n,r){const{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Pr.default.this:tt.nil;r?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const p=o.let("valid");o.try(()=>{o.code((0,tt._)`await ${(0,$m.callValidateCode)(t,e,u)}`),g(e),i||o.assign(p,!0)},y=>{o.if((0,tt._)`!(${y} instanceof ${s.ValidationError})`,()=>o.throw(y)),f(y),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,$m.callValidateCode)(t,e,u),()=>g(e),()=>f(e))}function f(p){const y=(0,tt._)`${p}.errors`;o.assign(Pr.default.vErrors,(0,tt._)`${Pr.default.vErrors} === null ? ${y} : ${Pr.default.vErrors}.concat(${y})`),o.assign(Pr.default.errors,(0,tt._)`${Pr.default.vErrors}.length`)}function g(p){var y;if(!s.opts.unevaluated)return;const w=(y=n==null?void 0:n.validate)===null||y===void 0?void 0:y.evaluated;if(s.props!==!0)if(w&&!w.dynamicProps)w.props!==void 0&&(s.props=Xs.mergeEvaluated.props(o,w.props,s.props));else{const h=o.var("props",(0,tt._)`${p}.evaluated.props`);s.props=Xs.mergeEvaluated.props(o,h,s.props,tt.Name)}if(s.items!==!0)if(w&&!w.dynamicItems)w.items!==void 0&&(s.items=Xs.mergeEvaluated.items(o,w.items,s.items));else{const h=o.var("items",(0,tt._)`${p}.evaluated.items`);s.items=Xs.mergeEvaluated.items(o,h,s.items,tt.Name)}}}br.callRef=Ri;br.default=AM;Object.defineProperty(uf,"__esModule",{value:!0});const IM=lf,PM=br,xM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",IM.default,PM.default];uf.default=xM;var df={},ff={};Object.defineProperty(ff,"__esModule",{value:!0});const ta=ce,fn=ta.operators,na={maximum:{okStr:"<=",ok:fn.LTE,fail:fn.GT},minimum:{okStr:">=",ok:fn.GTE,fail:fn.LT},exclusiveMaximum:{okStr:"<",ok:fn.LT,fail:fn.GTE},exclusiveMinimum:{okStr:">",ok:fn.GT,fail:fn.LTE}},RM={message:({keyword:t,schemaCode:e})=>(0,ta.str)`must be ${na[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ta._)`{comparison: ${na[t].okStr}, limit: ${e}}`},TM={keyword:Object.keys(na),type:"number",schemaType:"number",$data:!0,error:RM,code(t){const{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,ta._)`${n} ${na[e].fail} ${r} || isNaN(${n})`)}};ff.default=TM;var pf={};Object.defineProperty(pf,"__esModule",{value:!0});const Qo=ce,CM={message:({schemaCode:t})=>(0,Qo.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Qo._)`{multipleOf: ${t}}`},MM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:CM,code(t){const{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Qo._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Qo._)`${i} !== parseInt(${i})`;t.fail$data((0,Qo._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};pf.default=MM;var hf={},mf={};Object.defineProperty(mf,"__esModule",{value:!0});function b0(t){const e=t.length;let n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}mf.default=b0;b0.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(hf,"__esModule",{value:!0});const nr=ce,LM=V,DM=mf,UM={message({keyword:t,schemaCode:e}){const n=t==="maxLength"?"more":"fewer";return(0,nr.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,nr._)`{limit: ${t}}`},BM={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:UM,code(t){const{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?nr.operators.GT:nr.operators.LT,i=o.opts.unicode===!1?(0,nr._)`${n}.length`:(0,nr._)`${(0,LM.useFunc)(t.gen,DM.default)}(${n})`;t.fail$data((0,nr._)`${i} ${s} ${r}`)}};hf.default=BM;var gf={};Object.defineProperty(gf,"__esModule",{value:!0});const FM=ie,qM=V,Gr=ce,KM={message:({schemaCode:t})=>(0,Gr.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Gr._)`{pattern: ${t}}`},VM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:KM,code(t){const{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Gr._)`new RegExp`:(0,qM.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Gr._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,Gr._)`!${l}`)}else{const c=(0,FM.usePattern)(t,o);t.fail$data((0,Gr._)`!${c}.test(${n})`)}}};gf.default=VM;var yf={};Object.defineProperty(yf,"__esModule",{value:!0});const Yo=ce,GM={message({keyword:t,schemaCode:e}){const n=t==="maxProperties"?"more":"fewer";return(0,Yo.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Yo._)`{limit: ${t}}`},zM={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:GM,code(t){const{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Yo.operators.GT:Yo.operators.LT;t.fail$data((0,Yo._)`Object.keys(${n}).length ${o} ${r}`)}};yf.default=zM;var wf={};Object.defineProperty(wf,"__esModule",{value:!0});const _o=ie,Zo=ce,WM=V,HM={message:({params:{missingProperty:t}})=>(0,Zo.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Zo._)`{missingProperty: ${t}}`},JM={keyword:"required",type:"object",schemaType:"array",$data:!0,error:HM,code(t){const{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const g=t.parentSchema.properties,{definedProperties:p}=t.it;for(const y of n)if((g==null?void 0:g[y])===void 0&&!p.has(y)){const w=i.schemaEnv.baseId+i.errSchemaPath,h=`required property "${y}" is not defined at "${w}" (strictRequired)`;(0,WM.checkStrictMode)(i,h,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Zo.nil,d);else for(const g of n)(0,_o.checkReportMissingProp)(t,g)}function l(){const g=e.let("missing");if(c||s){const p=e.let("valid",!0);t.block$data(p,()=>f(g,p)),t.ok(p)}else e.if((0,_o.checkMissingProp)(t,n,g)),(0,_o.reportMissingProp)(t,g),e.else()}function d(){e.forOf("prop",r,g=>{t.setParams({missingProperty:g}),e.if((0,_o.noPropertyInData)(e,o,g,a.ownProperties),()=>t.error())})}function f(g,p){t.setParams({missingProperty:g}),e.forOf(g,r,()=>{e.assign(p,(0,_o.propertyInData)(e,o,g,a.ownProperties)),e.if((0,Zo.not)(p),()=>{t.error(),e.break()})},Zo.nil)}}};wf.default=JM;var vf={};Object.defineProperty(vf,"__esModule",{value:!0});const Xo=ce,QM={message({keyword:t,schemaCode:e}){const n=t==="maxItems"?"more":"fewer";return(0,Xo.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Xo._)`{limit: ${t}}`},YM={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:QM,code(t){const{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Xo.operators.GT:Xo.operators.LT;t.fail$data((0,Xo._)`${n}.length ${o} ${r}`)}};vf.default=YM;var $f={},As={};Object.defineProperty(As,"__esModule",{value:!0});const E0=q$;E0.code='require("ajv/dist/runtime/equal").default';As.default=E0;Object.defineProperty($f,"__esModule",{value:!0});const wc=Ie,Me=ce,ZM=V,XM=As,eL={message:({params:{i:t,j:e}})=>(0,Me.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Me._)`{i: ${t}, j: ${e}}`},tL={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:eL,code(t){const{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;const c=e.let("valid"),u=s.items?(0,wc.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Me._)`${i} === false`),t.ok(c);function l(){const p=e.let("i",(0,Me._)`${n}.length`),y=e.let("j");t.setParams({i:p,j:y}),e.assign(c,!0),e.if((0,Me._)`${p} > 1`,()=>(d()?f:g)(p,y))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,y){const w=e.name("item"),h=(0,wc.checkDataTypes)(u,w,a.opts.strictNumbers,wc.DataType.Wrong),v=e.const("indices",(0,Me._)`{}`);e.for((0,Me._)`;${p}--;`,()=>{e.let(w,(0,Me._)`${n}[${p}]`),e.if(h,(0,Me._)`continue`),u.length>1&&e.if((0,Me._)`typeof ${w} == "string"`,(0,Me._)`${w} += "_"`),e.if((0,Me._)`typeof ${v}[${w}] == "number"`,()=>{e.assign(y,(0,Me._)`${v}[${w}]`),t.error(),e.assign(c,!1).break()}).code((0,Me._)`${v}[${w}] = ${p}`)})}function g(p,y){const w=(0,ZM.useFunc)(e,XM.default),h=e.name("outer");e.label(h).for((0,Me._)`;${p}--;`,()=>e.for((0,Me._)`${y} = ${p}; ${y}--;`,()=>e.if((0,Me._)`${w}(${n}[${p}], ${n}[${y}])`,()=>{t.error(),e.assign(c,!1).break(h)})))}}};$f.default=tL;var bf={};Object.defineProperty(bf,"__esModule",{value:!0});const Ru=ce,nL=V,rL=As,oL={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ru._)`{allowedValue: ${t}}`},sL={keyword:"const",$data:!0,error:oL,code(t){const{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,Ru._)`!${(0,nL.useFunc)(e,rL.default)}(${n}, ${o})`):t.fail((0,Ru._)`${s} !== ${n}`)}};bf.default=sL;var Ef={};Object.defineProperty(Ef,"__esModule",{value:!0});const To=ce,iL=V,aL=As,cL={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,To._)`{allowedValues: ${t}}`},uL={keyword:"enum",schemaType:"array",$data:!0,error:cL,code(t){const{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");const a=o.length>=i.opts.loopEnum;let c;const u=()=>c??(c=(0,iL.useFunc)(e,aL.default));let l;if(a||r)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const g=e.const("vSchema",s);l=(0,To.or)(...o.map((p,y)=>f(g,y)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,g=>e.if((0,To._)`${u()}(${n}, ${g})`,()=>e.assign(l,!0).break()))}function f(g,p){const y=o[p];return typeof y=="object"&&y!==null?(0,To._)`${u()}(${n}, ${g}[${p}])`:(0,To._)`${n} === ${y}`}}};Ef.default=uL;Object.defineProperty(df,"__esModule",{value:!0});const lL=ff,dL=pf,fL=hf,pL=gf,hL=yf,mL=wf,gL=vf,yL=$f,wL=bf,vL=Ef,$L=[lL.default,dL.default,fL.default,pL.default,hL.default,mL.default,gL.default,yL.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},wL.default,vL.default];df.default=$L;var Sf={},mo={};Object.defineProperty(mo,"__esModule",{value:!0});mo.validateAdditionalItems=void 0;const rr=ce,Tu=V,bL={message:({params:{len:t}})=>(0,rr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,rr._)`{limit: ${t}}`},EL={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:bL,code(t){const{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Tu.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}S0(t,r)}};function S0(t,e){const{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;const a=n.const("len",(0,rr._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,rr._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Tu.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,rr._)`${a} <= ${e.length}`);n.if((0,rr.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Tu.Type.Num},u),i.allErrors||n.if((0,rr.not)(u),()=>n.break())})}}mo.validateAdditionalItems=S0;mo.default=EL;var _f={},go={};Object.defineProperty(go,"__esModule",{value:!0});go.validateTuple=void 0;const Em=ce,Ti=V,SL=ie,_L={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){const{schema:e,it:n}=t;if(Array.isArray(e))return _0(t,"additionalItems",e);n.items=!0,!(0,Ti.alwaysValidSchema)(n,e)&&t.ok((0,SL.validateArray)(t))}};function _0(t,e,n=t.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Ti.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,Em._)`${s}.length`);n.forEach((d,f)=>{(0,Ti.alwaysValidSchema)(a,d)||(r.if((0,Em._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){const{opts:f,errSchemaPath:g}=a,p=n.length,y=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!y){const w=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${g}"`;(0,Ti.checkStrictMode)(a,w,f.strictTuples)}}}go.validateTuple=_0;go.default=_L;Object.defineProperty(_f,"__esModule",{value:!0});const NL=go,OL={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,NL.validateTuple)(t,"items")};_f.default=OL;var Nf={};Object.defineProperty(Nf,"__esModule",{value:!0});const Sm=ce,kL=V,jL=ie,AL=mo,IL={message:({params:{len:t}})=>(0,Sm.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Sm._)`{limit: ${t}}`},PL={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:IL,code(t){const{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,kL.alwaysValidSchema)(r,e)&&(o?(0,AL.validateAdditionalItems)(t,o):t.ok((0,jL.validateArray)(t)))}};Nf.default=PL;var Of={};Object.defineProperty(Of,"__esModule",{value:!0});const ft=ce,ei=V,xL={message:({params:{min:t,max:e}})=>e===void 0?(0,ft.str)`must contain at least ${t} valid item(s)`:(0,ft.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,ft._)`{minContains: ${t}}`:(0,ft._)`{minContains: ${t}, maxContains: ${e}}`},RL={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:xL,code(t){const{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=e.const("len",(0,ft._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ei.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ei.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ei.alwaysValidSchema)(s,n)){let y=(0,ft._)`${l} >= ${i}`;a!==void 0&&(y=(0,ft._)`${y} && ${l} <= ${a}`),t.pass(y);return}s.items=!0;const d=e.name("valid");a===void 0&&i===1?g(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,ft._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){const y=e.name("_valid"),w=e.let("count",0);g(y,()=>e.if(y,()=>p(w)))}function g(y,w){e.forRange("i",0,l,h=>{t.subschema({keyword:"contains",dataProp:h,dataPropType:ei.Type.Num,compositeRule:!0},y),w()})}function p(y){e.code((0,ft._)`${y}++`),a===void 0?e.if((0,ft._)`${y} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,ft._)`${y} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,ft._)`${y} >= ${i}`,()=>e.assign(d,!0)))}}};Of.default=RL;var N0={};(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.validateSchemaDeps=t.validatePropertyDeps=t.error=void 0;const e=ce,n=V,r=ie;t.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const d=u===1?"property":"properties";return(0,e.str)`must have ${d} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:d}})=>(0,e._)`{property: ${c},
351
- missingProperty: ${d},
352
- depsCount: ${u},
353
- deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:t.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const d in c){if(d==="__proto__")continue;const f=Array.isArray(c[d])?u:l;f[d]=c[d]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:d,it:f}=c;if(Object.keys(u).length===0)return;const g=l.let("missing");for(const p in u){const y=u[p];if(y.length===0)continue;const w=(0,r.propertyInData)(l,d,p,f.opts.ownProperties);c.setParams({property:p,depsCount:y.length,deps:y.join(", ")}),f.allErrors?l.if(w,()=>{for(const h of y)(0,r.checkReportMissingProp)(c,h)}):(l.if((0,e._)`${w} && (${(0,r.checkMissingProp)(c,y,g)})`),(0,r.reportMissingProp)(c,g),l.else())}}t.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:d,keyword:f,it:g}=c,p=l.name("valid");for(const y in u)(0,n.alwaysValidSchema)(g,u[y])||(l.if((0,r.propertyInData)(l,d,y,g.opts.ownProperties),()=>{const w=c.subschema({keyword:f,schemaProp:y},p);c.mergeValidEvaluated(w,p)},()=>l.var(p,!0)),c.ok(p))}t.validateSchemaDeps=a,t.default=o})(N0);var kf={};Object.defineProperty(kf,"__esModule",{value:!0});const O0=ce,TL=V,CL={message:"property name must be valid",params:({params:t})=>(0,O0._)`{propertyName: ${t.propertyName}}`},ML={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:CL,code(t){const{gen:e,schema:n,data:r,it:o}=t;if((0,TL.alwaysValidSchema)(o,n))return;const s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,O0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};kf.default=ML;var Ba={};Object.defineProperty(Ba,"__esModule",{value:!0});const ti=ie,bt=ce,LL=Ft,ni=V,DL={message:"must NOT have additional properties",params:({params:t})=>(0,bt._)`{additionalProperty: ${t.additionalProperty}}`},UL={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:DL,code(t){const{gen:e,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,ni.alwaysValidSchema)(i,n))return;const u=(0,ti.allSchemaProperties)(r.properties),l=(0,ti.allSchemaProperties)(r.patternProperties);d(),t.ok((0,bt._)`${s} === ${LL.default.errors}`);function d(){e.forIn("key",o,w=>{!u.length&&!l.length?p(w):e.if(f(w),()=>p(w))})}function f(w){let h;if(u.length>8){const v=(0,ni.schemaRefOrVal)(i,r.properties,"properties");h=(0,ti.isOwnProperty)(e,v,w)}else u.length?h=(0,bt.or)(...u.map(v=>(0,bt._)`${w} === ${v}`)):h=bt.nil;return l.length&&(h=(0,bt.or)(h,...l.map(v=>(0,bt._)`${(0,ti.usePattern)(t,v)}.test(${w})`))),(0,bt.not)(h)}function g(w){e.code((0,bt._)`delete ${o}[${w}]`)}function p(w){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){g(w);return}if(n===!1){t.setParams({additionalProperty:w}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,ni.alwaysValidSchema)(i,n)){const h=e.name("valid");c.removeAdditional==="failing"?(y(w,h,!1),e.if((0,bt.not)(h),()=>{t.reset(),g(w)})):(y(w,h),a||e.if((0,bt.not)(h),()=>e.break()))}}function y(w,h,v){const b={keyword:"additionalProperties",dataProp:w,dataPropType:ni.Type.Str};v===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,h)}}};Ba.default=UL;var jf={};Object.defineProperty(jf,"__esModule",{value:!0});const BL=kt,_m=ie,vc=V,Nm=Ba,FL={keyword:"properties",type:"object",schemaType:"object",code(t){const{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Nm.default.code(new BL.KeywordCxt(s,Nm.default,"additionalProperties"));const i=(0,_m.allSchemaProperties)(n);for(const d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=vc.mergeEvaluated.props(e,(0,vc.toHash)(i),s.props));const a=i.filter(d=>!(0,vc.alwaysValidSchema)(s,n[d]));if(a.length===0)return;const c=e.name("valid");for(const d of a)u(d)?l(d):(e.if((0,_m.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};jf.default=FL;var Af={};Object.defineProperty(Af,"__esModule",{value:!0});const Om=ie,ri=ce,km=V,jm=V,qL={keyword:"patternProperties",type:"object",schemaType:"object",code(t){const{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Om.allSchemaProperties)(n),c=a.filter(y=>(0,km.alwaysValidSchema)(s,n[y]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof ri.Name)&&(s.props=(0,jm.evaluatedPropsToName)(e,s.props));const{props:d}=s;f();function f(){for(const y of a)u&&g(y),s.allErrors?p(y):(e.var(l,!0),p(y),e.if(l))}function g(y){for(const w in u)new RegExp(y).test(w)&&(0,km.checkStrictMode)(s,`property ${w} matches pattern ${y} (use allowMatchingProperties)`)}function p(y){e.forIn("key",r,w=>{e.if((0,ri._)`${(0,Om.usePattern)(t,y)}.test(${w})`,()=>{const h=c.includes(y);h||t.subschema({keyword:"patternProperties",schemaProp:y,dataProp:w,dataPropType:jm.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,ri._)`${d}[${w}]`,!0):!h&&!s.allErrors&&e.if((0,ri.not)(l),()=>e.break())})})}}};Af.default=qL;var If={};Object.defineProperty(If,"__esModule",{value:!0});const KL=V,VL={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){const{gen:e,schema:n,it:r}=t;if((0,KL.alwaysValidSchema)(r,n)){t.fail();return}const o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};If.default=VL;var Pf={};Object.defineProperty(Pf,"__esModule",{value:!0});const GL=ie,zL={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:GL.validateUnion,error:{message:"must match a schema in anyOf"}};Pf.default=zL;var xf={};Object.defineProperty(xf,"__esModule",{value:!0});const Ci=ce,WL=V,HL={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ci._)`{passingSchemas: ${t.passing}}`},JL={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:HL,code(t){const{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let f;(0,WL.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ci._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ci._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Ci.Name)})})}}};xf.default=JL;var Rf={};Object.defineProperty(Rf,"__esModule",{value:!0});const QL=V,YL={keyword:"allOf",schemaType:"array",code(t){const{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=e.name("valid");n.forEach((s,i)=>{if((0,QL.alwaysValidSchema)(r,s))return;const a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Rf.default=YL;var Tf={};Object.defineProperty(Tf,"__esModule",{value:!0});const ra=ce,k0=V,ZL={message:({params:t})=>(0,ra.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,ra._)`{failingKeyword: ${t.ifClause}}`},XL={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ZL,code(t){const{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,k0.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=Am(r,"then"),s=Am(r,"else");if(!o&&!s)return;const i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){const l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,ra.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){const l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{const f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,ra._)`${l}`):t.setParams({ifClause:l})}}}};function Am(t,e){const n=t.schema[e];return n!==void 0&&!(0,k0.alwaysValidSchema)(t,n)}Tf.default=XL;var Cf={};Object.defineProperty(Cf,"__esModule",{value:!0});const eD=V,tD={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,eD.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Cf.default=tD;Object.defineProperty(Sf,"__esModule",{value:!0});const nD=mo,rD=_f,oD=go,sD=Nf,iD=Of,aD=N0,cD=kf,uD=Ba,lD=jf,dD=Af,fD=If,pD=Pf,hD=xf,mD=Rf,gD=Tf,yD=Cf;function wD(t=!1){const e=[fD.default,pD.default,hD.default,mD.default,gD.default,yD.default,cD.default,uD.default,aD.default,lD.default,dD.default];return t?e.push(rD.default,sD.default):e.push(nD.default,oD.default),e.push(iD.default),e}Sf.default=wD;var Mf={},Lf={};Object.defineProperty(Lf,"__esModule",{value:!0});const _e=ce,vD={message:({schemaCode:t})=>(0,_e.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,_e._)`{format: ${t}}`},$D={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:vD,code(t,e){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?f():g();function f(){const p=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),y=n.const("fDef",(0,_e._)`${p}[${i}]`),w=n.let("fType"),h=n.let("format");n.if((0,_e._)`typeof ${y} == "object" && !(${y} instanceof RegExp)`,()=>n.assign(w,(0,_e._)`${y}.type || "string"`).assign(h,(0,_e._)`${y}.validate`),()=>n.assign(w,(0,_e._)`"string"`).assign(h,y)),t.fail$data((0,_e.or)(v(),b()));function v(){return c.strictSchema===!1?_e.nil:(0,_e._)`${i} && !${h}`}function b(){const E=l.$async?(0,_e._)`(${y}.async ? await ${h}(${r}) : ${h}(${r}))`:(0,_e._)`${h}(${r})`,N=(0,_e._)`(typeof ${h} == "function" ? ${E} : ${h}.test(${r}))`;return(0,_e._)`${h} && ${h} !== true && ${w} === ${e} && !${N}`}}function g(){const p=d.formats[s];if(!p){v();return}if(p===!0)return;const[y,w,h]=b(p);y===e&&t.pass(E());function v(){if(c.strictSchema===!1){d.logger.warn(N());return}throw new Error(N());function N(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function b(N){const j=N instanceof RegExp?(0,_e.regexpCode)(N):c.code.formats?(0,_e._)`${c.code.formats}${(0,_e.getProperty)(s)}`:void 0,T=n.scopeValue("formats",{key:s,ref:N,code:j});return typeof N=="object"&&!(N instanceof RegExp)?[N.type||"string",N.validate,(0,_e._)`${T}.validate`]:["string",N,T]}function E(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,_e._)`await ${h}(${r})`}return typeof w=="function"?(0,_e._)`${h}(${r})`:(0,_e._)`${h}.test(${r})`}}}};Lf.default=$D;Object.defineProperty(Mf,"__esModule",{value:!0});const bD=Lf,ED=[bD.default];Mf.default=ED;var io={};Object.defineProperty(io,"__esModule",{value:!0});io.contentVocabulary=io.metadataVocabulary=void 0;io.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];io.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(cf,"__esModule",{value:!0});const SD=uf,_D=df,ND=Sf,OD=Mf,Im=io,kD=[SD.default,_D.default,(0,ND.default)(),OD.default,Im.metadataVocabulary,Im.contentVocabulary];cf.default=kD;var Df={},Fa={};Object.defineProperty(Fa,"__esModule",{value:!0});Fa.DiscrError=void 0;var Pm;(function(t){t.Tag="tag",t.Mapping="mapping"})(Pm||(Fa.DiscrError=Pm={}));Object.defineProperty(Df,"__esModule",{value:!0});const Lr=ce,Cu=Fa,xm=at,jD=ho,AD=V,ID={message:({params:{discrError:t,tagName:e}})=>t===Cu.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Lr._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},PD={keyword:"discriminator",type:"object",schemaType:"object",error:ID,code(t){const{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");const a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");const c=e.let("valid",!1),u=e.const("tag",(0,Lr._)`${n}${(0,Lr.getProperty)(a)}`);e.if((0,Lr._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Cu.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){const g=f();e.if(!1);for(const p in g)e.elseIf((0,Lr._)`${u} === ${p}`),e.assign(c,d(g[p]));e.else(),t.error(!1,{discrError:Cu.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(g){const p=e.name("valid"),y=t.subschema({keyword:"oneOf",schemaProp:g},p);return t.mergeEvaluated(y,Lr.Name),p}function f(){var g;const p={},y=h(o);let w=!0;for(let E=0;E<i.length;E++){let N=i[E];if(N!=null&&N.$ref&&!(0,AD.schemaHasRulesButRef)(N,s.self.RULES)){const T=N.$ref;if(N=xm.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,T),N instanceof xm.SchemaEnv&&(N=N.schema),N===void 0)throw new jD.default(s.opts.uriResolver,s.baseId,T)}const j=(g=N==null?void 0:N.properties)===null||g===void 0?void 0:g[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);w=w&&(y||h(N)),v(j,E)}if(!w)throw new Error(`discriminator: "${a}" must be required`);return p;function h({required:E}){return Array.isArray(E)&&E.includes(a)}function v(E,N){if(E.const)b(E.const,N);else if(E.enum)for(const j of E.enum)b(j,N);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(E,N){if(typeof E!="string"||E in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[E]=N}}}};Df.default=PD;const xD="http://json-schema.org/draft-07/schema#",RD="http://json-schema.org/draft-07/schema#",TD="Core schema meta-schema",CD={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:[]}},MD=["object","boolean"],LD={$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:"#"}},DD={$schema:xD,$id:RD,title:TD,definitions:CD,type:MD,properties:LD,default:!0};(function(t,e){Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;const n=O$,r=cf,o=Df,s=DD,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(p=>this.addVocabulary(p)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const p=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(p,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var u=kt;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=ce;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var d=js;Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=ho;Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})(cm,cm.exports);Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const UD={"decimal.js":"Decimal"};function BD(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(UD).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${BD(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function FD(t,e){return`x-${t}-${e}`}function Rm(t){let e=t.replace(/[^a-zA-Z0-9_$]/g,"_");return(e===""||/^[0-9]/.test(e))&&(e=`_${e}`),e}const qD=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],KD={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let VD=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function Uf(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&qD.includes(t.code)&&typeof t.toJSON=="function"}const Mu="$apigen";let Tm=class extends Error{constructor(e){super(e),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function GD(t){const e=new Map;return{register(n,r){if(e.has(n.id)&&!(r!=null&&r.override))throw new Tm(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);e.set(n.id,n)},resolve(n){for(const r of e.values())if(r.matches(n))return r},get(n){return e.get(n)},ids(){return[...e.keys()]},freeze(){const n=new Map(e),r={register(){throw new Tm("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Bf="x-apigen-logical",Ff="x-apigen-codec",Lu="x-apigen-ctor",Du="x-apigen-tojson",zD="0.1.0";function Cm(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...e}}function Dr(t,e,n){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Dr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=j0(t,s,e,n);return Dr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return es(t,e,n);const a=e.items;if(!a)return t.map(u=>ur(u));const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?ur(u):Dr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Dr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return es(t,e,n);const a=e.properties;if(!a)return ur(t);const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Dr(f,d,{...n,path:`${c}/${l}`}))}return u}return i==null?es(t,e,n):ur(t)}function Ur(t,e,n){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Ur(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=j0(t,s,e,n);return Ur(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?u:Ur(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Ur(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Ur(f,d,{...n,path:`${c}/${l}`}))}for(const[l,d]of Object.entries(t))!(l in a)&&d!==void 0&&(u[l]=d);return u}return i==null?Uu(t,n):t}function j0(t,e,n,r){var o;const s=n.discriminator;if(s!=null&&s.propertyName){const u=s.propertyName,l=t!==null&&typeof t=="object"?t[u]:void 0;if(typeof l=="string"){if(s.mapping){const d=s.mapping[l];if(d){const f=e.find(g=>g.$ref===d);if(f)return f}}for(const d of e){const f=(o=oa(d,r).properties)==null?void 0:o[u];if(!f)continue;const g=f.enum;if(f.const===l||Array.isArray(g)&&g.includes(l))return d}}}const i=WD(t,e,r);if(i)return i;let a,c=-1;for(const u of e){const l=oa(u,r),d=A0(t,l,r);d!==null&&d>c&&(c=d,a=u)}return a!==void 0?a:e[0]??{}}function oa(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function Mm(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function WD(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t,o=e.map(i=>oa(i,n)),s=new Set;for(const i of o){const a=i.properties;if(a)for(const[c,u]of Object.entries(a))Mm(u)!==void 0&&s.add(c)}for(const i of s){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[i];return p?Mm(p):void 0}),c=a.filter(f=>f!==void 0),u=new Set(c);if(c.length<2||u.size!==c.length)continue;const l=r[i];if(l===void 0)continue;const d=a.findIndex(f=>f===l);if(d!==-1)return e[d]}}function HD(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function A0(t,e,n){const r=e.oneOf;if(Array.isArray(r)){let l=null;for(const d of r){const f=A0(t,oa(d,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,s=HD(t);if(typeof o=="string"){if(!(o===s||o==="number"&&s==="integer"))return null}else if(Array.isArray(o)&&!o.some(l=>l===s||l==="number"&&s==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const i=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(i[l]===void 0)return null;c+=2}}const u=e.properties;if(u){for(const l of Object.keys(u))i[l]!==void 0&&(c+=1);for(const l of Object.keys(i))u[l]===void 0&&(c-=1)}return c}function es(t,e,n){var r;for(const o of n.registry.ids()){const s=n.registry.get(o);if((r=s==null?void 0:s.ownsValue)!=null&&r.call(s,t))return{[Mu]:o,v:s.encode(t,s.schema,n)}}if(Array.isArray(t))return t.map(o=>es(o,{},n));if(I0(t)){const o={};for(const[s,i]of Object.entries(t))i!==void 0&&(o[s]=es(i,{},n));return o}return ur(t)}function I0(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Uu(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&Mu in t){const n=t,r=n[Mu],o=e.registry.get(r);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>Uu(n,e));if(I0(t)){const n={};for(const[r,o]of Object.entries(t))n[r]=Uu(o,e);return n}return t}function ur(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(ur);if(typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=ur(r));return e}return null}function JD(t){return{encode(e,n,r){const o=Cm(t,r);return Dr(e,n,o)},decode(e,n,r){const o=Cm(t,r);return Ur(e,n,o)}}}const qf={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},Kf={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}},Vf={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},Gf={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},QD=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,zf={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!QD.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},Bu="NaN",Fu="Infinity",qu="-Infinity",YD=new Set([Bu,Fu,qu]),Wf={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?Bu:t===1/0?Fu:t===-1/0?qu:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===Bu)return NaN;if(t===Fu)return 1/0;if(t===qu)return-1/0;const r=Number(t);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...YD].join(", ")}.`);return NaN}},ZD=[qf,Kf,Vf,Gf,zf,Wf];function XD(t,e={}){for(const n of ZD)t.register(n,{override:e.override??!1})}const eU=12;function tU(t,e){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(t);if(!n)return;const[,r,o]=n,s=r==="$defs"?e.$defs:e.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function Lm(t){return Array.isArray(t)&&t.length>0?t[0]:void 0}function nU(t){if(Array.isArray(t.type))return t.type.find(e=>e!=="null")??t.type[0];if(typeof t.type=="string")return t.type;if(t.properties)return"object"}function rU(t){switch(t.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function Dm(t,e,n){const r=t.properties??{},o=t.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?ys(a,e,n+1):`<${i}>`}return s}function oU(t,e,n){const r=Array.isArray(t.items)?t.items[0]:t.items;return r?[ys(r,e,n+1)]:[]}function ys(t,e=t??{},n=0){if(!t||n>eU)return null;if(typeof t.$ref=="string"){const o=tU(t.$ref,e);return o!==void 0?ys(o,e,n+1):null}if(t.const!==void 0)return t.const;if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum[0];if(Array.isArray(t.allOf)&&t.allOf.length>0){const o={},s=[];for(const i of t.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return Dm({...t,properties:o,required:s},e,n)}const r=Lm(t.oneOf)??Lm(t.anyOf);if(r)return ys(r,e,n+1);switch(nU(t)){case"object":return Dm(t,e,n);case"array":return oU(t,e,n);case"string":return rU(t);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function sU(t){if(!t)return;const e=ys(t);return`Example: ${JSON.stringify(e)}`}qf.id,Kf.id,Vf.id,Gf.id,zf.id,Wf.id;const P0=GD();XD(P0);const x0=JD(P0.freeze());function iU(t,e){var n;const r=((n=t.input)==null?void 0:n.properties)??{};return e in r}function aU(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function cU(t,e){var n,r,o;const s=(o=(r=(n=t.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[e];return i!==void 0?i:void 0}function uU(t,e){return e===void 0||t===void 0?t:x0.decode(t,e)}function $c(t,e){const n=e.output;return!n||Object.keys(n).length===0?t:x0.encode(t,n)}async function lU(t,e,n,r,o,s){const i=aU(n).map(c=>uU(s[c],cU(n,c)));if(iU(n,"session")&&e){const c=await e({session:o.session}),u=await t[r](c,...i);return $c(u,n)}if(n.hasCtx){const c=e?await e(o):void 0,u=await t[r](c,...i);return $c(u,n)}const a=await t[r](...i);return $c(a,n)}let R0=class{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};function dU(t=[]){return async function(e,n,r){const o=r.schemas[e];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${e}"`);const s=()=>lU(r.fns,r.createClient,o,e,n.envelope,n.domainArgs);return t.reduceRight((i,a)=>()=>a(n,i),s)()}}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const fU={"decimal.js":"Decimal"};function pU(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(fU).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${pU(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function hU(t={}){const e=t.level??"info",n=typeof t.destination=="string"&&t.destination.length>0,r=!n&&!!process.stderr.isTTY,o=t.format??(r?"pretty":"json"),s={level:e};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:t.destination,mkdir:!0}:{destination:2}}},pt(s);const i=n?pt.destination({dest:t.destination,mkdir:!0,sync:!0}):pt.destination(2);return pt(s,i)}function mU(t){if(!t||t.type!=="object"||!t.properties)return;const e=Object.entries(t.properties);if(e.length===0)return;const n=new Set(t.required??[]);return`{ ${e.map(([r,o])=>`${r}${n.has(r)?"":"?"}: ${qa(o)}`).join(", ")} }`}function gU(t){return typeof t=="string"?`'${t}'`:JSON.stringify(t)}function yU(t){const e=t.enum??[];return e.length===0?"unknown":e.map(gU).join("|")}function wU(t,e){return t.map(n=>qa(n,e)).join(" | ")}function qa(t,e=0){if(!t)return"unknown";if(t.type==="array")return`${qa(t.items,0)}[]`;if(t.enum)return yU(t);if(t.$ref)return String(t.$ref).split("/").pop()||"object";const n=t.anyOf??t.oneOf;return n?n.length===0?"unknown":e>=2?wU(n,e-1):"union":e>=1&&t.type==="object"?mU(t)??"object":t.type??"object"}function T0(t){var e;const n=(e=((t==null?void 0:t.input)??{}).properties)==null?void 0:e.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:qa(c,2),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function vU(t){let e;return Array.isArray(t)?e=t:t?e=[t]:e=[],e.find(n=>n==="number"||n==="integer"||n==="boolean")}function $U(t,e){var n,r;const o=((r=(n=((e==null?void 0:e.input)??{}).properties)==null?void 0:n.data)==null?void 0:r.properties)??{},s={...t};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=vU(a==null?void 0:a.type);if(u==="number"||u==="integer"){const l=Number(c);!Number.isNaN(l)&&c.trim()!==""&&(s[i]=l)}else u==="boolean"&&(c==="true"?s[i]=!0:c==="false"&&(s[i]=!1))}return s}let bU=class extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};const Ka=new ia({allErrors:!0});aa(Ka);for(const t of[Bf,Ff,Lu,Du,"discriminator"])Ka.addKeyword({keyword:t,valid:!0});Ka.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function EU(t){return t.map(e=>`${e.instancePath||"(root)"} ${e.message??"failed schema check"}`).join("; ")}function SU(t,e){const n=sU(e),r=[`Validation failed: ${EU(t)}`];return n&&r.push(n),r.join(" — ")}function _U(t){return async function(e,n){const r=e.operation.id,o=t[r];if(o===void 0)return n();const s={data:e.domainArgs,...e.envelope},i=Ka.compile(o.input);if(!i(s)){const a=i.errors??[];throw new bU("invalid_argument",SU(a,o.input),a)}return n()}}function NU(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}class Wn extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}}function bc(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function C0(t,e){const n=t[Ff];if(typeof n=="string"){const r=e.registry.get(n);if(r)return r}return e.registry.resolve(t)}function OU(t,e,n){const r=C0(e,n);return r?r.encode(t,e,n):t}function kU(t,e,n){const r=C0(e,n);return r?r.decode(t,e,n):t}function jU(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(r){if(r[Bf]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:bc(r)!==void 0},encode(r,o,s){const i=bc(o);if(!i)throw new Wn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new Wn("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),d=c[l];if(!d)throw new Wn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=s.resolve(d);return OU(r,f,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new Wn("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${p}.`)}const i=r,a=bc(o);if(!a)throw new Wn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new Wn("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const d=String(l),f=u[d];if(!f)throw new Wn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${d}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const g=s.resolve(f);return kU(r,g,{...s,path:`${s.path}[${d}]`})}}}const AU="x-apigen-instances";let oi=class extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}};function Um(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function IU(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function Bm(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n)}return t}function PU(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n)}return t}function xU(t){const{id:e,schema:n,ctor:r}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[Bf]==="nominal"?!0:o[Ff]===e},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new oi("E_NOMINAL_CYCLE",`[${e}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=Um(s),c=typeof s[Du]=="string"?s[Du]:"toJSON",u=o[c];if(typeof u=="function"){const p=u.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[w,h]of Object.entries(p))y[w]=Bm(h,a[w],{...i,path:`${i.path}/${w}`});return y}return p}const l={},d=Object.keys(a),f=o,g=d.length>0?d:Object.keys(f);for(const p of g){const y=f[p];y!==void 0&&(l[p]=Bm(y,a[p],{...i,path:`${i.path}/${p}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new oi("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of IU(s))if(!(l in a))throw new oi("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${i.path}".`);if(s[AU]===!1)throw new oi("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=Um(s),u={};for(const[l,d]of Object.entries(a))u[l]=PU(d,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Lu]=="string"?s[Lu]:"fromJSON",d=r[l];if(typeof d=="function")return d.call(r,u);const f=r;return new f(u)}return u}}}const RU=[qf,Kf,Vf,Gf,zf,Wf],TU={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Fm=xU({id:"ts.NominalSentinel",schema:TU}),CU={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},qm=jU({id:"ts.UnionSentinel",schema:CU});function MU(){const t=[...RU.map(e=>[e.id,e]),[Fm.id,Fm],[qm.id,qm]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:zD,codecs:MU()});Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const Km=new Set(["string","number","boolean","integer"]);function LU(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Km.has(n):Array.isArray(n)?n.every(r=>Km.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function DU(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(LU)}const UU={"decimal.js":"Decimal"};function BU(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(UU).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${BU(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function Vm(t){return t.words.join("-")}function Gm(t){return t.words.map(GU).join("")}function zm(t){return t.words.join("_")}function FU(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||DU(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>Vm(g)).join("/"),c=o.map(g=>zm(g)).join("_"),u=o.map(g=>zm(g)).slice(0,-1).join("."),l=Gm(o[o.length-2]??o[0]),d=Gm(o[o.length-1]),f=o.map(g=>Vm(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function qU(t,e){return`x-${t}-${e}`}function KU(t,e){return`--${t}-${e}`}function VU(t,e){const n=r=>r.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function GU(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function Hf(t){return t.anyOf??t.oneOf}function zU(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=Hf(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function WU(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=Hf(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function HU(t){if(!t)return!1;if(t.type==="number"||t.type==="integer")return!0;const e=Hf(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function JU(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function QU(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function Wm(t){return typeof t.handler=="function"}function YU(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=qU(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:KU(i,s),envVar:VU(i,s)})}return o}function ZU(t,e,n,r){e===n||t.has(e)||t.set(e,{...r,aliasOf:n})}function XU(t,e){const n=new Map,{props:r}=QU(t);for(const[o,s]of Object.entries(r)){let i="string";WU(s)?i="boolean":(zU(s)||HU(s))&&(i="json");const a=JU(o),c={camelKey:o,kind:"domain",valueKind:i};n.set(a,c),ZU(n,o,a,c)}for(const o of e){const s=o.cliFlag.replace(/^--/,""),i={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(s,i)}return n}function Ku(t){const{op:e,schema:n,transport:r,projection:o}=t,s=FU(e,o),i=n?YU(n):[],a=n?XU(n,i):new Map,c=n?T0(n).params:void 0,u={op:e,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:e.streaming,isMount:Wm(e)};if(Wm(e)){const l=e.handler;u.mountHandler=async d=>l(d)}return u}function e2(t){const e=t.usePlugins;return Array.isArray(e)?e:[]}function t2(t){const e=t.useOptions;return e&&typeof e=="object"?e:{}}function n2(t){return async function(e,n){const r=Object.assign(e,{data:e.domainArgs});return await t.layer(r,n)}}function Ec(t,e){var n;const r=[];for(const o of e){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(n2(s))}return r.push(_U(t)),dU(r)}function r2(){const t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}const o2={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Hm(t,e,n,r){const o={...n,operation:{id:t.op.id},ctx:new R0};if(t.isMount){const s=t.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${t.op.id}" has isMount=true but no mountHandler`);const i={operation:t.op,data:n.domainArgs,envelope:n.envelope,ctx:r2(),transport:t.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[t.op.id]:()=>s(i)},schemas:{[t.op.id]:o2}};return e(t.op.id,o,a)}return e(t.op.id,o,r)}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const s2={"decimal.js":"Decimal"};function i2(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(s2).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${i2(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function Vu(t){return t.split(/[-_.]+/).flatMap(e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(e=>e.toLowerCase()).filter(Boolean)}function Jm(t){return{raw:t,words:Vu(t)}}function M0(t,e,n,r){for(const o of r??[]){const s=o.path[o.path.length-1];if(o.namespace.raw===t&&(s==null?void 0:s.raw)===e)return o}return{id:`${Vu(t).join("-")}/${Vu(e).join("-")}`,host:"ts",namespace:Jm(t),path:[Jm(e)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function a2(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o={};for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd";o[s]=FD(i,s)}return o}function c2(t){const e=t.options.port??3e3,n=t.options.routePrefix??"",r=t.options.projection??{},o=["// Auto-generated by @adhd/apigen-cli — do not edit","import Fastify from 'fastify'","import { dispatch, buildFnTable, coerceQueryParams } from '@adhd/apigen-engine-runtime'"];for(const s of t.packages){const i=Rm(s.id);o.push(`import * as ${i}_ns from '${s.importPath}'`),o.push(`const ${i}_fns = buildFnTable(${i}_ns as Record<string, unknown>)`)}o.push(""),o.push(`const schemas: Record<string, unknown> = ${JSON.stringify(Object.fromEntries(t.packages.flatMap(s=>Object.entries(s.schemas).map(([i,a])=>[`${s.id}:${i}`,{schema:a,pkgId:s.id}]))),null,2)}`),o.push(""),o.push("const app = Fastify()"),o.push("");for(const s of t.packages){const i=Rm(s.id);for(const[a,c]of Object.entries(s.schemas)){const u=M0(s.id,a,c,t.operations),l=Ku({op:u,schema:c,transport:"http",projection:r}),d=n+l.http.route,f=l.http.verb,g=a2(c),p=Object.entries(g);if(f==="GET"){if(o.push(`app.get('${d}', async (req) => {`),o.push(` const query = coerceQueryParams(req.query as Record<string, unknown>, schemas['${s.id}:${a}']['schema'] as any)`),p.length>0){const y=p.map(([w,h])=>`'${w}': (req.headers as Record<string, unknown>)['${h}']`).join(", ");o.push(` const envelope: Record<string, unknown> = { ${y} }`)}else o.push(" const envelope: Record<string, unknown> = {}");o.push(` return dispatch(${i}_fns as any, undefined, schemas['${s.id}:${a}']['schema'] as any, '${a}', envelope, query as any)`),o.push("})")}else{if(o.push(`app.post('${d}', async (req) => {`),o.push(" const { data = {} } = req.body as Record<string, unknown>"),p.length>0){const y=p.map(([w,h])=>`'${w}': (req.headers as Record<string, unknown>)['${h}']`).join(", ");o.push(` const envelope: Record<string, unknown> = { ${y} }`)}else o.push(" const envelope: Record<string, unknown> = {}");o.push(` return dispatch(${i}_fns as any, undefined, schemas['${s.id}:${a}']['schema'] as any, '${a}', envelope, data as any)`),o.push("})")}}}return o.push(""),o.push(`app.listen({ port: ${e} })`),{files:[{path:"routes.ts",content:o.join(`
354
- `)}]}}function u2(t){return`data: ${t}
355
-
356
- `}function l2(t){return`event: error
357
- data: ${t}
358
-
359
- `}async function d2(t,e,n){const r=new AbortController;e.raw.once("close",()=>r.abort());const o=n.raw;let s=!1;try{for await(const i of t){if(r.signal.aborted)break;s||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),s=!0),o.write(u2(JSON.stringify(i)))}s||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(i){const a=Uf(i)?i:new VD("internal",i instanceof Error?i.message:String(i));if(s)o.write(l2(JSON.stringify(a.toJSON()))),o.end();else{const c=p2(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const f2={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function p2(t){return f2[t]??500}function L0(t){return Uf(t)?KD[t.code]??500:500}function D0(t){return Uf(t)?t.toJSON():{code:"internal",message:t instanceof Error?t.message:"Internal error"}}function h2(t,e){if(t)for(const n of e){const r={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(r.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),t.info(n,o)}}let m2=class{constructor(e,n,r){this.app=e,this.routePrefix=n,this.signal=r,this.schemasByOpId=new Map}bindSchema(e,n){this.schemasByOpId.set(e,n)}routeFor(e){return e.isMount?`${this.routePrefix}/${e.op.id}`:this.routePrefix+e.http.route}registerRoute(e,n){const r=this.routeFor(e),o=async(s,i)=>{const a={req:s,reply:i};try{const c=await this.readCall(a,e),u=await n(c);await this.writeResult(a,u,e)}catch(c){await this.writeError(a,c,e)}};e.http.verb==="GET"?this.app.get(r,o):this.app.post(r,o)}readCall(e,n){const{req:r}=e,o=r.headers,s={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(s[a.field]=c)}let i={};if(n.isMount)i=n.http.verb==="GET"?r.query??{}:r.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=r.query??{};i=a?$U(c,a):c}else{const{data:c={}}=r.body??{};i=c}}return{envelope:s,domainArgs:i,signal:this.signal}}async writeResult(e,n,r){const{req:o,reply:s}=e;if(NU(n)){await d2(n,o,s);return}s.type("application/json"),s.send(JSON.stringify(n===void 0?null:n))}writeError(e,n,r){const{reply:o}=e;o.status(L0(n)).send(D0(n))}};function g2(t,e,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of t){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,e[c.id],o);for(const d of l)d.transports&&!d.transports.includes("http")||i.push(d)}return i}async function y2(t){var e,n;const r=t.options.port??3e3,o=t.options.host??"127.0.0.1",s=t.options.routePrefix??"",i=t.options.projection??{},a=e2(t.options),c=t2(t.options),u=t.logger??hU(),l=nE({logger:u});l.setErrorHandler((b,E,N)=>{N.status(L0(b)).send(D0(b))});const d=new m2(l,s,t.signal),f=[],g={},p={};for(const b of t.packages){if(!b.fns)throw new Error(`Package "${b.id}" is missing fns`);const E=b.fns,N=Object.entries(b.schemas).map(([G,H])=>({fnName:G,fnSchema:H,op:M0(b.id,G,H,t.operations)})),j={},T={};for(const{fnName:G,fnSchema:H,op:Z}of N)j[Z.id]=H,T[Z.id]=E[G],g[Z.id]=H,p[Z.id]=E[G];const M=Ec(j,a),C={fns:T,createClient:b.createClient,schemas:j};for(const{fnSchema:G,op:H}of N){const Z=Ku({op:H,schema:G,transport:"http",projection:i});d.bindSchema(H.id,G),d.registerRoute(Z,he=>Hm(Z,M,he,C));const{params:ue,text:fe}=T0(G);f.push({method:Z.http.verb,route:s+Z.http.route,text:fe,params:ue})}}const y=((e=t.packages[0])==null?void 0:e.id)??"ts",w=Ec(g,a),h={invoke:(b,E,N)=>w(b,{operation:{id:b},ctx:new R0,domainArgs:E.domainArgs,envelope:E.envelope,signal:E.signal},N),invokeOptions:{fns:p,schemas:g,createClient:(n=t.packages[0])==null?void 0:n.createClient}},v=g2(a,c,y,t.operations??[],h);if(v.length>0){const b=Ec({},a),E={fns:{},schemas:{}};for(const N of v){const j=Ku({op:N,transport:"http",projection:i});d.registerRoute(j,T=>Hm(j,b,T,E)),f.push({method:j.http.verb,route:`${s}/${N.id}`,text:"",params:[]})}}return await l.listen({port:r,host:o}),u.info({host:o,port:r},`listening on http://${o}:${r}`),h2(u,f),new Promise(b=>{t.signal&&t.signal.addEventListener("abort",async()=>{await l.close(),b()})})}const w2={id:"api-fastify",description:"Expose functions as Fastify HTTP POST routes",language:"ts",optionsSchema:{type:"object",properties:{port:{type:"number",default:3e3},routePrefix:{type:"string",default:""}}},generate(t){return c2(t)},run(t){return y2(t)}};function Qm(t){return{raw:t,words:t.split(/(?=[A-Z])|[-_]/).map(e=>e.toLowerCase()).filter(Boolean)}}function v2(t,e,n={}){const r=t.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${t}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:t,host:e.host,namespace:Qm(i),path:s.map(Qm),kind:a,async:n.async??!1,streaming:n.streaming??!1,safe:n.safe??a==="query",input:n.input??{},output:n.output??{},envelope:n.envelope??{},typeText:n.typeText??null};return n.hasCtx!==void 0&&(c.hasCtx=n.hasCtx),n.transports!==void 0&&(c.transports=n.transports),c}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const $2={"decimal.js":"Decimal"};function b2(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries($2).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${b2(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const Ym=new Set(["string","number","boolean","integer"]);function E2(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?Ym.has(n):Array.isArray(n)?n.every(r=>Ym.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function S2(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(E2)}const _2={"decimal.js":"Decimal"};function N2(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(_2).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${N2(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function Zm(t){return t.words.join("-")}function Xm(t){return t.words.map(k2).join("")}function eg(t){return t.words.join("_")}function O2(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||S2(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>Zm(g)).join("/"),c=o.map(g=>eg(g)).join("_"),u=o.map(g=>eg(g)).slice(0,-1).join("."),l=Xm(o[o.length-2]??o[0]),d=Xm(o[o.length-1]),f=o.map(g=>Zm(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function k2(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function j2(t,e={}){const n=e.title??"API",r=e.version??"0.0.0",o={};for(const s of t){const i=O2(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:A2(s.output)}};if(a==="GET")l.parameters=I2(s.input);else{const d=s.input;typeof d=="object"&&d!==null&&Object.keys(d).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:d}}})}o[c]===void 0&&(o[c]={}),o[c][u]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function A2(t){return typeof t=="object"&&t!==null&&Object.keys(t).length>0?{description:"Success",content:{"application/json":{schema:t}}}:{description:"Success"}}function I2(t){if(typeof t!="object"||t===null||typeof t.properties!="object"||t.properties===null)return[];const e=Array.isArray(t.required)?t.required:[],n=t.properties;return Object.entries(n).map(([r,o])=>({name:r,in:"query",required:e.includes(r),schema:o}))}function P2(t,e={}){return[{...v2("_meta/openapi",t,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>j2(t.operations,{title:e.title,version:e.version})}]}const x2={id:"openapi",description:"Mount plugin: serves the OpenAPI 3.1 doc at GET /meta/openapi",language:"ts",optionsSchema:{type:"object",properties:{title:{type:"string",description:"OpenAPI info.title"},version:{type:"string",description:"OpenAPI info.version"}},additionalProperties:!1},capabilities:{mount:{operations(t,e){return P2(t,e)}}}},Gu="$apigen";let tg=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function R2(t){const e=new Map;return{register(n,r){if(e.has(n.id)&&!(r!=null&&r.override))throw new tg(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);e.set(n.id,n)},resolve(n){for(const r of e.values())if(r.matches(n))return r},get(n){return e.get(n)},ids(){return[...e.keys()]},freeze(){const n=new Map(e),r={register(){throw new tg("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const s of n.values())if(s.matches(o))return s},get(o){return n.get(o)},ids(){return[...n.keys()]},freeze(){return r}};return r}}}const Jf="x-apigen-logical",Qf="x-apigen-codec",zu="x-apigen-ctor",Wu="x-apigen-tojson",T2="0.1.0";function ng(t,e){return{registry:t,resolve:n=>{throw new Error(`[apigen-logical] $ref "${n}" cannot be resolved in run-mode without a descriptor root. Supply a resolve() in the ctx override to handle $ref.`)},seen:new WeakSet,path:"",mode:"strict",...e}}function Br(t,e,n){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Br(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=U0(t,s,e,n);return Br(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return ts(t,e,n);const a=e.items;if(!a)return t.map(u=>lr(u));const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?lr(u):Br(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Br(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return ts(t,e,n);const a=e.properties;if(!a)return lr(t);const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Br(f,d,{...n,path:`${c}/${l}`}))}return u}return i==null?ts(t,e,n):lr(t)}function Fr(t,e,n){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n);const o=e.$ref;if(typeof o=="string"){const a=n.resolve(o);return Fr(t,a,n)}const s=e.oneOf;if(Array.isArray(s)){const a=U0(t,s,e,n);return Fr(t,a,n)}const i=e.type;if(i==="array"){if(!Array.isArray(t))return t;const a=e.items;if(!a)return t;const c=n.path;return Array.isArray(a)?t.map((u,l)=>{const d=a[l];return d===void 0?u:Fr(u,d,{...n,path:`${c}/${l}`})}):t.map((u,l)=>Fr(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(t===null||typeof t!="object"||Array.isArray(t))return t;const a=e.properties;if(!a)return t;const c=n.path,u={};for(const[l,d]of Object.entries(a)){const f=t[l];f!==void 0&&(u[l]=Fr(f,d,{...n,path:`${c}/${l}`}))}for(const[l,d]of Object.entries(t))!(l in a)&&d!==void 0&&(u[l]=d);return u}return i==null?Hu(t,n):t}function U0(t,e,n,r){var o;const s=n.discriminator;if(s!=null&&s.propertyName){const u=s.propertyName,l=t!==null&&typeof t=="object"?t[u]:void 0;if(typeof l=="string"){if(s.mapping){const d=s.mapping[l];if(d){const f=e.find(g=>g.$ref===d);if(f)return f}}for(const d of e){const f=(o=sa(d,r).properties)==null?void 0:o[u];if(!f)continue;const g=f.enum;if(f.const===l||Array.isArray(g)&&g.includes(l))return d}}}const i=C2(t,e,r);if(i)return i;let a,c=-1;for(const u of e){const l=sa(u,r),d=B0(t,l,r);d!==null&&d>c&&(c=d,a=u)}return a!==void 0?a:e[0]??{}}function sa(t,e){const n=t.$ref;return typeof n=="string"?e.resolve(n):t}function rg(t){if("const"in t)return t.const;const e=t.enum;if(Array.isArray(e)&&e.length===1)return e[0]}function C2(t,e,n){if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t,o=e.map(i=>sa(i,n)),s=new Set;for(const i of o){const a=i.properties;if(a)for(const[c,u]of Object.entries(a))rg(u)!==void 0&&s.add(c)}for(const i of s){const a=o.map(f=>{const g=f.properties,p=g==null?void 0:g[i];return p?rg(p):void 0}),c=a.filter(f=>f!==void 0),u=new Set(c);if(c.length<2||u.size!==c.length)continue;const l=r[i];if(l===void 0)continue;const d=a.findIndex(f=>f===l);if(d!==-1)return e[d]}}function M2(t){if(t===null)return"null";if(Array.isArray(t))return"array";const e=typeof t;return e==="number"?Number.isInteger(t)?"integer":"number":e}function B0(t,e,n){const r=e.oneOf;if(Array.isArray(r)){let l=null;for(const d of r){const f=B0(t,sa(d,n),n);f!==null&&(l===null||f>l)&&(l=f)}return l}const o=e.type,s=M2(t);if(typeof o=="string"){if(!(o===s||o==="number"&&s==="integer"))return null}else if(Array.isArray(o)&&!o.some(l=>l===s||l==="number"&&s==="integer"))return null;if(t===null||typeof t!="object"||Array.isArray(t))return typeof o=="string"?1:0;const i=t,a=e.required;let c=0;if(Array.isArray(a)){for(const l of a)if(typeof l=="string"){if(i[l]===void 0)return null;c+=2}}const u=e.properties;if(u){for(const l of Object.keys(u))i[l]!==void 0&&(c+=1);for(const l of Object.keys(i))u[l]===void 0&&(c-=1)}return c}function ts(t,e,n){var r;for(const o of n.registry.ids()){const s=n.registry.get(o);if((r=s==null?void 0:s.ownsValue)!=null&&r.call(s,t))return{[Gu]:o,v:s.encode(t,s.schema,n)}}if(Array.isArray(t))return t.map(o=>ts(o,{},n));if(F0(t)){const o={};for(const[s,i]of Object.entries(t))i!==void 0&&(o[s]=ts(i,{},n));return o}return lr(t)}function F0(t){if(t===null||typeof t!="object"||Array.isArray(t))return!1;const e=Object.getPrototypeOf(t);return e===Object.prototype||e===null}function Hu(t,e){if(t!==null&&typeof t=="object"&&!Array.isArray(t)&&Gu in t){const n=t,r=n[Gu],o=e.registry.get(r);if(o)return o.decode(n.v,o.schema,e)}if(Array.isArray(t))return t.map(n=>Hu(n,e));if(F0(t)){const n={};for(const[r,o]of Object.entries(t))n[r]=Hu(o,e);return n}return t}function lr(t){if(t===null||typeof t=="string"||typeof t=="number"||typeof t=="boolean")return t;if(Array.isArray(t))return t.map(lr);if(typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=lr(r));return e}return null}function L2(t){return{encode(e,n,r){const o=ng(t,r);return Br(e,n,o)},decode(e,n,r){const o=ng(t,r);return Fr(e,n,o)}}}const Yf={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(t){return t.type==="string"&&t.format==="date-time"},ownsValue(t){return t instanceof Date},encode(t,e,n){return t.toISOString()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${n.path}", got ${typeof t}`);return new Date(String(t))}if(n.mode==="strict"&&Number.isNaN(new Date(t).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(t)}`);return new Date(t)}},Zf={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(t){return t.type==="string"&&t.format==="int64"},ownsValue(t){return typeof t=="bigint"},encode(t,e,n){return String(t)},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${n.path}", got ${typeof t}`);try{return BigInt(Math.trunc(Number(t)))}catch{return BigInt(0)}}if(n.mode==="strict")return BigInt(t);if(/^-?\d+$/.test(t))try{return BigInt(t)}catch{return BigInt(0)}return BigInt(0)}},Xf={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(t){return t.type==="string"&&t.format==="decimal"},encode(t,e,n){return t},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t)}if(n.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(t))throw new TypeError(`[decimal] wire value "${t}" at "${n.path}" is not a valid decimal string`);return t}},ep={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(t){return t.type==="string"&&t.format==="byte"},ownsValue(t){return t instanceof Uint8Array},encode(t,e,n){return Buffer.from(t).toString("base64")},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof t}`);return new Uint8Array(0)}if(n.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(t))throw new TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${t}"`);return new Uint8Array(Buffer.from(t,"base64"))}},D2=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,tp={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(t){return t.type==="string"&&t.format==="uuid"},encode(t,e,n){return t.toLowerCase()},decode(t,e,n){if(typeof t!="string"){if(n.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof t}`);return String(t).toLowerCase()}if(n.mode==="strict"&&!D2.test(t))throw new TypeError(`[uuid] wire value "${t}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return t}},Ju="NaN",Qu="Infinity",Yu="-Infinity",U2=new Set([Ju,Qu,Yu]),np={id:"number-special",kind:"scalar",schema:{type:"number"},matches(t){return t.type==="number"&&t.format===void 0},ownsValue(t){return typeof t=="number"&&!Number.isFinite(t)},encode(t,e,n){return Number.isNaN(t)?Ju:t===1/0?Qu:t===-1/0?Yu:t},decode(t,e,n){if(typeof t=="number")return t;if(typeof t=="string"){if(t===Ju)return NaN;if(t===Qu)return 1/0;if(t===Yu)return-1/0;const r=Number(t);if(!Number.isNaN(r))return r}if(n.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(t)}. Expected a number or one of ${[...U2].join(", ")}.`);return NaN}},B2=[Yf,Zf,Xf,ep,tp,np];function F2(t,e={}){for(const n of B2)t.register(n,{override:e.override??!1})}const q2=12;function K2(t,e){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(t);if(!n)return;const[,r,o]=n,s=r==="$defs"?e.$defs:e.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function og(t){return Array.isArray(t)&&t.length>0?t[0]:void 0}function V2(t){if(Array.isArray(t.type))return t.type.find(e=>e!=="null")??t.type[0];if(typeof t.type=="string")return t.type;if(t.properties)return"object"}function G2(t){switch(t.format){case"date-time":return"1970-01-01T00:00:00.000Z";case"date":return"1970-01-01";case"time":return"00:00:00Z";case"uuid":return"00000000-0000-0000-0000-000000000000";case"email":return"user@example.com";case"uri":case"url":case"uri-reference":return"https://example.com";case"hostname":return"example.com";case"ipv4":return"127.0.0.1";case"ipv6":return"::1";case"decimal":return"0";case"int64":return"0";case"byte":return"";default:return"<string>"}}function sg(t,e,n){const r=t.properties??{},o=t.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?ws(a,e,n+1):`<${i}>`}return s}function z2(t,e,n){const r=Array.isArray(t.items)?t.items[0]:t.items;return r?[ws(r,e,n+1)]:[]}function ws(t,e=t??{},n=0){if(!t||n>q2)return null;if(typeof t.$ref=="string"){const o=K2(t.$ref,e);return o!==void 0?ws(o,e,n+1):null}if(t.const!==void 0)return t.const;if(Array.isArray(t.enum)&&t.enum.length>0)return t.enum[0];if(Array.isArray(t.allOf)&&t.allOf.length>0){const o={},s=[];for(const i of t.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return sg({...t,properties:o,required:s},e,n)}const r=og(t.oneOf)??og(t.anyOf);if(r)return ws(r,e,n+1);switch(V2(t)){case"object":return sg(t,e,n);case"array":return z2(t,e,n);case"string":return G2(t);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function q0(t){if(!t)return;const e=ws(t);return`Example: ${JSON.stringify(e)}`}Yf.id,Zf.id,Xf.id,ep.id,tp.id,np.id;const K0=R2();F2(K0);const V0=L2(K0.freeze());function W2(t,e){var n;const r=((n=t.input)==null?void 0:n.properties)??{};return e in r}function H2(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function J2(t,e){var n,r,o;const s=(o=(r=(n=t.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[e];return i!==void 0?i:void 0}function Q2(t,e){return e===void 0||t===void 0?t:V0.decode(t,e)}function Sc(t,e){const n=e.output;return!n||Object.keys(n).length===0?t:V0.encode(t,n)}async function Y2(t,e,n,r,o,s){const i=H2(n).map(c=>Q2(s[c],J2(n,c)));if(W2(n,"session")&&e){const c=await e({session:o.session}),u=await t[r](c,...i);return Sc(u,n)}if(n.hasCtx){const c=e?await e(o):void 0,u=await t[r](c,...i);return Sc(u,n)}const a=await t[r](...i);return Sc(a,n)}class G0{constructor(){this._map=new Map}set(e,n){this._map.set(e,n)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}}function Z2(t=[]){return async function(e,n,r){const o=r.schemas[e];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${e}"`);const s=()=>Y2(r.fns,r.createClient,o,e,n.envelope,n.domainArgs);return t.reduceRight((i,a)=>()=>a(n,i),s)()}}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const X2={"decimal.js":"Decimal"};function eB(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(X2).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${eB(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function tB(t={}){const e=t.level??"info",n=typeof t.destination=="string"&&t.destination.length>0,r=!n&&!!process.stderr.isTTY,o=t.format??(r?"pretty":"json"),s={level:e};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:t.destination,mkdir:!0}:{destination:2}}},pt(s);const i=n?pt.destination({dest:t.destination,mkdir:!0,sync:!0}):pt.destination(2);return pt(s,i)}function nB(t){if(!t||t.type!=="object"||!t.properties)return;const e=Object.entries(t.properties);if(e.length===0)return;const n=new Set(t.required??[]);return`{ ${e.map(([r,o])=>`${r}${n.has(r)?"":"?"}: ${Va(o)}`).join(", ")} }`}function rB(t){return typeof t=="string"?`'${t}'`:JSON.stringify(t)}function oB(t){const e=t.enum??[];return e.length===0?"unknown":e.map(rB).join("|")}function sB(t,e){return t.map(n=>Va(n,e)).join(" | ")}function Va(t,e=0){if(!t)return"unknown";if(t.type==="array")return`${Va(t.items,0)}[]`;if(t.enum)return oB(t);if(t.$ref)return String(t.$ref).split("/").pop()||"object";const n=t.anyOf??t.oneOf;return n?n.length===0?"unknown":e>=2?sB(n,e-1):"union":e>=1&&t.type==="object"?nB(t)??"object":t.type??"object"}function iB(t){var e;const n=(e=((t==null?void 0:t.input)??{}).properties)==null?void 0:e.data,r=(n==null?void 0:n.properties)??{},o=new Set((n==null?void 0:n.required)??[]),s=Object.entries(r).map(([a,c])=>({name:a,type:Va(c,2),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const aB=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class z0 extends Error{constructor(e,n,r){super(n),this.name="ApiError",this.code=e,this.details=r,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){const e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}}function cB(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&aB.includes(t.code)&&typeof t.toJSON=="function"}function ig(t,e,n=0){return t==="before-first-chunk"?{phase:t,error:e}:{phase:t,error:e,chunksDelivered:n}}const Ga=new ia({allErrors:!0});aa(Ga);for(const t of[Jf,Qf,zu,Wu,"discriminator"])Ga.addKeyword({keyword:t,valid:!0});Ga.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function uB(t){return t.map(e=>`${e.instancePath||"(root)"} ${e.message??"failed schema check"}`).join("; ")}function lB(t,e){const n=q0(e),r=[`Validation failed: ${uB(t)}`];return n&&r.push(n),r.join(" — ")}function dB(t){return async function(e,n){const r=e.operation.id,o=t[r];if(o===void 0)return n();const s={data:e.domainArgs,...e.envelope},i=Ga.compile(o.input);if(!i(s)){const a=i.errors??[];throw new z0("invalid_argument",lB(a,o.input),a)}return n()}}async function fB(t){const e=[];try{for await(const n of t)e.push(n);return{ok:!0,chunks:e}}catch(n){const r=cB(n)?n:new z0("internal",n instanceof Error?n.message:String(n));return e.length===0?{ok:!1,carrier:ig("before-first-chunk",r)}:{ok:!1,carrier:ig("after-first-chunk",r,e.length)}}}function pB(t){return t!==null&&typeof t=="object"&&Symbol.asyncIterator in t}class Hn extends Error{constructor(e,n){super(n),this.name="UnionCodecError",this.code=e}}function _c(t){const e=t.discriminator;if(e===null||typeof e!="object"||Array.isArray(e))return;const n=e;if(typeof n.propertyName!="string")return;const r=n.mapping;if(!(r===null||typeof r!="object"||Array.isArray(r)))return{propertyName:n.propertyName,mapping:r}}function W0(t,e){const n=t[Qf];if(typeof n=="string"){const r=e.registry.get(n);if(r)return r}return e.registry.resolve(t)}function hB(t,e,n){const r=W0(e,n);return r?r.encode(t,e,n):t}function mB(t,e,n){const r=W0(e,n);return r?r.decode(t,e,n):t}function gB(t){const{id:e,schema:n}=t;return{id:e,kind:"union",schema:n,matches(r){if(r[Jf]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:_c(r)!==void 0},encode(r,o,s){const i=_c(o);if(!i)throw new Hn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:c}=i,u=r[a];if(u==null)throw new Hn("E_UNION_NO_DISCRIMINATOR",`[${e}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),d=c[l];if(!d)throw new Hn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const f=s.resolve(d);return hB(r,f,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let p;throw r===null?p="null":Array.isArray(r)?p="array":p=typeof r,new Hn("E_UNION_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${s.path}", got ${p}.`)}const i=r,a=_c(o);if(!a)throw new Hn("E_UNION_NO_DISCRIMINATOR",`[${e}] schema node at "${s.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:c,mapping:u}=a,l=i[c];if(l==null)throw new Hn("E_UNION_NO_DISCRIMINATOR",`[${e}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const d=String(l),f=u[d];if(!f)throw new Hn("E_UNION_UNKNOWN_TAG",`[${e}] discriminator tag "${d}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const g=s.resolve(f);return mB(r,g,{...s,path:`${s.path}[${d}]`})}}}const yB="x-apigen-instances";class si extends Error{constructor(e,n){super(n),this.name="NominalCodecError",this.code=e}}function ag(t){const e=t.properties;return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function wB(t){const e=t.required;return Array.isArray(e)?e.filter(n=>typeof n=="string"):[]}function cg(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.encode(t,e,n)}return t}function vB(t,e,n){if(e){const r=n.registry.resolve(e);if(r)return r.decode(t,e,n)}return t}function $B(t){const{id:e,schema:n,ctor:r}=t;return{id:e,kind:"nominal",schema:n,matches(o){return o[Jf]==="nominal"?!0:o[Qf]===e},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new si("E_NOMINAL_CYCLE",`[${e}] cycle detected at "${i.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN §8.3); break the cycle or use 'lossy' mode.`);return null}i.seen.add(o);try{const a=ag(s),c=typeof s[Wu]=="string"?s[Wu]:"toJSON",u=o[c];if(typeof u=="function"){const p=u.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[w,h]of Object.entries(p))y[w]=cg(h,a[w],{...i,path:`${i.path}/${w}`});return y}return p}const l={},d=Object.keys(a),f=o,g=d.length>0?d:Object.keys(f);for(const p of g){const y=f[p];y!==void 0&&(l[p]=cg(y,a[p],{...i,path:`${i.path}/${p}`}))}return l}finally{i.seen.delete(o)}},decode(o,s,i){if(o===null||typeof o!="object"||Array.isArray(o)){let l;throw o===null?l="null":Array.isArray(o)?l="array":l=typeof o,new si("E_NOMINAL_INVALID_WIRE",`[${e}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of wB(s))if(!(l in a))throw new si("E_NOMINAL_INVALID_WIRE",`[${e}] required field "${l}" missing on the wire at "${i.path}".`);if(s[yB]===!1)throw new si("E_NOMINAL_NONRECONSTRUCTABLE",`[${e}] is encode-only: the extractor marked it non-reconstructable (x-apigen-instances:false). It cannot be decoded back to a live instance.`);const c=ag(s),u={};for(const[l,d]of Object.entries(a))u[l]=vB(d,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[zu]=="string"?s[zu]:"fromJSON",d=r[l];if(typeof d=="function")return d.call(r,u);const f=r;return new f(u)}return u}}}const bB=[Yf,Zf,Xf,ep,tp,np],EB={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},ug=$B({id:"ts.NominalSentinel",schema:EB}),SB={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},lg=gB({id:"ts.UnionSentinel",schema:SB});function _B(){const t=[...bB.map(e=>[e.id,e]),[ug.id,ug],[lg.id,lg]];return Object.freeze(new Map(t))}Object.freeze({host:"ts",logicalTypeVersion:T2,codecs:_B()});function Zu(t,e,n){var r;const o=typeof((r=e==null?void 0:e.input)==null?void 0:r.description)=="string"?e.input.description:void 0,s=q0(e==null?void 0:e.input),i=[n,o,s].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):t}function H0(t){if(!t||typeof t!="object"||Array.isArray(t)||Object.keys(t).length===0)return{outputSchema:void 0,wrapped:!1};const e=t;return e.type==="object"?{outputSchema:e,wrapped:!1}:{outputSchema:{type:"object",properties:{result:e},required:["result"]},wrapped:!0}}function NB(t,e){return t?{result:e}:e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const dg=new Set(["string","number","boolean","integer"]);function OB(t){if(typeof t!="object"||t===null)return!1;const e=t;if(e.$ref!==void 0||e.oneOf||e.anyOf||e.allOf)return!1;const{type:n}=e;return typeof n=="string"?dg.has(n):Array.isArray(n)?n.every(r=>dg.has(r)||r==="null"):Array.isArray(e.enum)&&e.enum.length>0?e.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function kB(t){if(!t||typeof t!="object")return!1;const e=t.properties;return e===void 0||typeof e!="object"||e===null?!1:Object.values(e).every(OB)}const jB={"decimal.js":"Decimal"};function AB(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(jB).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${AB(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function fg(t){return t.words.join("-")}function pg(t){return t.words.map(TB).join("")}function hg(t){return t.words.join("_")}function IB(t,e={}){var n,r;const o=[t.namespace,...t.path],s=t.safe||kB(t.input)?"GET":"POST",i=((r=(n=e.http)==null?void 0:n.verb)==null?void 0:r[t.id])??s,a="/"+o.map(g=>fg(g)).join("/"),c=o.map(g=>hg(g)).join("_"),u=o.map(g=>hg(g)).slice(0,-1).join("."),l=pg(o[o.length-2]??o[0]),d=pg(o[o.length-1]),f=o.map(g=>fg(g));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:d},cli:{path:f}}}function PB(t,e){return`x-${t}-${e}`}function xB(t,e){return`--${t}-${e}`}function RB(t,e){const n=r=>r.toUpperCase().replace(/-/g,"_");return t==="adhd"?`APIGEN_${n(e)}`:`APIGEN_${n(t)}_${n(e)}`}function TB(t){return t.length===0?t:t[0].toUpperCase()+t.slice(1)}function rp(t){return t.anyOf??t.oneOf}function CB(t){if(!t)return!1;if(t.type==="array"||t.type==="object")return!0;const e=rp(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="array"||r.type==="object")}return!1}function MB(t){if(!t)return!1;if(t.type==="boolean")return!0;const e=rp(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function LB(t){if(!t)return!1;if(t.type==="number"||t.type==="integer")return!0;const e=rp(t);if(e){const n=e.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="number"||r.type==="integer")}return!1}function DB(t){return t.replace(/[A-Z]/g,e=>"-"+e.toLowerCase())}function UB(t){var e,n;const r=(n=(e=t.input)==null?void 0:e.properties)==null?void 0:n.data,o=(r==null?void 0:r.properties)??{},s=(r==null?void 0:r.required)??[];return{props:o,required:s}}function mg(t){return typeof t.handler=="function"}function BB(t){var e;const n=((e=t.input)==null?void 0:e.properties)??{},r=t["x-apigen-envelope"],o=[];for(const s of Object.keys(n)){if(s==="data")continue;const i=(r==null?void 0:r[s])??"adhd",a=PB(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:xB(i,s),envVar:RB(i,s)})}return o}function FB(t,e,n,r){e===n||t.has(e)||t.set(e,{...r,aliasOf:n})}function qB(t,e){const n=new Map,{props:r}=UB(t);for(const[o,s]of Object.entries(r)){let i="string";MB(s)?i="boolean":(CB(s)||LB(s))&&(i="json");const a=DB(o),c={camelKey:o,kind:"domain",valueKind:i};n.set(a,c),FB(n,o,a,c)}for(const o of e){const s=o.cliFlag.replace(/^--/,""),i={camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar};n.set(s,i)}return n}function Xu(t){const{op:e,schema:n,transport:r,projection:o}=t,s=IB(e,o),i=n?BB(n):[],a=n?qB(n,i):new Map,c=n?iB(n).params:void 0,u={op:e,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:e.streaming,isMount:mg(e)};if(mg(e)){const l=e.handler;u.mountHandler=async d=>l(d)}return u}function KB(t){const e=t.usePlugins;return Array.isArray(e)?e:[]}function VB(t){const e=t.useOptions;return e&&typeof e=="object"?e:{}}function GB(t){return async function(e,n){const r=Object.assign(e,{data:e.domainArgs});return await t.layer(r,n)}}function Nc(t,e){var n;const r=[];for(const o of e){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(GB(s))}return r.push(dB(t)),Z2(r)}function zB(){const t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}const WB={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function gg(t,e,n,r){const o={...n,operation:{id:t.op.id},ctx:new G0};if(t.isMount){const s=t.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${t.op.id}" has isMount=true but no mountHandler`);const i={operation:t.op,data:n.domainArgs,envelope:n.envelope,ctx:zB(),transport:t.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[t.op.id]:()=>s(i)},schemas:{[t.op.id]:WB}};return e(t.op.id,o,a)}return e(t.op.id,o,r)}function HB(){return`// Auto-generated by @adhd/apigen-cli — do not edit
47
+ `}async function Hu(e,t,n){const r=new AbortController;t.raw.once("close",()=>r.abort());const o=n.raw;let i=!1;try{for await(const s of e){if(r.signal.aborted)break;i||(o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive","Transfer-Encoding":"chunked"}),i=!0),o.write(qu(JSON.stringify(s)))}i||o.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),o.end()}catch(s){const a=re(s)?s:new L("internal",s instanceof Error?s.message:String(s));if(i)o.write(Ku(JSON.stringify(a.toJSON()))),o.end();else{const c=Gu(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const Vu={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function Gu(e){return Vu[e]??500}function as(e){return re(e)?id[e.code]??500:500}function cs(e){return re(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function Ju(e,t){if(e)for(const n of t){const r={method:n.method,route:n.route};let o=`${n.method} ${n.route}`;n.params.length&&(r.method==="GET"?o+=` params {${n.text?` ${n.text} `:""}}`:o+=` body { data: {${n.text?` ${n.text} `:""}} }`),e.info(n,o)}}class Wu{constructor(t,n,r){this.app=t,this.routePrefix=n,this.signal=r,this.schemasByOpId=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}routeFor(t){return t.isMount?`${this.routePrefix}/${t.op.id}`:this.routePrefix+t.http.route}registerRoute(t,n){const r=this.routeFor(t),o=async(i,s)=>{const a={req:i,reply:s};try{const c=await this.readCall(a,t),d=await n(c);await this.writeResult(a,d,t)}catch(c){await this.writeError(a,c,t)}};t.http.verb==="GET"?this.app.get(r,o):this.app.post(r,o)}readCall(t,n){const{req:r}=t,o=r.headers,i={};for(const a of n.envelope){const c=o[a.httpHeader];c!==void 0&&(i[a.field]=c)}let s={};if(n.isMount)s=n.http.verb==="GET"?r.query??{}:r.body??{};else{const a=this.schemasByOpId.get(n.op.id);if(n.http.verb==="GET"){const c=r.query??{};s=a?od(c,a):c}else{const{data:c={}}=r.body??{};s=c}}return{envelope:i,domainArgs:s,signal:this.signal}}async writeResult(t,n,r){const{req:o,reply:i}=t;if(Dt(n)){await Hu(n,o,i);return}i.type("application/json"),i.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){const{reply:o}=t;o.status(as(n)).send(cs(n))}}function zu(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("http")||i.push(u)}return i}async function Yu(e){var h,y;const t=e.options.port??3e3,n=e.options.host??"127.0.0.1",r=e.options.routePrefix??"",o=e.options.projection??{},i=Zn(e.options),s=eo(e.options),a=e.logger??Xn(),c=ja({logger:a});c.setErrorHandler((w,b,S)=>{S.status(as(w)).send(cs(w))});const d=new Wu(c,r,e.signal),l=[],u={},f={};for(const w of e.packages){if(!w.fns)throw new Error(`Package "${w.id}" is missing fns`);const b=w.fns,S=Object.entries(w.schemas).map(([_,R])=>({fnName:_,fnSchema:R,op:ss(w.id,_,R,e.operations)})),E={},A={};for(const{fnName:_,fnSchema:R,op:T}of S)E[T.id]=R,A[T.id]=b[_],u[T.id]=R,f[T.id]=b[_];const j=de(E,i),N={fns:A,createClient:w.createClient,schemas:E};for(const{fnSchema:_,op:R}of S){const T=ye({op:R,schema:_,transport:"http",projection:o});d.bindSchema(R.id,_),d.registerRoute(T,x=>xe(T,j,x,N));const{params:C,text:q}=bi(_);l.push({method:T.http.verb,route:r+T.http.route,text:q,params:C})}}const g=((h=e.packages[0])==null?void 0:h.id)??"ts",p=de(u,i),m={invoke:(w,b,S)=>p(w,{operation:{id:w},ctx:new tt,domainArgs:b.domainArgs,envelope:b.envelope,signal:b.signal},S),invokeOptions:{fns:f,schemas:u,createClient:(y=e.packages[0])==null?void 0:y.createClient}},v=zu(i,s,g,e.operations??[],m);if(v.length>0){const w=de({},i),b={fns:{},schemas:{}};for(const S of v){const E=ye({op:S,transport:"http",projection:o});d.registerRoute(E,A=>xe(E,w,A,b)),l.push({method:E.http.verb,route:`${r}/${S.id}`,text:"",params:[]})}}return await c.listen({port:t,host:n}),a.info({host:n,port:t},`listening on http://${n}:${t}`),Ju(a,l),new Promise(w=>{e.signal&&e.signal.addEventListener("abort",async()=>{await c.close(),w()})})}const Xu={id:"api-fastify",description:"Expose functions as Fastify HTTP POST routes",language:"ts",optionsSchema:{type:"object",properties:{port:{type:"number",default:3e3},routePrefix:{type:"string",default:""}}},generate(e){return Bu(e)},run(e){return Yu(e)}};function Qu(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const i of e){const s=Me(i),{verb:a,route:c}=s.http,d=a.toLowerCase(),l={operationId:i.id,summary:i.id,responses:{200:Zu(i.output)}};if(a==="GET")l.parameters=ef(i.input);else{const u=i.input;typeof u=="object"&&u!==null&&Object.keys(u).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:u}}})}o[c]===void 0&&(o[c]={}),o[c][d]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function Zu(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function ef(e){if(typeof e!="object"||e===null||typeof e.properties!="object"||e.properties===null)return[];const t=Array.isArray(e.required)?e.required:[],n=e.properties;return Object.entries(n).map(([r,o])=>({name:r,in:"query",required:t.includes(r),schema:o}))}function tf(e,t={}){return[{...ai("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>Qu(e.operations,{title:t.title,version:t.version})}]}const nf={id:"openapi",description:"Mount plugin: serves the OpenAPI 3.1 doc at GET /meta/openapi",language:"ts",optionsSchema:{type:"object",properties:{title:{type:"string",description:"OpenAPI info.title"},version:{type:"string",description:"OpenAPI info.version"}},additionalProperties:!1},capabilities:{mount:{operations(e,t){return tf(e,t)}}}};function of(){return`// Auto-generated by @adhd/apigen-cli — do not edit
360
48
  import { Server } from '@modelcontextprotocol/sdk/server/index.js'
361
49
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
362
50
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
@@ -382,9 +70,10 @@ const server = new Server({ name: 'apigen-mcp', version: '1.0.0' }, { capabiliti
382
70
 
383
71
  server.setRequestHandler(ListToolsRequestSchema, async () => ({
384
72
  tools: Object.entries(toolMetas).map(([name, meta]) => {
385
- // BUG-APIGEN-019: publish the function's return-type schema (oneOf+discriminator
386
- // for unions) as MCP's outputSchema — wrapped under \`result\` when it isn't
387
- // top-level type:"object", since the MCP protocol requires that shape.
73
+ // ADR-0004: publish the function's return-type schema as MCP's outputSchema
74
+ // ONLY when it is already a top-level type:"object". A union/array/scalar
75
+ // return carries no outputSchema (it is optional in MCP) and is passed
76
+ // through flat — never wrapped under \`result\`.
388
77
  const { outputSchema } = buildMcpOutputSchema((meta.schema as any).output)
389
78
  return {
390
79
  name,
@@ -416,7 +105,9 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
416
105
  envelope,
417
106
  ((args as any)['data'] ?? {}) as Record<string, unknown>,
418
107
  )
419
- // BUG-APIGEN-019: pair outputSchema with a matching structuredContent value.
108
+ // ADR-0004: \`content\` is the canonical flat payload. \`structuredContent\` is
109
+ // emitted only for an already-object return (\`wrapped === true\` == emit),
110
+ // and then it is the value itself — never \`{ result: value }\`.
420
111
  const { wrapped } = buildMcpOutputSchema((meta.schema as any).output)
421
112
  const structuredContent = wrapMcpStructuredContent(wrapped, result)
422
113
  return {
@@ -427,10 +118,10 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
427
118
 
428
119
  const transport = new StdioServerTransport()
429
120
  server.connect(transport)
430
- `}function JB(t,e){return`// Auto-generated by @adhd/apigen-cli — do not edit
121
+ `}function rf(e,t){return`// Auto-generated by @adhd/apigen-cli — do not edit
431
122
  import { createServer } from 'node:http'
432
123
  import { Server } from '@modelcontextprotocol/sdk/server/index.js'
433
- ${t==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
124
+ ${e==="sse"?"import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js'":"import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'"}
434
125
  import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'
435
126
  import { dispatch, buildMcpOutputSchema, wrapMcpStructuredContent } from '@adhd/apigen-engine-runtime'
436
127
  import { toolMetas, groupFns, groupCreateClient } from './index.js'
@@ -454,9 +145,10 @@ const mcpServer = new Server({ name: 'apigen-mcp', version: '1.0.0' }, { capabil
454
145
 
455
146
  mcpServer.setRequestHandler(ListToolsRequestSchema, async () => ({
456
147
  tools: Object.entries(toolMetas).map(([name, meta]) => {
457
- // BUG-APIGEN-019: publish the function's return-type schema (oneOf+discriminator
458
- // for unions) as MCP's outputSchema — wrapped under \`result\` when it isn't
459
- // top-level type:"object", since the MCP protocol requires that shape.
148
+ // ADR-0004: publish the function's return-type schema as MCP's outputSchema
149
+ // ONLY when it is already a top-level type:"object". A union/array/scalar
150
+ // return carries no outputSchema (it is optional in MCP) and is passed
151
+ // through flat — never wrapped under \`result\`.
460
152
  const { outputSchema } = buildMcpOutputSchema((meta.schema as any).output)
461
153
  return {
462
154
  name,
@@ -488,7 +180,9 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
488
180
  envelope,
489
181
  ((args as any)['data'] ?? {}) as Record<string, unknown>,
490
182
  )
491
- // BUG-APIGEN-019: pair outputSchema with a matching structuredContent value.
183
+ // ADR-0004: \`content\` is the canonical flat payload. \`structuredContent\` is
184
+ // emitted only for an already-object return (\`wrapped === true\` == emit),
185
+ // and then it is the value itself — never \`{ result: value }\`.
492
186
  const { wrapped } = buildMcpOutputSchema((meta.schema as any).output)
493
187
  const structuredContent = wrapMcpStructuredContent(wrapped, result)
494
188
  return {
@@ -497,28 +191,34 @@ mcpServer.setRequestHandler(CallToolRequestSchema, async (req) => {
497
191
  }
498
192
  })
499
193
 
500
- const mcpTransport = new ${t==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
194
+ const mcpTransport = new ${e==="sse"?"SSEServerTransport":"StreamableHTTPServerTransport"}({ sessionIdGenerator: undefined } as any)
501
195
  const httpServer = createServer((req, res) => (mcpTransport as any).handleRequest(req, res))
502
- httpServer.listen(${e}, () => console.error('MCP ${t} server on port ${e}'))
503
- `}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const QB={"decimal.js":"Decimal"};function YB(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(QB).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${YB(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function ZB(t){return t.split(/[-_.]+/).flatMap(e=>e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").split("_").filter(Boolean)).map(e=>e.toLowerCase()).filter(Boolean)}Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href);const XB={"decimal.js":"Decimal"};function eF(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(XB).map(([t,e])=>({pattern:new RegExp(`import\\(["'][^"']*${eF(t)}[^"']*["']\\)\\.\\w+`,"g"),key:e}));function tF(t){return t.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function el(t){return{raw:t,words:ZB(t)}}function nF(t){return el(tF(Ic.basename(t)))}function J0(t,e,n){if(n){const o=n.find(s=>{var i;return s.kind==="action"&&s.namespace.raw===t.id&&((i=s.path[s.path.length-1])==null?void 0:i.raw)===e});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${t.id}" fn "${e}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return o}const r=el(e);return{id:`${t.id}/${e}`,host:"ts",namespace:el(t.id),path:t.dropFileSegment?[r]:[nF(t.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function rF(t,e,n){const r=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const o of t)r.push(`import * as ${o.id}_ns from '${o.importPath}'`),r.push(`const ${o.id}_fns = buildFnTable(${o.id}_ns as Record<string, unknown>)`);r.push(""),r.push("export const toolMetas: Record<string, { group: string; fnName: string; schema: unknown; description: string }> = {");for(const o of t)for(const[s,i]of Object.entries(o.schemas)){const a=J0({id:o.id,importPath:o.importPath},s,n),c=Xu({op:a,schema:i,transport:"mcp"}).mcp.name,u=Zu(c,i,e[c]??e[s]);r.push(` ${JSON.stringify(c)}: { group: '${o.id}', fnName: ${JSON.stringify(s)}, schema: ${JSON.stringify(i)}, description: ${JSON.stringify(u)} },`)}r.push("}"),r.push(""),r.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const o of t)r.push(` '${o.id}': ${o.id}_fns as Record<string, (...args: unknown[]) => unknown>,`);r.push("}"),r.push(""),r.push("export const groupCreateClient: Record<string, ((e: Record<string, unknown>) => Promise<unknown>) | undefined> = {");for(const o of t)r.push(` '${o.id}': undefined, // injected at startup if createClient provided`);return r.push("}"),r.join(`
504
- `)}function oF(t){const e=t.options.transport??"stdio",n=t.options.port??3e3,r=t.options.toolDescriptions??{},o=t.operations,s=rF(t.packages,r,o),i=e==="stdio"?HB():JB(e,n);return{files:[{path:"index.ts",content:s},{path:"server.ts",content:i}]}}const sF=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function Q0(t){return typeof t=="object"&&t!==null&&t.name==="ApiError"&&sF.includes(t.code)&&typeof t.toJSON=="function"}async function iF(t){const e=await fB(t);if(e.ok){const o=e.chunks.map(s=>({type:"text",text:JSON.stringify(s)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=e;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const r={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(r)}],isError:!0}}class aF{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(e,n){this.schemasByOpId.set(e,n)}bindToolMeta(e,n){this.toolMeta.set(e,n)}registerRoute(e,n){this.plans.set(e.mcp.name,e),this.dispatchers.set(e.mcp.name,n)}getPlan(e){return this.plans.get(e)}getDispatch(e){return this.dispatchers.get(e)}listTools(){return[...this.plans.keys()].map(e=>{const n=this.toolMeta.get(e);return{name:e,description:(n==null?void 0:n.description)??e,inputSchema:(n==null?void 0:n.inputSchema)??{type:"object",properties:{}},...n!=null&&n.outputSchema?{outputSchema:n.outputSchema}:{}}})}readCall(e,n){const r={};for(const s of n.envelope){const i=e.meta[s.mcpMetaKey];i!==void 0&&(r[s.field]=i)}const o=n.isMount?e.args:e.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(e,n,r){if(pB(n)){e.output=await iF(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=H0(o==null?void 0:o.output),i=NB(s,n);e.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(e,n,r){throw Q0(n)&&n.code,n}}function cF(t){if(t&&typeof t=="object"&&t.type==="object")return t;const e=t==null?void 0:t.oneOf;if(Array.isArray(e)&&e.length>0){const n={};let r=null;for(const o of e){if(!o||typeof o!="object")continue;const s=o,i=s.properties;if(i&&typeof i=="object")for(const[c,u]of Object.entries(i))c in n||(n[c]=u);const a=Array.isArray(s.required)?s.required:[];r=r===null?[...a]:r.filter(c=>a.includes(c))}return{...t,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function uF(t,e,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of t){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,e[c.id],o);for(const d of l)d.transports&&!d.transports.includes("mcp")||i.push(d)}return i}function lF(t,e){var n,r;const o=t.options.projection??{},s=t.options.toolDescriptions??{},i=KB(t.options),a=VB(t.options),c={},u={};for(const p of t.packages){if(!p.fns)throw new Error(`Package "${p.id}" is missing fns`);const y=p.fns,w=Object.entries(p.schemas).map(([N,j])=>({fnName:N,fnSchema:j,op:J0({id:p.id,importPath:p.importPath},N,t.operations)})),h={},v={};for(const{fnName:N,fnSchema:j,op:T}of w)h[T.id]=j,v[T.id]=y[N],c[T.id]=j,u[T.id]=y[N];const b=Nc(h,i),E={fns:v,createClient:p.createClient,schemas:h};for(const{fnName:N,fnSchema:j,op:T}of w){const M=Xu({op:T,schema:j,transport:"mcp",projection:o});e.bindSchema(T.id,j);const{outputSchema:C}=H0(j.output),G=Zu(M.mcp.name,j,s[M.mcp.name]??s[N]);e.bindToolMeta(M.mcp.name,{description:G,inputSchema:j.input,outputSchema:C}),e.registerRoute(M,H=>gg(M,b,H,E))}}const l=((n=t.packages[0])==null?void 0:n.id)??"ts",d=Nc(c,i),f={invoke:(p,y,w)=>d(p,{operation:{id:p},ctx:new G0,domainArgs:y.domainArgs,envelope:y.envelope,signal:y.signal},w),invokeOptions:{fns:u,schemas:c,createClient:(r=t.packages[0])==null?void 0:r.createClient}},g=uF(i,a,l,t.operations??[],f);if(g.length>0){const p=Nc({},i),y={fns:{},schemas:{}};for(const w of g){const h=Xu({op:w,transport:"mcp",projection:o}),v=cF(w.input),b=Zu(h.mcp.name,{input:v},s[h.mcp.name]);e.bindToolMeta(h.mcp.name,{description:b,inputSchema:v}),e.registerRoute(h,E=>gg(h,p,E,y))}}}function dF(t){const e=t.packages[0];return{name:(e==null?void 0:e.id)??"apigen-mcp",version:(e==null?void 0:e.version)??"1.0.0"}}function Oc(t,e,n){const r=new rE.Server(n,{capabilities:{tools:{}}});return r.setRequestHandler(gp.ListToolsRequestSchema,async()=>({tools:t.listTools()})),r.setRequestHandler(gp.CallToolRequestSchema,async o=>{const{name:s,arguments:i={}}=o.params,a=t.getPlan(s),c=t.getDispatch(s);if(!a||!c)throw new Error(`Unknown tool: ${s}`);const u=i,l=u._meta??{},d={args:u,meta:l},f=Date.now();try{const g=await t.readCall(d,a),p=await c(g);return await t.writeResult(d,p,a),e.info({tool:s,ms:Date.now()-f},`→ ${s}`),d.output}catch(g){throw Q0(g)&&g.code!=="internal"?e.error({tool:s,ms:Date.now()-f,code:g.code,message:g.message},`✗ ${s}`):e.error({tool:s,ms:Date.now()-f,err:g},`✗ ${s}`),t.writeError(d,g,a),g}}),r}function yg(t,e){return async(n,r)=>{try{await e(n,r)}catch(o){t.error({err:o},"mcp http transport handler error"),r.headersSent||r.writeHead(500),r.writableEnded||r.end("Internal Server Error")}}}async function fF(t){const e=t.options.transport??"stdio",n=t.options.port??3e3,r=t.options.host??"127.0.0.1",o=t.logger??tB();o.info(`mcp server starting (${e})`);const s=new aF;lF(t,s);const i=s.listTools().map(u=>u.name);o.info({tools:i},`${i.length} tools available`);for(const u of i){const l=s.getPlan(u),d=(l==null?void 0:l.params)??[],f=d.map(g=>`${g.name}${g.required?"":"?"}: ${g.type}`).join(", ");o.info({tool:u,args:{data:d}},`tool: ${u} args { data: {${f?` ${f} `:""}} }`)}const a=dF(t);if(o.info({identity:a},`mcp handshake identity: ${a.name}@${a.version}`),e==="stdio"){const u=Oc(s,o,a),l=new oE.StdioServerTransport;return await u.connect(l),o.info("stdio transport ready"),new Promise(d=>{t.signal&&t.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),d()})})}if(e==="sse"){const u=new Map,l=mp.createServer(yg(o,async(d,f)=>{const g=d.url??"";if(d.method==="GET"&&g==="/sse"){const p=Oc(s,o,a),y=new sE.SSEServerTransport("/messages",f);u.set(y.sessionId,y),y.onclose=()=>u.delete(y.sessionId),await p.connect(y)}else if(d.method==="POST"&&g.startsWith("/messages")){const p=new URLSearchParams(g.split("?")[1]??"").get("sessionId"),y=p?u.get(p):void 0;if(!y){f.writeHead(404),f.end("Session not found");return}await y.handlePostMessage(d,f)}else f.writeHead(404),f.end("Not found")}));return l.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(d=>{t.signal&&t.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),l.close(()=>d())})})}const c=mp.createServer(yg(o,async(u,l)=>{const d=Oc(s,o,a),f=new iE.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await d.connect(f),await f.handleRequest(u,l)}));return c.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(u=>{t.signal&&t.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),c.close(()=>u())})})}const pF={id:"mcp",description:"Expose functions as MCP tools (stdio, SSE, or streaming-HTTP transport)",language:"ts",optionsSchema:{type:"object",properties:{transport:{type:"string",enum:["stdio","sse","streaming-http"]},port:{type:"number"},toolDescriptions:{type:"object",additionalProperties:{type:"string"}}}},generate(t){return oF(t)},run(t){return fF(t)}},Y0=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],Z0=["body","citations","notes","auditTrail","blockers","related","_score","_vector"],hF=new Set([...Y0,...Z0]);function mF(t){return hF.has(t)}const Is=["uid","kind","title","status","priority"],Mt=1e3,X0=50;async function op(t,e){const n=await t.getNodeByUid(e);if(!n||n.kind!=="issue"||n.tInvalid)throw new fa(e);if(n.isSuperseded)throw new da(e,await gF(t,n));return n}async function gF(t,e){const n=new Set([e.id]);let r,o=e;for(;;){const i=(await t.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(c=>!n.has(c.src));if(!i)return r==null?void 0:r.uid;n.add(i.src);const a=(await t.getNodesByIds([i.src]))[0];if(!a||a.tInvalid)return r==null?void 0:r.uid;if(r=a,!a.isSuperseded)return a.uid;o=a}}async function xe(t,e,n){if(_r(n)){const s=await t.getNodeByUid(n);return!s||s.kind!==e||s.tInvalid?null:{id:s.id,uid:s.uid,name:s.name??n,record:s}}const o=(await t.queryNodes({kind:e,name:n,liveOnly:!0,limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}async function yo(t,e,n){var s;if(_r(n)){const i=await xe(t,"component",n);return!i||((s=i.record.metadata)==null?void 0:s.projectUid)!==e?null:i}const o=(await t.queryNodes({kind:"component",name:n,liveOnly:!0,metadata:{projectUid:{eq:e}},limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}function ao(t,e){return t.getEdges({src:e})}async function eb(t,e){var c,u;const r=(c=(await t.getEdges({dst:e,rel:"owns_component"}))[0])==null?void 0:c.src;if(r===void 0)return{};const[o]=await t.getNodesByIds([r]);if(!o)return{};const i=(u=(await t.getEdges({dst:r,rel:"owns_project"}))[0])==null?void 0:u.src;if(i===void 0)return{component:o};const[a]=await t.getNodesByIds([i]);return{component:o,project:a}}async function yF(t,e){const n=e.expectedKind==="component"&&e.projectUid!==void 0?await yo(t,e.projectUid,e.ref):await xe(t,e.expectedKind,e.ref);if(!n)return;if(await wF(t,e.rel,e.expectedKind)){const o=await t.getEdges({src:n.id,rel:e.rel});return new Set(o.map(s=>s.dst))}const r=await t.getEdges({dst:n.id,rel:e.rel});return new Set(r.map(o=>o.src))}async function wF(t,e,n){var s;const o=(s=(await t.queryNodes({kind:"edge_kind",name:e,liveOnly:!0,limit:1}))[0])==null?void 0:s.metadata;return typeof(o==null?void 0:o.source_kind)=="string"&&o.source_kind===n}async function vF(t,e){return(await t.queryNodes({kind:e,liveOnly:!0})).map(r=>r.name).filter(r=>typeof r=="string")}function $F(t,e){const n=t.length+1,r=e.length+1,o=Array.from({length:n},()=>new Array(r).fill(0));for(let s=0;s<n;s+=1)o[s][0]=s;for(let s=0;s<r;s+=1)o[0][s]=s;for(let s=1;s<n;s+=1)for(let i=1;i<r;i+=1)o[s][i]=t[s-1]===e[i-1]?o[s-1][i-1]:1+Math.min(o[s-1][i],o[s][i-1],o[s-1][i-1]);return o[t.length][e.length]}function tb(t,e,n=3){const r=Math.max(2,Math.ceil(t.length/2));return e.map(o=>({candidate:o,distance:$F(t.toLowerCase(),o.toLowerCase())})).filter(o=>o.distance<=r).sort((o,s)=>o.distance-s.distance).slice(0,n).map(o=>o.candidate)}async function Qr(t,e){const n=await vF(t,e.catalogKind),r=new Set,o=[];for(const s of e.refs){const i=await xe(t,e.catalogKind,s);if(!i){o.push(s);continue}const a=await t.getEdges({dst:i.id,rel:e.rel});for(const c of a)r.add(c.src)}if(o.length>0){const s=n.length>0?n.map(a=>`"${a}"`).join(", "):"(no live rows exist for this catalog yet)",i=o.map(a=>{const c=tb(a,n);return c.length>0?`"${a}" (did you mean ${c.map(u=>`"${u}"`).join(" or ")}?)`:`"${a}"`}).join(", ");throw new Er(e.field,`unknown ${e.catalogKind} value(s): ${i} — no live "${e.catalogKind}" catalog row matches (existing ${e.catalogKind} values: ${s})`)}return r}function bF(t){if(t.length===0)return;let[e]=t;for(const n of t.slice(1)){const r=new Set;for(const o of e)n.has(o)&&r.add(o);e=r}return e}function sp(t){if(t){for(const e of t)if(!mF(e))throw new Er("fields",`unknown field "${e}" — known fields: ${[...Y0,...Z0].join(", ")}`)}}function Nr(t){var e;return((e=t==null?void 0:t.metadata)==null?void 0:e.terminal)===!0}async function EF(t,e,n){const r=n.find(l=>l.rel==="has_kind"&&l.src===e),o=n.find(l=>l.rel==="has_status"&&l.src===e),s=n.find(l=>l.rel==="has_priority"&&l.src===e),i=n.find(l=>l.rel==="authored_by"&&l.src===e),a=[r==null?void 0:r.dst,o==null?void 0:o.dst,s==null?void 0:s.dst,i==null?void 0:i.dst].filter(l=>l!==void 0);if(a.length===0)return{};const c=await t.getNodesByIds(a),u=new Map(c.map(l=>[l.id,l]));return{kind:r?u.get(r.dst):void 0,status:o?u.get(o.dst):void 0,priority:s?u.get(s.dst):void 0,author:i?u.get(i.dst):void 0}}async function SF(t,e,n){const r=n.filter(s=>s.rel==="has_citation"&&s.src===e);return r.length===0?[]:(await t.getNodesByIds(r.map(s=>s.dst))).map(s=>{var i,a,c,u,l;return{uid:s.uid,file:typeof((i=s.metadata)==null?void 0:i.target)=="string"?s.metadata.target:s.name??"",lines:typeof((a=s.metadata)==null?void 0:a.line)=="string"?s.metadata.line:void 0,context:s.content||void 0,symbol:typeof((c=s.metadata)==null?void 0:c.symbol)=="string"?s.metadata.symbol:void 0,sha:typeof((u=s.metadata)==null?void 0:u.sha)=="string"?s.metadata.sha:"unverified",at:typeof((l=s.metadata)==null?void 0:l.at)=="string"?s.metadata.at:s.tCreated}})}async function _F(t,e,n){const r=n.filter(s=>s.rel==="has_note"&&s.src===e);return r.length===0?[]:(await t.getNodesByIds(r.map(s=>s.dst))).map(s=>{var i,a,c;return{uid:s.uid,author:typeof((i=s.metadata)==null?void 0:i.author)=="string"?s.metadata.author:"",text:typeof((a=s.metadata)==null?void 0:a.text)=="string"?s.metadata.text:s.content,at:typeof((c=s.metadata)==null?void 0:c.at)=="string"?s.metadata.at:s.tCreated}})}async function NF(t,e,n){const r=(n??await ao(t,e)).filter(i=>i.rel==="audits"&&i.src===e);return r.length===0?[]:(await t.getNodesByIds(r.map(i=>i.dst))).map(i=>{var a,c,u,l,d,f,g;return{uid:i.uid,actor:typeof((a=i.metadata)==null?void 0:a.actor)=="string"?i.metadata.actor:"",action:typeof((c=i.metadata)==null?void 0:c.action)=="string"?i.metadata.action:i.name??"",from:typeof((u=i.metadata)==null?void 0:u.from)=="string"?i.metadata.from:void 0,to:typeof((l=i.metadata)==null?void 0:l.to)=="string"?i.metadata.to:void 0,note:typeof((d=i.metadata)==null?void 0:d.note)=="string"?i.metadata.note:void 0,sha:typeof((f=i.metadata)==null?void 0:f.sha)=="string"?i.metadata.sha:"",at:typeof((g=i.metadata)==null?void 0:g.at)=="string"?i.metadata.at:i.tCreated}}).sort((i,a)=>i.at.localeCompare(a.at))}async function OF(t,e){const n=await t.getEdges({dst:e,rel:"blocks"});if(n.length===0)return[];const r=n.map(i=>i.src),o=await t.getNodesByIds(r),s=await nb(t,o);return o.filter(i=>!Nr(s.get(i.id))).map(i=>{var a;return{uid:i.uid,title:i.name??"",status:((a=s.get(i.id))==null?void 0:a.name)??""}})}async function kF(t,e,n){const r=(n??await ao(t,e)).filter(c=>c.rel==="relates_to"&&c.src===e),o=await t.getEdges({dst:e,rel:"relates_to"}),s=new Set([...r.map(c=>c.dst),...o.map(c=>c.src)]);if(s.size===0)return[];const i=await t.getNodesByIds([...s]),a=await nb(t,i);return i.map(c=>{var u;return{uid:c.uid,title:c.name??"",status:((u=a.get(c.id))==null?void 0:u.name)??""}})}async function nb(t,e){if(e.length===0)return new Map;const n=new Set(e.map(u=>u.id)),r=await t.getEdges({rel:"has_status"}),o=new Map;for(const u of r)n.has(u.src)&&!o.has(u.src)&&o.set(u.src,u.dst);const s=[...new Set(o.values())];if(s.length===0)return new Map;const i=await t.getNodesByIds(s),a=new Map(i.map(u=>[u.id,u])),c=new Map;for(const[u,l]of o){const d=a.get(l);d&&c.set(u,d)}return c}async function rb(t,e,n,r={}){var p,y,w;const o={uid:e.uid},s=h=>n.includes(h),i=s("kind")||s("status")||s("priority")||s("author"),a=s("project")||s("component"),c=s("citations"),u=s("notes"),l=s("auditTrail"),d=s("blockers"),f=s("related"),g=r.outgoingEdges??(i||c||u||l||f?await ao(t,e.id):void 0);if(s("title")&&(o.title=e.name??""),s("createdAt")&&(o.createdAt=e.tCreated),s("updatedAt")&&(o.updatedAt=e.tValid),s("assignee")){const h=(p=e.metadata)==null?void 0:p.assignee;typeof h=="string"&&(o.assignee=h)}if(s("gitContext")){const h=(y=e.metadata)==null?void 0:y.gitContext;typeof h=="string"&&h.length>0&&(o.gitContext=h)}if(s("closedAt")){const h=(w=e.metadata)==null?void 0:w.closedAt;typeof h=="string"&&(o.closedAt=h)}if(s("body")&&(o.body=e.content),i&&g){const h=await EF(t,e.id,g);s("kind")&&h.kind&&(o.kind=h.kind.name??""),s("status")&&h.status&&(o.status=h.status.name??""),s("priority")&&h.priority&&(o.priority=h.priority.name??""),s("author")&&h.author&&(o.author=h.author.name??"")}if(a){const{project:h,component:v}=await eb(t,e.id);s("project")&&h&&(o.project=h.uid),s("component")&&v&&(o.component=v.uid)}return c&&g&&(o.citations=await SF(t,e.id,g)),u&&g&&(o.notes=await _F(t,e.id,g)),l&&g&&(o.auditTrail=await NF(t,e.id,g)),d&&(o.blockers=await OF(t,e.id)),f&&g&&(o.related=await kF(t,e.id,g)),s("_score")&&r.score!==void 0&&(o._score=r.score),o}async function vs(t,e,n,r){return Promise.all(e.map(o=>rb(t,o,n,{score:r==null?void 0:r.get(o.uid)})))}const jF=.0050125;function AF(t){if(t===void 0)return X0;if(!Number.isInteger(t)||t<=0||t>Mt)throw new Er("limit",`must be a positive integer ≤ ${Mt}, got ${t}`);return t}async function IF(t,e){const n=new Set;for(const r of e.refs){const o=await yF(t,{rel:e.rel,expectedKind:e.expectedKind,ref:r});if(o)for(const s of o)n.add(s)}return n}async function PF(t,e){const r=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(s=>Nr(s)===(e==="closed")),o=new Set;for(const s of r){const i=await t.getEdges({dst:s.id,rel:"has_status"});for(const a of i)o.add(a.src)}return o}async function xF(t,e){if(e.project===void 0&&e.component===void 0)return;let n,r;if(e.project!==void 0){const c=await xe(t,"project",e.project);if(!c)return new Set;n=c.uid;const u=await t.getEdges({src:c.id,rel:"owns_project"}),l=new Set;for(const d of u){const f=await t.getEdges({src:d.dst,rel:"owns_component"});for(const g of f)l.add(g.dst)}r=l}if(e.component===void 0)return r;const o=n!==void 0?await yo(t,n,e.component):await xe(t,"component",e.component);if(!o)return new Set;const s=await t.getEdges({src:o.id,rel:"owns_component"}),i=new Set(s.map(c=>c.dst));if(!r)return i;const a=new Set;for(const c of i)r.has(c)&&a.add(c);return a}function RF(t){var r,o,s,i;const e={};t.assignee!==void 0&&(e.assignee={eq:t.assignee}),t.claimedBy!==void 0&&(e.claimedBy={eq:t.claimedBy}),t.closedAt!==void 0&&(t.closedAt.since&&t.closedAt.until?e.closedAt={between:[t.closedAt.since,t.closedAt.until]}:t.closedAt.since?e.closedAt={gte:t.closedAt.since}:t.closedAt.until&&(e.closedAt={lte:t.closedAt.until}));const n={};return Object.keys(e).length>0&&(n.metadata=e),(r=t.createdAt)!=null&&r.since&&(n.tCreatedAfter=t.createdAt.since),(o=t.createdAt)!=null&&o.until&&(n.tCreatedBefore=t.createdAt.until),(s=t.updatedAt)!=null&&s.since&&(n.tUpdatedAfter=t.updatedAt.since),(i=t.updatedAt)!=null&&i.until&&(n.tUpdatedBefore=t.updatedAt.until),Object.keys(n).length>0?n:void 0}async function ob(t,e){if(!e)return;const n=[],r=await xF(t,e);if(r!==void 0&&n.push(r),e.kind!==void 0){const c=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await Qr(t,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:c}))}if(e.status!==void 0&&e.status!=="all")if(e.status==="open"||e.status==="closed")n.push(await PF(t,e.status));else{const c=Array.isArray(e.status)?e.status:[e.status];n.push(await Qr(t,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:c}))}if(e.priority!==void 0){const c=Array.isArray(e.priority)?e.priority:[e.priority];n.push(await Qr(t,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:c}))}e.author!==void 0&&n.push(await IF(t,{rel:"authored_by",expectedKind:"agent",refs:[e.author]}));const o=RF(e);if(n.length===0&&!o)return;let s;if(n.length>0){let[c]=n;for(const u of n.slice(1)){const l=new Set;for(const d of c)u.has(d)&&l.add(d);c=l}if(s=c,s.size===0)return new Set}const i={kind:"issue",liveOnly:!0,isSuperseded:!1,...s?{ids:[...s]}:{},...o},a=await t.queryNodes(i);return new Set(a.map(c=>c.id))}const TF=4;async function CF(t,e){if(e.length===0)return[];const n=e.map(i=>i.id),r={ids:n,isSuperseded:!1,limit:n.length},o=await t.queryNodes(r),s=new Set(o.map(i=>i.id));return e.filter(i=>s.has(i.id))}async function MF(t,e){if(!t.search)throw new oe("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");if(e.candidateIds&&e.candidateIds.size===0)return[];const n=e.candidateIds?{ids:[...e.candidateIds]}:{kind:"issue"},r={text:e.text,vec:e.vec,signals:[{kind:"text"},{kind:"vec"}],rescore:[{kind:"temporal",decay:e.decayPerHour??jF}],filters:n},o=[];let s=e.limit;for(let i=0;i<TF;i++){const a=await t.search.backend.searchRanked(r,s);if(o.length=0,o.push(...await CF(t.graph,a)),o.length>=e.limit||a.length<s)break;s*=2}return o.slice(0,e.limit)}async function LF(t,e){var w,h;const{graph:n}=t;if(!t.search)throw new oe("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");sp(e.fields);const r=e.fields??Is,o=AF(e.limit);let s,i;if(((w=e.filter)==null?void 0:w.anchor)!==void 0)i=await op(n,e.filter.anchor),s=`${i.name??""}
505
- ${i.content}`.trim();else if(((h=e.filter)==null?void 0:h.semantic)!==void 0)s=e.filter.semantic;else throw new oe("filter",'`view:"similar"` requires `filter.anchor` or `filter.semantic`');const a=await ob(n,e.filter);if(a&&i&&a.delete(i.id),a&&a.size===0)return[];const c=await t.search.embedQuery(s),u=i?o+1:o,l=await MF(t,{text:s,vec:c,candidateIds:a,limit:u}),d=(i?l.filter(v=>v.id!==i.id):l).slice(0,o);if(d.length===0)return[];const f=await n.getNodesByIds(d.map(v=>v.id)),g=new Map(f.map(v=>[v.id,v])),p=d.map(v=>g.get(v.id)).filter(v=>v!==void 0),y=new Map(d.map(v=>{var b;return[(b=g.get(v.id))==null?void 0:b.uid,v.score]}).filter(v=>v[0]!==void 0));return vs(n,p,r,y)}function DF(t){return t.replace(/\s+/g," ").replace(/[[\]]/g,"").trim()}function UF(t){const e=typeof t.gitContext=="string"&&t.gitContext.length>0?t.gitContext:void 0,n=t.citations??[];if(e===void 0&&n.length===0)return[];const r=["",e!==void 0?`Citations: [${DF(e)}]`:"Citations:"];for(const o of n){const s=o.lines?`${o.file}:${o.lines}`:o.file;r.push(`- [${s} sha:${o.sha}]`)}return r}function BF(t){const e=[];return t.kind!==void 0&&e.push(`kind: ${t.kind}`),t.status!==void 0&&e.push(`status: ${t.status}`),t.priority!==void 0&&e.push(`priority: ${t.priority}`),t.assignee!==void 0&&e.push(`assignee: ${t.assignee}`),t.project!==void 0&&e.push(`project: ${t.project}`),t.component!==void 0&&e.push(`component: ${t.component}`),e.length>0?e.join(" · "):void 0}function FF(t){const e=[`## ${t.title??"(untitled)"}`],n=BF(t);return n!==void 0&&e.push(n),t.body!==void 0&&t.body.length>0&&e.push("",t.body),e.push(...UF(t)),e.join(`
506
- `)}function qF(t){return t.length===0?`_No matching issues._
507
- `:`${t.map(FF).join(`
196
+ httpServer.listen(${t}, () => console.error('MCP ${e} server on port ${t}'))
197
+ `}function Pn(e){return{raw:e,words:ze(e)}}function sf(e){return Pn(Nd(cn.basename(e)))}function ds(e,t,n){if(n){const o=n.find(i=>{var s;return i.kind==="action"&&i.namespace.raw===e.id&&((s=i.path[i.path.length-1])==null?void 0:s.raw)===t});if(!o)throw new Error(`@adhd/apigen-plugin-mcp: no Operation found for package "${e.id}" fn "${t}" in the supplied operations[] — every fn in pkg.schemas must correspond to a real extracted Operation (orchestrator.ts buildDescriptor Step 5 invariant). This indicates a correlation bug, not a naming gap.`);return o}const r=Pn(t);return{id:`${e.id}/${t}`,host:"ts",namespace:Pn(e.id),path:e.dropFileSegment?[r]:[sf(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}function af(e,t,n){const r=["// Auto-generated by @adhd/apigen-cli — do not edit","import { buildFnTable } from '@adhd/apigen-engine-runtime'"];for(const o of e)r.push(`import * as ${o.id}_ns from '${o.importPath}'`),r.push(`const ${o.id}_fns = buildFnTable(${o.id}_ns as Record<string, unknown>)`);r.push(""),r.push("export const toolMetas: Record<string, { group: string; fnName: string; schema: unknown; description: string }> = {");for(const o of e)for(const[i,s]of Object.entries(o.schemas)){const a=ds({id:o.id,importPath:o.importPath},i,n),d=ye({op:a,schema:s,transport:"mcp"}).mcp.name,l=En(d,s,t[d]??t[i]);r.push(` ${JSON.stringify(d)}: { group: '${o.id}', fnName: ${JSON.stringify(i)}, schema: ${JSON.stringify(s)}, description: ${JSON.stringify(l)} },`)}r.push("}"),r.push(""),r.push("export const groupFns: Record<string, Record<string, (...args: unknown[]) => unknown>> = {");for(const o of e)r.push(` '${o.id}': ${o.id}_fns as Record<string, (...args: unknown[]) => unknown>,`);r.push("}"),r.push(""),r.push("export const groupCreateClient: Record<string, ((e: Record<string, unknown>) => Promise<unknown>) | undefined> = {");for(const o of e)r.push(` '${o.id}': undefined, // injected at startup if createClient provided`);return r.push("}"),r.join(`
198
+ `)}function cf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.toolDescriptions??{},o=e.operations,i=af(e.packages,r,o),s=t==="stdio"?of():rf(t,n);return{files:[{path:"index.ts",content:i},{path:"server.ts",content:s}]}}async function df(e){const t=await Si(e);if(t.ok){const o=t.chunks.map(i=>({type:"text",text:JSON.stringify(i)}));return o.push({type:"text",text:"[stream complete]"}),{content:o}}const{carrier:n}=t;if(n.phase==="before-first-chunk")return{content:[{type:"text",text:JSON.stringify(n.error.toJSON())}],isError:!0};const r={...n.error.toJSON(),chunksDelivered:n.chunksDelivered};return{content:[{type:"text",text:JSON.stringify(r)}],isError:!0}}const lf=Object.freeze({type:"object",properties:{}});class uf{constructor(){this.plans=new Map,this.dispatchers=new Map,this.schemasByOpId=new Map,this.toolMeta=new Map}bindSchema(t,n){this.schemasByOpId.set(t,n)}bindToolMeta(t,n){this.cachedList=void 0,this.toolMeta.set(t,n)}registerRoute(t,n){this.cachedList=void 0,this.plans.set(t.mcp.name,t),this.dispatchers.set(t.mcp.name,n)}getPlan(t){return this.plans.get(t)}getDispatch(t){return this.dispatchers.get(t)}listTools(){if(this.cachedList)return this.cachedList;const t=[...this.plans.keys()].map(n=>{const r=this.toolMeta.get(n);return Object.freeze({name:n,description:(r==null?void 0:r.description)??n,inputSchema:(r==null?void 0:r.inputSchema)??lf,...r!=null&&r.outputSchema?{outputSchema:r.outputSchema}:{}})});return this.cachedList=Object.freeze(t),this.cachedList}readCall(t,n){const r={};for(const i of n.envelope){const s=t.meta[i.mcpMetaKey];s!==void 0&&(r[i.field]=s)}const o=n.isMount?t.args:t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(Dt(n)){t.output=await df(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:i}=ki(o==null?void 0:o.output),s=bd(i,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...s?{structuredContent:s}:{}}}writeError(t,n,r){throw re(n)&&n.code,n}}function ff(e){if(e&&typeof e=="object"&&e.type==="object")return e;const t=e==null?void 0:e.oneOf;if(Array.isArray(t)&&t.length>0){const n={};let r=null;for(const o of t){if(!o||typeof o!="object")continue;const i=o,s=i.properties;if(s&&typeof s=="object")for(const[c,d]of Object.entries(s))c in n||(n[c]=d);const a=Array.isArray(i.required)?i.required:[];r=r===null?[...a]:r.filter(c=>a.includes(c))}return{...e,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function pf(e,t,n,r,o){var a;const i=[],s={host:n,operations:r};for(const c of e){const d=(a=c.capabilities)==null?void 0:a.mount;if(!d)continue;const l=d.operations(s,t[c.id],o);for(const u of l)u.transports&&!u.transports.includes("mcp")||i.push(u)}return i}function mf(e,t){var f,g;const n=e.options.projection??{},r=e.options.toolDescriptions??{},o=Zn(e.options),i=eo(e.options),s={},a={};for(const p of e.packages){if(!p.fns)throw new Error(`Package "${p.id}" is missing fns`);const m=p.fns,v=Object.entries(p.schemas).map(([S,E])=>({fnName:S,fnSchema:E,op:ds({id:p.id,importPath:p.importPath},S,e.operations)})),h={},y={};for(const{fnName:S,fnSchema:E,op:A}of v)h[A.id]=E,y[A.id]=m[S],s[A.id]=E,a[A.id]=m[S];const w=de(h,o),b={fns:y,createClient:p.createClient,schemas:h};for(const{fnName:S,fnSchema:E,op:A}of v){const j=ye({op:A,schema:E,transport:"mcp",projection:n});t.bindSchema(A.id,E);const{outputSchema:N}=ki(E.output),_=En(j.mcp.name,E,r[j.mcp.name]??r[S]);t.bindToolMeta(j.mcp.name,{description:_,inputSchema:E.input,outputSchema:N}),t.registerRoute(j,R=>xe(j,w,R,b))}}const c=((f=e.packages[0])==null?void 0:f.id)??"ts",d=de(s,o),l={invoke:(p,m,v)=>d(p,{operation:{id:p},ctx:new tt,domainArgs:m.domainArgs,envelope:m.envelope,signal:m.signal},v),invokeOptions:{fns:a,schemas:s,createClient:(g=e.packages[0])==null?void 0:g.createClient}},u=pf(o,i,c,e.operations??[],l);if(u.length>0){const p=de({},o),m={fns:{},schemas:{}};for(const v of u){const h=ye({op:v,transport:"mcp",projection:n}),y=ff(v.input),w=En(h.mcp.name,{input:y},r[h.mcp.name]);t.bindToolMeta(h.mcp.name,{description:w,inputSchema:y}),t.registerRoute(h,b=>xe(h,p,b,m))}}}function gf(e){const t=e.packages[0];return{name:(t==null?void 0:t.id)??"apigen-mcp",version:(t==null?void 0:t.version)??"1.0.0"}}function on(e,t,n){const r=new _a.Server(n,{capabilities:{tools:{}}});return r.setRequestHandler($o.ListToolsRequestSchema,async()=>({tools:e.listTools()})),r.setRequestHandler($o.CallToolRequestSchema,async o=>{const{name:i,arguments:s={}}=o.params,a=e.getPlan(i),c=e.getDispatch(i);if(!a||!c)throw new Error(`Unknown tool: ${i}`);const d=s,l=d._meta??{},u={args:d,meta:l},f=Date.now();try{const g=await e.readCall(u,a),p=await c(g);return await e.writeResult(u,p,a),t.info({tool:i,ms:Date.now()-f},`→ ${i}`),u.output}catch(g){throw re(g)&&g.code!=="internal"?t.error({tool:i,ms:Date.now()-f,code:g.code,message:g.message},`✗ ${i}`):t.error({tool:i,ms:Date.now()-f,err:g},`✗ ${i}`),e.writeError(u,g,a),g}}),r}function Ar(e,t){return async(n,r)=>{try{await t(n,r)}catch(o){e.error({err:o},"mcp http transport handler error"),r.headersSent||r.writeHead(500),r.writableEnded||r.end("Internal Server Error")}}}function jr(e,t){const n=e.signal;if(!n)throw new L("invalid_argument",`apigen mcp transport "${t}" requires RunInput.signal (an AbortSignal) to shut down; none was supplied`);return n}function _r(e,t,n,r,o,i){return new Promise((s,a)=>{const c=d=>{a(new L("internal",`failed to bind mcp ${r} server on ${n}:${t}: ${d.message}`,{cause:d}))};e.once("error",c),e.listen(t,n,()=>{e.removeListener("error",c),e.on("error",l=>o.error({err:l},"mcp http server error")),o.info({host:n,port:t},`listening on http://${n}:${t}`);const d=()=>{o.info("mcp server shutting down"),e.close(()=>s()),e.closeAllConnections()};if(i.aborted){d();return}i.addEventListener("abort",d,{once:!0})})})}function hf(e,t,n,r=process.stdin){return new Promise(o=>{let i=!1;function s(l){i||(i=!0,r.off("end",a),r.off("close",a),n==null||n.removeEventListener("abort",c),t.info(l),o())}function a(){s("stdio transport closed (stdin EOF)")}function c(){s("mcp server shutting down")}const d=e.onclose;if(e.onclose=()=>{d==null||d(),s("stdio transport closed")},r.once("end",a),r.once("close",a),n){if(n.aborted){s("mcp server shutting down");return}n.addEventListener("abort",c,{once:!0})}})}async function yf(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??Xn();o.info(`mcp server starting (${t})`);const i=new uf;mf(e,i);const a=i.listTools().map(u=>u.name);o.info({tools:a},`${a.length} tools available`);for(const u of a){const f=i.getPlan(u),g=(f==null?void 0:f.params)??[],p=g.map(m=>`${m.name}${m.required?"":"?"}: ${m.type}`).join(", ");o.info({tool:u,args:{data:g}},`tool: ${u} args { data: {${p?` ${p} `:""}} }`)}const c=gf(e);if(o.info({identity:c},`mcp handshake identity: ${c.name}@${c.version}`),t==="stdio"){const u=on(i,o,c),f=new Na.StdioServerTransport;return await u.connect(f),o.info("stdio transport ready"),hf(f,o,e.signal)}if(t==="sse"){const u=jr(e,t),f=new Map,g=To.createServer(Ar(o,async(p,m)=>{const v=p.url??"";if(p.method==="GET"&&v==="/sse"){const h=on(i,o,c),y=new Oa.SSEServerTransport("/messages",m);f.set(y.sessionId,y),y.onclose=()=>f.delete(y.sessionId),await h.connect(y)}else if(p.method==="POST"&&v.startsWith("/messages")){const h=new URLSearchParams(v.split("?")[1]??"").get("sessionId"),y=h?f.get(h):void 0;if(!y){m.writeHead(404),m.end("Session not found");return}await y.handlePostMessage(p,m)}else m.writeHead(404),m.end("Not found")}));return _r(g,n,r,t,o,u)}const d=jr(e,t),l=To.createServer(Ar(o,async(u,f)=>{const g=on(i,o,c),p=new Ra.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await g.connect(p),await p.handleRequest(u,f)}));return _r(l,n,r,t,o,d)}const wf={id:"mcp",description:"Expose functions as MCP tools (stdio, SSE, or streaming-HTTP transport)",language:"ts",optionsSchema:{type:"object",properties:{transport:{type:"string",enum:["stdio","sse","streaming-http"]},port:{type:"number"},toolDescriptions:{type:"object",additionalProperties:{type:"string"}}}},generate(e){return cf(e)},run(e){return yf(e)}},ls=["uid","title","kind","status","priority","project","component","createdAt","updatedAt","assignee","author","closedAt","gitContext"],us=["body","citations","notes","auditTrail","blockers","related","_score","_vector"],vf=new Set([...ls,...us]);function bf(e){return vf.has(e)}const ot=["uid","kind","title","status","priority"],ne=1e3,fs=50;async function po(e,t){const n=await e.getNodeByUid(t);if((n==null?void 0:n.kind)!=="issue"||n.tInvalid)throw new Ft(t);if(n.isSuperseded)throw new Mt(t,await Sf(e,n));return n}async function Sf(e,t){const n=new Set([t.id]);let r,o=t;for(;;){const s=(await e.getEdges({dst:o.id,rel:"SUPERSEDES"})).find(c=>!n.has(c.src));if(!s)return r==null?void 0:r.uid;n.add(s.src);const a=(await e.getNodesByIds([s.src]))[0];if(!a||a.tInvalid)return r==null?void 0:r.uid;if(r=a,!a.isSuperseded)return a.uid;o=a}}async function D(e,t,n){if(Ne(n)){const i=await e.getNodeByUid(n);return(i==null?void 0:i.kind)!==t||i.tInvalid?null:{id:i.id,uid:i.uid,name:i.name??n,record:i}}const o=(await e.queryNodes({kind:t,name:n,liveOnly:!0,limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}async function Fe(e,t,n){var i;if(Ne(n)){const s=await D(e,"component",n);return!s||((i=s.record.metadata)==null?void 0:i.projectUid)!==t?null:s}const o=(await e.queryNodes({kind:"component",name:n,liveOnly:!0,metadata:{projectUid:{eq:t}},limit:1}))[0];return o?{id:o.id,uid:o.uid,name:o.name??n,record:o}:null}function De(e,t){return e.getEdges({src:t})}async function ps(e,t){var c,d;const r=(c=(await e.getEdges({dst:t,rel:"owns_component"}))[0])==null?void 0:c.src;if(r===void 0)return{};const[o]=await e.getNodesByIds([r]);if(!o)return{};const s=(d=(await e.getEdges({dst:r,rel:"owns_project"}))[0])==null?void 0:d.src;if(s===void 0)return{component:o};const[a]=await e.getNodesByIds([s]);return{component:o,project:a}}async function Ef(e,t){const n=t.expectedKind==="component"&&t.projectUid!==void 0?await Fe(e,t.projectUid,t.ref):await D(e,t.expectedKind,t.ref);if(!n)return;if(await kf(e,t.rel,t.expectedKind)){const o=await e.getEdges({src:n.id,rel:t.rel});return new Set(o.map(i=>i.dst))}const r=await e.getEdges({dst:n.id,rel:t.rel});return new Set(r.map(o=>o.src))}async function kf(e,t,n){var i;const o=(i=(await e.queryNodes({kind:"edge_kind",name:t,liveOnly:!0,limit:1}))[0])==null?void 0:i.metadata;return typeof(o==null?void 0:o.source_kind)=="string"&&o.source_kind===n}async function Af(e,t){return(await e.queryNodes({kind:t,liveOnly:!0})).map(r=>r.name).filter(r=>typeof r=="string")}function jf(e,t){const n=e.length+1,r=t.length+1,o=Array.from({length:n},()=>new Array(r).fill(0));for(let i=0;i<n;i+=1)o[i][0]=i;for(let i=0;i<r;i+=1)o[0][i]=i;for(let i=1;i<n;i+=1)for(let s=1;s<r;s+=1)o[i][s]=e[i-1]===t[s-1]?o[i-1][s-1]:1+Math.min(o[i-1][s],o[i][s-1],o[i-1][s-1]);return o[e.length][t.length]}function ms(e,t,n=3){const r=Math.max(2,Math.ceil(e.length/2));return t.map(o=>({candidate:o,distance:jf(e.toLowerCase(),o.toLowerCase())})).filter(o=>o.distance<=r).sort((o,i)=>o.distance-i.distance).slice(0,n).map(o=>o.candidate)}async function Ce(e,t){const n=await Af(e,t.catalogKind),r=new Set,o=[];for(const i of t.refs){const s=await D(e,t.catalogKind,i);if(!s){o.push(i);continue}const a=await e.getEdges({dst:s.id,rel:t.rel});for(const c of a)r.add(c.src)}if(o.length>0){const i=n.length>0?n.map(a=>`"${a}"`).join(", "):"(no live rows exist for this catalog yet)",s=o.map(a=>{const c=ms(a,n);return c.length>0?`"${a}" (did you mean ${c.map(d=>`"${d}"`).join(" or ")}?)`:`"${a}"`}).join(", ");throw new je(t.field,`unknown ${t.catalogKind} value(s): ${s} — no live "${t.catalogKind}" catalog row matches (existing ${t.catalogKind} values: ${i})`)}return r}function _f(e){if(e.length===0)return;let[t]=e;for(const n of e.slice(1)){const r=new Set;for(const o of t)n.has(o)&&r.add(o);t=r}return t}function mo(e){if(e){for(const t of e)if(!bf(t))throw new je("fields",`unknown field "${t}" — known fields: ${[...ls,...us].join(", ")}`)}}function Oe(e){var t;return((t=e==null?void 0:e.metadata)==null?void 0:t.terminal)===!0}async function Nf(e,t,n){const r=n.find(l=>l.rel==="has_kind"&&l.src===t),o=n.find(l=>l.rel==="has_status"&&l.src===t),i=n.find(l=>l.rel==="has_priority"&&l.src===t),s=n.find(l=>l.rel==="authored_by"&&l.src===t),a=[r==null?void 0:r.dst,o==null?void 0:o.dst,i==null?void 0:i.dst,s==null?void 0:s.dst].filter(l=>l!==void 0);if(a.length===0)return{};const c=await e.getNodesByIds(a),d=new Map(c.map(l=>[l.id,l]));return{kind:r?d.get(r.dst):void 0,status:o?d.get(o.dst):void 0,priority:i?d.get(i.dst):void 0,author:s?d.get(s.dst):void 0}}async function Of(e,t,n){const r=n.filter(i=>i.rel==="has_citation"&&i.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(i=>i.dst))).map(i=>{var s,a,c,d,l;return{uid:i.uid,file:typeof((s=i.metadata)==null?void 0:s.target)=="string"?i.metadata.target:i.name??"",lines:typeof((a=i.metadata)==null?void 0:a.line)=="string"?i.metadata.line:void 0,context:i.content||void 0,symbol:typeof((c=i.metadata)==null?void 0:c.symbol)=="string"?i.metadata.symbol:void 0,sha:typeof((d=i.metadata)==null?void 0:d.sha)=="string"?i.metadata.sha:"unverified",at:typeof((l=i.metadata)==null?void 0:l.at)=="string"?i.metadata.at:i.tCreated}})}async function Rf(e,t,n){const r=n.filter(i=>i.rel==="has_note"&&i.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(i=>i.dst))).map(i=>{var s,a,c;return{uid:i.uid,author:typeof((s=i.metadata)==null?void 0:s.author)=="string"?i.metadata.author:"",text:typeof((a=i.metadata)==null?void 0:a.text)=="string"?i.metadata.text:i.content,at:typeof((c=i.metadata)==null?void 0:c.at)=="string"?i.metadata.at:i.tCreated}})}async function If(e,t,n){const r=(n??await De(e,t)).filter(s=>s.rel==="audits"&&s.src===t);return r.length===0?[]:(await e.getNodesByIds(r.map(s=>s.dst))).map(s=>{var a,c,d,l,u,f,g;return{uid:s.uid,actor:typeof((a=s.metadata)==null?void 0:a.actor)=="string"?s.metadata.actor:"",action:typeof((c=s.metadata)==null?void 0:c.action)=="string"?s.metadata.action:s.name??"",from:typeof((d=s.metadata)==null?void 0:d.from)=="string"?s.metadata.from:void 0,to:typeof((l=s.metadata)==null?void 0:l.to)=="string"?s.metadata.to:void 0,note:typeof((u=s.metadata)==null?void 0:u.note)=="string"?s.metadata.note:void 0,sha:typeof((f=s.metadata)==null?void 0:f.sha)=="string"?s.metadata.sha:"",at:typeof((g=s.metadata)==null?void 0:g.at)=="string"?s.metadata.at:s.tCreated}}).sort((s,a)=>s.at.localeCompare(a.at))}async function Tf(e,t){const n=await e.getEdges({dst:t,rel:"blocks"});if(n.length===0)return[];const r=n.map(s=>s.src),o=await e.getNodesByIds(r),i=await gs(e,o);return o.filter(s=>!Oe(i.get(s.id))).map(s=>{var a;return{uid:s.uid,title:s.name??"",status:((a=i.get(s.id))==null?void 0:a.name)??""}})}async function $f(e,t,n){const r=(n??await De(e,t)).filter(c=>c.rel==="relates_to"&&c.src===t),o=await e.getEdges({dst:t,rel:"relates_to"}),i=new Set([...r.map(c=>c.dst),...o.map(c=>c.src)]);if(i.size===0)return[];const s=await e.getNodesByIds([...i]),a=await gs(e,s);return s.map(c=>{var d;return{uid:c.uid,title:c.name??"",status:((d=a.get(c.id))==null?void 0:d.name)??""}})}async function gs(e,t){if(t.length===0)return new Map;const n=new Set(t.map(d=>d.id)),r=await e.getEdges({rel:"has_status"}),o=new Map;for(const d of r)n.has(d.src)&&!o.has(d.src)&&o.set(d.src,d.dst);const i=[...new Set(o.values())];if(i.length===0)return new Map;const s=await e.getNodesByIds(i),a=new Map(s.map(d=>[d.id,d])),c=new Map;for(const[d,l]of o){const u=a.get(l);u&&c.set(d,u)}return c}async function hs(e,t,n,r={}){var p,m,v;const o={uid:t.uid},i=h=>n.includes(h),s=i("kind")||i("status")||i("priority")||i("author"),a=i("project")||i("component"),c=i("citations"),d=i("notes"),l=i("auditTrail"),u=i("blockers"),f=i("related"),g=r.outgoingEdges??(s||c||d||l||f?await De(e,t.id):void 0);if(i("title")&&(o.title=t.name??""),i("createdAt")&&(o.createdAt=t.tCreated),i("updatedAt")&&(o.updatedAt=t.tValid),i("assignee")){const h=(p=t.metadata)==null?void 0:p.assignee;typeof h=="string"&&(o.assignee=h)}if(i("gitContext")){const h=(m=t.metadata)==null?void 0:m.gitContext;typeof h=="string"&&h.length>0&&(o.gitContext=h)}if(i("closedAt")){const h=(v=t.metadata)==null?void 0:v.closedAt;typeof h=="string"&&(o.closedAt=h)}if(i("body")&&(o.body=t.content),s&&g){const h=await Nf(e,t.id,g);i("kind")&&h.kind&&(o.kind=h.kind.name??""),i("status")&&h.status&&(o.status=h.status.name??""),i("priority")&&h.priority&&(o.priority=h.priority.name??""),i("author")&&h.author&&(o.author=h.author.name??"")}if(a){const{project:h,component:y}=await ps(e,t.id);i("project")&&h&&(o.project=h.uid),i("component")&&y&&(o.component=y.uid)}return c&&g&&(o.citations=await Of(e,t.id,g)),d&&g&&(o.notes=await Rf(e,t.id,g)),l&&g&&(o.auditTrail=await If(e,t.id,g)),u&&(o.blockers=await Tf(e,t.id)),f&&g&&(o.related=await $f(e,t.id,g)),i("_score")&&r.score!==void 0&&(o._score=r.score),o}async function Qe(e,t,n,r){return Promise.all(t.map(o=>hs(e,o,n,{score:r==null?void 0:r.get(o.uid)})))}const Cf=.0050125;function Pf(e){if(e===void 0)return fs;if(!Number.isInteger(e)||e<=0||e>ne)throw new je("limit",`must be a positive integer ≤ ${ne}, got ${e}`);return e}async function xf(e,t){const n=new Set;for(const r of t.refs){const o=await Ef(e,{rel:t.rel,expectedKind:t.expectedKind,ref:r});if(o)for(const i of o)n.add(i)}return n}async function Lf(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Oe(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function Uf(e,t){if(t.project===void 0&&t.component===void 0)return;let n,r;if(t.project!==void 0){const c=await D(e,"project",t.project);if(!c)return new Set;n=c.uid;const d=await e.getEdges({src:c.id,rel:"owns_project"}),l=new Set;for(const u of d){const f=await e.getEdges({src:u.dst,rel:"owns_component"});for(const g of f)l.add(g.dst)}r=l}if(t.component===void 0)return r;const o=n!==void 0?await Fe(e,n,t.component):await D(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"}),s=new Set(i.map(c=>c.dst));if(!r)return s;const a=new Set;for(const c of s)r.has(c)&&a.add(c);return a}function Df(e){var r,o,i,s;const t={};e.assignee!==void 0&&(t.assignee={eq:e.assignee}),e.claimedBy!==void 0&&(t.claimedBy={eq:e.claimedBy}),e.closedAt!==void 0&&(e.closedAt.since&&e.closedAt.until?t.closedAt={between:[e.closedAt.since,e.closedAt.until]}:e.closedAt.since?t.closedAt={gte:e.closedAt.since}:e.closedAt.until&&(t.closedAt={lte:e.closedAt.until}));const n={};return Object.keys(t).length>0&&(n.metadata=t),(r=e.createdAt)!=null&&r.since&&(n.tCreatedAfter=e.createdAt.since),(o=e.createdAt)!=null&&o.until&&(n.tCreatedBefore=e.createdAt.until),(i=e.updatedAt)!=null&&i.since&&(n.tUpdatedAfter=e.updatedAt.since),(s=e.updatedAt)!=null&&s.until&&(n.tUpdatedBefore=e.updatedAt.until),Object.keys(n).length>0?n:void 0}async function ys(e,t){if(!t)return;const n=[],r=await Uf(e,t);if(r!==void 0&&n.push(r),t.kind!==void 0){const c=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Ce(e,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:c}))}if(t.status!==void 0&&t.status!=="all")if(t.status==="open"||t.status==="closed")n.push(await Lf(e,t.status));else{const c=Array.isArray(t.status)?t.status:[t.status];n.push(await Ce(e,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:c}))}if(t.priority!==void 0){const c=Array.isArray(t.priority)?t.priority:[t.priority];n.push(await Ce(e,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:c}))}t.author!==void 0&&n.push(await xf(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]}));const o=Df(t);if(n.length===0&&!o)return;let i;if(n.length>0){let[c]=n;for(const d of n.slice(1)){const l=new Set;for(const u of c)d.has(u)&&l.add(u);c=l}if(i=c,i.size===0)return new Set}const s={kind:"issue",liveOnly:!0,isSuperseded:!1,...i?{ids:[...i]}:{},...o},a=await e.queryNodes(s);return new Set(a.map(c=>c.id))}const Mf=4;async function Ff(e,t){if(t.length===0)return[];const n=t.map(s=>s.id),r={ids:n,isSuperseded:!1,limit:n.length},o=await e.queryNodes(r),i=new Set(o.map(s=>s.id));return t.filter(s=>i.has(s.id))}async function Bf(e,t){var s;if(!e.search)throw new I("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");if(((s=t.candidateIds)==null?void 0:s.size)===0)return[];const n=t.candidateIds?{ids:[...t.candidateIds]}:{kind:"issue"},r={text:t.text,vec:t.vec,signals:[{kind:"text"},{kind:"vec"}],rescore:[{kind:"temporal",decay:t.decayPerHour??Cf}],filters:n},o=[];let i=t.limit;for(let a=0;a<Mf;a++){const c=await e.search.backend.searchRanked(r,i);if(o.length=0,o.push(...await Ff(e.graph,c)),o.length>=t.limit||c.length<i)break;i*=2}return o.slice(0,t.limit)}async function qf(e,t){var v,h;const{graph:n}=e;if(!e.search)throw new I("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");mo(t.fields);const r=t.fields??ot,o=Pf(t.limit);let i,s;if(((v=t.filter)==null?void 0:v.anchor)!==void 0)s=await po(n,t.filter.anchor),i=`${s.name??""}
199
+ ${s.content}`.trim();else if(((h=t.filter)==null?void 0:h.semantic)!==void 0)i=t.filter.semantic;else throw new I("filter",'`view:"similar"` requires `filter.anchor` or `filter.semantic`');const a=await ys(n,t.filter);if(a&&s&&a.delete(s.id),(a==null?void 0:a.size)===0)return[];const c=await e.search.embedQuery(i),d=s?o+1:o,l=await Bf(e,{text:i,vec:c,candidateIds:a,limit:d}),u=(s?l.filter(y=>y.id!==s.id):l).slice(0,o);if(u.length===0)return[];const f=await n.getNodesByIds(u.map(y=>y.id)),g=new Map(f.map(y=>[y.id,y])),p=u.map(y=>g.get(y.id)).filter(y=>y!==void 0),m=new Map(u.map(y=>{var w;return[(w=g.get(y.id))==null?void 0:w.uid,y.score]}).filter(y=>y[0]!==void 0));return Qe(n,p,r,m)}function Kf(e){return e.replace(/\s+/g," ").replace(/[[\]]/g,"").trim()}function Hf(e){const t=typeof e.gitContext=="string"&&e.gitContext.length>0?e.gitContext:void 0,n=e.citations??[];if(t===void 0&&n.length===0)return[];const r=["",t!==void 0?`Citations: [${Kf(t)}]`:"Citations:"];for(const o of n){const i=o.lines?`${o.file}:${o.lines}`:o.file;r.push(`- [${i} sha:${o.sha}]`)}return r}function Vf(e){const t=[];return e.kind!==void 0&&t.push(`kind: ${e.kind}`),e.status!==void 0&&t.push(`status: ${e.status}`),e.priority!==void 0&&t.push(`priority: ${e.priority}`),e.assignee!==void 0&&t.push(`assignee: ${e.assignee}`),e.project!==void 0&&t.push(`project: ${e.project}`),e.component!==void 0&&t.push(`component: ${e.component}`),t.length>0?t.join(" · "):void 0}function Gf(e){const t=[`## ${e.title??"(untitled)"}`],n=Vf(e);return n!==void 0&&t.push(n),e.body!==void 0&&e.body.length>0&&t.push("",e.body),t.push(...Hf(e)),t.join(`
200
+ `)}function Jf(e){return e.length===0?`_No matching issues._
201
+ `:`${e.map(Gf).join(`
508
202
 
509
203
  `)}
510
- `}function tl(t){var e,n,r,o;return{uid:t.uid,name:t.name??"",path:typeof((e=t.metadata)==null?void 0:e.path)=="string"?t.metadata.path:void 0,repoUrl:typeof((n=t.metadata)==null?void 0:n.repoUrl)=="string"?t.metadata.repoUrl:void 0,monorepo:typeof((r=t.metadata)==null?void 0:r.monorepo)=="boolean"?t.metadata.monorepo:void 0,description:typeof((o=t.metadata)==null?void 0:o.description)=="string"?t.metadata.description:void 0}}function nl(t){var e,n,r;return{uid:t.uid,name:t.name??"",projectUid:typeof((e=t.metadata)==null?void 0:e.projectUid)=="string"?t.metadata.projectUid:"",path:typeof((n=t.metadata)==null?void 0:n.path)=="string"?t.metadata.path:void 0,description:typeof((r=t.metadata)==null?void 0:r.description)=="string"?t.metadata.description:void 0}}function rl(t){var e,n,r;return{uid:t.uid,locType:typeof((e=t.metadata)==null?void 0:e.locType)=="string"?t.metadata.locType:"path",value:typeof((n=t.metadata)==null?void 0:n.value)=="string"?t.metadata.value:t.name??"",componentUid:typeof((r=t.metadata)==null?void 0:r.componentUid)=="string"?t.metadata.componentUid:""}}async function KF(t,e){if((e==null?void 0:e.project)!==void 0){const r=await xe(t,"project",e.project);return r?[tl(r.record)]:[]}return(await t.queryNodes({kind:"project",liveOnly:!0})).map(tl)}async function VF(t,e){if((e==null?void 0:e.project)!==void 0){const r=await xe(t,"project",e.project);return r?(await t.queryNodes({kind:"component",liveOnly:!0,metadata:{projectUid:{eq:r.uid}}})).map(nl):[]}return(await t.queryNodes({kind:"component",liveOnly:!0})).map(nl)}async function GF(t,e){if((e==null?void 0:e.component)!==void 0){const r=e.project!==void 0?await(async()=>{const s=await xe(t,"project",e.project);return s?yo(t,s.uid,e.component):null})():await xe(t,"component",e.component);return r?(await t.queryNodes({kind:"location",liveOnly:!0,metadata:{componentUid:{eq:r.uid}}})).map(rl):[]}return(await t.queryNodes({kind:"location",liveOnly:!0})).map(rl)}async function kc(t,e){var u,l,d,f,g,p,y,w,h;if(e.registry==="project"){const v=await xe(t,"project",e.name);if(!v)throw new Xe("project",e.name);const b=await t.getEdges({src:v.id,rel:"owns_project"}),E=b.length>0?await t.getNodesByIds(b.map(M=>M.dst),{liveOnly:!0}):[],j=(await Promise.all(E.map(M=>t.getEdges({src:M.id,rel:"has_location"})))).flatMap(M=>M.map(C=>C.dst)),T=j.length>0?await t.getNodesByIds(j,{liveOnly:!0}):[];return{...tl(v.record),components:E.map(M=>{var C;return{name:M.name??"",path:typeof((C=M.metadata)==null?void 0:C.path)=="string"?M.metadata.path:void 0}}),locations:T.map(M=>{var C,G;return{locType:typeof((C=M.metadata)==null?void 0:C.locType)=="string"?M.metadata.locType:"path",value:typeof((G=M.metadata)==null?void 0:G.value)=="string"?M.metadata.value:M.name??""}})}}if(e.registry==="component"){const v=(u=e.filter)==null?void 0:u.project,b=v!==void 0?await(async()=>{const C=await xe(t,"project",v);if(!C)throw new Xe("project",v);return yo(t,C.uid,e.name)})():await xe(t,"component",e.name);if(!b)throw new Xe("component",e.name);const E=typeof((l=b.record.metadata)==null?void 0:l.projectUid)=="string"?b.record.metadata.projectUid:void 0,N=E?await t.getNodeByUid(E):null,j=N&&!N.tInvalid?N:null,T=await t.getEdges({src:b.id,rel:"has_location"}),M=T.length>0?await t.getNodesByIds(T.map(C=>C.dst),{liveOnly:!0}):[];return{...nl(b.record),project:{name:(j==null?void 0:j.name)??"",path:typeof((d=j==null?void 0:j.metadata)==null?void 0:d.path)=="string"?j.metadata.path:void 0,repoUrl:typeof((f=j==null?void 0:j.metadata)==null?void 0:f.repoUrl)=="string"?j.metadata.repoUrl:void 0},locations:M.map(C=>{var G,H;return{locType:typeof((G=C.metadata)==null?void 0:G.locType)=="string"?C.metadata.locType:"path",value:typeof((H=C.metadata)==null?void 0:H.value)=="string"?C.metadata.value:C.name??""}})}}if(!_r(e.name))throw new oe("name","a location has no name — pass its uid");const n=await t.getNodeByUid(e.name);if(!n||n.kind!=="location"||n.tInvalid)throw new Xe("location",e.name);const r=typeof((g=n.metadata)==null?void 0:g.componentUid)=="string"?n.metadata.componentUid:void 0,o=r?await t.getNodeByUid(r):null,s=o&&!o.tInvalid?o:null,i=typeof((p=s==null?void 0:s.metadata)==null?void 0:p.projectUid)=="string"?s.metadata.projectUid:void 0,a=i?await t.getNodeByUid(i):null,c=a&&!a.tInvalid?a:null;return{...rl(n),component:{name:(s==null?void 0:s.name)??"",path:typeof((y=s==null?void 0:s.metadata)==null?void 0:y.path)=="string"?s.metadata.path:void 0},project:{name:(c==null?void 0:c.name)??"",path:typeof((w=c==null?void 0:c.metadata)==null?void 0:w.path)=="string"?c.metadata.path:void 0,repoUrl:typeof((h=c==null?void 0:c.metadata)==null?void 0:h.repoUrl)=="string"?c.metadata.repoUrl:void 0}}}function zF(t){try{return new URL(t),!0}catch{return!1}}function WF(t){return zF(t)?"url":t.includes("/")||t.includes(".")||t.startsWith("~")?"path":"tool"}async function HF(t,e){var f,g,p,y,w,h;const n=WF(e);let r=(await t.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:n},value:{eq:e}},limit:1}))[0],o,s=!1;if(!r&&n==="path"){const v=await t.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:"path"}},limit:Mt+1});s=v.length>Mt;const E=(s?v.slice(0,Mt):v).find(N=>{var T;const j=typeof((T=N.metadata)==null?void 0:T.value)=="string"?N.metadata.value:"";return j.endsWith(e)||e.endsWith(j)});E&&(r=E,o="matched by path suffix/prefix fallback, not an exact value match")}if(!r)throw new Xe("location",s?`${e} (path suffix/prefix fallback scanned only the first ${Mt} live path locations; a match may exist beyond this cap)`:e);const i=typeof((f=r.metadata)==null?void 0:f.componentUid)=="string"?r.metadata.componentUid:void 0,a=i?await t.getNodeByUid(i):null,c=a&&!a.tInvalid?a:null;if(!c)throw new Xe("component",i??"(unresolved)");const u=typeof((g=c.metadata)==null?void 0:g.projectUid)=="string"?c.metadata.projectUid:void 0,l=u?await t.getNodeByUid(u):null,d=l&&!l.tInvalid?l:null;return d?{project:{uid:d.uid,name:d.name??"",path:typeof((p=d.metadata)==null?void 0:p.path)=="string"?d.metadata.path:void 0,repoUrl:typeof((y=d.metadata)==null?void 0:y.repoUrl)=="string"?d.metadata.repoUrl:void 0},component:{uid:c.uid,name:c.name??"",path:typeof((w=c.metadata)==null?void 0:w.path)=="string"?c.metadata.path:void 0},location:{uid:r.uid,locType:n,value:typeof((h=r.metadata)==null?void 0:h.value)=="string"?r.metadata.value:e},hint:o}:{project:{uid:"",name:""},component:{uid:c.uid,name:c.name??""},location:{uid:r.uid,locType:n,value:e},hint:"component resolved but its owning project could not be found — data integrity gap, not a query error"}}function Ps(t){if(t===void 0)return X0;if(!Number.isInteger(t)||t<=0||t>Mt)throw new Er("limit",`must be a positive integer ≤ ${Mt}, got ${t}`);return t}function JF(t){var e,n;if(t.after!==void 0){if(t.sort!==void 0)throw new oe("sort","sort is incompatible with keyset pagination (after) — request the first page unsorted, or page by offset if a non-insertion order is required");if(((e=t.filter)==null?void 0:e.grep)!==void 0||((n=t.filter)==null?void 0:n.semantic)!==void 0)throw new oe("after","after (keyset) is incompatible with grep/semantic search — these route through the ranked search primitives, which have no rowid-ordered keyset contract; page a searched result set by sort + offset (rule 6) instead")}}async function QF(t,e){const n=new Set;for(const r of e.refs){const o=await xe(t,e.expectedKind,r);if(!o)continue;const s=await t.getEdges({dst:o.id,rel:e.rel});for(const i of s)n.add(i.src)}return n}async function sb(t,e){const r=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(s=>Nr(s)===(e==="closed")),o=new Set;for(const s of r){const i=await t.getEdges({dst:s.id,rel:"has_status"});for(const a of i)o.add(a.src)}return o}async function xs(t,e){if(!e)return;const n=[];let r;if(e.project!==void 0){const o=await xe(t,"project",e.project);if(!o)return new Set;r=o.uid;const s=await t.getEdges({src:o.id,rel:"owns_project"}),i=new Set;for(const a of s){const c=await t.getEdges({src:a.dst,rel:"owns_component"});for(const u of c)i.add(u.dst)}n.push(i)}if(e.component!==void 0){const o=r!==void 0?await yo(t,r,e.component):await xe(t,"component",e.component);if(!o)return new Set;const s=await t.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(s.map(i=>i.dst)))}if(e.kind!==void 0){const o=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await Qr(t,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:o}))}if(e.status!==void 0&&e.status!=="all")if(e.status==="open"||e.status==="closed")n.push(await sb(t,e.status));else{const o=Array.isArray(e.status)?e.status:[e.status];n.push(await Qr(t,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:o}))}if(e.priority!==void 0){const o=Array.isArray(e.priority)?e.priority:[e.priority];n.push(await Qr(t,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:o}))}if(e.author!==void 0&&n.push(await QF(t,{rel:"authored_by",expectedKind:"agent",refs:[e.author]})),e.plan!==void 0){const o=await xe(t,"issue",e.plan);if(!o)return new Set;const s=await t.getEdges({dst:o.id,rel:"part_of"});n.push(new Set(s.map(i=>i.src)))}if(e.projectPath!==void 0){const o=await t.queryNodes({kind:"component",liveOnly:!0,metadata:{path:{eq:e.projectPath}}});if(o.length===0)return new Set;const s=new Set;for(const i of o){const a=await t.getEdges({src:i.id,rel:"owns_component"});for(const c of a)s.add(c.dst)}n.push(s)}return bF(n)}function YF(t){if(!t)return;const e={};return t.assignee!==void 0&&(e.assignee={eq:t.assignee}),t.claimedBy!==void 0&&(e.claimedBy={eq:t.claimedBy}),t.closedAt!==void 0&&(t.closedAt.since&&t.closedAt.until?e.closedAt={between:[t.closedAt.since,t.closedAt.until]}:t.closedAt.since?e.closedAt={gte:t.closedAt.since}:t.closedAt.until&&(e.closedAt={lte:t.closedAt.until})),Object.keys(e).length>0?e:void 0}function ZF(t){if(t==="created")return"tCreated";if(t==="updated")return"tValid"}async function XF(t,e,n){const r=await Promise.all(e.map(u=>t.getEdges({src:u.id,rel:"has_priority"}))),o=[...new Set(r.flatMap(u=>u.map(l=>l.dst)))],s=o.length>0?await t.getNodesByIds(o):[],i=new Map(s.map(u=>{var l;return[u.id,typeof((l=u.metadata)==null?void 0:l.rank)=="number"?u.metadata.rank:Number.MAX_SAFE_INTEGER]})),a=new Map;e.forEach((u,l)=>{var f;const d=(f=r[l][0])==null?void 0:f.dst;a.set(u.id,d!==void 0?i.get(d)??Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER)});const c=[...e].sort((u,l)=>a.get(u.id)-a.get(l.id));return n==="desc"?c.reverse():c}async function eq(t,e){var b,E,N,j,T,M,C,G,H,Z,ue,fe;const{graph:n}=t;JF(e),sp(e.fields);const r=Ps(e.limit),o=e.fields??Is;if((e.sort==="relevance"||e.sort==="textMatch")&&((b=e.filter)==null?void 0:b.grep)===void 0&&((E=e.filter)==null?void 0:E.semantic)===void 0)throw new Er("sort",`"${e.sort}" requires filter.grep or filter.semantic`);const s=await xs(n,e.filter);if(s&&s.size===0)return{page:{items:[],hasMore:!1},meta:{total:0,returned:0,limit:r}};const i=YF(e.filter),a=(N=e.filter)==null?void 0:N.grep,c=(j=e.filter)==null?void 0:j.semantic,u={kind:"issue",isSuperseded:!1,...s?{ids:[...s]}:{},...i?{metadata:i}:{},...(M=(T=e.filter)==null?void 0:T.createdAt)!=null&&M.since?{tCreatedAfter:e.filter.createdAt.since}:{},...(G=(C=e.filter)==null?void 0:C.createdAt)!=null&&G.until?{tCreatedBefore:e.filter.createdAt.until}:{},...(Z=(H=e.filter)==null?void 0:H.updatedAt)!=null&&Z.since?{tUpdatedAfter:e.filter.updatedAt.since}:{},...(fe=(ue=e.filter)==null?void 0:ue.updatedAt)!=null&&fe.until?{tUpdatedBefore:e.filter.updatedAt.until}:{}};if(a!==void 0||c!==void 0){let he,pe;const Oe=e.offset??0,gt=Oe+r;if(a!==void 0){const U=await n.searchNodes(a,{limit:gt,filter:u});pe=new Set(U.map(q=>q.id))}if(c!==void 0){if(!t.search)throw new oe("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");const q={vec:await t.search.embedQuery(c),signals:[{kind:"vec"}],filters:u},re=await t.search.backend.searchRanked(q,gt);he=pe?re.filter(Qe=>pe.has(Qe.id)):re}else pe&&(he=(await n.searchNodes(a,{limit:gt,filter:u})).map(q=>({id:q.id,score:q.score,fields:{}})));const ut=(he??[]).map(U=>U.id).slice(Oe,Oe+r),A=ut.length>0?await n.getNodesByIds(ut):[],S=new Map(A.map(U=>[U.id,U])),k=ut.map(U=>S.get(U)).filter(U=>U!==void 0),_=new Map((he??[]).map(U=>{var q;return[(q=S.get(U.id))==null?void 0:q.uid,U.score]}).filter(U=>U[0]!==void 0)),m=await vs(n,k,o,_),$=a!==void 0?await n.countNodesFts(a,u):await n.countNodes(u),O=m.length,x=O<Math.min($-Oe,r),R=Oe+O<$;return{page:{items:m,hasMore:R},meta:{total:$,returned:O,limit:r,...e.offset!==void 0?{offset:e.offset}:{},...x?{truncated:!0}:{}}}}const l=ZF(e.sort),d={...u,limit:r+1,...e.after!==void 0?{after:Number(e.after)}:{},...l&&e.after===void 0?{orderBy:l,orderDir:e.direction??"desc"}:{},...e.after===void 0&&e.offset!==void 0?{offset:e.offset}:{}};let f=await n.queryNodes(d);e.sort==="priority"&&e.after===void 0&&(f=await XF(n,f,e.direction??"asc"));const g=f.length>r,p=g?f.slice(0,r):f,y=g?String(p[p.length-1].id):void 0,w=await vs(n,p,o),h=await n.countNodes(u),v=e.after===void 0?e.offset:void 0;return{page:{items:w,nextCursor:y,hasMore:g},meta:{total:h,returned:w.length,limit:r,...v!==void 0?{offset:v}:{}}}}async function tq(t,e){var v;const{graph:n}=t,r=Ps(e.limit),o=e.fields??Is,s=await sb(n,"open"),i=await xs(n,e.filter),a=i?[...s].filter(b=>i.has(b)):[...s];if(a.length===0)return[];const c=await n.getNodesByIds(a),u=await n.getEdges({rel:"blocks"}),l=new Map;for(const b of u){const E=l.get(b.dst);E?E.push(b.src):l.set(b.dst,[b.src])}const d=[...new Set(u.map(b=>b.src))],f=new Set((d.length>0?await n.getNodesByIds(d):[]).map(b=>b.id)),g=await n.getEdges({rel:"has_status"}),p=new Map;for(const b of g)p.has(b.src)||p.set(b.src,b.dst);const y=[...new Set(p.values())],w=new Map((y.length>0?await n.getNodesByIds(y):[]).map(b=>[b.id,b])),h=[];for(const b of c){if(h.length>=r)break;if(typeof((v=b.metadata)==null?void 0:v.claimedBy)=="string")continue;const E=(l.get(b.id)??[]).filter(j=>f.has(j));if(E.length===0){h.push(b);continue}E.every(j=>{const T=p.get(j);return T!==void 0&&Nr(w.get(T))})&&h.push(b)}return vs(n,h,o)}async function nq(t,e){const{graph:n}=t,r=Ps(e.limit),o=e.fields??Is,s=e.staleAfterMin??30,i=new Date(Date.now()-s*6e4).toISOString(),a=await xs(n,e.filter),c={kind:"issue",isSuperseded:!1,...a?{ids:[...a]}:{},metadata:{claimedBy:{exists:!0},claimedAt:{lt:i}},limit:r},u=await n.queryNodes(c);return vs(n,u,o)}const rq=["blocks","relates_to","part_of"];function oq(t){return rq.includes(t)}async function sq(t,e){var d;const{graph:n}=t,r=Ps(e.limit??Mt),o=await xs(n,e.filter),s={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},i=await n.queryNodes(s),a=new Set(i.map(f=>f.id)),c=await iq(n,i),u=i.map(f=>{var g;return{uid:f.uid,title:f.name??"",status:((g=c.get(f.id))==null?void 0:g.name)??""}}),l=[];for(const f of i){const g=await ao(n,f.id);for(const p of g)if(oq(p.rel)&&a.has(p.dst)){const y=(d=(await n.getNodesByIds([p.dst]))[0])==null?void 0:d.uid;y&&l.push({from:f.uid,to:y,rel:p.rel})}}return{nodes:u,edges:l}}async function iq(t,e){const n=await Promise.all(e.map(a=>t.getEdges({src:a.id,rel:"has_status"}))),r=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=r.length>0?await t.getNodesByIds(r):[],s=new Map(o.map(a=>[a.id,a])),i=new Map;return e.forEach((a,c)=>{var l;const u=(l=n[c][0])==null?void 0:l.dst;if(u!==void 0){const d=s.get(u);d&&i.set(a.id,d)}}),i}async function aq(t,e){const{graph:n}=t,r=Ps(e.limit??Mt),o=await xs(n,e.filter),s={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},i=await n.queryNodes(s),a=new Set(i.map(p=>p.id)),c=new Map(i.map(p=>[p.id,p.uid])),u=new Map,l=new Map;for(const p of i)u.set(p.id,0),l.set(p.id,[]);for(const p of i){const y=await n.getEdges({src:p.id,rel:"blocks"});for(const w of y)a.has(w.dst)&&(l.get(p.id).push(w.dst),u.set(w.dst,(u.get(w.dst)??0)+1))}const d=i.filter(p=>(u.get(p.id)??0)===0).map(p=>p.id),f=[],g=new Map(u);for(;d.length>0;){const p=d.shift();f.push(p);for(const y of l.get(p)??[]){const w=(g.get(y)??0)-1;g.set(y,w),w===0&&d.push(y)}}return f.length!==i.length?{ok:!1,cycle:i.filter(y=>!f.includes(y.id)).map(y=>c.get(y.id))}:{ok:!0,order:f.map(p=>c.get(p))}}async function cq(t,e){var i;const{graph:n}=t,r=e.overlapAxis,o=e.overlapUids;if(!r)throw new oe("overlapAxis",'required for view:"overlap"');if(!o||o.length<2)throw new oe("overlapUids","requires at least 2 uids to detect an overlap");const s=new Map;for(const a of o){const c=await n.getNodeByUid(a);if(!c||c.kind!=="issue")continue;if(r==="file"){const g=(await ao(n,c.id)).filter(y=>y.rel==="has_citation"),p=g.length>0?await n.getNodesByIds(g.map(y=>y.dst)):[];for(const y of p){const w=typeof((i=y.metadata)==null?void 0:i.target)=="string"?y.metadata.target:void 0;w&&(s.has(w)||s.set(w,new Set),s.get(w).add(a))}continue}if(r==="author"){const g=(await ao(n,c.id)).find(y=>y.rel==="authored_by");if(!g)continue;const[p]=await n.getNodesByIds([g.dst]);if(!p)continue;s.has(p.uid)||s.set(p.uid,new Set),s.get(p.uid).add(a);continue}const{project:u,component:l}=await eb(n,c.id),d=r==="project"?u:l;d&&(s.has(d.uid)||s.set(d.uid,new Set),s.get(d.uid).add(a))}return[...s.entries()].filter(([,a])=>a.size>=2).map(([a,c])=>({axisValue:a,uids:[...c]}))}async function uq(t,e){return KF(t.graph,e.filter)}async function lq(t,e){return VF(t.graph,e.filter)}async function dq(t,e){return GF(t.graph,e.filter)}function fq(t){var e,n;return t.text!==void 0||((e=t.filter)==null?void 0:e.semantic)!==void 0||((n=t.filter)==null?void 0:n.anchor)!==void 0||t.view==="similar"||t.sort==="relevance"||(t.fields??[]).includes("_vector")}function pq(t,e){var s,i;if(e.text===void 0)return e;if(((s=e.filter)==null?void 0:s.semantic)!==void 0||((i=e.filter)==null?void 0:i.grep)!==void 0)throw new oe("text","text is mutually exclusive with filter.semantic/filter.grep — pick one: the free-text positional (text), or an explicit filter.semantic/filter.grep");if(e.text.trim().length===0)throw new oe("text","must not be blank");const n=t.search!==void 0&&t.spacePopulated===!0,{text:r,...o}=e;return{...o,sort:o.sort??(n?"relevance":"textMatch"),filter:{...o.filter,...n?{semantic:r}:{grep:r}}}}async function hq(t,e){const n=e.view??"list";switch(n){case"list":{const{page:r,meta:o}=await eq(t,e);return{result:{view:"list",...r},meta:o}}case"ready":return{result:{view:"ready",items:await tq(t,e)}};case"graph":return{result:{view:"graph",graph:await sq(t,e)}};case"order":return{result:{view:"order",order:await aq(t,e)}};case"stale":return{result:{view:"stale",items:await nq(t,e)}};case"similar":return{result:{view:"similar",items:await LF(t,e)}};case"overlap":return{result:{view:"overlap",groups:await cq(t,e)}};case"projects":return{result:{view:"projects",items:await uq(t,e)}};case"components":return{result:{view:"components",items:await lq(t,e)}};case"locations":return{result:{view:"locations",items:await dq(t,e)}};default:{const r=n;throw new Er("view",`unknown view "${r}"`)}}}const mq=["list","ready","stale","similar"];async function gq(t,e={}){var a;await((a=t.assertVocabulary)==null?void 0:a.call(t));const n=pq(t,e),r=await hq(t,n);if(n.format!=="markdown")return r;const{result:o}=r,{view:s}=o;if(s!=="list"&&s!=="ready"&&s!=="stale"&&s!=="similar")throw new oe("format",`"markdown" is only supported for view:${mq.map(c=>`"${c}"`).join("/")} — view:"${s}" returns a graph/order/grouping/registry shape with no markdown projection (DATA_MODEL.md §8)`);const i=o.items;return{result:{view:s,format:"markdown",markdown:qF(i)},meta:r.meta}}const ib=["not_found","item_not_found","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],yq=new Set(ib);function ab(t){return typeof t=="string"&&yq.has(t)}const ip={not_found:4,item_not_found:1,invalid_argument:2,validation:2,store_busy:1,rag_not_configured:1,conflict:1,precondition_failed:1,internal:1};function wq(t){return t.ok===!0}function vq(t){return t.ok===!1&&typeof t.error=="object"&&t.error!==null&&ab(t.error.code)}function ap(t,e){const n={ok:!0,data:t};return e!=null&&e.warnings&&e.warnings.length>0&&(n.warnings=e.warnings),e!=null&&e.meta&&(n.meta=e.meta),n}function pr(t,e,n){const r={code:t,message:e},o={...n??{}};return t==="store_busy"&&o.retryable===void 0&&(o.retryable=!0),Object.keys(o).length>0&&(r.details=o),{ok:!1,error:r}}function Co(t){return t.ok?0:ip[t.error.code]}function cb(t){if(t===null||typeof t!="object")return!1;const e=t;if(typeof e.ok!="boolean")return!1;if(e.ok)return!0;const n=e.error;if(n===null||typeof n!="object")return!1;const r=n.code;return typeof r=="string"&&r in ip}class ub extends Error{constructor(e,n="not_configured"){super((n==="empty_vector_space"?`backlog: "${e}" needs an embedded vector space and this store has none — a backend is configured, but zero items have been embedded, so nearest-neighbour ranking has nothing to rank. Run an embedding backfill to populate it. `:`backlog: "${e}" needs a configured embedding backend and none is available. `)+"Keyword and dimensional queries still work."),this.reason=n,this.name="RagNotConfiguredError"}}class $q extends Error{constructor(e,n,r,o){super(`backlog embedding: ${e} produced a ${o}-dimensional vector but space "${n}" is ${r}-dimensional. The dimensional contract is structural and is never silently truncated — the configured provider does not match this vector space.`),this.operation=e,this.modelId=n,this.expected=r,this.actual=o,this.name="PermanentEmbeddingDimensionError"}}let wg=!1;async function bq(t,e){const n=t;return typeof n.hasVectors!="function"?(wg||(wg=!0,console.error(`isVectorSpacePopulated: vector backend exposes no hasVectors() probe — treating the space as EMPTY (modelId="${e}"). Bare \`text:\` queries will not route to the semantic ranker until the backend provides the probe.`)),!1):n.hasVectors(e)}async function vg(t){try{return{mod:await import(t)}}catch(e){return{err:e}}}const ii=t=>t instanceof Error?t.message:String(t),ai=new WeakMap;async function Eq(t,e,n,r=o=>console.error(o)){const o=ai.get(t);if(o)return o;const s=Sq(t,e,n,r);ai.set(t,s);try{const i=await s;return i.search===void 0&&i.embedding===void 0&&ai.delete(t),i}catch(i){throw ai.delete(t),i}}async function Sq(t,e,n,r){var g;if(!(n!=null&&n.enabled))return{};const o=(g=t.capabilities)==null?void 0:g.nativeVectors;if(o!==!0)return r(`backlog: embedding.enabled is set but this store's adapter does not report capabilities.nativeVectors (got ${JSON.stringify(o)}) — backlog's RAG layer requires a Turso-backed store. create()'s duplicate gate and query()'s/view:"similar"'s semantic filters will report as unconfigured.`),{};const[s,i]=await Promise.all([vg("@adhd/sox-vector-store"),vg("@adhd/sox-embedding-provider")]);if("err"in s||"err"in i){const p=[..."err"in s?[`@adhd/sox-vector-store (${ii(s.err)})`]:[],..."err"in i?[`@adhd/sox-embedding-provider (${ii(i.err)})`]:[]];return r(`backlog: embedding.enabled is set but optional embedding packages are unavailable: ${p.join("; ")}. Continuing WITHOUT semantic search.`),{}}let a;try{a=await i.mod.createEmbeddingProvider({type:n.provider,model:n.model})}catch(p){return r(`backlog: embedding.enabled is set but createEmbeddingProvider(${n.provider}:${n.model}) failed: ${ii(p)}. Continuing WITHOUT semantic search.`),{}}const c={modelId:a.metadata.modelId,dim:a.metadata.dimensions};let u;try{u=await s.mod.openTursoVectorStore(t,{dim:c.dim,modelId:c.modelId}),await u.ensureSpace(c)}catch(p){return r(`backlog: embedding.enabled is set but openTursoVectorStore(dim=${c.dim}, modelId=${c.modelId}) failed: ${ii(p)}. Continuing WITHOUT semantic search.`),{}}const l=(p,y)=>{if(p.length!==c.dim)throw new $q(y,c.modelId,c.dim,p.length);return p},d={modelId:c.modelId,async embedDocument(p){return l(await a.embedSingle(p,"document"),"embedDocument")},async upsertVector(p,y){await u.upsert(p,l(y,"upsertVector"),c)},async deleteVector(p){await u.delete(p,c.modelId)}};return{search:{backend:new aE.StoreSearchBackend(u,e),async embedQuery(p){return l(await a.embedSingle(p,"query"),"embedQuery")},async spacePopulated(){return bq(u,c.modelId)}},embedding:d}}async function _q(t,e){sp(e.fields);const n=e.fields??Is,r=await op(t,e.uid);return rb(t,r,n)}const Nq=["project","component","kind","status","priority","assignee","claimedBy","author","grep","semantic","anchor","closedAt","createdAt","updatedAt"];function lb(t,e,n){if(t){for(const r of Nq)if(t[r]!==void 0&&!e.has(r))throw new oe(`filter.${r}`,`not supported by ${n} — this view scopes by ${[...e].join("/")} only`)}}async function db(t,e){const n=new Set;for(const r of e.refs){const o=await xe(t,e.expectedKind,r);if(!o)continue;const s=await t.getEdges({dst:o.id,rel:e.rel});for(const i of s)n.add(i.src)}return n}async function Oq(t,e){const r=(await t.queryNodes({kind:"status",liveOnly:!0})).filter(s=>Nr(s)===(e==="closed")),o=new Set;for(const s of r){const i=await t.getEdges({dst:s.id,rel:"has_status"});for(const a of i)o.add(a.src)}return o}function fb(t){if(t.length===0)return;let[e]=t;for(const n of t.slice(1)){const r=new Set;for(const o of e)n.has(o)&&r.add(o);e=r}return e}async function pb(t,e){if(!e)return;const n=[];let r;if(e.project!==void 0){const o=await xe(t,"project",e.project);if(!o)return new Set;r=o.uid;const s=await t.getEdges({src:o.id,rel:"owns_project"}),i=new Set;for(const a of s){const c=await t.getEdges({src:a.dst,rel:"owns_component"});for(const u of c)i.add(u.dst)}n.push(i)}if(e.component!==void 0){const o=r!==void 0?await yo(t,r,e.component):await xe(t,"component",e.component);if(!o)return new Set;const s=await t.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(s.map(i=>i.dst)))}if(e.kind!==void 0){const o=Array.isArray(e.kind)?e.kind:[e.kind];n.push(await db(t,{rel:"has_kind",expectedKind:"kind",refs:o}))}return fb(n)}const kq=new Set(["project","component","kind","status"]);async function jq(t,e){const n=e??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await Oq(t,n),scope:n};const r=Array.isArray(n)?n:[n];return{candidates:await db(t,{rel:"has_status",expectedKind:"status",refs:r}),scope:n}}async function Aq(t,e={}){var f,g,p;const{graph:n}=t;lb(e.filter,kq,"priorityMatrix");const r=await pb(n,e.filter);if(r&&r.size===0)return{rows:[],unassigned:0,statusScope:((f=e.filter)==null?void 0:f.status)??"open"};const{candidates:o,scope:s}=await jq(n,(g=e.filter)==null?void 0:g.status),i=fb([r,o].filter(y=>y!==void 0));if(i&&i.size===0)return{rows:[],unassigned:0,statusScope:s};const a=new Set((await n.queryNodes({kind:"issue",liveOnly:!0,isSuperseded:!1,...i?{ids:[...i]}:{}})).map(y=>y.id)),c=await n.queryNodes({kind:"priority",liveOnly:!0}),u=new Set,l=[];for(const y of c){const w=await n.getEdges({dst:y.id,rel:"has_priority"});let h=0;for(const b of w)a.has(b.src)&&(h+=1,u.add(b.src));const v=typeof((p=y.metadata)==null?void 0:p.rank)=="number"?y.metadata.rank:void 0;l.push({priority:y.name??"",priorityUid:y.uid,rank:v,count:h})}l.sort((y,w)=>(y.rank??Number.MAX_SAFE_INTEGER)-(w.rank??Number.MAX_SAFE_INTEGER));let d=0;for(const y of a)u.has(y)||(d+=1);return{rows:l,unassigned:d,statusScope:s}}async function Iq(t,e){if(e.length===0)return new Map;const n=await Promise.all(e.map(c=>t.getEdges({src:c.id,rel:"has_status"}))),r=new Map;n.forEach((c,u)=>{const l=c[0];l&&r.set(e[u].id,l.dst)});const o=[...new Set(r.values())];if(o.length===0)return new Map;const s=await t.getNodesByIds(o),i=new Map(s.map(c=>[c.id,c])),a=new Map;for(const[c,u]of r){const l=i.get(u);l&&a.set(c,l)}return a}async function Pq(t,e){const{graph:n}=t,r=await op(n,e.uid),s=(await n.getSubgraph(r.id,{rel:"part_of",direction:"in",depth:-1})).nodes.filter(l=>l.id!==r.id&&l.kind==="issue"&&!l.tInvalid),i=await Iq(n,s);let a=0,c=0;const u=[];for(const l of s)Nr(i.get(l.id))?c+=1:(a+=1,u.push(l.uid));return{uid:r.uid,childrenTotal:s.length,childrenOpen:a,childrenClosed:c,childrenOpenUids:u}}const xq=new Set(["project","component","kind"]);function Rq(t,e,n){var s;const r=t.filter(i=>i.to!==void 0);if(r.length===0)return n;let o;for(const i of r)if(i.at<=e)o=i;else break;return o?o.to:(s=r[0])==null?void 0:s.from}async function Tq(t){var d;const e=await t.getEdges({rel:"has_status"}),n=new Map;for(const f of e)n.has(f.src)||n.set(f.src,f.dst);const r=[...new Set(n.values())],o=new Map((r.length>0?await t.getNodesByIds(r):[]).map(f=>[f.id,f])),s=new Map;for(const[f,g]of n)s.set(f,(d=o.get(g))==null?void 0:d.name);const i=await t.getEdges({rel:"audits"}),a=new Map;for(const f of i){const g=a.get(f.src);g?g.push(f.dst):a.set(f.src,[f.dst])}const c=[...new Set(i.map(f=>f.dst))],u=new Map((c.length>0?await t.getNodesByIds(c):[]).map(f=>[f.id,f])),l=new Map;for(const[f,g]of a){const p=g.map(y=>u.get(y)).filter(y=>y!==void 0).map(y=>{var w,h,v,b,E,N,j;return{uid:y.uid,actor:typeof((w=y.metadata)==null?void 0:w.actor)=="string"?y.metadata.actor:"",action:typeof((h=y.metadata)==null?void 0:h.action)=="string"?y.metadata.action:y.name??"",from:typeof((v=y.metadata)==null?void 0:v.from)=="string"?y.metadata.from:void 0,to:typeof((b=y.metadata)==null?void 0:b.to)=="string"?y.metadata.to:void 0,note:typeof((E=y.metadata)==null?void 0:E.note)=="string"?y.metadata.note:void 0,sha:typeof((N=y.metadata)==null?void 0:N.sha)=="string"?y.metadata.sha:"",at:typeof((j=y.metadata)==null?void 0:j.at)=="string"?y.metadata.at:y.tCreated}}).sort((y,w)=>y.at.localeCompare(w.at));l.set(f,p)}return{currentStatusNameByIssue:s,auditTrailByIssue:l}}async function Cq(t,e){const{graph:n}=t;if(lb(e.filter,xq,"openCurve"),e.at.length===0)throw new oe("at","requires at least one ISO-8601 instant to sample");const r=e.at.map(d=>{const f=new Date(d);if(Number.isNaN(f.getTime()))throw new oe("at",`"${d}" is not a parsable ISO-8601 instant`);return f.toISOString()}),o=await pb(n,e.filter);if(o&&o.size===0)return{points:r.map(d=>({at:d,existed:0,open:0,closed:0}))};const s=await n.queryNodes({kind:"status",liveOnly:!0}),i=new Map(s.map(d=>[d.name??"",Nr(d)])),{currentStatusNameByIssue:a,auditTrailByIssue:c}=await Tq(n),u=new Map;for(const d of await n.getEdges({rel:"SUPERSEDES"})){const f=u.get(d.dst);(f===void 0||d.tCreated<f)&&u.set(d.dst,d.tCreated)}const l=[];for(const d of r){const f={kind:"issue",validAt:d,liveOnly:!1,...o?{ids:[...o]}:{}},g=await n.queryNodes(f);let p=0,y=0;for(const w of g){const h=u.get(w.id);if(h!==void 0&&h<=d)continue;y+=1;const v=a.get(w.id),b=c.get(w.id)??[],E=Rq(b,d,v);(E!==void 0?i.get(E)??!1:!1)||(p+=1)}l.push({at:d,existed:y,open:p,closed:y-p})}return{points:l}}const $g=["abort","force","comment"];function No(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}const bg=512;function hb(t){if(typeof t=="string"&&t.length>bg)throw new oe("gitContext",`must be at most ${bg} characters, got ${t.length}`)}async function Mq(t,e){if(!ha(t))return"unverified";const n=L.resolve(t.metadata.path),r=L.isAbsolute(e)?L.resolve(e):L.resolve(n,e),o=L.relative(n,r);if(o===".."||o.startsWith("../")||o.startsWith("..\\")||L.isAbsolute(o))return"unverified";try{const i=await sl.readFile(r);return kn.createHash("sha256").update(i).digest("hex")}catch(i){const a=i==null?void 0:i.code;if(a==="ENOENT"||a==="ENOTDIR")return"unverified";throw new kl(i)}}function Eg(t,e,n){if(t.length>0&&!t.includes(n))throw new oe(e,`"${n}" is not in this project's allowed ${e} set`)}function Lq(t,e){for(const n of t){const r=e[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new oe(n,"is required by this project's field policy")}}async function Dq(t,e,n,r,o){if(!n.dedupeScanEnabled)return[];const{search:s,graph:i}=t;if(!s||!i)return[];const a={project:e.uid},c=await ob(i,a);if(!c||c.size===0)return[];const u=xl(r,o),d=typeof s.embedQuery=="function"?await s.embedQuery(u):void 0,g={text:u,vec:d,signals:d?[{kind:"text"},{kind:"vec"}]:[{kind:"text"}],filters:{ids:[...c]}},p=5,y=p*4,w=await s.backend.search(g,y);if(w.length===0)return[];const h=await i.getNodesByIds(w.map(E=>E.id)),v=new Map(h.map(E=>[E.id,E])),b=[];for(const E of w){const N=v.get(E.id);if(!N||N.tInvalid!==void 0||N.isSuperseded)continue;const j=E.vecScore;j!==void 0&&c.has(E.id)&&j>=n.dedupeThreshold&&b.push({uid:N.uid,title:N.name??"",score:j})}return b.sort((E,N)=>N.score-E.score),b.slice(0,p)}async function Uq(t,e){No("title",e.title),No("body",e.body),No("project",e.project),No("by",e.by),jt("by",e.by),hb(e.gitContext);const n=e.citations??[];n.forEach((d,f)=>No(`citations[${f}].file`,d.file));const r=typeof e.gitContext=="string"&&e.gitContext.trim().length>0?e.gitContext:void 0,o=e.duplicateAction??"abort";if(e.duplicateAction!==void 0&&!$g.includes(e.duplicateAction))throw new oe("duplicateAction",`must be one of ${$g.map(d=>`'${d}'`).join("|")}, got "${e.duplicateAction}"`);const s=await rs(t.adapter,e.project),i=Zr(s),a=[];for(const d of n){const f=await Mq(s,d.file);if(f==="unverified"&&i.citationRequiresSha){if(ha(s))throw new jl(d.file);console.error(`createIssue: citation_requires_sha waived for path-less project uid="${s.uid}" — cannot verify citation "${d.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}a.push(f)}const c=await Dq(t,s,i,e.title,e.body);if(c.length>0&&o==="abort")return{created:!1,reason:"duplicate-suppressed",duplicateCandidates:c};let u;const l=await lt(t,async d=>{const f=He();if(c.length>0&&o==="comment"){const[ue]=c,fe=await _n(d,ue.uid),he=`${e.title}
204
+ `}function xn(e){var t,n,r,o;return{uid:e.uid,name:e.name??"",path:typeof((t=e.metadata)==null?void 0:t.path)=="string"?e.metadata.path:void 0,repoUrl:typeof((n=e.metadata)==null?void 0:n.repoUrl)=="string"?e.metadata.repoUrl:void 0,monorepo:typeof((r=e.metadata)==null?void 0:r.monorepo)=="boolean"?e.metadata.monorepo:void 0,description:typeof((o=e.metadata)==null?void 0:o.description)=="string"?e.metadata.description:void 0}}function Ln(e){var t,n,r;return{uid:e.uid,name:e.name??"",projectUid:typeof((t=e.metadata)==null?void 0:t.projectUid)=="string"?e.metadata.projectUid:"",path:typeof((n=e.metadata)==null?void 0:n.path)=="string"?e.metadata.path:void 0,description:typeof((r=e.metadata)==null?void 0:r.description)=="string"?e.metadata.description:void 0}}function Un(e){var t,n,r;return{uid:e.uid,locType:typeof((t=e.metadata)==null?void 0:t.locType)=="string"?e.metadata.locType:"path",value:typeof((n=e.metadata)==null?void 0:n.value)=="string"?e.metadata.value:e.name??"",componentUid:typeof((r=e.metadata)==null?void 0:r.componentUid)=="string"?e.metadata.componentUid:""}}async function Wf(e,t){if((t==null?void 0:t.project)!==void 0){const r=await D(e,"project",t.project);return r?[xn(r.record)]:[]}return(await e.queryNodes({kind:"project",liveOnly:!0})).map(xn)}async function zf(e,t){if((t==null?void 0:t.project)!==void 0){const r=await D(e,"project",t.project);return r?(await e.queryNodes({kind:"component",liveOnly:!0,metadata:{projectUid:{eq:r.uid}}})).map(Ln):[]}return(await e.queryNodes({kind:"component",liveOnly:!0})).map(Ln)}async function Yf(e,t){if((t==null?void 0:t.component)!==void 0){const r=t.project!==void 0?await(async()=>{const i=await D(e,"project",t.project);return i?Fe(e,i.uid,t.component):null})():await D(e,"component",t.component);return r?(await e.queryNodes({kind:"location",liveOnly:!0,metadata:{componentUid:{eq:r.uid}}})).map(Un):[]}return(await e.queryNodes({kind:"location",liveOnly:!0})).map(Un)}async function rn(e,t){var d,l,u,f,g,p,m,v,h;if(t.registry==="project"){const y=await D(e,"project",t.name);if(!y)throw new G("project",t.name);const w=await e.getEdges({src:y.id,rel:"owns_project"}),b=w.length>0?await e.getNodesByIds(w.map(j=>j.dst),{liveOnly:!0}):[],E=(await Promise.all(b.map(j=>e.getEdges({src:j.id,rel:"has_location"})))).flatMap(j=>j.map(N=>N.dst)),A=E.length>0?await e.getNodesByIds(E,{liveOnly:!0}):[];return{...xn(y.record),components:b.map(j=>{var N;return{name:j.name??"",path:typeof((N=j.metadata)==null?void 0:N.path)=="string"?j.metadata.path:void 0}}),locations:A.map(j=>{var N,_;return{locType:typeof((N=j.metadata)==null?void 0:N.locType)=="string"?j.metadata.locType:"path",value:typeof((_=j.metadata)==null?void 0:_.value)=="string"?j.metadata.value:j.name??""}})}}if(t.registry==="component"){const y=(d=t.filter)==null?void 0:d.project,w=y!==void 0?await(async()=>{const N=await D(e,"project",y);if(!N)throw new G("project",y);return Fe(e,N.uid,t.name)})():await D(e,"component",t.name);if(!w)throw new G("component",t.name);const b=typeof((l=w.record.metadata)==null?void 0:l.projectUid)=="string"?w.record.metadata.projectUid:void 0,S=b?await e.getNodeByUid(b):null,E=S&&!S.tInvalid?S:null,A=await e.getEdges({src:w.id,rel:"has_location"}),j=A.length>0?await e.getNodesByIds(A.map(N=>N.dst),{liveOnly:!0}):[];return{...Ln(w.record),project:{name:(E==null?void 0:E.name)??"",path:typeof((u=E==null?void 0:E.metadata)==null?void 0:u.path)=="string"?E.metadata.path:void 0,repoUrl:typeof((f=E==null?void 0:E.metadata)==null?void 0:f.repoUrl)=="string"?E.metadata.repoUrl:void 0},locations:j.map(N=>{var _,R;return{locType:typeof((_=N.metadata)==null?void 0:_.locType)=="string"?N.metadata.locType:"path",value:typeof((R=N.metadata)==null?void 0:R.value)=="string"?N.metadata.value:N.name??""}})}}if(!Ne(t.name))throw new I("name","a location has no name — pass its uid");const n=await e.getNodeByUid(t.name);if((n==null?void 0:n.kind)!=="location"||n.tInvalid)throw new G("location",t.name);const r=typeof((g=n.metadata)==null?void 0:g.componentUid)=="string"?n.metadata.componentUid:void 0,o=r?await e.getNodeByUid(r):null,i=o&&!o.tInvalid?o:null,s=typeof((p=i==null?void 0:i.metadata)==null?void 0:p.projectUid)=="string"?i.metadata.projectUid:void 0,a=s?await e.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;return{...Un(n),component:{name:(i==null?void 0:i.name)??"",path:typeof((m=i==null?void 0:i.metadata)==null?void 0:m.path)=="string"?i.metadata.path:void 0},project:{name:(c==null?void 0:c.name)??"",path:typeof((v=c==null?void 0:c.metadata)==null?void 0:v.path)=="string"?c.metadata.path:void 0,repoUrl:typeof((h=c==null?void 0:c.metadata)==null?void 0:h.repoUrl)=="string"?c.metadata.repoUrl:void 0}}}function Xf(e){try{return new URL(e),!0}catch{return!1}}function Qf(e){return Xf(e)?"url":e.includes("/")||e.includes(".")||e.startsWith("~")?"path":"tool"}async function Zf(e,t){var f,g,p,m,v,h;const n=Qf(t);let r=(await e.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:n},value:{eq:t}},limit:1}))[0],o,i=!1;if(!r&&n==="path"){const y=await e.queryNodes({kind:"location",liveOnly:!0,metadata:{locType:{eq:"path"}},limit:ne+1});i=y.length>ne;const b=(i?y.slice(0,ne):y).find(S=>{var A;const E=typeof((A=S.metadata)==null?void 0:A.value)=="string"?S.metadata.value:"";return E.endsWith(t)||t.endsWith(E)});b&&(r=b,o="matched by path suffix/prefix fallback, not an exact value match")}if(!r)throw new G("location",i?`${t} (path suffix/prefix fallback scanned only the first ${ne} live path locations; a match may exist beyond this cap)`:t);const s=typeof((f=r.metadata)==null?void 0:f.componentUid)=="string"?r.metadata.componentUid:void 0,a=s?await e.getNodeByUid(s):null,c=a&&!a.tInvalid?a:null;if(!c)throw new G("component",s??"(unresolved)");const d=typeof((g=c.metadata)==null?void 0:g.projectUid)=="string"?c.metadata.projectUid:void 0,l=d?await e.getNodeByUid(d):null,u=l&&!l.tInvalid?l:null;return u?{project:{uid:u.uid,name:u.name??"",path:typeof((p=u.metadata)==null?void 0:p.path)=="string"?u.metadata.path:void 0,repoUrl:typeof((m=u.metadata)==null?void 0:m.repoUrl)=="string"?u.metadata.repoUrl:void 0},component:{uid:c.uid,name:c.name??"",path:typeof((v=c.metadata)==null?void 0:v.path)=="string"?c.metadata.path:void 0},location:{uid:r.uid,locType:n,value:typeof((h=r.metadata)==null?void 0:h.value)=="string"?r.metadata.value:t},hint:o}:{project:{uid:"",name:""},component:{uid:c.uid,name:c.name??""},location:{uid:r.uid,locType:n,value:t},hint:"component resolved but its owning project could not be found — data integrity gap, not a query error"}}function rt(e){if(e===void 0)return fs;if(!Number.isInteger(e)||e<=0||e>ne)throw new je("limit",`must be a positive integer ≤ ${ne}, got ${e}`);return e}function ep(e){var t,n;if(e.after!==void 0){if(e.sort!==void 0)throw new I("sort","sort is incompatible with keyset pagination (after) — request the first page unsorted, or page by offset if a non-insertion order is required");if(((t=e.filter)==null?void 0:t.grep)!==void 0||((n=e.filter)==null?void 0:n.semantic)!==void 0)throw new I("after","after (keyset) is incompatible with grep/semantic search — these route through the ranked search primitives, which have no rowid-ordered keyset contract; page a searched result set by sort + offset (rule 6) instead")}}async function tp(e,t){const n=new Set;for(const r of t.refs){const o=await D(e,t.expectedKind,r);if(!o)continue;const i=await e.getEdges({dst:o.id,rel:t.rel});for(const s of i)n.add(s.src)}return n}async function ws(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Oe(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}async function it(e,t){if(!t)return;const n=[];let r;if(t.project!==void 0){const o=await D(e,"project",t.project);if(!o)return new Set;r=o.uid;const i=await e.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of i){const c=await e.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(t.component!==void 0){const o=r!==void 0?await Fe(e,r,t.component):await D(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(i.map(s=>s.dst)))}if(t.kind!==void 0){const o=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await Ce(e,{rel:"has_kind",catalogKind:"kind",field:"filter.kind",refs:o}))}if(t.status!==void 0&&t.status!=="all")if(t.status==="open"||t.status==="closed")n.push(await ws(e,t.status));else{const o=Array.isArray(t.status)?t.status:[t.status];n.push(await Ce(e,{rel:"has_status",catalogKind:"status",field:"filter.status",refs:o}))}if(t.priority!==void 0){const o=Array.isArray(t.priority)?t.priority:[t.priority];n.push(await Ce(e,{rel:"has_priority",catalogKind:"priority",field:"filter.priority",refs:o}))}if(t.author!==void 0&&n.push(await tp(e,{rel:"authored_by",expectedKind:"agent",refs:[t.author]})),t.plan!==void 0){const o=await D(e,"issue",t.plan);if(!o)return new Set;const i=await e.getEdges({dst:o.id,rel:"part_of"});n.push(new Set(i.map(s=>s.src)))}if(t.projectPath!==void 0){const o=await e.queryNodes({kind:"component",liveOnly:!0,metadata:{path:{eq:t.projectPath}}});if(o.length===0)return new Set;const i=new Set;for(const s of o){const a=await e.getEdges({src:s.id,rel:"owns_component"});for(const c of a)i.add(c.dst)}n.push(i)}return _f(n)}function np(e){if(!e)return;const t={};return e.assignee!==void 0&&(t.assignee={eq:e.assignee}),e.claimedBy!==void 0&&(t.claimedBy={eq:e.claimedBy}),e.closedAt!==void 0&&(e.closedAt.since&&e.closedAt.until?t.closedAt={between:[e.closedAt.since,e.closedAt.until]}:e.closedAt.since?t.closedAt={gte:e.closedAt.since}:e.closedAt.until&&(t.closedAt={lte:e.closedAt.until})),Object.keys(t).length>0?t:void 0}function op(e){if(e==="created")return"tCreated";if(e==="updated")return"tValid"}async function rp(e,t,n){const r=await Promise.all(t.map(d=>e.getEdges({src:d.id,rel:"has_priority"}))),o=[...new Set(r.flatMap(d=>d.map(l=>l.dst)))],i=o.length>0?await e.getNodesByIds(o):[],s=new Map(i.map(d=>{var l;return[d.id,typeof((l=d.metadata)==null?void 0:l.rank)=="number"?d.metadata.rank:Number.MAX_SAFE_INTEGER]})),a=new Map;t.forEach((d,l)=>{var f;const u=(f=r[l][0])==null?void 0:f.dst;a.set(d.id,u!==void 0?s.get(u)??Number.MAX_SAFE_INTEGER:Number.MAX_SAFE_INTEGER)});const c=[...t].sort((d,l)=>a.get(d.id)-a.get(l.id));return n==="desc"?c.reverse():c}async function ip(e,t){var w,b,S,E,A,j,N,_,R,T,C,q;const{graph:n}=e;ep(t),mo(t.fields);const r=rt(t.limit),o=t.fields??ot;if((t.sort==="relevance"||t.sort==="textMatch")&&((w=t.filter)==null?void 0:w.grep)===void 0&&((b=t.filter)==null?void 0:b.semantic)===void 0)throw new je("sort",`"${t.sort}" requires filter.grep or filter.semantic`);const i=await it(n,t.filter);if((i==null?void 0:i.size)===0)return{page:{items:[],hasMore:!1},meta:{total:0,returned:0,limit:r}};const s=np(t.filter),a=(S=t.filter)==null?void 0:S.grep,c=(E=t.filter)==null?void 0:E.semantic,d={kind:"issue",isSuperseded:!1,...i?{ids:[...i]}:{},...s?{metadata:s}:{},...(j=(A=t.filter)==null?void 0:A.createdAt)!=null&&j.since?{tCreatedAfter:t.filter.createdAt.since}:{},...(_=(N=t.filter)==null?void 0:N.createdAt)!=null&&_.until?{tCreatedBefore:t.filter.createdAt.until}:{},...(T=(R=t.filter)==null?void 0:R.updatedAt)!=null&&T.since?{tUpdatedAfter:t.filter.updatedAt.since}:{},...(q=(C=t.filter)==null?void 0:C.updatedAt)!=null&&q.until?{tUpdatedBefore:t.filter.updatedAt.until}:{}};if(a!==void 0||c!==void 0){let x,P;const Y=t.offset??0,Jt=Y+r;if(a!==void 0){const K=await n.searchNodes(a,{limit:Jt,filter:d});P=new Set(K.map(ie=>ie.id))}if(c!==void 0){if(!e.search)throw new I("semantic","semantic search is not configured for this store (no embedding/vector backend injected)");const ie={vec:await e.search.embedQuery(c),signals:[{kind:"vec"}],filters:d},Io=await e.search.backend.searchRanked(ie,Jt);x=P?Io.filter(Ea=>P.has(Ea.id)):Io}else P&&(x=(await n.searchNodes(a,{limit:Jt,filter:d})).map(ie=>({id:ie.id,score:ie.score,fields:{}})));const Wt=(x??[]).map(K=>K.id).slice(Y,Y+r),ya=Wt.length>0?await n.getNodesByIds(Wt):[],Oo=new Map(ya.map(K=>[K.id,K])),wa=Wt.map(K=>Oo.get(K)).filter(K=>K!==void 0),va=new Map((x??[]).map(K=>{var ie;return[(ie=Oo.get(K.id))==null?void 0:ie.uid,K.score]}).filter(K=>K[0]!==void 0)),Ro=await Qe(n,wa,o,va),zt=a!==void 0?await n.countNodesFts(a,d):await n.countNodes(d),Yt=Ro.length,ba=Yt<Math.min(zt-Y,r),Sa=Y+Yt<zt;return{page:{items:Ro,hasMore:Sa},meta:{total:zt,returned:Yt,limit:r,...t.offset!==void 0?{offset:t.offset}:{},...ba?{truncated:!0}:{}}}}const l=op(t.sort),u={...d,limit:r+1,...t.after!==void 0?{after:Number(t.after)}:{},...l&&t.after===void 0?{orderBy:l,orderDir:t.direction??"desc"}:{},...t.after===void 0&&t.offset!==void 0?{offset:t.offset}:{}};let f=await n.queryNodes(u);t.sort==="priority"&&t.after===void 0&&(f=await rp(n,f,t.direction??"asc"));const g=f.length>r,p=g?f.slice(0,r):f,m=g?String(p[p.length-1].id):void 0,v=await Qe(n,p,o),h=await n.countNodes(d),y=t.after===void 0?t.offset:void 0;return{page:{items:v,nextCursor:m,hasMore:g},meta:{total:h,returned:v.length,limit:r,...y!==void 0?{offset:y}:{}}}}async function sp(e,t){var y;const{graph:n}=e,r=rt(t.limit),o=t.fields??ot,i=await ws(n,"open"),s=await it(n,t.filter),a=s?[...i].filter(w=>s.has(w)):[...i];if(a.length===0)return[];const c=await n.getNodesByIds(a),d=await n.getEdges({rel:"blocks"}),l=new Map;for(const w of d){const b=l.get(w.dst);b?b.push(w.src):l.set(w.dst,[w.src])}const u=[...new Set(d.map(w=>w.src))],f=new Set((u.length>0?await n.getNodesByIds(u):[]).map(w=>w.id)),g=await n.getEdges({rel:"has_status"}),p=new Map;for(const w of g)p.has(w.src)||p.set(w.src,w.dst);const m=[...new Set(p.values())],v=new Map((m.length>0?await n.getNodesByIds(m):[]).map(w=>[w.id,w])),h=[];for(const w of c){if(h.length>=r)break;if(typeof((y=w.metadata)==null?void 0:y.claimedBy)=="string")continue;const b=(l.get(w.id)??[]).filter(E=>f.has(E));if(b.length===0){h.push(w);continue}b.every(E=>{const A=p.get(E);return A!==void 0&&Oe(v.get(A))})&&h.push(w)}return Qe(n,h,o)}async function ap(e,t){const{graph:n}=e,r=rt(t.limit),o=t.fields??ot,i=t.staleAfterMin??30,s=new Date(Date.now()-i*6e4).toISOString(),a=await it(n,t.filter),c={kind:"issue",isSuperseded:!1,...a?{ids:[...a]}:{},metadata:{claimedBy:{exists:!0},claimedAt:{lt:s}},limit:r},d=await n.queryNodes(c);return Qe(n,d,o)}const cp=["blocks","relates_to","part_of"];function dp(e){return cp.includes(e)}async function lp(e,t){var u;const{graph:n}=e,r=rt(t.limit??ne),o=await it(n,t.filter),i={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},s=await n.queryNodes(i),a=new Set(s.map(f=>f.id)),c=await up(n,s),d=s.map(f=>{var g;return{uid:f.uid,title:f.name??"",status:((g=c.get(f.id))==null?void 0:g.name)??""}}),l=[];for(const f of s){const g=await De(n,f.id);for(const p of g)if(dp(p.rel)&&a.has(p.dst)){const m=(u=(await n.getNodesByIds([p.dst]))[0])==null?void 0:u.uid;m&&l.push({from:f.uid,to:m,rel:p.rel})}}return{nodes:d,edges:l}}async function up(e,t){const n=await Promise.all(t.map(a=>e.getEdges({src:a.id,rel:"has_status"}))),r=[...new Set(n.flatMap(a=>a.map(c=>c.dst)))],o=r.length>0?await e.getNodesByIds(r):[],i=new Map(o.map(a=>[a.id,a])),s=new Map;return t.forEach((a,c)=>{var l;const d=(l=n[c][0])==null?void 0:l.dst;if(d!==void 0){const u=i.get(d);u&&s.set(a.id,u)}}),s}async function fp(e,t){const{graph:n}=e,r=rt(t.limit??ne),o=await it(n,t.filter),i={kind:"issue",isSuperseded:!1,...o?{ids:[...o]}:{},limit:r},s=await n.queryNodes(i),a=new Set(s.map(p=>p.id)),c=new Map(s.map(p=>[p.id,p.uid])),d=new Map,l=new Map;for(const p of s)d.set(p.id,0),l.set(p.id,[]);for(const p of s){const m=await n.getEdges({src:p.id,rel:"blocks"});for(const v of m)a.has(v.dst)&&(l.get(p.id).push(v.dst),d.set(v.dst,(d.get(v.dst)??0)+1))}const u=s.filter(p=>(d.get(p.id)??0)===0).map(p=>p.id),f=[],g=new Map(d);for(;u.length>0;){const p=u.shift();f.push(p);for(const m of l.get(p)??[]){const v=(g.get(m)??0)-1;g.set(m,v),v===0&&u.push(m)}}return f.length!==s.length?{ok:!1,cycle:s.filter(m=>!f.includes(m.id)).map(m=>c.get(m.id))}:{ok:!0,order:f.map(p=>c.get(p))}}async function pp(e,t){var s;const{graph:n}=e,r=t.overlapAxis,o=t.overlapUids;if(!r)throw new I("overlapAxis",'required for view:"overlap"');if(!o||o.length<2)throw new I("overlapUids","requires at least 2 uids to detect an overlap");const i=new Map;for(const a of o){const c=await n.getNodeByUid(a);if((c==null?void 0:c.kind)!=="issue")continue;if(r==="file"){const g=(await De(n,c.id)).filter(m=>m.rel==="has_citation"),p=g.length>0?await n.getNodesByIds(g.map(m=>m.dst)):[];for(const m of p){const v=typeof((s=m.metadata)==null?void 0:s.target)=="string"?m.metadata.target:void 0;v&&(i.has(v)||i.set(v,new Set),i.get(v).add(a))}continue}if(r==="author"){const g=(await De(n,c.id)).find(m=>m.rel==="authored_by");if(!g)continue;const[p]=await n.getNodesByIds([g.dst]);if(!p)continue;i.has(p.uid)||i.set(p.uid,new Set),i.get(p.uid).add(a);continue}const{project:d,component:l}=await ps(n,c.id),u=r==="project"?d:l;u&&(i.has(u.uid)||i.set(u.uid,new Set),i.get(u.uid).add(a))}return[...i.entries()].filter(([,a])=>a.size>=2).map(([a,c])=>({axisValue:a,uids:[...c]}))}async function mp(e,t){return Wf(e.graph,t.filter)}async function gp(e,t){return zf(e.graph,t.filter)}async function hp(e,t){return Yf(e.graph,t.filter)}function yp(e){var t,n;return e.text!==void 0||((t=e.filter)==null?void 0:t.semantic)!==void 0||((n=e.filter)==null?void 0:n.anchor)!==void 0||e.view==="similar"||e.sort==="relevance"||(e.fields??[]).includes("_vector")}function wp(e,t){var i,s;if(t.text===void 0)return t;if(((i=t.filter)==null?void 0:i.semantic)!==void 0||((s=t.filter)==null?void 0:s.grep)!==void 0)throw new I("text","text is mutually exclusive with filter.semantic/filter.grep — pick one: the free-text positional (text), or an explicit filter.semantic/filter.grep");if(t.text.trim().length===0)throw new I("text","must not be blank");const n=e.search!==void 0&&e.spacePopulated===!0,{text:r,...o}=t;return{...o,sort:o.sort??(n?"relevance":"textMatch"),filter:{...o.filter,...n?{semantic:r}:{grep:r}}}}async function vp(e,t){const n=t.view??"list";switch(n){case"list":{const{page:r,meta:o}=await ip(e,t);return{result:{view:"list",...r},meta:o}}case"ready":return{result:{view:"ready",items:await sp(e,t)}};case"graph":return{result:{view:"graph",graph:await lp(e,t)}};case"order":return{result:{view:"order",order:await fp(e,t)}};case"stale":return{result:{view:"stale",items:await ap(e,t)}};case"similar":return{result:{view:"similar",items:await qf(e,t)}};case"overlap":return{result:{view:"overlap",groups:await pp(e,t)}};case"projects":return{result:{view:"projects",items:await mp(e,t)}};case"components":return{result:{view:"components",items:await gp(e,t)}};case"locations":return{result:{view:"locations",items:await hp(e,t)}};default:{const r=n;throw new je("view",`unknown view "${r}"`)}}}const bp=["list","ready","stale","similar"];async function Sp(e,t={}){var a;await((a=e.assertVocabulary)==null?void 0:a.call(e));const n=wp(e,t),r=await vp(e,n);if(n.format!=="markdown")return r;const{result:o}=r,{view:i}=o;if(i!=="list"&&i!=="ready"&&i!=="stale"&&i!=="similar")throw new I("format",`"markdown" is only supported for view:${bp.map(c=>`"${c}"`).join("/")} — view:"${i}" returns a graph/order/grouping/registry shape with no markdown projection (DATA_MODEL.md §8)`);const s=o.items;return{result:{view:i,format:"markdown",markdown:Jf(s)},meta:r.meta}}const vs=["not_found","item_not_found","invalid_argument","validation","store_busy","rag_not_configured","conflict","precondition_failed","internal"],Ep=new Set(vs);function bs(e){return typeof e=="string"&&Ep.has(e)}const go={not_found:4,item_not_found:1,invalid_argument:2,validation:2,store_busy:1,rag_not_configured:1,conflict:1,precondition_failed:1,internal:1};function kp(e){return e.ok===!0}function Ap(e){return e.ok===!1&&typeof e.error=="object"&&e.error!==null&&bs(e.error.code)}function ho(e,t){const n={ok:!0,data:e};return t!=null&&t.warnings&&t.warnings.length>0&&(n.warnings=t.warnings),t!=null&&t.meta&&(n.meta=t.meta),n}function le(e,t,n){const r={code:e,message:t},o={...n??{}};return e==="store_busy"&&o.retryable===void 0&&(o.retryable=!0),Object.keys(o).length>0&&(r.details=o),{ok:!1,error:r}}function ke(e){return e.ok?0:go[e.error.code]}function Ss(e){if(e===null||typeof e!="object")return!1;const t=e;if(typeof t.ok!="boolean")return!1;if(t.ok)return!0;const n=t.error;if(n===null||typeof n!="object")return!1;const r=n.code;return typeof r=="string"&&r in go}class Es extends Error{constructor(t,n="not_configured"){super((n==="empty_vector_space"?`backlog: "${t}" needs an embedded vector space and this store has none — a backend is configured, but zero items have been embedded, so nearest-neighbour ranking has nothing to rank. Run an embedding backfill to populate it. `:`backlog: "${t}" needs a configured embedding backend and none is available. `)+"Keyword and dimensional queries still work."),this.reason=n,this.name="RagNotConfiguredError"}}class jp extends Error{constructor(t,n,r,o){super(`backlog embedding: ${t} produced a ${o}-dimensional vector but space "${n}" is ${r}-dimensional. The dimensional contract is structural and is never silently truncated — the configured provider does not match this vector space.`),this.operation=t,this.modelId=n,this.expected=r,this.actual=o,this.name="PermanentEmbeddingDimensionError"}}let Nr=!1,Or=!1,Rr=!1;const It=new WeakMap;async function _p(e,t){const n=e;return typeof n.hasVectors!="function"?(Nr||(Nr=!0,console.error(`isVectorSpacePopulated: vector backend exposes no hasVectors() probe — treating the space as EMPTY (modelId="${t}"). Bare \`text:\` queries will not route to the semantic ranker until the backend provides the probe.`)),!1):n.hasVectors(t)}async function Ir(e){try{return{mod:await import(e)}}catch(t){return{err:t}}}const ht=e=>e instanceof Error?e.message:String(e),He=new WeakMap;async function Np(e,t,n,r=i=>console.error(i),o){const i=He.get(e);if(i)return i;const s=Ip(e,t,n,r,o);He.set(e,s);try{const a=await s;return a.search===void 0&&a.embedding===void 0?He.delete(e):It.set(e,{embedding:a.embedding!==void 0,search:a.search!==void 0}),a}catch(a){throw He.delete(e),It.delete(e),a}}function Op(e){const t=It.get(e);if(t)return{present:!0,embedding:t.embedding,search:t.search}}function Rp(e){He.delete(e),It.delete(e)}function Tr(e){return e&&e.length>0?e.join(", "):"(no config layer files found on disk)"}async function Ip(e,t,n,r,o){var p;if(!(n!=null&&n.enabled))return(o==null?void 0:o.configuredEnabled)===!0?Rr||(Rr=!0,r(`backlog: embedding.enabled is TRUE in the on-disk config but this process is still running with it DISABLED (startup configHash ${o.startupHash??"unknown"}, on-disk configHash ${o.configuredHash??"unknown"}). The next semantic verb adopts it without a restart; if it does not, restart the process. Resolved config layers: ${Tr(o.configPaths)}.`)):Or||(Or=!0,r(`backlog: embedding is DISABLED (the default) — semantic/RAG features are OFF for this process. Set embedding.enabled: true in a resolved config layer to opt in (adopted without a restart). Resolved config layers: ${Tr(o==null?void 0:o.configPaths)}.`)),{};const i=(p=e.capabilities)==null?void 0:p.nativeVectors;if(i!==!0)return r(`backlog: embedding.enabled is set but this store's adapter does not report capabilities.nativeVectors (got ${JSON.stringify(i)}) — backlog's RAG layer requires a Turso-backed store. create()'s duplicate gate and query()'s/view:"similar"'s semantic filters will report as unconfigured.`),{};const[s,a]=await Promise.all([Ir("@adhd/sox-vector-store"),Ir("@adhd/sox-embedding-provider")]);if("err"in s||"err"in a){const m=[..."err"in s?[`@adhd/sox-vector-store (${ht(s.err)})`]:[],..."err"in a?[`@adhd/sox-embedding-provider (${ht(a.err)})`]:[]];return r(`backlog: embedding.enabled is set but optional embedding packages are unavailable: ${m.join("; ")}. Continuing WITHOUT semantic search.`),{}}let c;try{c=await a.mod.createEmbeddingProvider({type:n.provider,model:n.model})}catch(m){return r(`backlog: embedding.enabled is set but createEmbeddingProvider(${n.provider}:${n.model}) failed: ${ht(m)}. Continuing WITHOUT semantic search.`),{}}const d={modelId:c.metadata.modelId,dim:c.metadata.dimensions};let l;try{l=await s.mod.openTursoVectorStore(e,{dim:d.dim,modelId:d.modelId}),await l.ensureSpace(d)}catch(m){return r(`backlog: embedding.enabled is set but openTursoVectorStore(dim=${d.dim}, modelId=${d.modelId}) failed: ${ht(m)}. Continuing WITHOUT semantic search.`),{}}const u=(m,v)=>{if(m.length!==d.dim)throw new jp(v,d.modelId,d.dim,m.length);return m},f={modelId:d.modelId,async embedDocument(m){return u(await c.embedSingle(m,"document"),"embedDocument")},async upsertVector(m,v){await l.upsert(m,u(v,"upsertVector"),d)},async deleteVector(m){await l.delete(m,d.modelId)}};return{search:{backend:new Ia.StoreSearchBackend(l,t),async embedQuery(m){return u(await c.embedSingle(m,"query"),"embedQuery")},async spacePopulated(){return _p(l,d.modelId)}},embedding:f}}async function Tp(e,t){mo(t.fields);const n=t.fields??ot,r=await po(e,t.uid);return hs(e,r,n)}const $p=["project","component","kind","status","priority","assignee","claimedBy","author","grep","semantic","anchor","closedAt","createdAt","updatedAt"];function ks(e,t,n){if(e){for(const r of $p)if(e[r]!==void 0&&!t.has(r))throw new I(`filter.${r}`,`not supported by ${n} — this view scopes by ${[...t].join("/")} only`)}}async function As(e,t){const n=new Set;for(const r of t.refs){const o=await D(e,t.expectedKind,r);if(!o)continue;const i=await e.getEdges({dst:o.id,rel:t.rel});for(const s of i)n.add(s.src)}return n}async function Cp(e,t){const r=(await e.queryNodes({kind:"status",liveOnly:!0})).filter(i=>Oe(i)===(t==="closed")),o=new Set;for(const i of r){const s=await e.getEdges({dst:i.id,rel:"has_status"});for(const a of s)o.add(a.src)}return o}function js(e){if(e.length===0)return;let[t]=e;for(const n of e.slice(1)){const r=new Set;for(const o of t)n.has(o)&&r.add(o);t=r}return t}async function _s(e,t){if(!t)return;const n=[];let r;if(t.project!==void 0){const o=await D(e,"project",t.project);if(!o)return new Set;r=o.uid;const i=await e.getEdges({src:o.id,rel:"owns_project"}),s=new Set;for(const a of i){const c=await e.getEdges({src:a.dst,rel:"owns_component"});for(const d of c)s.add(d.dst)}n.push(s)}if(t.component!==void 0){const o=r!==void 0?await Fe(e,r,t.component):await D(e,"component",t.component);if(!o)return new Set;const i=await e.getEdges({src:o.id,rel:"owns_component"});n.push(new Set(i.map(s=>s.dst)))}if(t.kind!==void 0){const o=Array.isArray(t.kind)?t.kind:[t.kind];n.push(await As(e,{rel:"has_kind",expectedKind:"kind",refs:o}))}return js(n)}const Pp=new Set(["project","component","kind","status"]);async function xp(e,t){const n=t??"open";if(n==="all")return{candidates:void 0,scope:n};if(n==="open"||n==="closed")return{candidates:await Cp(e,n),scope:n};const r=Array.isArray(n)?n:[n];return{candidates:await As(e,{rel:"has_status",expectedKind:"status",refs:r}),scope:n}}async function Lp(e,t={}){var f,g,p;const{graph:n}=e;ks(t.filter,Pp,"priorityMatrix");const r=await _s(n,t.filter);if((r==null?void 0:r.size)===0)return{rows:[],unassigned:0,statusScope:((f=t.filter)==null?void 0:f.status)??"open"};const{candidates:o,scope:i}=await xp(n,(g=t.filter)==null?void 0:g.status),s=js([r,o].filter(m=>m!==void 0));if((s==null?void 0:s.size)===0)return{rows:[],unassigned:0,statusScope:i};const a=new Set((await n.queryNodes({kind:"issue",liveOnly:!0,isSuperseded:!1,...s?{ids:[...s]}:{}})).map(m=>m.id)),c=await n.queryNodes({kind:"priority",liveOnly:!0}),d=new Set,l=[];for(const m of c){const v=await n.getEdges({dst:m.id,rel:"has_priority"});let h=0;for(const w of v)a.has(w.src)&&(h+=1,d.add(w.src));const y=typeof((p=m.metadata)==null?void 0:p.rank)=="number"?m.metadata.rank:void 0;l.push({priority:m.name??"",priorityUid:m.uid,rank:y,count:h})}l.sort((m,v)=>(m.rank??Number.MAX_SAFE_INTEGER)-(v.rank??Number.MAX_SAFE_INTEGER));let u=0;for(const m of a)d.has(m)||(u+=1);return{rows:l,unassigned:u,statusScope:i}}async function Up(e,t){if(t.length===0)return new Map;const n=await Promise.all(t.map(c=>e.getEdges({src:c.id,rel:"has_status"}))),r=new Map;n.forEach((c,d)=>{const l=c[0];l&&r.set(t[d].id,l.dst)});const o=[...new Set(r.values())];if(o.length===0)return new Map;const i=await e.getNodesByIds(o),s=new Map(i.map(c=>[c.id,c])),a=new Map;for(const[c,d]of r){const l=s.get(d);l&&a.set(c,l)}return a}async function Dp(e,t){const{graph:n}=e,r=await po(n,t.uid),i=(await n.getSubgraph(r.id,{rel:"part_of",direction:"in",depth:-1})).nodes.filter(l=>l.id!==r.id&&l.kind==="issue"&&!l.tInvalid),s=await Up(n,i);let a=0,c=0;const d=[];for(const l of i)Oe(s.get(l.id))?c+=1:(a+=1,d.push(l.uid));return{uid:r.uid,childrenTotal:i.length,childrenOpen:a,childrenClosed:c,childrenOpenUids:d}}const Mp=new Set(["project","component","kind"]);function Fp(e,t,n){var i;const r=e.filter(s=>s.to!==void 0);if(r.length===0)return n;let o;for(const s of r)if(s.at<=t)o=s;else break;return o?o.to:(i=r[0])==null?void 0:i.from}async function Bp(e){var u;const t=await e.getEdges({rel:"has_status"}),n=new Map;for(const f of t)n.has(f.src)||n.set(f.src,f.dst);const r=[...new Set(n.values())],o=new Map((r.length>0?await e.getNodesByIds(r):[]).map(f=>[f.id,f])),i=new Map;for(const[f,g]of n)i.set(f,(u=o.get(g))==null?void 0:u.name);const s=await e.getEdges({rel:"audits"}),a=new Map;for(const f of s){const g=a.get(f.src);g?g.push(f.dst):a.set(f.src,[f.dst])}const c=[...new Set(s.map(f=>f.dst))],d=new Map((c.length>0?await e.getNodesByIds(c):[]).map(f=>[f.id,f])),l=new Map;for(const[f,g]of a){const p=g.map(m=>d.get(m)).filter(m=>m!==void 0).map(m=>{var v,h,y,w,b,S,E;return{uid:m.uid,actor:typeof((v=m.metadata)==null?void 0:v.actor)=="string"?m.metadata.actor:"",action:typeof((h=m.metadata)==null?void 0:h.action)=="string"?m.metadata.action:m.name??"",from:typeof((y=m.metadata)==null?void 0:y.from)=="string"?m.metadata.from:void 0,to:typeof((w=m.metadata)==null?void 0:w.to)=="string"?m.metadata.to:void 0,note:typeof((b=m.metadata)==null?void 0:b.note)=="string"?m.metadata.note:void 0,sha:typeof((S=m.metadata)==null?void 0:S.sha)=="string"?m.metadata.sha:"",at:typeof((E=m.metadata)==null?void 0:E.at)=="string"?m.metadata.at:m.tCreated}}).sort((m,v)=>m.at.localeCompare(v.at));l.set(f,p)}return{currentStatusNameByIssue:i,auditTrailByIssue:l}}async function qp(e,t){const{graph:n}=e;if(ks(t.filter,Mp,"openCurve"),t.at.length===0)throw new I("at","requires at least one ISO-8601 instant to sample");const r=t.at.map(u=>{const f=new Date(u);if(Number.isNaN(f.getTime()))throw new I("at",`"${u}" is not a parsable ISO-8601 instant`);return f.toISOString()}),o=await _s(n,t.filter);if((o==null?void 0:o.size)===0)return{points:r.map(u=>({at:u,existed:0,open:0,closed:0}))};const i=await n.queryNodes({kind:"status",liveOnly:!0}),s=new Map(i.map(u=>[u.name??"",Oe(u)])),{currentStatusNameByIssue:a,auditTrailByIssue:c}=await Bp(n),d=new Map;for(const u of await n.getEdges({rel:"SUPERSEDES"})){const f=d.get(u.dst);(f===void 0||u.tCreated<f)&&d.set(u.dst,u.tCreated)}const l=[];for(const u of r){const f={kind:"issue",validAt:u,liveOnly:!1,...o?{ids:[...o]}:{}},g=await n.queryNodes(f);let p=0,m=0;for(const v of g){const h=d.get(v.id);if(h!==void 0&&h<=u)continue;m+=1;const y=a.get(v.id),w=c.get(v.id)??[],b=Fp(w,u,y);(b!==void 0?s.get(b)??!1:!1)||(p+=1)}l.push({at:u,existed:m,open:p,closed:m-p})}return{points:l}}const $r=["abort","force","comment"];function qe(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}const Cr=512;function Ns(e){if(typeof e=="string"&&e.length>Cr)throw new I("gitContext",`must be at most ${Cr} characters, got ${e.length}`)}async function Kp(e,t,n){if(!qt(e))return"unverified";try{const{accepted:r,candidate:o}=await Di(e.metadata.path,t,n);if(!r)return"unverified";const i=await Ct.readFile(o);return ue.createHash("sha256").update(i).digest("hex")}catch(r){if(ro(r))return"unverified";throw Ki(r,t)}}function Pr(e,t,n){if(e.length>0&&!e.includes(n))throw new I(t,`"${n}" is not in this project's allowed ${t} set`)}function Hp(e,t){for(const n of e){const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new I(n,"is required by this project's field policy")}}async function Vp(e,t,n,r,o){if(!n.dedupeScanEnabled)return[];const{search:i,graph:s}=e;if(!i||!s)return[];const a={project:t.uid},c=await ys(s,a);if(!c||c.size===0)return[];const d=lo(r,o),l=typeof i.embedQuery=="function"?await i.embedQuery(d):void 0,f={text:d,vec:l,signals:l?[{kind:"text"},{kind:"vec"}]:[{kind:"text"}],filters:{ids:[...c]}},g=5,p=g*4,m=await i.backend.search(f,p);if(m.length===0)return[];const v=await s.getNodesByIds(m.map(w=>w.id)),h=new Map(v.map(w=>[w.id,w])),y=[];for(const w of m){const b=h.get(w.id);if(!b||b.tInvalid!==void 0||b.isSuperseded)continue;const S=w.vecScore;S!==void 0&&c.has(w.id)&&S>=n.dedupeThreshold&&y.push({uid:b.uid,title:b.name??"",score:S})}return y.sort((w,b)=>b.score-w.score),y.slice(0,g)}async function Gp(e,t){qe("title",t.title),qe("body",t.body),qe("project",t.project),qe("by",t.by),Q("by",t.by),Ns(t.gitContext);const n=t.citations??[];n.forEach((u,f)=>qe(`citations[${f}].file`,u.file));const r=typeof t.gitContext=="string"&&t.gitContext.trim().length>0?t.gitContext:void 0,o=t.duplicateAction??"abort";if(t.duplicateAction!==void 0&&!$r.includes(t.duplicateAction))throw new I("duplicateAction",`must be one of ${$r.map(u=>`'${u}'`).join("|")}, got "${t.duplicateAction}"`);const i=await Ye(e.adapter,t.project),s=Le(i),a=[];for(const u of n){const f=await Kp(i,u.file,s.citationAllowedExternalRoots);if(f==="unverified"&&s.citationRequiresSha){if(qt(i))throw new io(u.file,s.citationAllowedExternalRoots);console.error(`createIssue: citation_requires_sha waived for path-less project uid="${i.uid}" — cannot verify citation "${u.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}a.push(f)}const c=await Vp(e,i,s,t.title,t.body);if(c.length>0&&o==="abort")return{created:!1,reason:"duplicate-suppressed",duplicateCandidates:c};let d;const l=await z(e,async u=>{const f=V();if(c.length>0&&o==="comment"){const[C]=c,q=await we(u,C.uid),x=`${t.title}
511
205
 
512
- ${e.body}`,pe=await ct(d,{kind:"note",content:he,metadata:{author:e.by,text:he,at:f},at:f}),Oe=await Te(d,"has_note");return await Re(d,{at:f,srcRowid:fe.rowid,srcUid:fe.uid,srcKind:"issue",dstRowid:pe.rowid,dstUid:pe.uid,dstKind:"note",rel:"has_note",rule:Oe,typePolicy:t.typePolicy}),{created:!1,commentedOn:{uid:fe.uid,noteId:pe.uid},duplicateCandidates:c}}const g=await rs(d,e.project),p=Zr(g),y=e.component!==void 0?await Pl(d,{projectUid:g.uid,ref:e.component}):await wy(d,{projectRowid:g.rowid}),w=e.kind??p.defaultKind??"issue",h=await mn(d,{catalogKind:"kind",ref:w,at:f});Eg(p.allowedKinds,"kind",h.name);const v=e.status??p.defaultStatus??"open",b=await mn(d,{catalogKind:"status",ref:v,at:f,mintMetadata:async()=>({terminal:!1})});Eg(p.allowedStatuses,"status",b.name);let E;e.priority!==void 0&&(E=await mn(d,{catalogKind:"priority",ref:e.priority,at:f,mintMetadata:async ue=>({rank:await vy(ue)})}));const N=e.author??e.by,j=await mn(d,{catalogKind:"agent",ref:N,at:f});Lq(p.requiredFields,{...e,component:y.name,kind:h.name,status:b.name,priority:E==null?void 0:E.name});const T={};e.assignee!==void 0&&(T.assignee=e.assignee),r!==void 0&&(T.gitContext=r);const M=await ct(d,{kind:"issue",name:e.title,content:e.body,metadata:T,at:f});u={rowid:M.rowid,uid:M.uid};const C=await Te(d,"owns_component");await Re(d,{at:f,srcRowid:y.rowid,srcUid:y.uid,srcKind:"component",dstRowid:M.rowid,dstUid:M.uid,dstKind:"issue",rel:"owns_component",rule:C,typePolicy:t.typePolicy});const G=await Te(d,"has_kind");await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:h.rowid,dstUid:h.uid,dstKind:"kind",rel:"has_kind",rule:G,typePolicy:t.typePolicy});const H=await Te(d,"has_status");if(await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:b.rowid,dstUid:b.uid,dstKind:"status",rel:"has_status",rule:H,typePolicy:t.typePolicy}),E){const ue=await Te(d,"has_priority");await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:E.rowid,dstUid:E.uid,dstKind:"priority",rel:"has_priority",rule:ue,typePolicy:t.typePolicy})}const Z=await Te(d,"authored_by");if(await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:j.rowid,dstUid:j.uid,dstKind:"agent",rel:"authored_by",rule:Z,typePolicy:t.typePolicy}),n.length>0){const ue=await Te(d,"has_citation");for(let fe=0;fe<n.length;fe+=1){const he=n[fe],pe=a[fe],Oe=await ct(d,{at:f,kind:"citation",name:he.file,content:he.context??he.file,metadata:{target:he.file,target_type:"path",sha:pe,line:he.lines??null,at:f,symbol:he.symbol??null,blastRadius:he.blastRadius??null}});await Re(d,{at:f,srcRowid:M.rowid,srcUid:M.uid,srcKind:"issue",dstRowid:Oe.rowid,dstUid:Oe.uid,dstKind:"citation",rel:"has_citation",rule:ue,typePolicy:t.typePolicy})}}return await Pe({tx:d,typePolicy:t.typePolicy,subjectRowid:M.rowid,subjectUid:M.uid,subjectKind:"issue",actor:e.by,action:"created",at:f}),{created:!0,uid:M.uid,item:{uid:M.uid,title:e.title,kind:h.name,status:b.name,priority:E==null?void 0:E.name,project:g.uid,component:y.uid,createdAt:f,assignee:e.assignee,author:j.name,...r!==void 0?{gitContext:r}:{}},...c.length>0?{duplicateCandidates:c}:{}}});if(u){const d=qi(t,{action:"upsert",subjectRowid:u.rowid,subjectUid:u.uid,actor:e.by,content:xl(e.title,e.body)});e.awaitEmbed?await d:d.catch(()=>{})}return l}function ci(t,e){if(typeof e!="string"||e.trim().length===0)throw new oe(t,"is required")}async function Bq(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`update: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`update: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await sn(t,r.src);if(!o||o.kind!=="project"||o.tInvalid!==null)throw new Error(`update: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}function Fq(t,e){if(t.length>0&&!t.includes(e))throw new oe("kind",`"${e}" is not in this project's allowed kind set`)}function qq(t,e){for(const n of t){if(!(n in e))continue;const r=e[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new oe(n,"is required by this project's field policy")}}async function Sg(t,e,n,r){const o=[],s=[];n.name!==void 0&&(o.push("name = ?"),s.push(n.name)),n.metadata!==void 0&&(o.push("meta = ?"),s.push(JSON.stringify(n.metadata))),o.push("t_updated = ?"),s.push(r);const i=await t.executeRun(`UPDATE node SET ${o.join(", ")} WHERE rowid = ?`,[...s,e]);if(i.rowsAffected!==1)throw new Error(`update: touch UPDATE affected ${i.rowsAffected} rows for rowid=${e}, expected exactly 1.`)}async function ui(t,e,n){if(!(n.newSrcRowid!==n.oldSrcRowid)&&!n.override)return;const o=await t.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[n.oldSrcRowid,n.rel]);let s=n.override;if(!s&&o){const a=await sn(t,o.dst);a&&a.tInvalid===null&&(s={rowid:a.rowid,uid:a.uid,kind:a.kind,name:a.name??""})}if(!s){if(n.required)throw new Error(`update: issue rowid=${n.oldSrcRowid} has no live "${n.rel}" edge — graph invariant violation (every live issue must carry exactly one live ${n.rel}).`);return}o&&await Sr(t,{srcRowid:n.oldSrcRowid,dstRowid:o.dst,rel:n.rel,reason:n.reason,at:n.at});const i=await Te(t,n.rel);await Re(t,{at:n.at,srcRowid:n.newSrcRowid,srcUid:n.newSrcUid,srcKind:"issue",dstRowid:s.rowid,dstUid:s.uid,dstKind:s.kind,rel:n.rel,rule:i,typePolicy:e.typePolicy})}async function Kq(t,e,n){if(n.oldIssueRowid===n.newIssueRowid)return;const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.oldIssueRowid,"owns_component"]);if(!r)throw new Error(`update: issue rowid=${n.oldIssueRowid} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const o=await sn(t,r.src);if(!o||o.kind!=="component"||o.tInvalid!==null)throw new Error(`update: resolved component rowid=${r.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);await Sr(t,{srcRowid:r.src,dstRowid:n.oldIssueRowid,rel:"owns_component",reason:"superseded — placement carried forward to the new node",at:n.at});const s=await Te(t,"owns_component");await Re(t,{at:n.at,srcRowid:r.src,srcUid:o.uid,srcKind:"component",dstRowid:n.newIssueRowid,dstUid:n.newIssueUid,dstKind:"issue",rel:"owns_component",rule:s,typePolicy:e.typePolicy})}const _g=["SUPERSEDES","owns_component","has_status","has_kind","has_priority","authored_by"];async function Vq(t,e){if(e.oldIssueRowid===e.newIssueRowid)return;const n=_g.map(()=>"?").join(", ");for(const r of["outgoing","incoming"]){const o=r==="outgoing"?"src":"dst",s=r==="outgoing"?"dst":"src",{rows:i}=await t.executeAll(`SELECT ${s} AS other, rel, weight, confidence, origin, meta FROM edge WHERE ${o} = ? AND t_invalid IS NULL AND rel NOT IN (${n})`,[e.oldIssueRowid,..._g]);for(const a of i){const c=r==="outgoing"?e.oldIssueRowid:a.other,u=r==="outgoing"?a.other:e.oldIssueRowid,l=r==="outgoing"?e.newIssueRowid:a.other,d=r==="outgoing"?a.other:e.newIssueRowid;await Sr(t,{srcRowid:c,dstRowid:u,rel:a.rel,reason:`superseded — "${a.rel}" carried forward to the new node`,at:e.at}),await t.executeRun(`INSERT INTO edge (src, dst, rel, weight, confidence, origin, meta, t_created, t_valid)
206
+ ${t.body}`,P=await J(u,{kind:"note",content:x,metadata:{author:t.by,text:x,at:f},at:f}),Y=await F(u,"has_note");return await M(u,{at:f,srcRowid:q.rowid,srcUid:q.uid,srcKind:"issue",dstRowid:P.rowid,dstUid:P.uid,dstKind:"note",rel:"has_note",rule:Y,typePolicy:e.typePolicy}),{created:!1,commentedOn:{uid:q.uid,noteId:P.uid},duplicateCandidates:c}}const g=await Ye(u,t.project),p=Le(g),m=t.component!==void 0?await co(u,{projectUid:g.uid,ref:t.component}):await zi(u,{projectRowid:g.rowid}),v=t.kind??p.defaultKind??"issue",h=await he(u,{catalogKind:"kind",ref:v,at:f});Pr(p.allowedKinds,"kind",h.name);const y=t.status??p.defaultStatus??"open",w=await he(u,{catalogKind:"status",ref:y,at:f,mintMetadata:async()=>({terminal:!1})});Pr(p.allowedStatuses,"status",w.name);let b;t.priority!==void 0&&(b=await he(u,{catalogKind:"priority",ref:t.priority,at:f,mintMetadata:async C=>({rank:await Yi(C)})}));const S=t.author??t.by,E=await he(u,{catalogKind:"agent",ref:S,at:f});Hp(p.requiredFields,{...t,component:m.name,kind:h.name,status:w.name,priority:b==null?void 0:b.name});const A={};t.assignee!==void 0&&(A.assignee=t.assignee),r!==void 0&&(A.gitContext=r);const j=await J(u,{kind:"issue",name:t.title,content:t.body,metadata:A,at:f});d={rowid:j.rowid,uid:j.uid};const N=await F(u,"owns_component");await M(u,{at:f,srcRowid:m.rowid,srcUid:m.uid,srcKind:"component",dstRowid:j.rowid,dstUid:j.uid,dstKind:"issue",rel:"owns_component",rule:N,typePolicy:e.typePolicy});const _=await F(u,"has_kind");await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:h.rowid,dstUid:h.uid,dstKind:"kind",rel:"has_kind",rule:_,typePolicy:e.typePolicy});const R=await F(u,"has_status");if(await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:w.rowid,dstUid:w.uid,dstKind:"status",rel:"has_status",rule:R,typePolicy:e.typePolicy}),b){const C=await F(u,"has_priority");await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:b.rowid,dstUid:b.uid,dstKind:"priority",rel:"has_priority",rule:C,typePolicy:e.typePolicy})}const T=await F(u,"authored_by");if(await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:E.rowid,dstUid:E.uid,dstKind:"agent",rel:"authored_by",rule:T,typePolicy:e.typePolicy}),n.length>0){const C=await F(u,"has_citation");for(let q=0;q<n.length;q+=1){const x=n[q],P=a[q],Y=await J(u,{at:f,kind:"citation",name:x.file,content:x.context??x.file,metadata:{target:x.file,target_type:"path",sha:P,line:x.lines??null,at:f,symbol:x.symbol??null,blastRadius:x.blastRadius??null}});await M(u,{at:f,srcRowid:j.rowid,srcUid:j.uid,srcKind:"issue",dstRowid:Y.rowid,dstUid:Y.uid,dstKind:"citation",rel:"has_citation",rule:C,typePolicy:e.typePolicy})}}return await U({tx:u,typePolicy:e.typePolicy,subjectRowid:j.rowid,subjectUid:j.uid,subjectKind:"issue",actor:t.by,action:"created",at:f}),{created:!0,uid:j.uid,item:{uid:j.uid,title:t.title,kind:h.name,status:w.name,priority:b==null?void 0:b.name,project:g.uid,component:m.uid,createdAt:f,assignee:t.assignee,author:E.name,...r!==void 0?{gitContext:r}:{}},...c.length>0?{duplicateCandidates:c}:{}}});if(d){const u=Ot(e,{action:"upsert",subjectRowid:d.rowid,subjectUid:d.uid,actor:t.by,content:lo(t.title,t.body)});t.awaitEmbed?await u:u.catch(()=>{})}return l}function yt(e,t){if(typeof t!="string"||t.trim().length===0)throw new I(e,"is required")}async function Jp(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`update: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`update: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await fe(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`update: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}function Wp(e,t){if(e.length>0&&!e.includes(t))throw new I("kind",`"${t}" is not in this project's allowed kind set`)}function zp(e,t){for(const n of e){if(!(n in t))continue;const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new I(n,"is required by this project's field policy")}}async function xr(e,t,n,r){const o=[],i=[];n.name!==void 0&&(o.push("name = ?"),i.push(n.name)),n.metadata!==void 0&&(o.push("meta = ?"),i.push(JSON.stringify(n.metadata))),o.push("t_updated = ?"),i.push(r);const s=await e.executeRun(`UPDATE node SET ${o.join(", ")} WHERE rowid = ?`,[...i,t]);if(s.rowsAffected!==1)throw new Error(`update: touch UPDATE affected ${s.rowsAffected} rows for rowid=${t}, expected exactly 1.`)}async function wt(e,t,n){if(!(n.newSrcRowid!==n.oldSrcRowid)&&!n.override)return;const o=await e.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[n.oldSrcRowid,n.rel]);let i=n.override;if(!i&&o){const a=await fe(e,o.dst);(a==null?void 0:a.tInvalid)===null&&(i={rowid:a.rowid,uid:a.uid,kind:a.kind,name:a.name??""})}if(!i){if(n.required)throw new Error(`update: issue rowid=${n.oldSrcRowid} has no live "${n.rel}" edge — graph invariant violation (every live issue must carry exactly one live ${n.rel}).`);return}o&&await _e(e,{srcRowid:n.oldSrcRowid,dstRowid:o.dst,rel:n.rel,reason:n.reason,at:n.at});const s=await F(e,n.rel);await M(e,{at:n.at,srcRowid:n.newSrcRowid,srcUid:n.newSrcUid,srcKind:"issue",dstRowid:i.rowid,dstUid:i.uid,dstKind:i.kind,rel:n.rel,rule:s,typePolicy:t.typePolicy})}async function Yp(e,t,n){if(n.oldIssueRowid===n.newIssueRowid)return;const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.oldIssueRowid,"owns_component"]);if(!r)throw new Error(`update: issue rowid=${n.oldIssueRowid} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const o=await fe(e,r.src);if((o==null?void 0:o.kind)!=="component"||o.tInvalid!==null)throw new Error(`update: resolved component rowid=${r.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);await _e(e,{srcRowid:r.src,dstRowid:n.oldIssueRowid,rel:"owns_component",reason:"superseded — placement carried forward to the new node",at:n.at});const i=await F(e,"owns_component");await M(e,{at:n.at,srcRowid:r.src,srcUid:o.uid,srcKind:"component",dstRowid:n.newIssueRowid,dstUid:n.newIssueUid,dstKind:"issue",rel:"owns_component",rule:i,typePolicy:t.typePolicy})}const Lr=["SUPERSEDES","owns_component","has_status","has_kind","has_priority","authored_by"];async function Xp(e,t){if(t.oldIssueRowid===t.newIssueRowid)return;const n=Lr.map(()=>"?").join(", ");for(const r of["outgoing","incoming"]){const o=r==="outgoing"?"src":"dst",i=r==="outgoing"?"dst":"src",{rows:s}=await e.executeAll(`SELECT ${i} AS other, rel, weight, confidence, origin, meta FROM edge WHERE ${o} = ? AND t_invalid IS NULL AND rel NOT IN (${n})`,[t.oldIssueRowid,...Lr]);for(const a of s){const c=r==="outgoing"?t.oldIssueRowid:a.other,d=r==="outgoing"?a.other:t.oldIssueRowid,l=r==="outgoing"?t.newIssueRowid:a.other,u=r==="outgoing"?a.other:t.newIssueRowid;await _e(e,{srcRowid:c,dstRowid:d,rel:a.rel,reason:`superseded — "${a.rel}" carried forward to the new node`,at:t.at}),await e.executeRun(`INSERT INTO edge (src, dst, rel, weight, confidence, origin, meta, t_created, t_valid)
513
207
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
514
208
  ON CONFLICT(src, dst, rel) DO UPDATE SET
515
209
  weight = excluded.weight, confidence = excluded.confidence,
516
210
  origin = excluded.origin, meta = excluded.meta,
517
- t_invalid = NULL, t_valid = excluded.t_valid`,[l,d,a.rel,a.weight,a.confidence,a.origin,a.meta,e.at,e.at])}}}function Gq(t){const e=[];return t.title!==void 0&&e.push("title"),t.body!==void 0&&e.push("body"),t.kind!==void 0&&e.push("kind"),t.priority!==void 0&&e.push("priority"),t.assignee!==void 0&&e.push("assignee"),t.author!==void 0&&e.push("author"),e}function zq(t,e){const n=["title","body","kind","priority","assignee","author"];for(const r of n)if(t[r]!==void 0&&!e.includes(r))throw new Error(`update: patch key "${r}" was given but not recorded in \`changed\` — assertNoSilentlyDiscardedPatchKeys invariant violated (SPEC.md §6.3.3).`)}async function Wq(t,e){if(ci("uid",e.uid),ci("by",e.by),jt("by",e.by),e.status!==void 0)throw new Er("status","status changes are not an `update` field — call `transition(uid, toStatus, ...)` instead");e.title!==void 0&&ci("title",e.title),e.body!==void 0&&ci("body",e.body);const r=Gq(e);if(r.length===0)throw new oe("patch","update requires at least one of title/body/kind/priority/assignee/author");zq(e,r);let o;const s=await lt(t,async i=>{const a=He(),c=await _n(i,e.uid),u=await Bq(i,c.rowid),l=Zr(u);let d;if(e.kind!==void 0){const v=await mn(i,{catalogKind:"kind",ref:e.kind,at:a});Fq(l.allowedKinds,v.name),d={rowid:v.rowid,uid:v.uid,kind:"kind",name:v.name}}let f;if(e.priority!==void 0){const v=await mn(i,{catalogKind:"priority",ref:e.priority,at:a,mintMetadata:async b=>({rank:await vy(b)})});f={rowid:v.rowid,uid:v.uid,kind:"priority",name:v.name}}let g;if(e.author!==void 0){const v=await mn(i,{catalogKind:"agent",ref:e.author,at:a});g={rowid:v.rowid,uid:v.uid,kind:"agent",name:v.name}}const p={...e};d&&(p.kind=d.name),f&&(p.priority=f.name),g&&(p.author=g.name),qq(l.requiredFields,p);let y=c.rowid,w=c.uid,h=!1;if(e.body!==void 0){if((await i.executeRun("UPDATE node SET is_superseded = 1 WHERE rowid = ? AND is_superseded = 0",[c.rowid])).rowsAffected!==1)throw new da(e.uid);const b=e.title??c.name??void 0,E={...c.metadata??{}};e.assignee!==void 0&&(E.assignee=e.assignee);const N=await ct(i,{kind:"issue",name:b,content:e.body,metadata:E,at:a});await i.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
211
+ t_invalid = NULL, t_valid = excluded.t_valid`,[l,u,a.rel,a.weight,a.confidence,a.origin,a.meta,t.at,t.at])}}}function Qp(e){const t=[];return e.title!==void 0&&t.push("title"),e.body!==void 0&&t.push("body"),e.kind!==void 0&&t.push("kind"),e.priority!==void 0&&t.push("priority"),e.assignee!==void 0&&t.push("assignee"),e.author!==void 0&&t.push("author"),t}function Zp(e,t){const n=["title","body","kind","priority","assignee","author"];for(const r of n)if(e[r]!==void 0&&!t.includes(r))throw new Error(`update: patch key "${r}" was given but not recorded in \`changed\` — assertNoSilentlyDiscardedPatchKeys invariant violated (SPEC.md §6.3.3).`)}async function em(e,t){if(yt("uid",t.uid),yt("by",t.by),Q("by",t.by),t.status!==void 0)throw new je("status","status changes are not an `update` field — call `transition(uid, toStatus, ...)` instead");t.title!==void 0&&yt("title",t.title),t.body!==void 0&&yt("body",t.body);const r=Qp(t);if(r.length===0)throw new I("patch","update requires at least one of title/body/kind/priority/assignee/author");Zp(t,r);let o;const i=await z(e,async s=>{const a=V(),c=await we(s,t.uid),d=await Jp(s,c.rowid),l=Le(d);let u;if(t.kind!==void 0){const y=await he(s,{catalogKind:"kind",ref:t.kind,at:a});Wp(l.allowedKinds,y.name),u={rowid:y.rowid,uid:y.uid,kind:"kind",name:y.name}}let f;if(t.priority!==void 0){const y=await he(s,{catalogKind:"priority",ref:t.priority,at:a,mintMetadata:async w=>({rank:await Yi(w)})});f={rowid:y.rowid,uid:y.uid,kind:"priority",name:y.name}}let g;if(t.author!==void 0){const y=await he(s,{catalogKind:"agent",ref:t.author,at:a});g={rowid:y.rowid,uid:y.uid,kind:"agent",name:y.name}}const p={...t};u&&(p.kind=u.name),f&&(p.priority=f.name),g&&(p.author=g.name),zp(l.requiredFields,p);let m=c.rowid,v=c.uid,h=!1;if(t.body!==void 0){if((await s.executeRun("UPDATE node SET is_superseded = 1 WHERE rowid = ? AND is_superseded = 0",[c.rowid])).rowsAffected!==1)throw new Mt(t.uid);const w=t.title??c.name??void 0,b={...c.metadata??{}};t.assignee!==void 0&&(b.assignee=t.assignee);const S=await J(s,{kind:"issue",name:w,content:t.body,metadata:b,at:a});await s.executeRun(`INSERT INTO edge (src, dst, rel, weight, origin, meta, t_created, t_valid)
518
212
  VALUES (?, ?, 'SUPERSEDES', 1.0, 'user_asserted', NULL, ?, ?)
519
213
  ON CONFLICT(src, dst, rel) DO UPDATE SET
520
214
  meta = excluded.meta, weight = excluded.weight,
521
- t_invalid = NULL, t_valid = excluded.t_valid`,[N.rowid,c.rowid,a,a]),await Sg(i,N.rowid,{},a),o={oldRowid:c.rowid,oldUid:c.uid,newRowid:N.rowid,newUid:N.uid,newTitle:b??"",newBody:e.body},y=N.rowid,w=N.uid,h=!0}else{const v=e.assignee!==void 0?{...c.metadata??{},assignee:e.assignee}:void 0;await Sg(i,c.rowid,{name:e.title,metadata:v},a)}return await Kq(i,t,{oldIssueRowid:c.rowid,newIssueRowid:y,newIssueUid:w,at:a}),await ui(i,t,{rel:"has_status",oldSrcRowid:c.rowid,newSrcRowid:y,newSrcUid:w,reason:"superseded — status carried forward to the new node (update never changes status)",at:a,required:!0}),await ui(i,t,{rel:"has_kind",oldSrcRowid:c.rowid,newSrcRowid:y,newSrcUid:w,override:d,reason:"kind changed via update",at:a}),await ui(i,t,{rel:"has_priority",oldSrcRowid:c.rowid,newSrcRowid:y,newSrcUid:w,override:f,reason:"priority changed via update",at:a}),await ui(i,t,{rel:"authored_by",oldSrcRowid:c.rowid,newSrcRowid:y,newSrcUid:w,override:g,reason:"author changed via update",at:a}),await Vq(i,{oldIssueRowid:c.rowid,newIssueRowid:y,at:a}),await Pe({tx:i,typePolicy:t.typePolicy,subjectRowid:y,subjectUid:w,subjectKind:"issue",actor:e.by,action:"updated",from:h?c.uid:void 0,to:h?w:void 0,note:`fields changed: ${r.join(", ")}`,at:a}),{uid:w,changed:r}});if(o){const{oldRowid:i,oldUid:a,newRowid:c,newUid:u,newTitle:l,newBody:d}=o,f=Promise.all([qi(t,{action:"delete",subjectRowid:i,subjectUid:a,actor:e.by}),qi(t,{action:"upsert",subjectRowid:c,subjectUid:u,actor:e.by,content:xl(l,d)})]);e.awaitEmbed?await f:f.catch(()=>{})}return s}function mb(t){const e=t??{};return{claimedBy:typeof e.claimedBy=="string"?e.claimedBy:void 0,claimedAt:typeof e.claimedAt=="string"?e.claimedAt:void 0}}function gb(t,e){return t!==void 0?(Date.parse(e)-Date.parse(t))/6e4:Number.POSITIVE_INFINITY}function yb(t,e,n){return gb(t,e)>=n}async function wb(t,e,n){const r=await t.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[e,"has_status"]);if(!r)throw new Error(`${n}: issue rowid=${e} has no live "has_status" edge — graph invariant violation (every live issue must carry exactly one live status).`);const o=await sn(t,r.dst);if(!o||o.kind!=="status"||o.tInvalid!==null)throw new Error(`${n}: resolved status rowid=${r.dst} is missing, invalidated, or not a "status" node — graph invariant violation.`);return o}function li(t,e){if(typeof e!="string"||e.trim().length===0)throw new oe(t,"is required")}async function Ng(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`transition: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`transition: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await sn(t,r.src);if(!o||o.kind!=="project"||o.tInvalid!==null)throw new Error(`transition: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}async function Hq(t,e){if(!ha(t))return"unverified";const n=L.resolve(t.metadata.path),r=L.isAbsolute(e)?L.resolve(e):L.resolve(n,e),o=L.relative(n,r);if(o===".."||o.startsWith("../")||o.startsWith("..\\")||L.isAbsolute(o))return"unverified";try{const i=await sl.readFile(r);return kn.createHash("sha256").update(i).digest("hex")}catch(i){const a=i==null?void 0:i.code;if(a==="ENOENT"||a==="ENOTDIR")return"unverified";throw new kl(i)}}function Jq(t,e){if(t.length>0&&!t.includes(e))throw new oe("toStatus",`"${e}" is not in this project's allowed status set`)}function Qq(t,e){for(const n of t){if(!(n in e))continue;const r=e[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new oe(n,"is required by this project's field policy")}}async function Yq(t,e){li("uid",e.uid),li("by",e.by),jt("by",e.by),li("toStatus",e.toStatus),hb(e.gitContext);const n=e.citations??[];n.forEach((o,s)=>li(`citations[${s}].file`,o.file));const r=[];if(n.length>0){const o=await pa(t.adapter,e.uid);if(!o||o.kind!=="issue"||o.tInvalid!==null)throw new fa(e.uid);const s=await Ng(t.adapter,o.rowid),i=Zr(s);for(const a of n){const c=await Hq(s,a.file);if(c==="unverified"&&i.citationRequiresSha){if(ha(s))throw new jl(a.file);console.error(`transition: citation_requires_sha waived for path-less project uid="${s.uid}" — cannot verify citation "${a.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}r.push(c)}}return lt(t,async o=>{var M;const s=He(),i=await _n(o,e.uid),a=await Ng(o,i.rowid),c=Zr(a),{claimedBy:u,claimedAt:l}=mb(i.metadata);if(u!==void 0&&u!==e.by&&!yb(l,s,c.claimStaleAfterMin))throw new Bi(u,l??s);const d=await wb(o,i.rowid,"transition"),f=d.name??"",g=await mn(o,{catalogKind:"status",ref:e.toStatus,at:s,mintMetadata:async()=>({terminal:!1})});Jq(c.allowedStatuses,g.name),Qq(c.requiredFields,{status:g.name,note:e.note});const p=await sn(o,g.rowid),y=((M=p==null?void 0:p.metadata)==null?void 0:M.terminal)===!0;if(!(typeof e.note=="string"&&e.note.trim().length>0)&&c.transitionRequiresNote)throw new py(i.uid);if(y&&c.citationRequired&&n.length===0)throw new hy(i.uid);const h={target_uid:i.uid,from:f,to:g.name,agent:e.by,note:e.note??null,at:s},v=Al(yy(h)),b=await ct(o,{kind:"transition",content:e.note??"",metadata:{from_status:f,to_status:g.name,agent:e.by,note:e.note??null,sha:v,at:s},at:s}),E=await Te(o,"has_transition");await Re(o,{at:s,srcRowid:i.rowid,srcUid:i.uid,srcKind:"issue",dstRowid:b.rowid,dstUid:b.uid,dstKind:"transition",rel:"has_transition",rule:E,typePolicy:t.typePolicy}),await Sr(o,{srcRowid:i.rowid,dstRowid:d.rowid,rel:"has_status",reason:`transitioned to "${g.name}"`,at:s});const N=await Te(o,"has_status");if(await Re(o,{at:s,srcRowid:i.rowid,srcUid:i.uid,srcKind:"issue",dstRowid:g.rowid,dstUid:g.uid,dstKind:"status",rel:"has_status",rule:N,typePolicy:t.typePolicy}),n.length>0){const C=await Te(o,"has_citation");for(let G=0;G<n.length;G+=1){const H=n[G],Z=r[G],ue=await ct(o,{at:s,kind:"citation",name:H.file,content:H.context??H.file,metadata:{target:H.file,target_type:"path",sha:Z,line:H.lines??null,at:s,symbol:H.symbol??null,blastRadius:H.blastRadius??null}});await Re(o,{at:s,srcRowid:i.rowid,srcUid:i.uid,srcKind:"issue",dstRowid:ue.rowid,dstUid:ue.uid,dstKind:"citation",rel:"has_citation",rule:C,typePolicy:t.typePolicy})}}const j={...i.metadata??{}};y?j.closedAt=s:delete j.closedAt,typeof e.gitContext=="string"&&e.gitContext.trim().length>0&&(j.gitContext=e.gitContext);const T=await o.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(j),s,i.rowid]);if(T.rowsAffected!==1)throw new Error(`transition: closedAt touch UPDATE affected ${T.rowsAffected} rows for rowid=${i.rowid}, expected exactly 1.`);return await Pe({tx:o,typePolicy:t.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:e.by,action:"transitioned",from:f,to:g.name,note:e.note,at:s}),{uid:i.uid,fromStatus:f,toStatus:g.name,closedAt:y?s:void 0,transitionUid:b.uid}})}function Og(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}async function Zq(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`claim: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`claim: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await sn(t,r.src);if(!o||o.kind!=="project"||o.tInvalid!==null)throw new Error(`claim: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const s={rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata};return Zr(s)}async function Oo(t,e,n,r){const o=await t.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(n),r,e]);if(o.rowsAffected!==1)throw new Error(`claim: touch UPDATE affected ${o.rowsAffected} rows for rowid=${e}, expected exactly 1.`)}async function Xq(t,e){if(Og("uid",e.uid),Og("by",e.by),jt("by",e.by),e.action!=="claim"&&e.action!=="release"&&e.action!=="renew")throw new oe("action",`must be "claim", "release", or "renew" (got ${JSON.stringify(e.action)})`);const n=e.force===!0;return lt(t,async r=>{var u;const o=He(),s=await _n(r,e.uid),i={...s.metadata??{}},{claimedBy:a,claimedAt:c}=mb(i);if(e.action==="claim"){const l=await wb(r,s.rowid,"claim");if(((u=l.metadata)==null?void 0:u.terminal)===!0)throw new fy(s.uid,l.name??"");if(a===void 0){const y={...i,claimedBy:e.by,claimedAt:o};return await Oo(r,s.rowid,y,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"claimed",to:e.by,at:o}),{uid:s.uid,status:"claimed",claimedBy:e.by,claimedAt:o}}if(a===e.by){const y={...i,claimedAt:o};return await Oo(r,s.rowid,y,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"claimed",from:e.by,to:e.by,note:"re-affirmed (held)",at:o}),{uid:s.uid,status:"held",heldBy:e.by,claimedBy:e.by,claimedAt:o}}const d=await Zq(r,s.rowid),f=gb(c,o),g=yb(c,o,d.claimStaleAfterMin);if(!g&&!n)throw new Bi(a,c??o);const p={...i,claimedBy:e.by,claimedAt:o,previousClaimant:a};return await Oo(r,s.rowid,p,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"reclaimed-stale",from:a,to:e.by,note:g?`stale claim reclaimed after ~${Math.floor(f)}min (threshold ${d.claimStaleAfterMin}min)`:"force override of a non-stale claim",at:o}),{uid:s.uid,status:"reclaimed-stale",claimedBy:e.by,claimedAt:o,previousClaimant:a}}if(e.action==="release"){if(a===e.by){const l={...i};return delete l.claimedBy,delete l.claimedAt,await Oo(r,s.rowid,l,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"released",from:e.by,at:o}),{uid:s.uid,status:"released"}}return{uid:s.uid,status:"release-noop",wasClaimedBy:a}}if(a===e.by){const l={...i,claimedAt:o};return await Oo(r,s.rowid,l,o),await Pe({tx:r,typePolicy:t.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:e.by,action:"renewed",from:e.by,to:e.by,at:o}),{uid:s.uid,status:"renewed",claimedBy:e.by,claimedAt:o}}throw new Bi(a??"",c??"")})}const kg=["relates_to","supersedes","blocks","duplicate_of","part_of"];function jc(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}async function eK(t,e,n,r){const o=await t.executeGet("SELECT rowid FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[e,n,r]);return o?o.rowid:null}async function tK(t,e){if(jc("sourceUid",e.sourceUid),jc("targetUid",e.targetUid),jc("by",e.by),jt("by",e.by),!kg.includes(e.rel))throw new oe("rel",`must be one of ${kg.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.rel)})`);if(e.action!=="add"&&e.action!=="remove")throw new oe("action",`must be "add" or "remove" (got ${JSON.stringify(e.action)})`);if(e.sourceUid===e.targetUid)throw new oe("targetUid","a self-relation (sourceUid === targetUid) is never allowed");return lt(t,async n=>{const r=He(),o=await _n(n,e.sourceUid),s=await _n(n,e.targetUid),i=await eK(n,o.rowid,s.rowid,e.rel);if(e.action==="add"){if(i!==null)return{sourceUid:o.uid,targetUid:s.uid,rel:e.rel,action:"add",noop:!0};const a=await Te(n,e.rel);return await Re(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"issue",dstRowid:s.rowid,dstUid:s.uid,dstKind:"issue",rel:e.rel,rule:a,typePolicy:t.typePolicy}),await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"related",to:s.uid,note:e.rel,at:r}),{sourceUid:o.uid,targetUid:s.uid,rel:e.rel,action:"add",noop:!1}}return i===null?{sourceUid:o.uid,targetUid:s.uid,rel:e.rel,action:"remove",noop:!0}:(await Sr(n,{srcRowid:o.rowid,dstRowid:s.rowid,rel:e.rel,reason:`relate: removed by "${e.by}"`,at:r}),await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"unrelated",to:s.uid,note:e.rel,at:r}),{sourceUid:o.uid,targetUid:s.uid,rel:e.rel,action:"remove",noop:!1})})}function jg(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}async function nK(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_component"]);if(!n)throw new Error(`move: issue rowid=${e} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await sn(t,n.src);if(!r||r.kind!=="component"||r.tInvalid!==null)throw new Error(`move: resolved component rowid=${n.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function rK(t,e){const n=await t.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[e,"owns_project"]);if(!n)throw new Error(`move: component rowid=${e} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const r=await sn(t,n.src);if(!r||r.kind!=="project"||r.tInvalid!==null)throw new Error(`move: resolved project rowid=${n.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function oK(t,e){return jg("uid",e.uid),jg("by",e.by),jt("by",e.by),lt(t,async n=>{const r=He(),o=await _n(n,e.uid),s=await nK(n,o.rowid),i=await rK(n,s.rowid);let a;if(e.toProject!==void 0){const l=await rs(n,e.toProject);a={rowid:l.rowid,uid:l.uid,name:l.name}}else a=i;let c;if(e.toComponent!==void 0?c=await Pl(n,{projectUid:a.uid,ref:e.toComponent}):c=await wy(n,{projectRowid:a.rowid}),c.rowid===s.rowid)return{uid:o.uid,noop:!0,fromProject:i.uid,toProject:a.uid,fromComponent:s.uid,toComponent:c.uid};await Sr(n,{srcRowid:s.rowid,dstRowid:o.rowid,rel:"owns_component",reason:`moved to component "${c.name}"`,at:r});const u=await Te(n,"owns_component");return await Re(n,{at:r,srcRowid:c.rowid,srcUid:c.uid,srcKind:"component",dstRowid:o.rowid,dstUid:o.uid,dstKind:"issue",rel:"owns_component",rule:u,typePolicy:t.typePolicy}),await Pe({tx:n,typePolicy:t.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:e.by,action:"moved",from:s.uid,to:c.uid,at:r}),{uid:o.uid,noop:!1,fromProject:i.uid,toProject:a.uid,fromComponent:s.uid,toComponent:c.uid}})}function Ac(t,e){if(e===void 0||e.trim().length===0)throw new oe(t,"is required")}async function sK(t,e){Ac("uid",e.uid),Ac("by",e.by),jt("by",e.by),Ac("reason",e.reason);let n;const r=await lt(t,async o=>{const s=He(),i=await _n(o,e.uid);n={rowid:i.rowid,uid:i.uid};const a={...i.metadata??{},invalidatedReason:e.reason,invalidatedAt:s},c=await o.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[s,JSON.stringify(a),i.rowid]);if(c.rowsAffected!==1)throw new Error(`deleteIssue: invalidate UPDATE affected ${c.rowsAffected} rows for uid="${e.uid}", expected exactly 1.`);return await Pe({tx:o,typePolicy:t.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:e.by,action:"deleted",note:e.reason,at:s}),{uid:i.uid,invalidated:!0}});if(n){const o=qi(t,{action:"delete",subjectRowid:n.rowid,subjectUid:n.uid,actor:e.by});e.awaitEmbed?await o:o.catch(()=>{})}return r}async function vb(t){return Eq(t.store.adapter,t.store.graph,t.env.config.embedding)}async function At(t,e){await Ol(t.store.adapter);const{search:n,embedding:r}=e.needsSemantic?await vb(t):{};return{adapter:t.store.adapter,typePolicy:t.store.typePolicy,graph:t.store.graph,...n!==void 0?{search:n}:{},...r!==void 0?{embedding:r}:{}}}async function za(t,e){const{search:n}=e.needsSemantic?await vb(t):{},r=n!==void 0&&e.probeSpace?await n.spacePopulated():void 0;return{graph:t.store.graph,assertVocabulary:()=>Ol(t.store.adapter),...n!==void 0?{search:n}:{},...r!==void 0?{spacePopulated:r}:{}}}const iK=[[fa,"item_not_found"],[Xe,"not_found"],[oe,"invalid_argument"],[Bi,"conflict"],[Qc,"conflict"],[da,"conflict"],[fy,"precondition_failed"],[hy,"precondition_failed"],[py,"precondition_failed"],[jl,"precondition_failed"],[dy,"store_busy"],[ub,"rag_not_configured"]],aK={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function $b(t){for(const[e,n]of iK)if(t instanceof e){const r=t instanceof Ke?{retryable:t.retryable,...t.retry_after_ms===void 0?{}:{retryAfterMs:t.retry_after_ms}}:void 0;return pr(n,t.message,r)}return t instanceof Ke?pr(aK[t.code]??"internal",t.message,{retryable:t.retryable,...t.retry_after_ms===void 0?{}:{retryAfterMs:t.retry_after_ms}}):pr("internal",t instanceof Error?t.message:String(t))}async function Je(t){try{return ap(await t())}catch(e){return $b(e)}}async function bb(t,e){return Je(()=>"registry"in e?e.registry==="project"?kc(t.store.graph,{registry:"project",name:e.name}):e.registry==="component"?kc(t.store.graph,{registry:"component",name:e.name,filter:e.filter}):kc(t.store.graph,{registry:"location",name:e.name}):_q(t.store.graph,e))}async function Eb(t,e){try{const{result:n,meta:r}=await gq(await za(t,{needsSemantic:fq(e),probeSpace:e.text!==void 0}),e);return ap(n,r?{meta:r}:void 0)}catch(n){return $b(n)}}async function Sb(t,e){return Je(async()=>Aq(await za(t,{needsSemantic:!1,probeSpace:!1}),e))}async function _b(t,e){return Je(async()=>Pq(await za(t,{needsSemantic:!1,probeSpace:!1}),e))}async function Nb(t,e){return Je(async()=>Cq(await za(t,{needsSemantic:!1,probeSpace:!1}),e))}async function Ob(t,e){return Je(()=>HF(t.store.graph,e.q))}async function kb(t,e){return Je(async()=>Uq(await At(t,{needsSemantic:!0}),e))}async function jb(t,e){return Je(async()=>Wq(await At(t,{needsSemantic:!0}),e))}async function Ab(t,e){return Je(async()=>Yq(await At(t,{needsSemantic:!1}),e))}async function Ib(t,e){return Je(async()=>Xq(await At(t,{needsSemantic:!1}),e))}async function Pb(t,e){return Je(async()=>tK(await At(t,{needsSemantic:!1}),e))}async function xb(t,e){return Je(async()=>oK(await At(t,{needsSemantic:!1}),e))}async function Rb(t,e){return Je(async()=>sK(await At(t,{needsSemantic:!1}),e))}async function Tb(t,e){return Je(async()=>uN(await At(t,{needsSemantic:!1}),e))}async function Cb(t,e){return Je(async()=>dN(await At(t,{needsSemantic:!1}),e))}async function Mb(t,e){return Je(async()=>pN(await At(t,{needsSemantic:!1}),e))}async function Lb(t,e){return Je(async()=>hN(await At(t,{needsSemantic:!1}),e))}const cK=Object.freeze(Object.defineProperty({__proto__:null,claim:Ib,create:kb,delete:Rb,get:bb,lookup:Ob,move:xb,openCurve:Nb,partOfRollup:_b,priorityMatrix:Sb,query:Eb,relate:Pb,rmLocation:Lb,transition:Ab,update:jb,upsertComponent:Cb,upsertLocation:Mb,upsertProject:Tb},Symbol.toStringTag,{value:"Module"}));function uK(){const t=L.dirname($s.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href)),e=L.join(t,"package.json");return J.existsSync(e)?e:L.join(t,"..","package.json")}function cp(){const t=uK(),e=JSON.parse(J.readFileSync(t,"utf8"));return{name:e.name,version:e.version}}function ol(t){if(!t.run)throw new Error(`@adhd/backlog: apigen plugin "${t.id}" declares no run() — cannot mount live`);return t.run}function Db(){if(!process.env.VITEST)return;const t=()=>{},e={info:t,error:t,debug:t,fatal:t,warn:t,trace:t};return e.child=()=>e,e}const Ag=["install","install-skill","serve"];function Ub(t){return t.filter(e=>e.kind==="action").map(e=>{const n=la(e);return{id:e.id,cliCommand:n.cli.path.join(" "),cliPath:n.cli.path,mcpTool:n.mcp.name,httpVerb:n.http.verb,httpRoute:n.http.route}}).sort((e,n)=>e.id.localeCompare(n.id))}function lK(t){const e=t.filter(n=>{const r=n.cliPath[n.cliPath.length-1]??"";return Ag.includes(r)||Ag.some(o=>n.mcpTool.endsWith(`_${o.replace(/-/g,"_")}`))});if(e.length>0)throw new Error(`@adhd/backlog: host-command carve-out violated (SPEC.md §6.6) — ${e.map(n=>n.id).join(", ")} was mounted as a data operation. install/install-skill must never open the store (DEBT-BACKLOG-CLI-EAGER-STORE-OPEN-001) and serve must never be reachable as a tool — it has a completely different lifecycle than a mounted data operation. Keep them host commands in cli.ts.`)}function dK(t,e=[Ui]){const n=Ub(t),r=new Set(n.map(s=>s.mcpTool)),o={host:"backlog",operations:t};for(const s of e){const i=s.capabilities.mount;if(i)for(const a of i.operations(o,void 0,void 0))r.add(la(a).mcp.name)}return[...r].sort()}function Bb(){const t=L.dirname($s.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href));return J.existsSync(L.join(t,"api.d.ts"))?t:L.join(t,"..","dist")}function Ig(t){if(!t||typeof t!="object")return t;const e={},n=o=>{if(Array.isArray(o)){for(const i of o)n(i);return}if(!o||typeof o!="object")return;const s=o;for(const i of["definitions","$defs"]){const a=s[i];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,u]of Object.entries(a))c in e||(e[c]=u)}for(const[i,a]of Object.entries(s))i==="definitions"||i==="$defs"||n(a)};if(n(t),n(e),Object.keys(e).length===0)return t;const r=(o,s)=>{if(Array.isArray(o))return o.map(u=>r(u,s));if(!o||typeof o!="object")return o;const i=o,a=i.$ref;if(typeof a=="string"){const u=a.replace(/^#\/(?:definitions|\$defs)\//,"");return s.has(u)||!(u in e)?{}:r(e[u],new Set([...s,u]))}const c={};for(const[u,l]of Object.entries(i))u==="definitions"||u==="$defs"||(c[u]=r(l,s));return c};return r(t,new Set)}const fK=Ne.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href),pK=fK("@adhd/apigen-core-client/package.json").version;function hK(t={}){return _P(t)}function mK(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function gK(t={}){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:Ix({cache:hK(t),extractorVersion:pK})}}}}let Pg;function yK(t={}){return Pg??(Pg=$x(mK()?[gK(t)]:[],e=>{var n;return lx({sourceFile:e.source,namespace:e.namespace,tsconfig:typeof((n=e.extractorOptions)==null?void 0:n.tsconfig)=="string"?e.extractorOptions.tsconfig:void 0,dropFileSegment:!0})})),Pg}async function wK(t={}){const e=L.join(Bb(),"api.d.ts");if(!J.existsSync(e))throw new Error(`@adhd/backlog: cannot mount — ${e} does not exist. Run "nx build backlog" first (extract() needs the built .d.ts for type information).`);return yK(t)({source:e,host:"ts",namespace:"backlog",extractorOptions:{}})}async function up(t,e={}){const n=typeof t=="function"?t:()=>t,r=await wK(e),o={schemas:Object.fromEntries(r.filter(c=>c.kind==="action").map(c=>{var u;return[((u=c.path[c.path.length-1])==null?void 0:u.raw)??"",{input:Ig(c.input),output:Ig(c.output),hasCtx:c.hasCtx,safe:c.safe}]}))},s=RP(o,[]),i=Ub(r);lK(i);const{version:a}=cp();return{pkg:{id:"backlog",version:a,schemas:s,importPath:L.join(Bb(),"api.js"),fns:cK,createClient:async()=>n()},operations:r,surface:i}}async function Fb(t){const e=Go({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd,namespace:t.namespace});e.ensureDirs();let n,r;const o=zo(e),s=()=>(n||(n=Zc(r)),n),i=wN()?void 0:by(s);try{r=await Ki(o,e.config.db.busyTimeoutMs)}catch(c){throw i==null||i.dispose(),c}const a={store:r,env:e};try{const{pkg:c,operations:u}=await up(a,{adhdRoot:t.adhdRoot}),l=Db(),d=[];(t.transport==="http"||t.transport==="both")&&d.push(ol(w2)({packages:[c],outputDir:"",options:{port:t.port??3300,host:t.host??"127.0.0.1",usePlugins:[x2,Ui]},signal:t.signal,operations:u,logger:l})),(t.transport==="mcp"||t.transport==="both")&&d.push(ol(pF)({packages:[c],outputDir:"",options:{transport:"stdio",usePlugins:[Ui]},signal:t.signal,operations:u,logger:l})),await Promise.all(d)}finally{i==null||i.dispose(),await s()}}const Yr=["claude","codex","opencode"],vK={claude:".claude",codex:".codex",opencode:".opencode"};function qb(t,e){return e?L.join(t,".codex"):process.env.CODEX_HOME??L.join(t,".codex")}function $K(t,e,n,r){if(e==="project")return L.join(n,vK[t],"skills");const o=r??mt.homedir();return t==="claude"?L.join(o,".claude","skills"):t==="codex"?L.join(qb(o,r),"skills"):L.join(o,".config","opencode","skills")}function bK(){const t=L.dirname($s.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href)),e=L.join(t,"skill","SKILL.md");return J.existsSync(e)?e:L.join(t,"..","skill","SKILL.md")}class ht extends Error{constructor(e){super(e),this.name="BacklogUsageError"}}function lp(t,e){console.error(JSON.stringify({code:"invalid_argument",message:t.message})),console.error(""),console.error(e),process.exitCode=2}const xg=`backlog install-skill [--host claude|codex|opencode|all] [--scope user|project]
215
+ t_invalid = NULL, t_valid = excluded.t_valid`,[S.rowid,c.rowid,a,a]),await xr(s,S.rowid,{},a),o={oldRowid:c.rowid,oldUid:c.uid,newRowid:S.rowid,newUid:S.uid,newTitle:w??"",newBody:t.body},m=S.rowid,v=S.uid,h=!0}else{const y=t.assignee!==void 0?{...c.metadata??{},assignee:t.assignee}:void 0;await xr(s,c.rowid,{name:t.title,metadata:y},a)}return await Yp(s,e,{oldIssueRowid:c.rowid,newIssueRowid:m,newIssueUid:v,at:a}),await wt(s,e,{rel:"has_status",oldSrcRowid:c.rowid,newSrcRowid:m,newSrcUid:v,reason:"superseded — status carried forward to the new node (update never changes status)",at:a,required:!0}),await wt(s,e,{rel:"has_kind",oldSrcRowid:c.rowid,newSrcRowid:m,newSrcUid:v,override:u,reason:"kind changed via update",at:a}),await wt(s,e,{rel:"has_priority",oldSrcRowid:c.rowid,newSrcRowid:m,newSrcUid:v,override:f,reason:"priority changed via update",at:a}),await wt(s,e,{rel:"authored_by",oldSrcRowid:c.rowid,newSrcRowid:m,newSrcUid:v,override:g,reason:"author changed via update",at:a}),await Xp(s,{oldIssueRowid:c.rowid,newIssueRowid:m,at:a}),await U({tx:s,typePolicy:e.typePolicy,subjectRowid:m,subjectUid:v,subjectKind:"issue",actor:t.by,action:"updated",from:h?c.uid:void 0,to:h?v:void 0,note:`fields changed: ${r.join(", ")}`,at:a}),{uid:v,changed:r}});if(o){const{oldRowid:s,oldUid:a,newRowid:c,newUid:d,newTitle:l,newBody:u}=o,f=Promise.all([Ot(e,{action:"delete",subjectRowid:s,subjectUid:a,actor:t.by}),Ot(e,{action:"upsert",subjectRowid:c,subjectUid:d,actor:t.by,content:lo(l,u)})]);t.awaitEmbed?await f:f.catch(()=>{})}return i}function Os(e){const t=e??{};return{claimedBy:typeof t.claimedBy=="string"?t.claimedBy:void 0,claimedAt:typeof t.claimedAt=="string"?t.claimedAt:void 0}}function Rs(e,t){return e!==void 0?(Date.parse(t)-Date.parse(e))/6e4:Number.POSITIVE_INFINITY}function Is(e,t,n){return Rs(e,t)>=n}async function Ts(e,t,n){const r=await e.executeGet("SELECT dst FROM edge WHERE src = ? AND rel = ? AND t_invalid IS NULL",[t,"has_status"]);if(!r)throw new Error(`${n}: issue rowid=${t} has no live "has_status" edge — graph invariant violation (every live issue must carry exactly one live status).`);const o=await fe(e,r.dst);if((o==null?void 0:o.kind)!=="status"||o.tInvalid!==null)throw new Error(`${n}: resolved status rowid=${r.dst} is missing, invalidated, or not a "status" node — graph invariant violation.`);return o}function vt(e,t){if(typeof t!="string"||t.trim().length===0)throw new I(e,"is required")}async function Ur(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`transition: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`transition: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await fe(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`transition: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata}}async function tm(e,t,n){if(!qt(e))return"unverified";try{const{accepted:r,candidate:o}=await Di(e.metadata.path,t,n);if(!r)return"unverified";const i=await Ct.readFile(o);return ue.createHash("sha256").update(i).digest("hex")}catch(r){if(ro(r))return"unverified";throw Ki(r,t)}}function nm(e,t){if(e.length>0&&!e.includes(t))throw new I("toStatus",`"${t}" is not in this project's allowed status set`)}function om(e,t){for(const n of e){if(!(n in t))continue;const r=t[n];if(r==null||typeof r=="string"&&r.trim().length===0)throw new I(n,"is required by this project's field policy")}}async function rm(e,t){vt("uid",t.uid),vt("by",t.by),Q("by",t.by),vt("toStatus",t.toStatus),Ns(t.gitContext);const n=t.citations??[];n.forEach((o,i)=>vt(`citations[${i}].file`,o.file));const r=[];if(n.length>0){const o=await Bt(e.adapter,t.uid);if((o==null?void 0:o.kind)!=="issue"||o.tInvalid!==null)throw new Ft(t.uid);const i=await Ur(e.adapter,o.rowid),s=Le(i);for(const a of n){const c=await tm(i,a.file,s.citationAllowedExternalRoots);if(c==="unverified"&&s.citationRequiresSha){if(qt(i))throw new io(a.file,s.citationAllowedExternalRoots);console.error(`transition: citation_requires_sha waived for path-less project uid="${i.uid}" — cannot verify citation "${a.file}", persisting sha:"unverified" (set the project's metadata.path to make citation_requires_sha enforceable).`)}r.push(c)}}return z(e,async o=>{var j;const i=V(),s=await we(o,t.uid),a=await Ur(o,s.rowid),c=Le(a),{claimedBy:d,claimedAt:l}=Os(s.metadata);if(d!==void 0&&d!==t.by&&!Is(l,i,c.claimStaleAfterMin))throw new _t(d,l??i);const u=await Ts(o,s.rowid,"transition"),f=u.name??"",g=await he(o,{catalogKind:"status",ref:t.toStatus,at:i,mintMetadata:async()=>({terminal:!1})});nm(c.allowedStatuses,g.name),om(c.requiredFields,{status:g.name,note:t.note});const p=await fe(o,g.rowid),m=((j=p==null?void 0:p.metadata)==null?void 0:j.terminal)===!0;if(!(typeof t.note=="string"&&t.note.trim().length>0)&&c.transitionRequiresNote)throw new Hi(s.uid);if(m&&c.citationRequired&&n.length===0)throw new Vi(s.uid);const h={target_uid:s.uid,from:f,to:g.name,agent:t.by,note:t.note??null,at:i},y=so(Wi(h)),w=await J(o,{kind:"transition",content:t.note??"",metadata:{from_status:f,to_status:g.name,agent:t.by,note:t.note??null,sha:y,at:i},at:i}),b=await F(o,"has_transition");await M(o,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:w.rowid,dstUid:w.uid,dstKind:"transition",rel:"has_transition",rule:b,typePolicy:e.typePolicy}),await _e(o,{srcRowid:s.rowid,dstRowid:u.rowid,rel:"has_status",reason:`transitioned to "${g.name}"`,at:i});const S=await F(o,"has_status");if(await M(o,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:g.rowid,dstUid:g.uid,dstKind:"status",rel:"has_status",rule:S,typePolicy:e.typePolicy}),n.length>0){const N=await F(o,"has_citation");for(let _=0;_<n.length;_+=1){const R=n[_],T=r[_],C=await J(o,{at:i,kind:"citation",name:R.file,content:R.context??R.file,metadata:{target:R.file,target_type:"path",sha:T,line:R.lines??null,at:i,symbol:R.symbol??null,blastRadius:R.blastRadius??null}});await M(o,{at:i,srcRowid:s.rowid,srcUid:s.uid,srcKind:"issue",dstRowid:C.rowid,dstUid:C.uid,dstKind:"citation",rel:"has_citation",rule:N,typePolicy:e.typePolicy})}}const E={...s.metadata??{}};m?E.closedAt=i:delete E.closedAt,typeof t.gitContext=="string"&&t.gitContext.trim().length>0&&(E.gitContext=t.gitContext);const A=await o.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(E),i,s.rowid]);if(A.rowsAffected!==1)throw new Error(`transition: closedAt touch UPDATE affected ${A.rowsAffected} rows for rowid=${s.rowid}, expected exactly 1.`);return await U({tx:o,typePolicy:e.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:t.by,action:"transitioned",from:f,to:g.name,note:t.note,at:i}),{uid:s.uid,fromStatus:f,toStatus:g.name,closedAt:m?i:void 0,transitionUid:w.uid}})}function Dr(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}async function im(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`claim: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[n.src,"owns_project"]);if(!r)throw new Error(`claim: component rowid=${n.src} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const o=await fe(e,r.src);if((o==null?void 0:o.kind)!=="project"||o.tInvalid!==null)throw new Error(`claim: resolved project rowid=${r.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);const i={rowid:o.rowid,uid:o.uid,name:o.name??"",metadata:o.metadata};return Le(i)}async function Ke(e,t,n,r){const o=await e.executeRun("UPDATE node SET meta = ?, t_updated = ? WHERE rowid = ?",[JSON.stringify(n),r,t]);if(o.rowsAffected!==1)throw new Error(`claim: touch UPDATE affected ${o.rowsAffected} rows for rowid=${t}, expected exactly 1.`)}async function sm(e,t){if(Dr("uid",t.uid),Dr("by",t.by),Q("by",t.by),t.action!=="claim"&&t.action!=="release"&&t.action!=="renew")throw new I("action",`must be "claim", "release", or "renew" (got ${JSON.stringify(t.action)})`);const n=t.force===!0;return z(e,async r=>{var d;const o=V(),i=await we(r,t.uid),s={...i.metadata??{}},{claimedBy:a,claimedAt:c}=Os(s);if(t.action==="claim"){const l=await Ts(r,i.rowid,"claim");if(((d=l.metadata)==null?void 0:d.terminal)===!0)throw new qi(i.uid,l.name??"");if(a===void 0){const m={...s,claimedBy:t.by,claimedAt:o};return await Ke(r,i.rowid,m,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"claimed",to:t.by,at:o}),{uid:i.uid,status:"claimed",claimedBy:t.by,claimedAt:o}}if(a===t.by){const m={...s,claimedAt:o};return await Ke(r,i.rowid,m,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"claimed",from:t.by,to:t.by,note:"re-affirmed (held)",at:o}),{uid:i.uid,status:"held",heldBy:t.by,claimedBy:t.by,claimedAt:o}}const u=await im(r,i.rowid),f=Rs(c,o),g=Is(c,o,u.claimStaleAfterMin);if(!g&&!n)throw new _t(a,c??o);const p={...s,claimedBy:t.by,claimedAt:o,previousClaimant:a};return await Ke(r,i.rowid,p,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"reclaimed-stale",from:a,to:t.by,note:g?`stale claim reclaimed after ~${Math.floor(f)}min (threshold ${u.claimStaleAfterMin}min)`:"force override of a non-stale claim",at:o}),{uid:i.uid,status:"reclaimed-stale",claimedBy:t.by,claimedAt:o,previousClaimant:a}}if(t.action==="release"){if(a===t.by){const l={...s};return delete l.claimedBy,delete l.claimedAt,await Ke(r,i.rowid,l,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"released",from:t.by,at:o}),{uid:i.uid,status:"released"}}return{uid:i.uid,status:"release-noop",wasClaimedBy:a}}if(a===t.by){const l={...s,claimedAt:o};return await Ke(r,i.rowid,l,o),await U({tx:r,typePolicy:e.typePolicy,subjectRowid:i.rowid,subjectUid:i.uid,subjectKind:"issue",actor:t.by,action:"renewed",from:t.by,to:t.by,at:o}),{uid:i.uid,status:"renewed",claimedBy:t.by,claimedAt:o}}throw new _t(a??"",c??"")})}const Mr=["relates_to","supersedes","blocks","duplicate_of","part_of"];function sn(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}async function am(e,t,n,r){const o=await e.executeGet("SELECT rowid FROM edge WHERE src = ? AND dst = ? AND rel = ? AND t_invalid IS NULL",[t,n,r]);return o?o.rowid:null}async function cm(e,t){if(sn("sourceUid",t.sourceUid),sn("targetUid",t.targetUid),sn("by",t.by),Q("by",t.by),!Mr.includes(t.rel))throw new I("rel",`must be one of ${Mr.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.rel)})`);if(t.action!=="add"&&t.action!=="remove")throw new I("action",`must be "add" or "remove" (got ${JSON.stringify(t.action)})`);if(t.sourceUid===t.targetUid)throw new I("targetUid","a self-relation (sourceUid === targetUid) is never allowed");return z(e,async n=>{const r=V(),o=await we(n,t.sourceUid),i=await we(n,t.targetUid),s=await am(n,o.rowid,i.rowid,t.rel);if(t.action==="add"){if(s!==null)return{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"add",noop:!0};const a=await F(n,t.rel);return await M(n,{at:r,srcRowid:o.rowid,srcUid:o.uid,srcKind:"issue",dstRowid:i.rowid,dstUid:i.uid,dstKind:"issue",rel:t.rel,rule:a,typePolicy:e.typePolicy}),await U({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"related",to:i.uid,note:t.rel,at:r}),{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"add",noop:!1}}return s===null?{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"remove",noop:!0}:(await _e(n,{srcRowid:o.rowid,dstRowid:i.rowid,rel:t.rel,reason:`relate: removed by "${t.by}"`,at:r}),await U({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"unrelated",to:i.uid,note:t.rel,at:r}),{sourceUid:o.uid,targetUid:i.uid,rel:t.rel,action:"remove",noop:!1})})}function Fr(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}async function dm(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_component"]);if(!n)throw new Error(`move: issue rowid=${t} has no live "owns_component" edge — graph invariant violation (every live issue must own exactly one live parent component).`);const r=await fe(e,n.src);if((r==null?void 0:r.kind)!=="component"||r.tInvalid!==null)throw new Error(`move: resolved component rowid=${n.src} is missing, invalidated, or not a "component" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function lm(e,t){const n=await e.executeGet("SELECT src FROM edge WHERE dst = ? AND rel = ? AND t_invalid IS NULL",[t,"owns_project"]);if(!n)throw new Error(`move: component rowid=${t} has no live "owns_project" edge — graph invariant violation (every live component must be owned by exactly one live project).`);const r=await fe(e,n.src);if((r==null?void 0:r.kind)!=="project"||r.tInvalid!==null)throw new Error(`move: resolved project rowid=${n.src} is missing, invalidated, or not a "project" node — graph invariant violation.`);return{rowid:r.rowid,uid:r.uid,name:r.name??""}}async function um(e,t){return Fr("uid",t.uid),Fr("by",t.by),Q("by",t.by),z(e,async n=>{const r=V(),o=await we(n,t.uid),i=await dm(n,o.rowid),s=await lm(n,i.rowid);let a;if(t.toProject!==void 0){const l=await Ye(n,t.toProject);a={rowid:l.rowid,uid:l.uid,name:l.name}}else a=s;let c;if(t.toComponent!==void 0?c=await co(n,{projectUid:a.uid,ref:t.toComponent}):c=await zi(n,{projectRowid:a.rowid}),c.rowid===i.rowid)return{uid:o.uid,noop:!0,fromProject:s.uid,toProject:a.uid,fromComponent:i.uid,toComponent:c.uid};await _e(n,{srcRowid:i.rowid,dstRowid:o.rowid,rel:"owns_component",reason:`moved to component "${c.name}"`,at:r});const d=await F(n,"owns_component");return await M(n,{at:r,srcRowid:c.rowid,srcUid:c.uid,srcKind:"component",dstRowid:o.rowid,dstUid:o.uid,dstKind:"issue",rel:"owns_component",rule:d,typePolicy:e.typePolicy}),await U({tx:n,typePolicy:e.typePolicy,subjectRowid:o.rowid,subjectUid:o.uid,subjectKind:"issue",actor:t.by,action:"moved",from:i.uid,to:c.uid,at:r}),{uid:o.uid,noop:!1,fromProject:s.uid,toProject:a.uid,fromComponent:i.uid,toComponent:c.uid}})}function an(e,t){if(t===void 0||t.trim().length===0)throw new I(e,"is required")}async function fm(e,t){an("uid",t.uid),an("by",t.by),Q("by",t.by),an("reason",t.reason);let n;const r=await z(e,async o=>{const i=V(),s=await we(o,t.uid);n={rowid:s.rowid,uid:s.uid};const a={...s.metadata??{},invalidatedReason:t.reason,invalidatedAt:i},c=await o.executeRun("UPDATE node SET t_invalid = ?, meta = ? WHERE rowid = ?",[i,JSON.stringify(a),s.rowid]);if(c.rowsAffected!==1)throw new Error(`deleteIssue: invalidate UPDATE affected ${c.rowsAffected} rows for uid="${t.uid}", expected exactly 1.`);return await U({tx:o,typePolicy:e.typePolicy,subjectRowid:s.rowid,subjectUid:s.uid,subjectKind:"issue",actor:t.by,action:"deleted",note:t.reason,at:i}),{uid:s.uid,invalidated:!0}});if(n){const o=Ot(e,{action:"delete",subjectRowid:n.rowid,subjectUid:n.uid,actor:t.by});t.awaitEmbed?await o:o.catch(()=>{})}return r}function Tt(e){var t;return(t=e.env.version)==null?void 0:t.configHash}async function $s(e){const t=e.embeddingConfig;t!=null&&t.refresh().changed&&Rp(e.store.adapter);const n=t?t.current():e.env.config.embedding;return Np(e.store.adapter,e.store.graph,n,void 0,{configuredEnabled:t?t.configured().enabled:n==null?void 0:n.enabled,startupHash:Tt(e),configuredHash:t?t.fingerprint().configHash:Tt(e),configPaths:t?t.fingerprint().files.map(r=>r.path):void 0})}async function Z(e,t){await oo(e.store.adapter);const{search:n,embedding:r}=t.needsSemantic?await $s(e):{};return{adapter:e.store.adapter,typePolicy:e.store.typePolicy,graph:e.store.graph,...n!==void 0?{search:n}:{},...r!==void 0?{embedding:r}:{}}}async function Ht(e,t){const{search:n}=t.needsSemantic?await $s(e):{},r=n!==void 0&&t.probeSpace?await n.spacePopulated():void 0;return{graph:e.store.graph,assertVocabulary:()=>oo(e.store.adapter),...n!==void 0?{search:n}:{},...r!==void 0?{spacePopulated:r}:{}}}const pm=[[Ft,"item_not_found"],[G,"not_found"],[I,"invalid_argument"],[_t,"conflict"],[On,"conflict"],[Mt,"conflict"],[qi,"precondition_failed"],[Vi,"precondition_failed"],[Hi,"precondition_failed"],[io,"precondition_failed"],[Mi,"store_busy"],[Es,"rag_not_configured"]],mm={E_VALIDATION:"validation",E_CONTENTION:"store_busy",E_IO:"internal",E_CONSTRAINT:"conflict"};function Cs(e){for(const[t,n]of pm)if(e instanceof t){const r=e instanceof B?{retryable:e.retryable,...e.retry_after_ms===void 0?{}:{retryAfterMs:e.retry_after_ms}}:void 0;return le(n,e.message,r)}return e instanceof B?le(mm[e.code]??"internal",e.message,{retryable:e.retryable,...e.retry_after_ms===void 0?{}:{retryAfterMs:e.retry_after_ms}}):le("internal",e instanceof Error?e.message:String(e))}async function H(e){try{return ho(await e())}catch(t){return Cs(t)}}async function Ps(e,t){return H(()=>"registry"in t?t.registry==="project"?rn(e.store.graph,{registry:"project",name:t.name}):t.registry==="component"?rn(e.store.graph,{registry:"component",name:t.name,filter:t.filter}):rn(e.store.graph,{registry:"location",name:t.name}):Tp(e.store.graph,t))}async function xs(e,t){try{const{result:n,meta:r}=await Sp(await Ht(e,{needsSemantic:yp(t),probeSpace:t.text!==void 0}),t);return ho(n,r?{meta:r}:void 0)}catch(n){return Cs(n)}}async function Ls(e,t){return H(async()=>Lp(await Ht(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Us(e,t){return H(async()=>Dp(await Ht(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Ds(e,t){return H(async()=>qp(await Ht(e,{needsSemantic:!1,probeSpace:!1}),t))}async function Ms(e){return H(async()=>{const t=e.embeddingConfig,n=t?t.configured():e.env.config.embedding,r=t?t.current():e.env.config.embedding,o=Op(e.store.adapter);return{configuredEnabled:(n==null?void 0:n.enabled)===!0,effectiveEnabled:(r==null?void 0:r.enabled)===!0,provider:(r==null?void 0:r.provider)??"",model:(r==null?void 0:r.model)??"",membersPresent:{embedding:(o==null?void 0:o.embedding)??!1,search:(o==null?void 0:o.search)??!1},divergent:(n==null?void 0:n.enabled)===!0!=((r==null?void 0:r.enabled)===!0),startupHash:Tt(e)??"",currentHash:t?t.fingerprint().configHash:Tt(e)??""}})}async function Fs(e,t){return H(()=>Zf(e.store.graph,t.q))}async function Bs(e,t){return H(async()=>Gp(await Z(e,{needsSemantic:!0}),t))}async function qs(e,t){return H(async()=>em(await Z(e,{needsSemantic:!0}),t))}async function Ks(e,t){return H(async()=>rm(await Z(e,{needsSemantic:!1}),t))}async function Hs(e,t){return H(async()=>sm(await Z(e,{needsSemantic:!1}),t))}async function Vs(e,t){return H(async()=>cm(await Z(e,{needsSemantic:!1}),t))}async function Gs(e,t){return H(async()=>um(await Z(e,{needsSemantic:!1}),t))}async function Js(e,t){return H(async()=>fm(await Z(e,{needsSemantic:!1}),t))}async function Ws(e,t){return H(async()=>Dl(await Z(e,{needsSemantic:!1}),t))}async function zs(e,t){return H(async()=>Fl(await Z(e,{needsSemantic:!1}),t))}async function Ys(e,t){return H(async()=>ql(await Z(e,{needsSemantic:!1}),t))}async function Xs(e,t){return H(async()=>Kl(await Z(e,{needsSemantic:!1}),t))}const gm=Object.freeze(Object.defineProperty({__proto__:null,claim:Hs,create:Bs,delete:Js,embeddingStatus:Ms,get:Ps,lookup:Fs,move:Gs,openCurve:Ds,partOfRollup:Us,priorityMatrix:Ls,query:xs,relate:Vs,rmLocation:Xs,transition:Ks,update:qs,upsertComponent:zs,upsertLocation:Ys,upsertProject:Ws},Symbol.toStringTag,{value:"Module"}));async function hm(e){let t;try{t=await ge.open(e,"r"),await t.sync()}catch{}finally{t&&await t.close().catch(()=>{})}}async function Qs(e,t){const n=k.dirname(e);await ge.mkdir(n,{recursive:!0});const r=`${e}.${process.pid}.${ue.randomUUID()}.tmp`;let o;try{o=await ge.open(r,"w"),await o.writeFile(JSON.stringify(t),"utf8"),await o.sync(),await o.close(),o=void 0,await ge.rename(r,e),await hm(n)}catch(i){throw o&&await o.close().catch(()=>{}),await ge.unlink(r).catch(()=>{}),i}}function ym(e){return{async get(){try{const t=await ge.readFile(e,"utf8");return JSON.parse(t)}catch{return}},async put(t,n){await Qs(e,n)}}}const Ze=1;function wm(e){return ue.createHash("sha256").update(e).digest("hex")}async function Br(e){return wm(await ge.readFile(e,"utf8"))}async function $t(e){try{return(await ge.stat(e)).mtimeMs}catch{return}}async function qr(e,t){const n=await Br(e.source),r=ue.createHash("sha256");r.update(`formatVersion:${Ze}
216
+ `),r.update(`extractorVersion:${t}
217
+ `),r.update(`host:${e.host}
218
+ `),r.update(`namespace:${e.namespace??""}
219
+ `),r.update(`source:${n}
220
+ `);for(const o of ui(e.source))o!==e.source&&r.update(`dep:${o}:${await Br(o)}
221
+ `);return r.digest("hex")}async function Kr(e,t){const n=await $t(e.source)??0,r=[];for(const o of ui(e.source)){if(o===e.source)continue;const i=await $t(o);i!==void 0&&r.push({path:o,mtimeMs:i})}return{contentKey:t,source:{path:e.source,mtimeMs:n},deps:r}}async function vm(e,t){if(t.source.path!==e.source)return!1;const n=await $t(t.source.path);if(n===void 0||n!==t.source.mtimeMs)return!1;for(const r of t.deps){const o=await $t(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function bm(e){if(e.cache==="artifact")throw new Error("apigen-plugin-ir-cache: createIrCacheLayer() (the RUNTIME CACHE 'extractLayer' capability) received cache: 'artifact'. That value selects the ARTIFACT-mode 'target' capability instead (--type ir-cache --opt cache=artifact) — a file path is required here. See docs/apigen/design-notes/extract-stage-onion-and-ir-cache.md Revision 2 (R2.2).");const t=ym(e.cache),n=e.extractorVersion;async function r(o,i,s){const a=s??await qr(o,n),c=await Kr(o,a);await t.put(e.cache,{formatVersion:Ze,operations:i,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,i)=>{const s=await t.get(e.cache);if((s==null?void 0:s.formatVersion)!==Ze||s.extractorVersion!==n||!s.staleness){const d=await i();try{await r(o,d)}catch{}return d}if(await vm(o,s.staleness))return s.operations;const a=await qr(o,n);if(a===s.staleness.contentKey)return Kr(o,a).then(d=>t.put(e.cache,{...s,staleness:d})).catch(()=>{}),s.operations;const c=await i();try{await r(o,c,a)}catch{}return c}}Fn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href);const Sm="api.ir.json",Em=Fn.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href),yo=Em("@adhd/apigen-core-client/package.json").version;function Vt(){const e=k.dirname(et.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href));return O.existsSync(k.join(e,"api.d.ts"))?e:k.join(e,"..","dist")}function km(e){return k.join(e,Sm)}function wo(e){return ue.createHash("sha256").update(e).digest("hex")}function Zs(e){const t=[],n=o=>{let i;try{i=O.readdirSync(o,{withFileTypes:!0})}catch{return}for(const s of i){const a=k.join(o,String(s.name));s.isDirectory()?n(a):s.isFile()&&String(s.name).endsWith(".d.ts")&&t.push(a)}};n(e),t.sort();const r={};for(const o of t)r[k.relative(e,o).split(k.sep).join("/")]=wo(O.readFileSync(o));return r}function Am(e,t){const n=Object.keys(e).sort(),r=Object.keys(t).sort();if(n.length!==r.length)return!1;for(let o=0;o<n.length;o++){const i=n[o];if(i!==r[o]||e[i]!==t[i])return!1}return!0}function jm(e){try{const t=km(e);if(!O.existsSync(t))return;const n=JSON.parse(O.readFileSync(t,"utf8"));if(!n||typeof n!="object"||n.formatVersion!==Ze||n.extractorVersion!==yo)return;const r=n.artifactSource;if(!r||typeof r.sha256!="string"||typeof r.bytes!="number"||!Array.isArray(n.operations)||n.operations.length===0)return;const o=k.join(e,"api.d.ts");if(!O.existsSync(o))return;const i=O.readFileSync(o);if(i.byteLength!==r.bytes||wo(i)!==r.sha256)return;const s=r.deps;if(s===null||typeof s!="object"||Array.isArray(s))return;for(const a of Object.values(s))if(typeof a!="string")return;return Am(s,Zs(e))?n.operations:void 0}catch{return}}async function _m(e){const t=O.readFileSync(e.apiDts),n={formatVersion:Ze,operations:e.operations,extractorVersion:e.extractorVersion,createdAt:new Date().toISOString(),artifactSource:{path:e.apiDts,sha256:wo(t),bytes:t.byteLength,deps:Zs(k.dirname(e.apiDts))}};await Qs(e.outFile,n)}function Nm(e={}){const t=uo("backlog",Ue,{namespace:e.namespace??"production",scope:fo(e.scope),...e.adhdRoot!==void 0?{adhdRoot:e.adhdRoot}:{},...e.cwd!==void 0?{cwd:e.cwd}:{}}),n=[k.join(t.roots.system,Te),k.join(t.roots.global,Te)];return t.roots.project&&(n.push(k.join(t.roots.project,Te)),n.push(k.join(t.roots.project,es))),[...new Set(n)]}const Om=e=>e instanceof Error?e.message:String(e),Hr=e=>({enabled:e.enabled===!0,provider:e.provider,model:e.model}),Rm=(e,t)=>e.enabled===t.enabled&&e.provider===t.provider&&e.model===t.model;function Im(e){const t=()=>e.layerFiles().map(a=>{try{const c=O.statSync(a);return{path:a,stamp:`${c.mtimeMs}:${c.size}`}}catch{return{path:a,stamp:"absent"}}}),n=(a,c)=>a.length===c.length&&a.every((d,l)=>d.path===c[l].path&&d.stamp===c[l].stamp);let r=Hr(e.baseline.config.embedding),o=r,i={configHash:e.baseline.version.configHash,files:t()};const s=()=>{const a=t();if(n(a,i.files))return!1;let c;try{c=e.rebuild()}catch(d){return e.log("warn",`backlog: could not re-read the embedding config layers (${Om(d)}) — continuing with the last known effective embedding settings`),!1}return i={configHash:c.version.configHash,files:a},o=Hr(c.config.embedding),!0};return{current:()=>r,configured:()=>(s(),o),divergent:()=>(s(),o.enabled&&!r.enabled),refresh:()=>{const a=r;return s(),Rm(o,r)?{changed:!1,from:a,to:r}:(r=o,e.log("info",`backlog: embedding config changed on disk (enabled ${a.enabled}→${r.enabled}, provider ${r.provider}, model ${r.model}); adopting without restart`),{changed:!0,from:a,to:r})},fingerprint:()=>i}}function Tm(){const e=k.dirname(et.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)),t=k.join(e,"package.json");return O.existsSync(t)?t:k.join(e,"..","package.json")}function vo(){const e=Tm(),t=JSON.parse(O.readFileSync(e,"utf8"));return{name:t.name,version:t.version}}function Dn(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function ea(){if(!process.env.VITEST)return;const e=()=>{},t={info:e,error:e,debug:e,fatal:e,warn:e,trace:e};return t.child=()=>t,t}const Vr=["install","install-skill","serve"];function ta(e){return e.filter(t=>t.kind==="action").map(t=>{const n=Me(t);return{id:t.id,cliCommand:n.cli.path.join(" "),cliPath:n.cli.path,mcpTool:n.mcp.name,httpVerb:n.http.verb,httpRoute:n.http.route}}).sort((t,n)=>t.id.localeCompare(n.id))}function $m(e){const t=e.filter(n=>{const r=n.cliPath[n.cliPath.length-1]??"";return Vr.includes(r)||Vr.some(o=>n.mcpTool.endsWith(`_${o.replace(/-/g,"_")}`))});if(t.length>0)throw new Error(`@adhd/backlog: host-command carve-out violated (SPEC.md §6.6) — ${t.map(n=>n.id).join(", ")} was mounted as a data operation. install/install-skill must never open the store (DEBT-BACKLOG-CLI-EAGER-STORE-OPEN-001) and serve must never be reachable as a tool — it has a completely different lifecycle than a mounted data operation. Keep them host commands in cli.ts.`)}function Cm(e,t=[jt]){const n=ta(e),r=new Set(n.map(i=>i.mcpTool)),o={host:"backlog",operations:e};for(const i of t){const s=i.capabilities.mount;if(s)for(const a of s.operations(o,void 0,void 0))r.add(Me(a).mcp.name)}return[...r].sort()}function Gr(e){if(!e||typeof e!="object")return e;const t={},n=o=>{if(Array.isArray(o)){for(const s of o)n(s);return}if(!o||typeof o!="object")return;const i=o;for(const s of["definitions","$defs"]){const a=i[s];if(a&&typeof a=="object"&&!Array.isArray(a))for(const[c,d]of Object.entries(a))c in t||(t[c]=d)}for(const[s,a]of Object.entries(i))s==="definitions"||s==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;const r=(o,i)=>{if(Array.isArray(o))return o.map(d=>r(d,i));if(!o||typeof o!="object")return o;const s=o,a=s.$ref;if(typeof a=="string"){const d=a.replace(/^#\/(?:definitions|\$defs)\//,"");return i.has(d)||!(d in t)?{}:r(t[d],new Set([...i,d]))}const c={};for(const[d,l]of Object.entries(s))d==="definitions"||d==="$defs"||(c[d]=r(l,i));return c};return r(e,new Set)}async function Pm(e={}){const t=Vt(),n=k.join(t,"api.d.ts");if(!O.existsSync(n))throw new Error(`@adhd/backlog: cannot mount — ${n} does not exist. Run "nx build backlog" first (the mounted surface is derived from the built .d.ts).`);const r=jm(t);return r||(await Promise.resolve().then(()=>ha)).extractApiOperationsLive(e)}async function bo(e,t={}){const n=typeof e=="function"?e:()=>e,r=await Pm(t),o={schemas:Object.fromEntries(r.filter(c=>c.kind==="action").map(c=>{var d;return[((d=c.path[c.path.length-1])==null?void 0:d.raw)??"",{input:Gr(c.input),output:Gr(c.output),hasCtx:c.hasCtx,safe:c.safe}]}))},i=oc(o,[]),s=ta(r);$m(s);const{version:a}=vo();return{pkg:{id:"backlog",version:a,schemas:i,importPath:k.join(Vt(),"api.js"),fns:gm,createClient:async()=>n()},operations:r,surface:s}}async function na(e){const t=$e({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace});t.ensureDirs();let n,r;const o=Ge(t),i=()=>(n||(n=In(r)),n),s=Jl()?void 0:Qi(i);try{r=await Rt(o,t.config.db.busyTimeoutMs)}catch(c){throw s==null||s.dispose(),c}const a={store:r,env:t,embeddingConfig:Im({baseline:t,rebuild:()=>$e({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace}),layerFiles:()=>Nm({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd,namespace:e.namespace}),log:(c,d)=>console.error(d)})};try{const{pkg:c,operations:d}=await bo(a,{adhdRoot:e.adhdRoot}),l=ea(),u=[];(e.transport==="http"||e.transport==="both")&&u.push(Dn(Xu)({packages:[c],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[nf,jt]},signal:e.signal,operations:d,logger:l})),(e.transport==="mcp"||e.transport==="both")&&u.push(Dn(wf)({packages:[c],outputDir:"",options:{transport:"stdio",usePlugins:[jt]},signal:e.signal,operations:d,logger:l})),await Promise.all(u)}finally{s==null||s.dispose(),await i()}}const Pe=["claude","codex","opencode"],xm={claude:".claude",codex:".codex",opencode:".opencode"};function oa(e,t){return t?k.join(e,".codex"):process.env.CODEX_HOME??k.join(e,".codex")}function Lm(e,t,n,r){if(t==="project")return k.join(n,xm[e],"skills");const o=r??W.homedir();return e==="claude"?k.join(o,".claude","skills"):e==="codex"?k.join(oa(o,r),"skills"):k.join(o,".config","opencode","skills")}function Um(){const e=k.dirname(et.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)),t=k.join(e,"skill","SKILL.md");return O.existsSync(t)?t:k.join(e,"..","skill","SKILL.md")}class X extends Error{constructor(t){super(t),this.name="BacklogUsageError"}}function So(e,t){console.error(JSON.stringify({code:"invalid_argument",message:e.message})),console.error(""),console.error(t),process.exitCode=2}const Jr=`backlog install-skill [--host claude|codex|opencode|all] [--scope user|project]
522
222
 
523
223
  Copies the packaged backlog SKILL.md into an agent host's skills directory.
524
224
  (\`backlog install\` is the richer successor — it also registers the MCP server.)
@@ -532,16 +232,16 @@ Examples:
532
232
  backlog install-skill
533
233
  backlog install-skill --host opencode --scope user
534
234
  backlog install-skill --host claude --scope project
535
- `;function EK(t){let e="all",n="user";for(let o=0;o<t.length;o++){const s=t[o];if(s==="--host")e=t[++o]??"all";else if(s==="--scope")n=t[++o]??"user";else throw new ht(`backlog install-skill: unknown argument "${s}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project"){const o=n==="global"?' — the machine-wide scope is spelled "user"':"";throw new ht(`backlog install-skill: --scope must be "user" or "project", got "${n}"${o}`)}const r=e==="all"?[...Yr]:[e];for(const o of r)if(!Yr.includes(o))throw new ht(`backlog install-skill: --host must be one of ${Yr.join("|")}|all, got "${e}"`);return{hosts:r,scope:n}}function Kb(t,e=process.cwd(),n){const{hosts:r,scope:o}=EK(t);return Vb(r,o,e,n)}function Vb(t,e,n,r){const o=bK();if(!J.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const s=J.readFileSync(o,"utf8"),i=L.dirname($s.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href)),a=L.join(i,"package.json"),c=J.existsSync(a)?a:L.join(i,"..","package.json"),u=JSON.parse(J.readFileSync(c,"utf8")),l=[];for(const d of t){const f=L.join($K(d,e,n,r),"backlog");J.mkdirSync(f,{recursive:!0});const g=L.join(f,"SKILL.md");J.writeFileSync(g,s,"utf8"),J.writeFileSync(L.join(f,"extension.json"),JSON.stringify({name:u.name,version:u.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
536
- `,"utf8"),l.push({host:d,scope:e,path:g})}return l}async function Gb(t){if(t.includes("--help")||t.includes("-h")){console.log(xg);return}let e;try{e=Kb(t)}catch(n){if(n instanceof ht)return lp(n,xg);throw n}console.log(JSON.stringify({installed:e}))}const dp=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function SK(t){if(!J.existsSync(t))return{};const e=J.readFileSync(t,"utf8").trim();if(e==="")return{};const n=JSON.parse(e);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`backlog install: expected ${t} to contain a JSON object, got ${Array.isArray(n)?"an array":typeof n}`);return n}function zb(t,e,n,r){const o=SK(t),s=o[e],i=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:{};i[n]=r,o[e]=i,J.mkdirSync(L.dirname(t),{recursive:!0}),J.writeFileSync(t,JSON.stringify(o,null,2)+`
537
- `,"utf8")}function _K(t,e,n){if(t==="project")return L.join(e,".mcp.json");const r=mt.homedir();return L.join(r,".claude.json")}function NK(t,e,n){if(t==="project")return L.join(e,"opencode.json");const r=mt.homedir();return L.join(r,".config","opencode","opencode.json")}function OK(t,e,n){if(t==="project")return L.join(e,".codex","config.toml");const r=mt.homedir();return L.join(qb(r,n),"config.toml")}function kK(t,e,n){var u,l;const r=`[${e}]`,o=t.length>0?t.split(`
538
- `):[],s=o.findIndex(d=>d.trim()===r),i=[r,...n];if(s===-1){if(o.length===0||o.every(d=>d.trim()===""))return i.join(`
235
+ `;function Dm(e){let t="all",n="user";for(let o=0;o<e.length;o++){const i=e[o];if(i==="--host")t=e[++o]??"all";else if(i==="--scope")n=e[++o]??"user";else throw new X(`backlog install-skill: unknown argument "${i}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project"){const o=n==="global"?' — the machine-wide scope is spelled "user"':"";throw new X(`backlog install-skill: --scope must be "user" or "project", got "${n}"${o}`)}const r=t==="all"?[...Pe]:[t];for(const o of r)if(!Pe.includes(o))throw new X(`backlog install-skill: --host must be one of ${Pe.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function ra(e,t=process.cwd(),n){const{hosts:r,scope:o}=Dm(e);return ia(r,o,t,n)}function ia(e,t,n,r){const o=Um();if(!O.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const i=O.readFileSync(o,"utf8"),s=k.dirname(et.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)),a=k.join(s,"package.json"),c=O.existsSync(a)?a:k.join(s,"..","package.json"),d=JSON.parse(O.readFileSync(c,"utf8")),l=[];for(const u of e){const f=k.join(Lm(u,t,n,r),"backlog");O.mkdirSync(f,{recursive:!0});const g=k.join(f,"SKILL.md");O.writeFileSync(g,i,"utf8"),O.writeFileSync(k.join(f,"extension.json"),JSON.stringify({name:d.name,version:d.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
236
+ `,"utf8"),l.push({host:u,scope:t,path:g})}return l}async function sa(e){if(e.includes("--help")||e.includes("-h")){console.log(Jr);return}let t;try{t=ra(e)}catch(n){if(n instanceof X)return So(n,Jr);throw n}console.log(JSON.stringify({installed:t}))}const Eo=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function Mm(e){if(!O.existsSync(e))return{};const t=O.readFileSync(e,"utf8").trim();if(t==="")return{};const n=JSON.parse(t);if(typeof n!="object"||n===null||Array.isArray(n))throw new Error(`backlog install: expected ${e} to contain a JSON object, got ${Array.isArray(n)?"an array":typeof n}`);return n}function aa(e,t,n,r){const o=Mm(e),i=o[t],s=typeof i=="object"&&i!==null&&!Array.isArray(i)?i:{};s[n]=r,o[t]=s,O.mkdirSync(k.dirname(e),{recursive:!0}),O.writeFileSync(e,JSON.stringify(o,null,2)+`
237
+ `,"utf8")}function Fm(e,t,n){if(e==="project")return k.join(t,".mcp.json");const r=W.homedir();return k.join(r,".claude.json")}function Bm(e,t,n){if(e==="project")return k.join(t,"opencode.json");const r=W.homedir();return k.join(r,".config","opencode","opencode.json")}function qm(e,t,n){if(e==="project")return k.join(t,".codex","config.toml");const r=W.homedir();return k.join(oa(r,n),"config.toml")}function Km(e,t,n){var d,l;const r=`[${t}]`,o=e.length>0?e.split(`
238
+ `):[],i=o.findIndex(u=>u.trim()===r),s=[r,...n];if(i===-1){if(o.length===0||o.every(u=>u.trim()===""))return s.join(`
539
239
  `)+`
540
- `;for(;o.length>0&&((u=o[o.length-1])==null?void 0:u.trim())==="";)o.pop();return[...o,"",...i].join(`
240
+ `;for(;o.length>0&&((d=o[o.length-1])==null?void 0:d.trim())==="";)o.pop();return[...o,"",...s].join(`
541
241
  `)+`
542
- `}let a=s+1;for(;a<o.length&&!(((l=o[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...o.slice(0,s),...i,...o.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
242
+ `}let a=i+1;for(;a<o.length&&!(((l=o[a])==null?void 0:l.trim().startsWith("["))??!0);)a++;const c=[...o.slice(0,i),...s,...o.slice(a)];for(;c.length>0&&c[c.length-1]==="";)c.pop();return c.join(`
543
243
  `)+`
544
- `}function jK(t){return`[${t.map(e=>JSON.stringify(e)).join(", ")}]`}function AK(t,e,n){const r=_K(t,e);return zb(r,"mcpServers","backlog",{type:"stdio",command:"npx",args:[...dp]}),{host:"claude",scope:t,configPath:r,status:"written"}}function IK(t,e,n){const r=NK(t,e);return zb(r,"mcp","backlog",{type:"local",command:["npx",...dp]}),{host:"opencode",scope:t,configPath:r,status:"written"}}function PK(t,e,n){const r=OK(t,e,n),o=J.existsSync(r)?J.readFileSync(r,"utf8"):"",s=kK(o,"mcp_servers.backlog",['command = "npx"',`args = ${jK(dp)}`]);return J.mkdirSync(L.dirname(r),{recursive:!0}),J.writeFileSync(r,s,"utf8"),{host:"codex",scope:t,configPath:r,status:"written"}}function xK(t,e,n,r){return t==="claude"?AK(e,n):t==="opencode"?IK(e,n):PK(e,n,r)}function RK(t,e){let n="all",r="user",o=!1,s=!1;for(let a=0;a<t.length;a++){const c=t[a];if(c==="--host")n=t[++a]??"all";else if(c==="--scope")r=t[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")s=!0;else throw new ht(`backlog ${e}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&s)throw new ht(`backlog ${e}: --skill-only and --mcp-only are mutually exclusive`);if(r!=="user"&&r!=="project"){const a=r==="global"?' — the machine-wide scope is spelled "user"':"";throw new ht(`backlog ${e}: --scope must be "user" or "project", got "${r}"${a}`)}const i=n==="all"?[...Yr]:[n];for(const a of i)if(!Yr.includes(a))throw new ht(`backlog ${e}: --host must be one of ${Yr.join("|")}|all, got "${n}"`);return{hosts:i,scope:r,skillOnly:o,mcpOnly:s}}const Rg=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
244
+ `}function Hm(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function Vm(e,t,n){const r=Fm(e,t);return aa(r,"mcpServers","backlog",{type:"stdio",command:"npx",args:[...Eo]}),{host:"claude",scope:e,configPath:r,status:"written"}}function Gm(e,t,n){const r=Bm(e,t);return aa(r,"mcp","backlog",{type:"local",command:["npx",...Eo]}),{host:"opencode",scope:e,configPath:r,status:"written"}}function Jm(e,t,n){const r=qm(e,t,n),o=O.existsSync(r)?O.readFileSync(r,"utf8"):"",i=Km(o,"mcp_servers.backlog",['command = "npx"',`args = ${Hm(Eo)}`]);return O.mkdirSync(k.dirname(r),{recursive:!0}),O.writeFileSync(r,i,"utf8"),{host:"codex",scope:e,configPath:r,status:"written"}}function Wm(e,t,n,r){return e==="claude"?Vm(t,n):e==="opencode"?Gm(t,n):Jm(t,n,r)}function zm(e,t){let n="all",r="user",o=!1,i=!1;for(let a=0;a<e.length;a++){const c=e[a];if(c==="--host")n=e[++a]??"all";else if(c==="--scope")r=e[++a]??"user";else if(c==="--skill-only")o=!0;else if(c==="--mcp-only")i=!0;else throw new X(`backlog ${t}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&i)throw new X(`backlog ${t}: --skill-only and --mcp-only are mutually exclusive`);if(r!=="user"&&r!=="project"){const a=r==="global"?' — the machine-wide scope is spelled "user"':"";throw new X(`backlog ${t}: --scope must be "user" or "project", got "${r}"${a}`)}const s=n==="all"?[...Pe]:[n];for(const a of s)if(!Pe.includes(a))throw new X(`backlog ${t}: --host must be one of ${Pe.join("|")}|all, got "${n}"`);return{hosts:s,scope:r,skillOnly:o,mcpOnly:i}}const Wr=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
545
245
 
546
246
  Installs the backlog skill AND registers the backlog MCP server into an agent
547
247
  host's config, in one step.
@@ -558,7 +258,7 @@ Examples:
558
258
 
559
259
  Back-compat: \`backlog install-skill\` remains available and behaves exactly
560
260
  like \`backlog install --skill-only\` (original --host/--scope grammar only).
561
- `;function TK(t,e=process.cwd(),n){const{hosts:r,scope:o,skillOnly:s,mcpOnly:i}=RK(t,"install"),a=i?[]:Vb(r,o,e,n),c=s?[]:r.map(u=>xK(u,o,e,n));return{skill:a,mcp:c}}async function CK(t){if(t.includes("--help")||t.includes("-h")){console.log(Rg);return}let e;try{e=TK(t)}catch(n){if(n instanceof ht)return lp(n,Rg);throw n}for(const n of e.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of e.mcp){const r=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${r}`)}console.log(JSON.stringify(e))}const Tg=`backlog serve [--transport mcp|http|both] [--port N] [--host H]
261
+ `;function Ym(e,t=process.cwd(),n){const{hosts:r,scope:o,skillOnly:i,mcpOnly:s}=zm(e,"install"),a=s?[]:ia(r,o,t,n),c=i?[]:r.map(d=>Wm(d,o,t,n));return{skill:a,mcp:c}}async function Xm(e){if(e.includes("--help")||e.includes("-h")){console.log(Wr);return}let t;try{t=Ym(e)}catch(n){if(n instanceof X)return So(n,Wr);throw n}for(const n of t.skill)console.error(`[backlog install] skill -> ${n.host} (${n.scope}): ${n.path}`);for(const n of t.mcp){const r=n.note?` — ${n.note}`:"";console.error(`[backlog install] mcp -> ${n.host} (${n.scope}) [${n.status}]: ${n.configPath}${r}`)}console.log(JSON.stringify(t))}const zr=`backlog serve [--transport mcp|http|both] [--port N] [--host H]
562
262
 
563
263
  Starts the long-lived backlog server (MCP and/or HTTP), matching one of the
564
264
  process's own configured transports to the way an agent host or a script
@@ -572,12 +272,12 @@ Examples:
572
272
  backlog serve
573
273
  backlog serve --transport http --port 3300
574
274
  backlog serve --transport both --host 0.0.0.0
575
- `;function MK(t){let e="mcp",n,r;for(let s=0;s<t.length;s++){const i=t[s];if(i==="--transport")e=t[++s];else if(i==="--port")n=Number(t[++s]);else if(i==="--host")r=t[++s];else throw new ht(`backlog serve: unknown argument "${i}" (expected --transport/--port/--host)`)}if(e!=="mcp"&&e!=="http"&&e!=="both")throw new ht(`backlog serve: --transport must be mcp|http|both, got "${e}"`);const o={transport:e};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function Wb(t,e={}){if(t.includes("--help")||t.includes("-h")){console.log(Tg);return}let n;try{n=MK(t)}catch(i){if(i instanceof ht)return lp(i,Tg);throw i}const r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort());const o=Fb({...n,...e,signal:r.signal}),s=e.namespace==="sandbox"?J.mkdtempSync(L.join(mt.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Lg.initTelemetry({service:"backlog",role:"live-service",logSink:"file",...s!==void 0?{logDir:s}:{}})}catch(i){console.error(`[sox-telemetry] WARNING: initTelemetry failed for serve (${i instanceof Error?i.message:String(i)}); telemetry records will be silently dropped this process`)}await o}const fp=["limit","offset","sort","direction"],Hb=["kind","plan","assignee","claimed-by","project-path","grep","anchor"],pp=["status","priority"],Wa=["fields"],LK={"claimed-by":"claimedBy","project-path":"projectPath"},Jb=[...fp,...Wa,...Hb,...pp].map(t=>`--${t}`).sort(),DK=new Set([...fp,...Wa]),UK=new Set([...pp,...Wa]),BK=new Set([...fp,...Wa,...Hb,...pp]),FK=new Set(["limit","offset"]),Qb=['backlog search "<natural-language query>" [flags]',"",'Shorthand for `backlog query --input \'{"text": "<query>", ...}\'` — the same',"command, the same JSON envelope, the same exit codes. The query text is","matched semantically when the embedding space is populated, and by keyword","(FTS) when it is not.","","Paging / ranking:"," --limit <n> max items to return"," --offset <n> skip the first n"," --sort <s> override the derived default (relevance / textMatch)"," --direction <d> asc | desc"," --fields <a,b,c> projection; add _score to see ranking scores","","Filters (all compose with the query text):"," --status <s> open | closed | OPEN,IN_PROGRESS | …"," --priority <p> CRITICAL | HIGH | MEDIUM | LOW (comma-separated for several)"," --kind <k> BUG | DEBT | FEAT | …"," --project-path <p> component's repo-relative path (component.meta.path)"," --plan <uid|title> the parent plan issue this item is filed under (part_of)"," --assignee <a> durable owner"," --claimed-by <c> ephemeral claim holder"," --grep <q> extra keyword predicate. Composes with the query text ONLY"," once the embedding space is populated — without it the query"," text IS the keyword query and the two collide (§2.1b step 1).","","More-like-this:",' --anchor <ID> nearest neighbours of an EXISTING item (view:"similar").'," Replaces the positional query rather than refining it."].join(`
576
- `);function Cg(t,e,n,r){if(!r){t[e]=n;return}const o=t[e]??[];t[e]=[...o,...n.split(",").map(s=>s.trim()).filter(s=>s.length>0)]}function Yb(t){if(t.includes("--help")||t.includes("-h"))return{kind:"help",text:Qb};const e={},n={};let r,o=0;for(;o<t.length;){const a=t[o];if(!a.startsWith("--")){if(r!==void 0)return{kind:"error",message:`Unexpected positional argument: "${a}"`};r=a,o+=1;continue}let c=a.slice(2),u;const l=c.indexOf("=");if(l!==-1&&(u=c.slice(l+1),c=c.slice(0,l)),c==="input")return{kind:"error",message:"Unknown option: --input. `search` takes the query as a positional argument; for the raw JSON form use `backlog query --input '{...}'`"};if(!BK.has(c))return{kind:"error",message:`Unknown option: --${c}. Available: ${Jb.join(", ")}`};o+=1;let d;if(u!==void 0)d=u;else{if(o>=t.length)return{kind:"error",message:`Missing value for --${c}`};d=t[o],o+=1}const f=UK.has(c);DK.has(c)?Cg(e,c,d,f):Cg(n,LK[c]??c,d,f)}for(const a of["status","priority"]){const c=n[a];c!==void 0&&c.length===1&&(n[a]=c[0])}for(const a of FK){const c=e[a];typeof c=="string"&&/^-?\d+$/.test(c)&&(e[a]=Number(c))}const s=n.anchor;if(s!==void 0&&r!==void 0)return{kind:"error",message:`Validation failed: --anchor and a positional query are mutually exclusive — --anchor ranks by an EXISTING item's vector (view:"similar"), so there is no query text to also match (mount-surface spec §2.1)`};if(s===void 0&&r===void 0)return{kind:"error",message:`Validation failed: /data must have required property 'text' — Example: {"data":{"text":"flaky publish gate"}}`};const i={...e};return s!==void 0?i.view="similar":i.text=r,Object.keys(n).length>0&&(i.filter=n),{kind:"argv",argv:["query","--input",JSON.stringify(i)]}}function Zb(t){const e=t.find(n=>n.kind==="action");if(!e)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return la(e).cli.path.slice(0,-1)}const Mg=[Ui];function qK(t,e,n){const r={host:n,operations:e},o=new Set;for(const s of t){const i=s.capabilities.mount;if(!i)continue;const a=i.operations(r,void 0,void 0);for(const c of a){const[u]=la(c).cli.path;u!==void 0&&o.add(u)}}return o}function Xb(t,e,n){var o;return t.length===0?[...t]:(o=t[0])!=null&&o.startsWith("-")?[...t]:t[0]!==void 0&&n.has(t[0])?[...t]:e.length>0&&e.every((s,i)=>t[i]===s)?[...t]:[...e,...t]}function hp(t){const e=[],n=[];let r=!1;for(let s=0;s<t.length;s++){const i=t[s];if(i!==void 0){if(i.startsWith("--namespace=")){const a=i.slice(12);a===""?r=!0:e.push(a);continue}if(i==="--namespace"){const a=t[s+1];a===void 0||a.startsWith("-")?r=!0:(e.push(a),s++);continue}n.push(i)}}const o=new Set(e);return{argv:n,namespace:e[e.length-1],missingValue:r,conflicting:o.size>1}}async function eE(t,e={}){var w;const{argv:n,namespace:r,missingValue:o,conflicting:s}=hp(t??process.argv.slice(2)),i={...e};if(o){const h=pr("invalid_argument",'Invalid argument "namespace": a value is required (e.g. --namespace production)');console.log(JSON.stringify(h)),process.exitCode=Co(h);return}if(s){const h=t??process.argv.slice(2),v=new Set;for(let E=0;E<h.length;E++){const N=h[E];N!==void 0&&(N.startsWith("--namespace=")?v.add(N.slice(12)):N==="--namespace"&&h[E+1]!==void 0&&v.add(h[E+1]))}const b=pr("invalid_argument",`Invalid argument "namespace": conflicting values ${[...v].map(E=>`"${E}"`).join(", ")}`);console.log(JSON.stringify(b)),process.exitCode=Co(b);return}if(r!==void 0&&!((w=ls.namespaces)!=null&&w.includes(r))){const h=ls.namespaces??[],v=tb(r,h),b=`must be one of ${h.map(N=>`"${N}"`).join(", ")}`+(v.length>0?` (did you mean ${v.map(N=>`"${N}"`).join(" or ")}?)`:""),E=pr("invalid_argument",`Invalid argument "namespace": ${b}`);console.log(JSON.stringify(E)),process.exitCode=Co(E);return}r!==void 0&&(i.namespace=r);const a=i.namespace??"production";i.adhdRoot===void 0&&process.env.ADHD_ROOT&&(i.adhdRoot=process.env.ADHD_ROOT);const c=h=>h.includes(`${L.sep}backlog-sandbox-`);if(a==="sandbox"){i.adhdRoot!==void 0&&!c(i.adhdRoot)&&(console.error(`[backlog] --namespace sandbox: ADHD_ROOT=${i.adhdRoot} is set but is not a sandbox this tool created — ignoring it and minting a fresh isolated store instead, so --namespace sandbox never writes into an unrecognized (possibly production) location.`),i.adhdRoot=void 0),i.adhdRoot===void 0&&(i.adhdRoot=J.mkdtempSync(L.join(mt.tmpdir(),"backlog-sandbox-")),console.error(`[backlog] --namespace sandbox: isolated store at ${i.adhdRoot} (not auto-deleted — pass ADHD_ROOT=${i.adhdRoot} to reuse it, or remove it yourself when done)`)),i.namespace="sandbox";const h=L.join(i.adhdRoot,"backlog","sandbox");J.mkdirSync(h,{recursive:!0}),J.writeFileSync(L.join(h,"config.yaml"),`# Written by --namespace sandbox on every invocation — DELIBERATE, not
275
+ `;function Qm(e){let t="mcp",n,r;for(let i=0;i<e.length;i++){const s=e[i];if(s==="--transport")t=e[++i];else if(s==="--port")n=Number(e[++i]);else if(s==="--host")r=e[++i];else throw new X(`backlog serve: unknown argument "${s}" (expected --transport/--port/--host)`)}if(t!=="mcp"&&t!=="http"&&t!=="both")throw new X(`backlog serve: --transport must be mcp|http|both, got "${t}"`);const o={transport:t};return n!==void 0&&(o.port=n),r!==void 0&&(o.host=r),o}async function ca(e,t={}){if(e.includes("--help")||e.includes("-h")){console.log(zr);return}let n;try{n=Qm(e)}catch(s){if(s instanceof X)return So(s,zr);throw s}const r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort());const o=na({...n,...t,signal:r.signal}),i=t.namespace==="sandbox"?O.mkdtempSync(k.join(W.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Mn.initTelemetry({service:"backlog",role:"live-service",logSink:"file",...i!==void 0?{logDir:i}:{}})}catch(s){console.error(`[sox-telemetry] WARNING: initTelemetry failed for serve (${s instanceof Error?s.message:String(s)}); telemetry records will be silently dropped this process`)}await o}const ko=["limit","offset","sort","direction"],da=["kind","plan","assignee","claimed-by","project-path","grep","anchor"],Ao=["status","priority"],Gt=["fields"],Zm={"claimed-by":"claimedBy","project-path":"projectPath"},la=[...ko,...Gt,...da,...Ao].map(e=>`--${e}`).sort(),eg=new Set([...ko,...Gt]),tg=new Set([...Ao,...Gt]),ng=new Set([...ko,...Gt,...da,...Ao]),og=new Set(["limit","offset"]),ua=['backlog search "<natural-language query>" [flags]',"",'Shorthand for `backlog query --input \'{"text": "<query>", ...}\'` — the same',"command, the same JSON envelope, the same exit codes. The query text is","matched semantically when the embedding space is populated, and by keyword","(FTS) when it is not.","","Paging / ranking:"," --limit <n> max items to return"," --offset <n> skip the first n"," --sort <s> override the derived default (relevance / textMatch)"," --direction <d> asc | desc"," --fields <a,b,c> projection; add _score to see ranking scores","","Filters (all compose with the query text):"," --status <s> open | closed | OPEN,IN_PROGRESS | …"," --priority <p> CRITICAL | HIGH | MEDIUM | LOW (comma-separated for several)"," --kind <k> BUG | DEBT | FEAT | …"," --project-path <p> component's repo-relative path (component.meta.path)"," --plan <uid|title> the parent plan issue this item is filed under (part_of)"," --assignee <a> durable owner"," --claimed-by <c> ephemeral claim holder"," --grep <q> extra keyword predicate. Composes with the query text ONLY"," once the embedding space is populated — without it the query"," text IS the keyword query and the two collide (§2.1b step 1).","","More-like-this:",' --anchor <ID> nearest neighbours of an EXISTING item (view:"similar").'," Replaces the positional query rather than refining it."].join(`
276
+ `);function Yr(e,t,n,r){if(!r){e[t]=n;return}const o=e[t]??[];e[t]=[...o,...n.split(",").map(i=>i.trim()).filter(i=>i.length>0)]}function fa(e){if(e.includes("--help")||e.includes("-h"))return{kind:"help",text:ua};const t={},n={};let r,o=0;for(;o<e.length;){const a=e[o];if(!a.startsWith("--")){if(r!==void 0)return{kind:"error",message:`Unexpected positional argument: "${a}"`};r=a,o+=1;continue}let c=a.slice(2),d;const l=c.indexOf("=");if(l!==-1&&(d=c.slice(l+1),c=c.slice(0,l)),c==="input")return{kind:"error",message:"Unknown option: --input. `search` takes the query as a positional argument; for the raw JSON form use `backlog query --input '{...}'`"};if(!ng.has(c))return{kind:"error",message:`Unknown option: --${c}. Available: ${la.join(", ")}`};o+=1;let u;if(d!==void 0)u=d;else{if(o>=e.length)return{kind:"error",message:`Missing value for --${c}`};u=e[o],o+=1}const f=tg.has(c);eg.has(c)?Yr(t,c,u,f):Yr(n,Zm[c]??c,u,f)}for(const a of["status","priority"]){const c=n[a];(c==null?void 0:c.length)===1&&(n[a]=c[0])}for(const a of og){const c=t[a];typeof c=="string"&&/^-?\d+$/.test(c)&&(t[a]=Number(c))}const i=n.anchor;if(i!==void 0&&r!==void 0)return{kind:"error",message:`Validation failed: --anchor and a positional query are mutually exclusive — --anchor ranks by an EXISTING item's vector (view:"similar"), so there is no query text to also match (mount-surface spec §2.1)`};if(i===void 0&&r===void 0)return{kind:"error",message:`Validation failed: /data must have required property 'text' — Example: {"data":{"text":"flaky publish gate"}}`};const s={...t};return i!==void 0?s.view="similar":s.text=r,Object.keys(n).length>0&&(s.filter=n),{kind:"argv",argv:["query","--input",JSON.stringify(s)]}}function pa(e){const t=e.find(n=>n.kind==="action");if(!t)throw new Error('@adhd/backlog: cli mount found zero "action" operations in client.ts — cannot derive a command prefix');return Me(t).cli.path.slice(0,-1)}const Xr=[jt];function rg(e,t,n){const r={host:n,operations:t},o=new Set;for(const i of e){const s=i.capabilities.mount;if(!s)continue;const a=s.operations(r,void 0,void 0);for(const c of a){const[d]=Me(c).cli.path;d!==void 0&&o.add(d)}}return o}function ma(e,t,n){var o;return e.length===0?[...e]:(o=e[0])!=null&&o.startsWith("-")?[...e]:e[0]!==void 0&&n.has(e[0])?[...e]:t.length>0&&t.every((i,s)=>e[s]===i)?[...e]:[...t,...e]}function jo(e){const t=[],n=[];let r=!1;for(let i=0;i<e.length;i++){const s=e[i];if(s!==void 0){if(s.startsWith("--namespace=")){const a=s.slice(12);a===""?r=!0:t.push(a);continue}if(s==="--namespace"){const a=e[i+1];a===void 0||a.startsWith("-")?r=!0:(t.push(a),i++);continue}n.push(s)}}const o=new Set(t);return{argv:n,namespace:t[t.length-1],missingValue:r,conflicting:o.size>1}}async function ig(e){let t;for(let s=0;s<e.length;s++){const a=e[s];if(a!==void 0){if(a==="--out"||a==="-o"){const c=e[s+1];c!==void 0&&!c.startsWith("-")&&(t=c,s++)}else if(a.startsWith("--out=")){const c=a.slice(6);c!==""&&(t=c)}}}if(!t){const s=le("invalid_argument","ir-artifact: --out <path> is required");console.error(JSON.stringify(s)),process.exitCode=ke(s);return}const n=k.join(Vt(),"api.d.ts");if(!O.existsSync(n)){const s=le("internal",`ir-artifact: ${n} does not exist — run "nx build backlog" first`);console.error(JSON.stringify(s)),process.exitCode=ke(s);return}const r=k.resolve(t),{buildBakedOperations:o}=await Promise.resolve().then(()=>ha),i=await o(n);await _m({apiDts:n,outFile:r,extractorVersion:yo,operations:i}),console.log(JSON.stringify({ok:!0,out:r,operations:i.length}))}async function ga(e,t={}){var v;const{argv:n,namespace:r,missingValue:o,conflicting:i}=jo(e??process.argv.slice(2)),s={...t};if(o){const h=le("invalid_argument",'Invalid argument "namespace": a value is required (e.g. --namespace production)');console.log(JSON.stringify(h)),process.exitCode=ke(h);return}if(i){const h=e??process.argv.slice(2),y=new Set;for(let b=0;b<h.length;b++){const S=h[b];S!==void 0&&(S.startsWith("--namespace=")?y.add(S.slice(12)):S==="--namespace"&&h[b+1]!==void 0&&y.add(h[b+1]))}const w=le("invalid_argument",`Invalid argument "namespace": conflicting values ${[...y].map(b=>`"${b}"`).join(", ")}`);console.log(JSON.stringify(w)),process.exitCode=ke(w);return}if(r!==void 0&&!((v=Ue.namespaces)!=null&&v.includes(r))){const h=Ue.namespaces??[],y=ms(r,h),w=`must be one of ${h.map(S=>`"${S}"`).join(", ")}`+(y.length>0?` (did you mean ${y.map(S=>`"${S}"`).join(" or ")}?)`:""),b=le("invalid_argument",`Invalid argument "namespace": ${w}`);console.log(JSON.stringify(b)),process.exitCode=ke(b);return}r!==void 0&&(s.namespace=r);const a=s.namespace??"production";s.adhdRoot===void 0&&process.env.ADHD_ROOT&&(s.adhdRoot=process.env.ADHD_ROOT);const c=h=>h.includes(`${k.sep}backlog-sandbox-`);if(a==="sandbox"){s.adhdRoot!==void 0&&!c(s.adhdRoot)&&(console.error(`[backlog] --namespace sandbox: ADHD_ROOT=${s.adhdRoot} is set but is not a sandbox this tool created — ignoring it and minting a fresh isolated store instead, so --namespace sandbox never writes into an unrecognized (possibly production) location.`),s.adhdRoot=void 0),s.adhdRoot===void 0&&(s.adhdRoot=O.mkdtempSync(k.join(W.tmpdir(),"backlog-sandbox-")),console.error(`[backlog] --namespace sandbox: isolated store at ${s.adhdRoot} (not auto-deleted — pass ADHD_ROOT=${s.adhdRoot} to reuse it, or remove it yourself when done)`)),s.namespace="sandbox";const h=k.join(s.adhdRoot,"backlog","sandbox");O.mkdirSync(h,{recursive:!0}),O.writeFileSync(k.join(h,"config.yaml"),`# Written by --namespace sandbox on every invocation — DELIBERATE, not
577
277
  # an absence-of-file default. embedding.enabled is off so a sandboxed
578
278
  # run never pays a real model-load cost or opens a real vector store.
579
279
  embedding:
580
280
  enabled: false
581
- `)}if(i.adhdRoot!==void 0&&process.env.APIGEN_IR_CACHE_FILE===void 0&&(process.env.APIGEN_IR_CACHE_FILE=L.join(i.adhdRoot,"ir-cache","backlog-client.ir.json")),n[0]==="sandbox-path"){const h=Go({scope:i.scope,adhdRoot:i.adhdRoot,cwd:i.cwd,namespace:i.namespace});console.log(JSON.stringify({adhdRoot:i.adhdRoot,namespace:i.namespace??"production",dbPath:zo(h),embeddingEnabled:h.config.embedding.enabled}));return}if(n[0]==="store-check"){const h=Go({scope:i.scope,adhdRoot:i.adhdRoot,cwd:i.cwd,namespace:i.namespace});h.ensureDirs();const v=zo(h);let b;try{b=await Ki(v,h.config.db.busyTimeoutMs);const{total:E,observed:N}=await uy(b.adapter);console.log(JSON.stringify({ok:!0,dbPath:v,total:E,kinds:N,expectedKinds:[...Nl]}));return}catch(E){if(E instanceof cy){console.error(JSON.stringify({ok:!1,dbPath:v,error:{code:"store_vocabulary_mismatch",message:E.message},observed:E.observed,expectedKinds:E.recognized})),process.exitCode=1;return}throw E}finally{b&&await Zc(b)}}if((n.length===0||n[0]==="--help"||n[0]==="-h")&&(console.log("Special commands (handled before the apigen command table):"),console.log(" install-skill [options] Install the backlog skill for a host (alias: install)"),console.log(" serve [options] Start the long-lived HTTP/MCP server (--transport http|mcp|both)"),console.log(' search "<query>" [flags] Natural-language search — `query --input` with the options as flags'),console.log(" sandbox-path Report the resolved store path (store-free) — see --namespace below"),console.log(" store-check Report the store vocabulary this build expects vs. the kinds present; non-zero on a mismatch"),console.log(""),console.log(" --namespace <value> Global flag, valid before ANY command: selects which"),console.log(' declared store instance to use — "production" (default),'),console.log(' "test" (a persisted, non-ephemeral store), or "sandbox"'),console.log(" (a fresh throwaway store minted per invocation, never"),console.log(" the live production one)."),console.log("")),n[0]==="install-skill"){await Gb(n.slice(1));return}if(n[0]==="install"){await CK(n.slice(1));return}if(n[0]==="serve"){await Wb(n.slice(1),i);return}if(n[0]==="version"){console.log(JSON.stringify(cp()));return}let l;if(n[0]==="search"){const h=Yb(n.slice(1));if(h.kind==="help"){console.log(h.text);return}if(h.kind==="error"){console.error(JSON.stringify({code:"invalid_argument",message:h.message})),process.exitCode=2;return}l=h.argv}let d;const f=async()=>{if(!d){const h=Go({scope:i.scope,adhdRoot:i.adhdRoot,cwd:i.cwd,namespace:i.namespace});h.ensureDirs();const v=await Ki(zo(h),h.config.db.busyTimeoutMs);d={store:v,ctx:{store:v,env:h}}}return d.ctx};let g;const p=()=>(g||(g=Zc(d==null?void 0:d.store)),g),y=by(p);try{const{pkg:h,operations:v}=await up(f,{adhdRoot:i.adhdRoot}),b=l??n,E=Zb(v),N=qK(Mg,v,h.id);await ol(GS)({packages:[h],operations:v,outputDir:"",options:{argv:Xb(b,E,N),usePlugins:[...Mg],exitCode:T=>cb(T)?Co(T):void 0},signal:i.signal??new AbortController().signal,logger:Db()});const j=b.length>1&&b[0]!=="batch"&&(b.includes("--help")||b.includes("-h"));j&&console.log("See also: `adhd-backlog batch action` — run this SAME operation over many items in one call instead of N one-at-a-time invocations (skill/SKILL.md §5)."),j&&b[0]==="query"&&console.log(`Notes:
281
+ `)}if(s.adhdRoot!==void 0&&process.env.APIGEN_IR_CACHE_FILE===void 0&&(process.env.APIGEN_IR_CACHE_FILE=k.join(s.adhdRoot,"ir-cache","backlog-client.ir.json")),n[0]==="sandbox-path"){const h=$e({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});console.log(JSON.stringify({adhdRoot:s.adhdRoot,namespace:s.namespace??"production",dbPath:Ge(h),embeddingEnabled:h.config.embedding.enabled}));return}if(n[0]==="ir-artifact"){await ig(n.slice(1));return}if(n[0]==="store-check"){const h=$e({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});h.ensureDirs();const y=Ge(h);let w;try{w=await Rt(y,h.config.db.busyTimeoutMs);const{total:b,observed:S}=await Li(w.adapter);console.log(JSON.stringify({ok:!0,dbPath:y,total:b,kinds:S,expectedKinds:[...no]}));return}catch(b){if(b instanceof xi){console.error(JSON.stringify({ok:!1,dbPath:y,error:{code:"store_vocabulary_mismatch",message:b.message},observed:b.observed,expectedKinds:b.recognized})),process.exitCode=1;return}throw b}finally{w&&await In(w)}}if((n.length===0||n[0]==="--help"||n[0]==="-h")&&(console.log("Special commands (handled before the apigen command table):"),console.log(" install-skill [options] Install the backlog skill for a host (alias: install)"),console.log(" serve [options] Start the long-lived HTTP/MCP server (--transport http|mcp|both)"),console.log(' search "<query>" [flags] Natural-language search — `query --input` with the options as flags'),console.log(" sandbox-path Report the resolved store path (store-free) — see --namespace below"),console.log(" store-check Report the store vocabulary this build expects vs. the kinds present; non-zero on a mismatch"),console.log(""),console.log(" --namespace <value> Global flag, valid before ANY command: selects which"),console.log(' declared store instance to use — "production" (default),'),console.log(' "test" (a persisted, non-ephemeral store), or "sandbox"'),console.log(" (a fresh throwaway store minted per invocation, never"),console.log(" the live production one)."),console.log("")),n[0]==="install-skill"){await sa(n.slice(1));return}if(n[0]==="install"){await Xm(n.slice(1));return}if(n[0]==="serve"){await ca(n.slice(1),s);return}if(n[0]==="version"){console.log(JSON.stringify(vo()));return}let l;if(n[0]==="search"){const h=fa(n.slice(1));if(h.kind==="help"){console.log(h.text);return}if(h.kind==="error"){console.error(JSON.stringify({code:"invalid_argument",message:h.message})),process.exitCode=2;return}l=h.argv}let u;const f=async()=>{if(!u){const h=$e({scope:s.scope,adhdRoot:s.adhdRoot,cwd:s.cwd,namespace:s.namespace});h.ensureDirs();const y=await Rt(Ge(h),h.config.db.busyTimeoutMs);u={store:y,ctx:{store:y,env:h}}}return u.ctx};let g;const p=()=>(g||(g=In(u==null?void 0:u.store)),g),m=Qi(p);try{const{pkg:h,operations:y}=await bo(f,{adhdRoot:s.adhdRoot}),w=l??n,b=pa(y),S=rg(Xr,y,h.id);await Dn(dl)({packages:[h],operations:y,outputDir:"",options:{argv:ma(w,b,S),usePlugins:[...Xr],exitCode:A=>Ss(A)?ke(A):void 0},signal:s.signal??new AbortController().signal,logger:ea()});const E=w.length>1&&w[0]!=="batch"&&(w.includes("--help")||w.includes("-h"));E&&console.log("See also: `adhd-backlog batch action` — run this SAME operation over many items in one call instead of N one-at-a-time invocations (skill/SKILL.md §5)."),E&&w[0]==="query"&&console.log(`Notes:
582
282
  - view:"similar" additionally requires filter.anchor (uid of the reference issue) OR filter.semantic (free text) — neither given throws invalid_argument.
583
- - view:"projects" | "components" | "locations" list the project/component/location registry (optionally scoped by filter.project/filter.component) — see skill/SKILL.md §3a for worked examples.`)}finally{y.dispose(),await p()}}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:D&&D.tagName.toUpperCase()==="SCRIPT"&&D.src||new URL("index.js",document.baseURI).href)===$s.pathToFileURL(J.realpathSync(process.argv[1])).href){const{namespace:t}=hp(process.argv.slice(2)),e=t==="sandbox"?J.mkdtempSync(L.join(mt.tmpdir(),"backlog-sandbox-logs-")):void 0;try{Lg.initTelemetry({service:"backlog",role:"cli",logSink:"file",...e!==void 0?{logDir:e}:{}})}catch(n){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${n instanceof Error?n.message:String(n)}); telemetry records will be silently dropped this process`)}eE().catch(n=>{console.error(n instanceof Error?n.stack??n.message:String(n)),process.exitCode=1})}exports.BACKLOG_ERROR_CODES=ib;exports.BACKLOG_EXIT_CODE=ip;exports.RagNotConfiguredError=ub;exports.SEARCH_FLAGS=Jb;exports.SEARCH_HELP=Qb;exports.backlogEnvironmentSpec=ls;exports.buildBacklogApigenPackage=up;exports.buildBacklogEnv=Go;exports.buildSearchArgv=Yb;exports.claim=Ib;exports.closeGraphBacklogStore=$y;exports.create=kb;exports.delete=Rb;exports.errorEnvelope=pr;exports.exitCodeForEnvelope=Co;exports.get=bb;exports.installSkill=Kb;exports.isBacklogErrorCode=ab;exports.isOutcomeEnvelope=cb;exports.isOutcomeError=vq;exports.isOutcomeOk=wq;exports.lookup=Ob;exports.move=xb;exports.okEnvelope=ap;exports.openCurve=Nb;exports.openGraphBacklogStore=Ki;exports.partOfRollup=_b;exports.prefixCommand=Xb;exports.priorityMatrix=Sb;exports.query=Eb;exports.readBacklogVersionInfo=cp;exports.relate=Pb;exports.resolveBacklogDbPath=zo;exports.resolveBacklogScope=_v;exports.resolveCommandPrefix=Zb;exports.resolveExpectedMcpToolNames=dK;exports.rmLocation=Lb;exports.runBacklogCli=eE;exports.runInstallSkillCommand=Gb;exports.runServeCommand=Wb;exports.startBacklogServer=Fb;exports.stripNamespaceFlag=hp;exports.suggestClaimantIdentity=SP;exports.transition=Ab;exports.update=jb;exports.upsertComponent=Cb;exports.upsertLocation=Mb;exports.upsertProject=Tb;
283
+ - view:"projects" | "components" | "locations" list the project/component/location registry (optionally scoped by filter.project/filter.component) — see skill/SKILL.md §3a for worked examples.`)}finally{m.dispose(),await p()}}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:$&&$.tagName.toUpperCase()==="SCRIPT"&&$.src||new URL("index.js",document.baseURI).href)===et.pathToFileURL(O.realpathSync(process.argv[1])).href){const{namespace:e,argv:t}=jo(process.argv.slice(2)),n=t[0]==="ir-artifact",r=e==="sandbox"?O.mkdtempSync(k.join(W.tmpdir(),"backlog-sandbox-logs-")):void 0;if(!n)try{Mn.initTelemetry({service:"backlog",role:"cli",logSink:"file",...r!==void 0?{logDir:r}:{}})}catch(o){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${o instanceof Error?o.message:String(o)}); telemetry records will be silently dropped this process`)}ga().catch(o=>{console.error(o instanceof Error?o.stack??o.message:String(o)),process.exitCode=1})}const sg=yo,_o="backlog";function No(e,t){return{sourceFile:e,namespace:_o,tsconfig:t,dropFileSegment:!0}}function ag(e={}){return Mu(e)}function cg(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function dg(e={}){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:bm({cache:ag(e),extractorVersion:sg})}}}}let Qr;function lg(e={}){return Qr??(Qr=Gc(cg()?[dg(e)]:[],t=>{var n;return wi(No(t.source,typeof((n=t.extractorOptions)==null?void 0:n.tsconfig)=="string"?t.extractorOptions.tsconfig:void 0))})),Qr}async function ug(e){return wi(No(e))}async function fg(e={}){const t=k.join(Vt(),"api.d.ts");return lg(e)({source:t,host:"ts",namespace:_o,extractorOptions:{}})}const ha=Object.freeze(Object.defineProperty({__proto__:null,BACKLOG_EXTRACT_NAMESPACE:_o,buildBacklogExtractOptions:No,buildBakedOperations:ug,extractApiOperationsLive:fg},Symbol.toStringTag,{value:"Module"}));exports.BACKLOG_ERROR_CODES=vs;exports.BACKLOG_EXIT_CODE=go;exports.RagNotConfiguredError=Es;exports.SEARCH_FLAGS=la;exports.SEARCH_HELP=ua;exports.backlogEnvironmentSpec=Ue;exports.buildBacklogApigenPackage=bo;exports.buildBacklogEnv=$e;exports.buildSearchArgv=fa;exports.claim=Hs;exports.closeGraphBacklogStore=Xi;exports.create=Bs;exports.delete=Js;exports.embeddingStatus=Ms;exports.errorEnvelope=le;exports.exitCodeForEnvelope=ke;exports.get=Ps;exports.installSkill=ra;exports.isBacklogErrorCode=bs;exports.isOutcomeEnvelope=Ss;exports.isOutcomeError=Ap;exports.isOutcomeOk=kp;exports.lookup=Fs;exports.move=Gs;exports.okEnvelope=ho;exports.openCurve=Ds;exports.openGraphBacklogStore=Rt;exports.partOfRollup=Us;exports.prefixCommand=ma;exports.priorityMatrix=Ls;exports.query=xs;exports.readBacklogVersionInfo=vo;exports.relate=Vs;exports.resolveBacklogDbPath=Ge;exports.resolveBacklogScope=fo;exports.resolveCommandPrefix=pa;exports.resolveExpectedMcpToolNames=Cm;exports.rmLocation=Xs;exports.runBacklogCli=ga;exports.runInstallSkillCommand=sa;exports.runServeCommand=ca;exports.startBacklogServer=na;exports.stripNamespaceFlag=jo;exports.suggestClaimantIdentity=Du;exports.transition=Ks;exports.update=qs;exports.upsertComponent=zs;exports.upsertLocation=Ys;exports.upsertProject=Ws;