@adhd/backlog 0.1.4 → 0.1.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/env.d.ts +23 -0
- package/index.d.ts +1 -1
- package/index.js +82 -82
- package/index.mjs +2480 -2442
- package/package.json +5 -4
- package/server.d.ts +1 -1
- package/store/audit-log.d.ts +2 -2
- package/store/claim.d.ts +3 -3
- package/store/crud.d.ts +10 -8
- package/store/graph-backlog-store.d.ts +27 -11
- package/store/ids.d.ts +2 -2
- package/store/immediate-retry.d.ts +23 -18
- package/store/lifecycle.d.ts +6 -6
- package/store/mutate-metadata.d.ts +1 -1
- package/store/query.d.ts +14 -14
- package/store/structure.d.ts +14 -12
package/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Yh=Object.create;var Ja=Object.defineProperty;var Qh=Object.getOwnPropertyDescriptor;var Zh=Object.getOwnPropertyNames;var Xh=Object.getPrototypeOf,em=Object.prototype.hasOwnProperty;var tm=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Zh(t))!em.call(e,o)&&o!==n&&Ja(e,o,{get:()=>t[o],enumerable:!(r=Qh(t,o))||r.enumerable});return e};var nm=(e,t,n)=>(n=e!=null?Yh(Xh(e)):{},tm(t||!e||!e.__esModule?Ja(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("node:fs"),Rn=require("node:url"),Sn=require("ts-morph"),T=require("node:path"),wt=require("ts-json-schema-generator"),ke=require("pino"),jr=require("ajv"),Ir=require("ajv-formats"),rm=require("better-sqlite3"),om=require("@adhd/sox-graph-store"),He=require("node:os"),Mn=require("node:crypto"),bl=require("node:module"),sm=require("node:fs/promises"),im=require("fastify"),Ha=require("node:http"),am=require("@modelcontextprotocol/sdk/server/index.js"),cm=require("@modelcontextprotocol/sdk/server/stdio.js"),um=require("@modelcontextprotocol/sdk/server/sse.js"),lm=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Wa=require("@modelcontextprotocol/sdk/types.js"),Ya=require("yaml");var re=typeof document<"u"?document.currentScript:null;function El(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 Uo=El(T),bt=El(sm),Bo="$apigen";let Qa=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function fm(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Qa(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new Qa("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 Fs="x-apigen-logical",qs="x-apigen-codec",Fo="x-apigen-ctor",qo="x-apigen-tojson",dm="0.1.0";function Za(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 Mt(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 Mt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Sl(e,s,t);return Mt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return po(e,t,n);const a=t.items;if(!a)return e.map(u=>Et(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Et(u):Mt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Mt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return po(e,t,n);const a=t.properties;if(!a)return Et(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Mt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?po(e,t,n):Et(e)}function Dt(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 Dt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Sl(e,s,t);return Dt(e,a,n)}const i=t.type;if(i==="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((u,l)=>{const f=a[l];return f===void 0?u:Dt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Dt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Dt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?pm(e,n):e}function Sl(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function po(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Bo]:r,v:s}}catch{}}return Et(e)}function pm(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Bo in e){const n=e,r=n[Bo],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Et(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Et);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Et(r));return t}return null}function hm(e){return{encode(t,n,r){const o=Za(e,r);return Mt(t,n,o)},decode(t,n,r){const o=Za(e,r);return Dt(t,n,o)}}}const Vs={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},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)}},Ks={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},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)}},Gs={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}},zs={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},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"))}},mm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Js={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"&&!mm.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Vo="NaN",Ko="Infinity",Go="-Infinity",gm=new Set([Vo,Ko,Go]),Hs={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Vo:e===1/0?Ko:e===-1/0?Go:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Vo)return NaN;if(e===Ko)return 1/0;if(e===Go)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 ${[...gm].join(", ")}.`);return NaN}},ym=[Vs,Ks,Gs,zs,Js,Hs];function $m(e,t={}){for(const n of ym)e.register(n,{override:t.override??!1})}const vm=12;function wm(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function Xa(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function bm(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 Em(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 ec(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?On(a,t,n+1):`<${i}>`}return s}function Sm(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[On(r,t,n+1)]:[]}function On(e,t=e??{},n=0){if(!e||n>vm)return null;if(typeof e.$ref=="string"){const o=wm(e.$ref,t);return o!==void 0?On(o,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 o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return ec({...e,properties:o,required:s},t,n)}const r=Xa(e.oneOf)??Xa(e.anyOf);if(r)return On(r,t,n+1);switch(bm(e)){case"object":return ec(e,t,n);case"array":return Sm(e,t,n);case"string":return Em(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function Om(e){if(!e)return;const t=On(e);return`Example: ${JSON.stringify(t)}`}Vs.id,Ks.id,Gs.id,zs.id,Js.id,Hs.id;const Ol=fm();$m(Ol);const Nl=hm(Ol.freeze());function _l(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function zo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function Nm(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function _m(e,t){return t===void 0||e===void 0?e:Nl.decode(e,t)}function ho(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:Nl.encode(e,n)}async function km(e,t,n,r,o,s){const i=zo(n).map(c=>_m(s[c],Nm(n,c)));if(_l(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return ho(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return ho(u,n)}const a=await e[r](...i);return ho(a,n)}let kl=class{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 Am(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>km(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const jm={"decimal.js":"Decimal"};function Im(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(jm).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Im(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function xm(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"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},ke(s);const i=n?ke.destination({dest:e.destination,mkdir:!0,sync:!0}):ke.destination(2);return ke(s,i)}function Al(e){return e?e.type==="array"?`${Al(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Pm(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.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:Al(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let Tm=class 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}};const xr=new jr({allErrors:!0});Ir(xr);for(const e of[Fs,qs,Fo,qo,"discriminator"])xr.addKeyword({keyword:e,valid:!0});xr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Cm(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Rm(e,t){const n=Om(t),r=[`Validation failed: ${Cm(e)}`];return n&&r.push(n),r.join(" — ")}function Mm(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=xr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Tm("invalid_argument",Rm(a,o.input),a)}return n()}}function Dm(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let ut=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function mo(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 jl(e,t){const n=e[qs];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function Lm(e,t,n){const r=jl(t,n);return r?r.encode(e,t,n):e}function Um(e,t,n){const r=jl(t,n);return r?r.decode(e,t,n):e}function Bm(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Fs]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:mo(r)!==void 0},encode(r,o,s){const i=mo(o);if(!i)throw new ut("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 ut("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ut("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return Lm(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ut("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=mo(o);if(!a)throw new ut("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 ut("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ut("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return Um(r,h,{...s,path:`${s.path}[${f}]`})}}}const Fm="x-apigen-instances";let qn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function tc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function qm(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function nc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function Vm(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function Km(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Fs]==="nominal"?!0:o[qs]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new qn("E_NOMINAL_CYCLE",`[${t}] 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=tc(s),c=typeof s[qo]=="string"?s[qo]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const g={};for(const[y,$]of Object.entries(d))g[y]=nc($,a[y],{...i,path:`${i.path}/${y}`});return g}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const g=p[d];g!==void 0&&(l[d]=nc(g,a[d],{...i,path:`${i.path}/${d}`}))}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 qn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of qm(s))if(!(l in a))throw new qn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[Fm]===!1)throw new qn("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=tc(s),u={};for(const[l,f]of Object.entries(a))u[l]=Vm(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Fo]=="string"?s[Fo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const Gm=[Vs,Ks,Gs,zs,Js,Hs],zm={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},rc=Km({id:"ts.NominalSentinel",schema:zm}),Jm={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},oc=Bm({id:"ts.UnionSentinel",schema:Jm});function Hm(){const e=[...Gm.map(t=>[t.id,t]),[rc.id,rc],[oc.id,oc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:dm,codecs:Hm()});const sc=new Set(["string","number","boolean","integer"]);function Wm(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"?sc.has(n):Array.isArray(n)?n.every(r=>sc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Ym(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(Wm)}const Qm={"decimal.js":"Decimal"};function Zm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Qm).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Zm(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ic(e){return e.words.join("-")}function ac(e){return e.words.map(rg).join("")}function cc(e){return e.words.join("_")}function Xm(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Ym(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>ic(h)).join("/"),c=o.map(h=>cc(h)).join("_"),u=o.map(h=>cc(h)).slice(0,-1).join("."),l=ac(o[o.length-2]??o[0]),f=ac(o[o.length-1]),p=o.map(h=>ic(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function eg(e,t){return`x-${e}-${t}`}function tg(e,t){return`--${e}-${t}`}function ng(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function rg(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Ws(e){return e.anyOf??e.oneOf}function og(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Ws(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 sg(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Ws(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function ig(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Ws(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 ag(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function cg(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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 uc(e){return typeof e.handler=="function"}function ug(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["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=eg(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:tg(i,s),envVar:ng(i,s)})}return o}function lg(e,t){const n=new Map,{props:r}=cg(e);for(const[o,s]of Object.entries(r)){let i="string";sg(s)?i="boolean":(og(s)||ig(s))&&(i="json"),n.set(ag(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Il(e){const{op:t,schema:n,transport:r,projection:o}=e,s=Xm(t,o),i=n?ug(n):[],a=n?lg(n,i):new Map,c=n?Pm(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:uc(t)};if(uc(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function fg(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function dg(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function pg(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function go(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(pg(s))}return r.push(Mm(e)),Am(r)}function hg(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const mg={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function lc(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new kl};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:hg(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:mg}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const gg={"decimal.js":"Decimal"};function yg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(gg).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${yg(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function $g(e,t){return`--${e}-${t}`}function vg(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Jo(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const wg=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],fc={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};let $r=class 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 dc(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&wg.includes(e.code)&&typeof e.toJSON=="function"}function xl(e){return e.anyOf??e.oneOf}function bg(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["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:$g(i,s),envVar:vg(i,s)})}return o}function Ho(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=xl(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 Eg(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=xl(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function pc(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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 Sg(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function Og(e){const t=Ys(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return t.length>0?t.toLowerCase():"branch"}function yo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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=Sg(c);if(u===void 0)continue;const l=o[u];if(!l)continue;const f=l.properties??{},p=l.required??[];i.push({value:a,commandName:Og(a),props:f,required:p})}if(i.length!==0)return{discriminatorProperty:s.propertyName,branches:i}}function Ys(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Ng(e,t){if(!Uo.isAbsolute(t))return t;const n=Uo.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const _g=["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
|
|
4
|
-
`)}]}}function
|
|
5
|
-
`)}function Vn(e){return new $r("invalid_argument",e)}function
|
|
2
|
+
"use strict";var Xh=Object.create;var Wa=Object.defineProperty;var em=Object.getOwnPropertyDescriptor;var tm=Object.getOwnPropertyNames;var nm=Object.getPrototypeOf,rm=Object.prototype.hasOwnProperty;var om=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of tm(t))!rm.call(e,o)&&o!==n&&Wa(e,o,{get:()=>t[o],enumerable:!(r=em(t,o))||r.enumerable});return e};var sm=(e,t,n)=>(n=e!=null?Xh(nm(e)):{},om(t||!e||!e.__esModule?Wa(n,"default",{value:e,enumerable:!0}):n,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const L=require("node:fs"),Rn=require("node:url"),im=require("@adhd/sox-telemetry"),Sn=require("ts-morph"),T=require("node:path"),wt=require("ts-json-schema-generator"),ke=require("pino"),jr=require("ajv"),Ir=require("ajv-formats"),Uo=require("@adhd/sox-store-adapter"),am=require("@adhd/sox-graph-store"),We=require("node:os"),Mn=require("node:crypto"),El=require("node:module"),cm=require("node:fs/promises"),um=require("fastify"),Ha=require("node:http"),lm=require("@modelcontextprotocol/sdk/server/index.js"),fm=require("@modelcontextprotocol/sdk/server/stdio.js"),dm=require("@modelcontextprotocol/sdk/server/sse.js"),pm=require("@modelcontextprotocol/sdk/server/streamableHttp.js"),Ya=require("@modelcontextprotocol/sdk/types.js"),Qa=require("yaml");var re=typeof document<"u"?document.currentScript:null;function Sl(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 Bo=Sl(T),bt=Sl(cm),Fo="$apigen";let Za=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function hm(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Za(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new Za("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 qs="x-apigen-logical",Vs="x-apigen-codec",qo="x-apigen-ctor",Vo="x-apigen-tojson",mm="0.1.0";function Xa(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 Mt(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 Mt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Ol(e,s,t);return Mt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return po(e,t,n);const a=t.items;if(!a)return e.map(u=>Et(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Et(u):Mt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Mt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return po(e,t,n);const a=t.properties;if(!a)return Et(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Mt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?po(e,t,n):Et(e)}function Dt(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 Dt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Ol(e,s,t);return Dt(e,a,n)}const i=t.type;if(i==="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((u,l)=>{const f=a[l];return f===void 0?u:Dt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Dt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Dt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?gm(e,n):e}function Ol(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function po(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Fo]:r,v:s}}catch{}}return Et(e)}function gm(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Fo in e){const n=e,r=n[Fo],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Et(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Et);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Et(r));return t}return null}function ym(e){return{encode(t,n,r){const o=Xa(e,r);return Mt(t,n,o)},decode(t,n,r){const o=Xa(e,r);return Dt(t,n,o)}}}const Ks={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},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)}},Gs={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},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)}},zs={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}},Js={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},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"))}},$m=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ws={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"&&!$m.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Ko="NaN",Go="Infinity",zo="-Infinity",vm=new Set([Ko,Go,zo]),Hs={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Ko:e===1/0?Go:e===-1/0?zo:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Ko)return NaN;if(e===Go)return 1/0;if(e===zo)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 ${[...vm].join(", ")}.`);return NaN}},wm=[Ks,Gs,zs,Js,Ws,Hs];function bm(e,t={}){for(const n of wm)e.register(n,{override:t.override??!1})}const Em=12;function Sm(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function ec(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function Om(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 Nm(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 tc(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?On(a,t,n+1):`<${i}>`}return s}function _m(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[On(r,t,n+1)]:[]}function On(e,t=e??{},n=0){if(!e||n>Em)return null;if(typeof e.$ref=="string"){const o=Sm(e.$ref,t);return o!==void 0?On(o,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 o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return tc({...e,properties:o,required:s},t,n)}const r=ec(e.oneOf)??ec(e.anyOf);if(r)return On(r,t,n+1);switch(Om(e)){case"object":return tc(e,t,n);case"array":return _m(e,t,n);case"string":return Nm(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function km(e){if(!e)return;const t=On(e);return`Example: ${JSON.stringify(t)}`}Ks.id,Gs.id,zs.id,Js.id,Ws.id,Hs.id;const Nl=hm();bm(Nl);const _l=ym(Nl.freeze());function kl(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function Jo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function Am(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function jm(e,t){return t===void 0||e===void 0?e:_l.decode(e,t)}function ho(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:_l.encode(e,n)}async function Im(e,t,n,r,o,s){const i=Jo(n).map(c=>jm(s[c],Am(n,c)));if(kl(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return ho(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return ho(u,n)}const a=await e[r](...i);return ho(a,n)}let Al=class{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 xm(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>Im(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const Pm={"decimal.js":"Decimal"};function Tm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Pm).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Tm(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Cm(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"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},ke(s);const i=n?ke.destination({dest:e.destination,mkdir:!0,sync:!0}):ke.destination(2);return ke(s,i)}function jl(e){return e?e.type==="array"?`${jl(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Rm(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.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:jl(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}let Mm=class 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}};const xr=new jr({allErrors:!0});Ir(xr);for(const e of[qs,Vs,qo,Vo,"discriminator"])xr.addKeyword({keyword:e,valid:!0});xr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Dm(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Lm(e,t){const n=km(t),r=[`Validation failed: ${Dm(e)}`];return n&&r.push(n),r.join(" — ")}function Um(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=xr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new Mm("invalid_argument",Lm(a,o.input),a)}return n()}}function Bm(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let ut=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function mo(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 Il(e,t){const n=e[Vs];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function Fm(e,t,n){const r=Il(t,n);return r?r.encode(e,t,n):e}function qm(e,t,n){const r=Il(t,n);return r?r.decode(e,t,n):e}function Vm(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[qs]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:mo(r)!==void 0},encode(r,o,s){const i=mo(o);if(!i)throw new ut("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 ut("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ut("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return Fm(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ut("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=mo(o);if(!a)throw new ut("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 ut("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ut("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return qm(r,h,{...s,path:`${s.path}[${f}]`})}}}const Km="x-apigen-instances";let qn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function nc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function Gm(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function rc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function zm(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function Jm(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[qs]==="nominal"?!0:o[Vs]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new qn("E_NOMINAL_CYCLE",`[${t}] 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=nc(s),c=typeof s[Vo]=="string"?s[Vo]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=rc($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=rc(m,a[d],{...i,path:`${i.path}/${d}`}))}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 qn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of Gm(s))if(!(l in a))throw new qn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[Km]===!1)throw new qn("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=nc(s),u={};for(const[l,f]of Object.entries(a))u[l]=zm(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[qo]=="string"?s[qo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const Wm=[Ks,Gs,zs,Js,Ws,Hs],Hm={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},oc=Jm({id:"ts.NominalSentinel",schema:Hm}),Ym={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},sc=Vm({id:"ts.UnionSentinel",schema:Ym});function Qm(){const e=[...Wm.map(t=>[t.id,t]),[oc.id,oc],[sc.id,sc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:mm,codecs:Qm()});const ic=new Set(["string","number","boolean","integer"]);function Zm(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"?ic.has(n):Array.isArray(n)?n.every(r=>ic.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Xm(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(Zm)}const eg={"decimal.js":"Decimal"};function tg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(eg).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${tg(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ac(e){return e.words.join("-")}function cc(e){return e.words.map(ig).join("")}function uc(e){return e.words.join("_")}function ng(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Xm(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>ac(h)).join("/"),c=o.map(h=>uc(h)).join("_"),u=o.map(h=>uc(h)).slice(0,-1).join("."),l=cc(o[o.length-2]??o[0]),f=cc(o[o.length-1]),p=o.map(h=>ac(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function rg(e,t){return`x-${e}-${t}`}function og(e,t){return`--${e}-${t}`}function sg(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function ig(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Ys(e){return e.anyOf??e.oneOf}function ag(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Ys(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 cg(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Ys(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function ug(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Ys(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 lg(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function fg(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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 lc(e){return typeof e.handler=="function"}function dg(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["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=rg(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:og(i,s),envVar:sg(i,s)})}return o}function pg(e,t){const n=new Map,{props:r}=fg(e);for(const[o,s]of Object.entries(r)){let i="string";cg(s)?i="boolean":(ag(s)||ug(s))&&(i="json"),n.set(lg(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function xl(e){const{op:t,schema:n,transport:r,projection:o}=e,s=ng(t,o),i=n?dg(n):[],a=n?pg(n,i):new Map,c=n?Rm(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:lc(t)};if(lc(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function hg(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function mg(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function gg(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function go(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(gg(s))}return r.push(Um(e)),xm(r)}function yg(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const $g={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function fc(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new Al};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:yg(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:$g}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const vg={"decimal.js":"Decimal"};function wg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(vg).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${wg(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function bg(e,t){return`--${e}-${t}`}function Eg(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Wo(e){let t=e.replace(/[^a-zA-Z0-9_$]/g,"_");return(t===""||/^[0-9]/.test(t))&&(t=`_${t}`),t}const Sg=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],dc={invalid_argument:2,unauthenticated:3,permission_denied:3,not_found:4,internal:1};let $r=class 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 pc(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&Sg.includes(e.code)&&typeof e.toJSON=="function"}function Pl(e){return e.anyOf??e.oneOf}function Og(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["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:bg(i,s),envVar:Eg(i,s)})}return o}function Ho(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Pl(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 Ng(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Pl(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function hc(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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 _g(e){const t=/^#\/oneOf\/(\d+)$/.exec(e);if(t)return Number(t[1])}function kg(e){const t=Qs(e).replace(/[^a-zA-Z0-9-]+/g,"-").replace(/^-+|-+$/g,"");return t.length>0?t.toLowerCase():"branch"}function yo(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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=_g(c);if(u===void 0)continue;const l=o[u];if(!l)continue;const f=l.properties??{},p=l.required??[];i.push({value:a,commandName:kg(a),props:f,required:p})}if(i.length!==0)return{discriminatorProperty:s.propertyName,branches:i}}function Qs(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function Ag(e,t){if(!Bo.isAbsolute(t))return t;const n=Bo.relative(e,t);return!n.startsWith(".")&&!n.startsWith("/")?`./${n}`:n}const jg=["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 Tl(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 Cl(e,t,n,r){var o;for(const s of t){const i=Qs(s),a=Ng(n[s]),c=r.includes(s);a?(e.push(` .option('--${i}')`),((o=n[s])==null?void 0:o.default)===!0&&e.push(` .option('--no-${i}')`)):c?e.push(` .requiredOption('--${i} <${i}>')`):e.push(` .option('--${i} <${i}>')`)}}function Rl(e,t,n){return`${e}:${t}::${n}`}function Ml(e,t){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,paramNames:a,schemaProps:c,literalDomainArgs:u}=t,l=t.dispatchSchemaKey??`${r}:${o}`;e.push(" .action(async (opts: Record<string, unknown>) => {");const f=Object.entries(u??{}).map(([h,d])=>`'${h}': ${d}`),p=a.map(h=>Ho(c[h])?`'${h}': __apigenParseJsonArg('${Qs(h)}', opts['${h}'])`:`'${h}': opts['${h}']`);if(e.push(` const domainArgs: Record<string, unknown> = { ${[...f,...p].join(", ")} }`),s.length>0){const h=s.map(d=>{const m=d.flag.replace(/^--/,"").replace(/-([a-z])/g,(y,$)=>$.toUpperCase());return`'${d.field}': opts['${m}'] ?? process.env['${d.envVar}']`});e.push(` const envelope: Record<string, unknown> = { ${h.join(", ")} }`)}else i?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 Ig(e,t){const{varName:n,pkgId:r,fnName:o,bindings:s,needsSession:i,rootUnion:a}=t,c=Wo(`${r}_${o}_cmd`);e.push(`const ${c} = program.command('${o}')`);for(const u of a.branches){const l=Object.keys(u.props).filter(p=>p!==a.discriminatorProperty),f=u.required.filter(p=>p!==a.discriminatorProperty);e.push(`${c}`),e.push(` .command('${u.commandName}')`),Tl(e,s,i),Cl(e,l,u.props,f),Ml(e,{varName:n,pkgId:r,fnName:o,dispatchSchemaKey:Rl(r,o,u.commandName),bindings:s,needsSession:i,paramNames:l,schemaProps:u.props,literalDomainArgs:{[a.discriminatorProperty]:JSON.stringify(u.value)}})}}function xg(e){const t=e.options.name??"cli",n=e.options.version??"0.1.0",r=e.packages.some(i=>Object.values(i.schemas).some(a=>{const c=yo(a);if(c)return c.branches.some(l=>Object.keys(l.props).filter(f=>f!==c.discriminatorProperty).some(f=>Ho(l.props[f])));const{props:u}=hc(a);return Jo(a).some(l=>Ho(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 e.packages){const a=Wo(i.id),c=Ag(e.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(jg),o.push(""));const s=Object.fromEntries(e.packages.flatMap(i=>Object.entries(i.schemas).map(([a,c])=>[`${i.id}:${a}`,c])));for(const i of e.packages)for(const[a,c]of Object.entries(i.schemas)){const u=yo(c);if(u)for(const l of u.branches){const f=Rl(i.id,a,l.commandName);s[f]={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('${t}').version('${n}')`),o.push("");for(const i of e.packages){const a=Wo(i.id);for(const[c,u]of Object.entries(i.schemas)){const l=kl(u,"session"),f=Og(u),p=yo(u);if(p){Ig(o,{varName:a,pkgId:i.id,fnName:c,bindings:f,needsSession:l,rootUnion:p});continue}const h=Jo(u),{props:d,required:m}=hc(u);o.push("program"),o.push(` .command('${c}')`),Tl(o,f,l),Cl(o,h,d,m),Ml(o,{varName:a,pkgId:i.id,fnName:c,bindings:f,needsSession:l,paramNames:h,schemaProps:d})}}return o.push(""),o.push("program.parseAsync()"),{files:[{path:"cli.ts",content:o.join(`
|
|
4
|
+
`)}]}}function Pg(e){return{props:e.properties??{},required:e.required??[]}}function Tg(e){const t=e??{},n=Array.isArray(t.oneOf)&&t.discriminator?t.oneOf:[t],r={},o=new Map;for(const i of n){const{props:a,required:c}=Pg(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 Cg(e){const t=[],n=/"([^"]*)"|'([^']*)'|(\S+)/g;let r;for(;r=n.exec(e);)t.push(r[1]??r[2]??r[3]);return t}function Rg(e){const t=e.argv;return Array.isArray(t)?t.map(String):typeof t=="string"?Cg(t):process.argv.slice(2)}function Mg(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 Dg(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,s]of Object.entries(r.schemas)){const i=t.get(`${r.id}:${o}`)??Mg(o,s),a=xl({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 Lg(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 Dl(e){return!e||e.length===0?"":e.map(t=>`${t.name}${t.required?"":"?"}: ${t.type}`).join(", ")}function mc(e){const t=["Available commands:",""],n=[...e.entries()].sort(([r],[o])=>r.localeCompare(o));for(const[r,{plan:o}]of n){const s=Dl(o.params);t.push(` ${r}${s?` { ${s} }`:""}`)}return t.join(`
|
|
5
|
+
`)}function Vn(e){return new $r("invalid_argument",e)}function Ug(e,t){var n;const r={},o={};let s=0;for(;s<e.length;){const i=e[s];if(!i.startsWith("--"))throw Vn(`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,f=a;a.startsWith("no-")&&((n=t.get(a.slice(3)))==null?void 0:n.valueKind)==="boolean"&&(l=!0,f=a.slice(3));const p=t.get(f);if(!p)throw Vn(`Unknown option: --${a}. Available: ${[...t.keys()].sort().map(d=>`--${d}`).join(", ")}`);s++;let h;if(p.valueKind==="boolean")l?h=!1:c===void 0?h=!0:h=c!=="false";else{const d=c!==void 0?c:e[s++];if(d===void 0)throw Vn(`Missing value for --${a}`);if(p.valueKind==="json")try{h=JSON.parse(d)}catch(m){throw Vn(`Invalid JSON for --${a}: ${m.message}`)}else h=d}p.kind==="domain"?r[p.camelKey]=h:o[p.camelKey]=h}for(const i of t.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 Ll(e){const t=pc(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:String(e)};console.error(JSON.stringify(t)),process.exitCode=pc(e)?dc[e.code]:dc.internal}class Bg{constructor(t){this.signal=t,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}=Ug(t.rest,n.cliFlags);return{domainArgs:r,envelope:o,signal:this.signal}}writeResult(t,n,r){if(Bm(n))throw new $r("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))}writeError(t,n,r){Ll(n)}}function Fg(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("cli")||i.push(f)}return i}async function qg(e){var t,n,r;const o=e.logger??Cm();if((t=e.signal)!=null&&t.aborted){o.info("cli run: signal already aborted before dispatch — skipping");return}let s=Rg(e.options);s[0]==="--"&&(s=s.slice(1));const i=hg(e.options),a=mg(e.options),c=new Bg(e.signal),u=Dg(e),l=new Map;for(const U of u.values()){const q=l.get(U.pkgId);q?q.push(U):l.set(U.pkgId,[U])}const f={},p={};for(const U of e.packages){const q=l.get(U.id);if(!q||q.length===0)continue;if(!U.fns)throw new Error(`apigen-plugin-cli-output: package "${U.id}" has no functions`);const Q=U.fns,Z={},me={};for(const de of q)Z[de.plan.op.id]=de.schema,me[de.plan.op.id]=Q[de.fnName],f[de.plan.op.id]=de.schema,p[de.plan.op.id]=Q[de.fnName];const Ne=go(Z,i),Fe={fns:me,createClient:U.createClient,schemas:Z};for(const de of q)c.registerRoute(de.plan,on=>fc(de.plan,Ne,on,Fe))}const h=((n=e.packages[0])==null?void 0:n.id)??"ts",d=go(f,i),m={invoke:(U,q,Q)=>d(U,{operation:{id:U},ctx:new Al,domainArgs:q.domainArgs,envelope:q.envelope,signal:q.signal},Q),invokeOptions:{fns:p,schemas:f,createClient:(r=e.packages[0])==null?void 0:r.createClient}},y=Fg(i,a,h,e.operations??[],m);if(y.length>0){const U=go({},i),q={fns:{},schemas:{}};for(const Q of y){const Z=xl({op:Q,schema:Tg(Q.input),transport:"cli"});c.registerRoute(Z,me=>fc(Z,U,me,q))}}const $=c.routeTable();if(s.length===0||s[0]==="--help"||s[0]==="-h"){console.log(mc($));return}const v=Lg(s,$);if(!v){Ll(new $r("not_found",`Unknown command: ${s.join(" ")}
|
|
6
6
|
|
|
7
|
-
${hc($)}`));return}const{entry:E,rest:b}=v,{plan:O,dispatch:j}=E,C=O.cli.path.join(" ");if(b.includes("--help")||b.includes("-h")){const U=Ml(O.params);console.log(`${C}${U?` { ${U} }`:""}`);return}const z={rest:b};try{if(O.streaming)throw new $r("invalid_argument",`Command "${C}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const U=await c.readCall(z,O),q=Date.now(),Q=await j(U);await c.writeResult(z,Q,O),o.info({command:C,ms:Date.now()-q},`→ ${C}`)}catch(U){o.error({command:C,err:U},`✗ ${C}`),await c.writeError(z,U,O)}}const Bg={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 Ag(e)},run(e){return Ug(e)}};let tt=class 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 mc(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Fg(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:mc(i),path:s.map(mc),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}function qg(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 s=!0;for(const a of t){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 Vg={"decimal.js":"Decimal"};function Kg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Vg).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Kg(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Gg(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 zg(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:Gg(e.output)}}function Jg(e,t={}){const n=new Set(t.exclude??[]),r=new Map;for(const o of e){if(n.has(o.id))continue;const s=r.get(o.kind);s?s.push(o):r.set(o.kind,[o])}return r}function gc(e){return{type:"string",enum:[e]}}function yc(e,t){return{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}}function Hg(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(zg);if(e.length===1){const[o]=e,[s]=t;return{input:yc(s,gc(o.id)),output:{type:"array",items:s.resultSchema}}}const n=e.map((o,s)=>yc(t[s],gc(o.id))),r=qg(n);return{input:{oneOf:n,...r?{discriminator:r}:{}},output:{oneOf:t.map(o=>({type:"array",items:o.resultSchema}))},...r?{discriminator:r}:{}}}function Wg(e,t={}){const n=Jg(e.operations,t),r=[];for(const[o,s]of n){const{input:i,output:a}=Hg(s),c=Fg(`_batch/${o}`,e,{kind:o,safe:o==="query",input:i,output:a});r.push({...c,operationIds:s.map(u=>u.id)})}return r}const Wo="$apigen";let $c=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Yg(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new $c(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new $c("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 Qs="x-apigen-logical",Zs="x-apigen-codec",Yo="x-apigen-ctor",Qo="x-apigen-tojson",Qg="0.1.0";function vc(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 Lt(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 Lt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Ll(e,s,t);return Lt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return $o(e,t,n);const a=t.items;if(!a)return e.map(u=>St(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?St(u):Lt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Lt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return $o(e,t,n);const a=t.properties;if(!a)return St(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Lt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?$o(e,t,n):St(e)}function Ut(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 Ut(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Ll(e,s,t);return Ut(e,a,n)}const i=t.type;if(i==="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((u,l)=>{const f=a[l];return f===void 0?u:Ut(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ut(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Ut(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Zg(e,n):e}function Ll(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function $o(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Wo]:r,v:s}}catch{}}return St(e)}function Zg(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Wo in e){const n=e,r=n[Wo],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function St(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(St);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=St(r));return t}return null}function Xg(e){return{encode(t,n,r){const o=vc(e,r);return Lt(t,n,o)},decode(t,n,r){const o=vc(e,r);return Ut(t,n,o)}}}const Xs={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},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)}},ei={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},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)}},ti={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}},ni={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},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"))}},ey=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,ri={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"&&!ey.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Zo="NaN",Xo="Infinity",es="-Infinity",ty=new Set([Zo,Xo,es]),oi={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Zo:e===1/0?Xo:e===-1/0?es:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Zo)return NaN;if(e===Xo)return 1/0;if(e===es)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 ${[...ty].join(", ")}.`);return NaN}},ny=[Xs,ei,ti,ni,ri,oi];function ry(e,t={}){for(const n of ny)e.register(n,{override:t.override??!1})}Xs.id,ei.id,ti.id,ni.id,ri.id,oi.id;const Ul=Yg();ry(Ul);Xg(Ul.freeze());let oy=class{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)}};const sy={"decimal.js":"Decimal"};function iy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(sy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${iy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const ay=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];let Bl=class 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 Fl(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&ay.includes(e.code)&&typeof e.toJSON=="function"}function wc(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const si=new jr({allErrors:!0});Ir(si);for(const e of[Qs,Zs,Yo,Qo,"discriminator"])si.addKeyword({keyword:e,valid:!0});si.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);async function cy(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=Fl(n)?n:new Bl("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:wc("before-first-chunk",r)}:{ok:!1,carrier:wc("after-first-chunk",r,t.length)}}}function uy(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let lt=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function vo(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 ql(e,t){const n=e[Zs];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function ly(e,t,n){const r=ql(t,n);return r?r.encode(e,t,n):e}function fy(e,t,n){const r=ql(t,n);return r?r.decode(e,t,n):e}function dy(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Qs]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:vo(r)!==void 0},encode(r,o,s){const i=vo(o);if(!i)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 lt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new lt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return ly(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new lt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=vo(o);if(!a)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 lt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new lt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return fy(r,h,{...s,path:`${s.path}[${f}]`})}}}const py="x-apigen-instances";let Kn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function bc(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function hy(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Ec(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function my(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function gy(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Qs]==="nominal"?!0:o[Zs]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Kn("E_NOMINAL_CYCLE",`[${t}] 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=bc(s),c=typeof s[Qo]=="string"?s[Qo]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const g={};for(const[y,$]of Object.entries(d))g[y]=Ec($,a[y],{...i,path:`${i.path}/${y}`});return g}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const g=p[d];g!==void 0&&(l[d]=Ec(g,a[d],{...i,path:`${i.path}/${d}`}))}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 Kn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of hy(s))if(!(l in a))throw new Kn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[py]===!1)throw new Kn("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=bc(s),u={};for(const[l,f]of Object.entries(a))u[l]=my(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Yo]=="string"?s[Yo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const yy=[Xs,ei,ti,ni,ri,oi],$y={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Sc=gy({id:"ts.NominalSentinel",schema:$y}),vy={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Oc=dy({id:"ts.UnionSentinel",schema:vy});function wy(){const e=[...yy.map(t=>[t.id,t]),[Sc.id,Sc],[Oc.id,Oc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:Qg,codecs:wy()});const by=4,Ey=32;function ts(e){return Fl(e)?e:e instanceof Error?new Bl("internal",e.message):e}function Sy(e,t){if(e==="serial"||e==="chained")return 1;const n=t??by;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Ey)}function Oy(){}function Ny(e,t){var n;if(!e&&!t)return{signal:void 0,dispose:Oy};const r=new AbortController,o=()=>{r.abort(e==null?void 0:e.reason)};e&&(e.aborted?r.abort(e.reason):e.addEventListener("abort",o,{once:!0}));let s;return t!==void 0&&!r.signal.aborted&&(s=setTimeout(()=>{r.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(n=s.unref)==null||n.call(s)),{signal:r.signal,dispose(){e&&e.removeEventListener("abort",o),s&&clearTimeout(s)}}}async function Nc(e,t,n,r,o,s){const i=Ny(r.signal,s);try{const a=i.signal?{...r,signal:i.signal}:r,c=await e(t,a,o);if(uy(c)){const u=await cy(c);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const l=u.carrier;return{index:n,status:"rejected",reason:ts(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:ts(a)}}finally{i.dispose()}}async function _y(e,t,n,r,o={}){const s=o.mode??"parallel",i=o.onItemError??"continue",a=Sy(s,o.concurrency),c=new Array(n.length),u=d=>({index:d,status:"rejected",reason:ts(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 d=!1;for(let g=0;g<n.length;g++){if(d){c[g]=u(g);continue}const y=await Nc(e,t,g,n[g],r,o.itemTimeoutMs);c[g]=y,y.status==="rejected"&&(s==="chained"||i==="abort")&&(d=!0)}return c}let l=0,f=!1;const p=Math.max(1,Math.min(a,n.length)),h=Array.from({length:p},async()=>{for(;;){const d=l++;if(d>=n.length)return;if(f){c[d]=u(d);continue}const g=await Nc(e,t,d,n[d],r,o.itemTimeoutMs);c[d]=g,g.status==="rejected"&&i==="abort"&&(f=!0)}});return await Promise.all(h),c}const ky={"decimal.js":"Decimal"};function Ay(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ky).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ay(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function jy(e,t){const n=e.operation;if(typeof n!="string"||n.length===0)throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "operation" must be a non-empty string naming the target operation id');if(!t.includes(n))throw new tt("invalid_argument",`@adhd/apigen-plugin-batch: "operation" ("${n}") is not one of this mount's batchable operations: ${t.join(", ")}`);const r=e.items;if(!Array.isArray(r))throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "items" must be an array');const o=e.concurrency;if(o!==void 0&&typeof o!="number")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "concurrency" must be a number');const s=e.mode;if(s!==void 0&&s!=="parallel"&&s!=="serial"&&s!=="chained")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "mode" must be one of "parallel" | "serial" | "chained"');const i=e.onItemError;if(i!==void 0&&i!=="continue"&&i!=="abort")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "onItemError" must be one of "continue" | "abort"');const a=e.itemTimeoutMs;if(a!==void 0&&typeof a!="number")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "itemTimeoutMs" must be a number');return{operation:n,items:r,concurrency:o,mode:s,onItemError:i,itemTimeoutMs:a}}function Iy(e,t){return async n=>{if(!t)throw new tt("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=jy(n.data,e),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},s=r.items.map(i=>({operation:{id:r.operation},ctx:new oy,domainArgs:i??{},envelope:n.envelope,signal:n.signal}));return _y(t.invoke,r.operation,s,t.invokeOptions,o)}}function xy(e,t={},n){return Wg(e,t).map(r=>({...r,handler:Iy(r.operationIds,n)}))}const ns={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 xy(e,t,n)}}}},_c=new Set(["string","number","boolean","integer"]);function Py(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"?_c.has(n):Array.isArray(n)?n.every(r=>_c.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function Ty(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(Py)}const Cy={"decimal.js":"Decimal"};function Ry(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Cy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ry(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function kc(e){return e.words.join("-")}function Ac(e){return e.words.map(My).join("")}function jc(e){return e.words.join("_")}function Vl(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||Ty(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>kc(h)).join("/"),c=o.map(h=>jc(h)).join("_"),u=o.map(h=>jc(h)).slice(0,-1).join("."),l=Ac(o[o.length-2]??o[0]),f=Ac(o[o.length-1]),p=o.map(h=>kc(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function My(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function ii(e,t=5e3){e!==":memory:"&&L.mkdirSync(T.dirname(e),{recursive:!0});const n=new rm(e);if(n.pragma("journal_mode = WAL"),!Number.isInteger(t)||t<0)throw new RangeError(`openGraphBacklogStore: busyTimeoutMs must be a non-negative integer, got ${t}`);const r=om.createGraphBackend(n);return r.applySchema(),n.pragma(`busy_timeout = ${t}`),{db:n,graph:r}}function ai(e){e.db.close()}const Dy=[".git",".adhd","adhd.environment.yaml"];function wo(e){let t=T.resolve(e);const{root:n}=T.parse(t);for(;;){for(const o of Dy)if(L.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=T.dirname(t);if(r===t)return;t=r}}const Ly=new Set(["system","global","project"]);function Uy(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:wo(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&Ly.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:wo(n)??n}:{scope:s}}const o=wo(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function Ic(e){return`.${e}`}function By(e){const t=He.homedir();if(process.platform==="darwin")return T.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??T.join(t,"AppData","Roaming");return T.join(r,e)}const n=process.env.XDG_DATA_HOME??T.join(t,".local","share");return T.join(n,e)}function Fy(e){const t=e.orgNamespace,n=e.adhdRoot??T.join(He.homedir(),Ic(t)),r=e.adhdRoot??By(t),o={system:T.join(r,e.project,e.namespace),global:T.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=T.join(e.projectRoot,Ic(t),e.project,e.namespace)),o}function Kl(e,t){return t==="project"?e.project??e.global:e[t]}function qy(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Vy(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}const oe={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},k={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"},sr="tag:yaml.org,2002:",rt={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function xc(e){const t=[0];let n=e.indexOf(`
|
|
7
|
+
${mc($)}`));return}const{entry:E,rest:b}=v,{plan:O,dispatch:j}=E,C=O.cli.path.join(" ");if(b.includes("--help")||b.includes("-h")){const U=Dl(O.params);console.log(`${C}${U?` { ${U} }`:""}`);return}const z={rest:b};try{if(O.streaming)throw new $r("invalid_argument",`Command "${C}" is a streaming operation and is not supported over the cli transport (DEBT-APIGEN-SERVE-CORE-002 cli half).`);const U=await c.readCall(z,O),q=Date.now(),Q=await j(U);await c.writeResult(z,Q,O),o.info({command:C,ms:Date.now()-q},`→ ${C}`)}catch(U){o.error({command:C,err:U},`✗ ${C}`),await c.writeError(z,U,O)}}const Vg={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 xg(e)},run(e){return qg(e)}};let tt=class 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 gc(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function Kg(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:gc(i),path:s.map(gc),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}function Gg(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 s=!0;for(const a of t){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 zg={"decimal.js":"Decimal"};function Jg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(zg).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Jg(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Wg(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 Hg(e){return{operationConst:e.id,itemsSchema:e.input,resultSchema:Wg(e.output)}}function Yg(e,t={}){const n=new Set(t.exclude??[]),r=new Map;for(const o of e){if(n.has(o.id))continue;const s=r.get(o.kind);s?s.push(o):r.set(o.kind,[o])}return r}function yc(e){return{type:"string",enum:[e]}}function $c(e,t){return{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}}function Qg(e){if(e.length===0)throw new Error("buildBatchKindSchema: at least one operation is required");const t=e.map(Hg);if(e.length===1){const[o]=e,[s]=t;return{input:$c(s,yc(o.id)),output:{type:"array",items:s.resultSchema}}}const n=e.map((o,s)=>$c(t[s],yc(o.id))),r=Gg(n);return{input:{oneOf:n,...r?{discriminator:r}:{}},output:{oneOf:t.map(o=>({type:"array",items:o.resultSchema}))},...r?{discriminator:r}:{}}}function Zg(e,t={}){const n=Yg(e.operations,t),r=[];for(const[o,s]of n){const{input:i,output:a}=Qg(s),c=Kg(`_batch/${o}`,e,{kind:o,safe:o==="query",input:i,output:a});r.push({...c,operationIds:s.map(u=>u.id)})}return r}const Yo="$apigen";let vc=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function Xg(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new vc(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new vc("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 Zs="x-apigen-logical",Xs="x-apigen-codec",Qo="x-apigen-ctor",Zo="x-apigen-tojson",ey="0.1.0";function wc(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 Lt(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 Lt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Ul(e,s,t);return Lt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return $o(e,t,n);const a=t.items;if(!a)return e.map(u=>St(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?St(u):Lt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Lt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return $o(e,t,n);const a=t.properties;if(!a)return St(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Lt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?$o(e,t,n):St(e)}function Ut(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 Ut(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=Ul(e,s,t);return Ut(e,a,n)}const i=t.type;if(i==="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((u,l)=>{const f=a[l];return f===void 0?u:Ut(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ut(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Ut(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?ty(e,n):e}function Ul(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function $o(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Yo]:r,v:s}}catch{}}return St(e)}function ty(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Yo in e){const n=e,r=n[Yo],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function St(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(St);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=St(r));return t}return null}function ny(e){return{encode(t,n,r){const o=wc(e,r);return Lt(t,n,o)},decode(t,n,r){const o=wc(e,r);return Ut(t,n,o)}}}const ei={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},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)}},ti={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},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)}},ni={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}},ri={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},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"))}},ry=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,oi={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"&&!ry.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Xo="NaN",es="Infinity",ts="-Infinity",oy=new Set([Xo,es,ts]),si={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Xo:e===1/0?es:e===-1/0?ts:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Xo)return NaN;if(e===es)return 1/0;if(e===ts)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 ${[...oy].join(", ")}.`);return NaN}},sy=[ei,ti,ni,ri,oi,si];function iy(e,t={}){for(const n of sy)e.register(n,{override:t.override??!1})}ei.id,ti.id,ni.id,ri.id,oi.id,si.id;const Bl=Xg();iy(Bl);ny(Bl.freeze());let ay=class{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)}};const cy={"decimal.js":"Decimal"};function uy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(cy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${uy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const ly=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];let Fl=class 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 ql(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&ly.includes(e.code)&&typeof e.toJSON=="function"}function bc(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const ii=new jr({allErrors:!0});Ir(ii);for(const e of[Zs,Xs,Qo,Zo,"discriminator"])ii.addKeyword({keyword:e,valid:!0});ii.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);async function fy(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=ql(n)?n:new Fl("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:bc("before-first-chunk",r)}:{ok:!1,carrier:bc("after-first-chunk",r,t.length)}}}function dy(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}let lt=class extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}};function vo(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 Vl(e,t){const n=e[Xs];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function py(e,t,n){const r=Vl(t,n);return r?r.encode(e,t,n):e}function hy(e,t,n){const r=Vl(t,n);return r?r.decode(e,t,n):e}function my(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Zs]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:vo(r)!==void 0},encode(r,o,s){const i=vo(o);if(!i)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 lt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new lt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return py(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new lt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=vo(o);if(!a)throw new lt("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 lt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new lt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return hy(r,h,{...s,path:`${s.path}[${f}]`})}}}const gy="x-apigen-instances";let Kn=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function Ec(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function yy(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Sc(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function $y(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function vy(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Zs]==="nominal"?!0:o[Xs]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new Kn("E_NOMINAL_CYCLE",`[${t}] 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=Ec(s),c=typeof s[Zo]=="string"?s[Zo]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=Sc($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=Sc(m,a[d],{...i,path:`${i.path}/${d}`}))}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 Kn("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of yy(s))if(!(l in a))throw new Kn("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[gy]===!1)throw new Kn("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=Ec(s),u={};for(const[l,f]of Object.entries(a))u[l]=$y(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Qo]=="string"?s[Qo]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const wy=[ei,ti,ni,ri,oi,si],by={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Oc=vy({id:"ts.NominalSentinel",schema:by}),Ey={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Nc=my({id:"ts.UnionSentinel",schema:Ey});function Sy(){const e=[...wy.map(t=>[t.id,t]),[Oc.id,Oc],[Nc.id,Nc]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:ey,codecs:Sy()});const Oy=4,Ny=32;function ns(e){return ql(e)?e:e instanceof Error?new Fl("internal",e.message):e}function _y(e,t){if(e==="serial"||e==="chained")return 1;const n=t??Oy;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),Ny)}function ky(){}function Ay(e,t){var n;if(!e&&!t)return{signal:void 0,dispose:ky};const r=new AbortController,o=()=>{r.abort(e==null?void 0:e.reason)};e&&(e.aborted?r.abort(e.reason):e.addEventListener("abort",o,{once:!0}));let s;return t!==void 0&&!r.signal.aborted&&(s=setTimeout(()=>{r.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(n=s.unref)==null||n.call(s)),{signal:r.signal,dispose(){e&&e.removeEventListener("abort",o),s&&clearTimeout(s)}}}async function _c(e,t,n,r,o,s){const i=Ay(r.signal,s);try{const a=i.signal?{...r,signal:i.signal}:r,c=await e(t,a,o);if(dy(c)){const u=await fy(c);if(u.ok)return{index:n,status:"fulfilled",chunks:u.chunks};const l=u.carrier;return{index:n,status:"rejected",reason:ns(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:ns(a)}}finally{i.dispose()}}async function jy(e,t,n,r,o={}){const s=o.mode??"parallel",i=o.onItemError??"continue",a=_y(s,o.concurrency),c=new Array(n.length),u=d=>({index:d,status:"rejected",reason:ns(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 d=!1;for(let m=0;m<n.length;m++){if(d){c[m]=u(m);continue}const y=await _c(e,t,m,n[m],r,o.itemTimeoutMs);c[m]=y,y.status==="rejected"&&(s==="chained"||i==="abort")&&(d=!0)}return c}let l=0,f=!1;const p=Math.max(1,Math.min(a,n.length)),h=Array.from({length:p},async()=>{for(;;){const d=l++;if(d>=n.length)return;if(f){c[d]=u(d);continue}const m=await _c(e,t,d,n[d],r,o.itemTimeoutMs);c[d]=m,m.status==="rejected"&&i==="abort"&&(f=!0)}});return await Promise.all(h),c}const Iy={"decimal.js":"Decimal"};function xy(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Iy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${xy(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Py(e,t){const n=e.operation;if(typeof n!="string"||n.length===0)throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "operation" must be a non-empty string naming the target operation id');if(!t.includes(n))throw new tt("invalid_argument",`@adhd/apigen-plugin-batch: "operation" ("${n}") is not one of this mount's batchable operations: ${t.join(", ")}`);const r=e.items;if(!Array.isArray(r))throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "items" must be an array');const o=e.concurrency;if(o!==void 0&&typeof o!="number")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "concurrency" must be a number');const s=e.mode;if(s!==void 0&&s!=="parallel"&&s!=="serial"&&s!=="chained")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "mode" must be one of "parallel" | "serial" | "chained"');const i=e.onItemError;if(i!==void 0&&i!=="continue"&&i!=="abort")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "onItemError" must be one of "continue" | "abort"');const a=e.itemTimeoutMs;if(a!==void 0&&typeof a!="number")throw new tt("invalid_argument",'@adhd/apigen-plugin-batch: "itemTimeoutMs" must be a number');return{operation:n,items:r,concurrency:o,mode:s,onItemError:i,itemTimeoutMs:a}}function Ty(e,t){return async n=>{if(!t)throw new tt("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=Py(n.data,e),o={concurrency:r.concurrency,mode:r.mode,onItemError:r.onItemError,itemTimeoutMs:r.itemTimeoutMs},s=r.items.map(i=>({operation:{id:r.operation},ctx:new ay,domainArgs:i??{},envelope:n.envelope,signal:n.signal}));return jy(t.invoke,r.operation,s,t.invokeOptions,o)}}function Cy(e,t={},n){return Zg(e,t).map(r=>({...r,handler:Ty(r.operationIds,n)}))}const rs={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 Cy(e,t,n)}}}},kc=new Set(["string","number","boolean","integer"]);function Ry(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"?kc.has(n):Array.isArray(n)?n.every(r=>kc.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function My(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(Ry)}const Dy={"decimal.js":"Decimal"};function Ly(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Dy).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Ly(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ac(e){return e.words.join("-")}function jc(e){return e.words.map(Uy).join("")}function Ic(e){return e.words.join("_")}function Kl(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||My(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Ac(h)).join("/"),c=o.map(h=>Ic(h)).join("_"),u=o.map(h=>Ic(h)).slice(0,-1).join("."),l=jc(o[o.length-2]??o[0]),f=jc(o[o.length-1]),p=o.map(h=>Ac(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function Uy(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}async function ai(e,t=5e3){if(e!==":memory:"&&L.mkdirSync(T.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 Uo.createStoreAdapter({dbPath:e},{migrateOnAdapterChange:e!==":memory:"&&L.existsSync(e)});await n.pragmaSet("busy_timeout",t);const r=am.createGraphBackend(n);return await r.applySchema(),{adapter:n,graph:r}}async function Gl(e){await e.adapter.close()}async function zl(e){if(e)try{await Gl(e)}catch(t){console.error(`backlog: store close failed (data is durable; WAL checkpoint may be pending): ${t instanceof Error?t.message:String(t)}`)}}const By=[".git",".adhd","adhd.environment.yaml"];function wo(e){let t=T.resolve(e);const{root:n}=T.parse(t);for(;;){for(const o of By)if(L.existsSync(`${t}/${o}`))return t;if(t===n)return;const r=T.dirname(t);if(r===t)return;t=r}}const Fy=new Set(["system","global","project"]);function qy(e,t){const n=e.cwd??process.cwd();if(e.scope)return e.scope==="project"?{scope:"project",projectRoot:wo(n)??n}:{scope:e.scope};const r=t.ADHD_ENV_SCOPE;if(r!==void 0&&Fy.has(r)){const s=r;return s==="project"?{scope:"project",projectRoot:wo(n)??n}:{scope:s}}const o=wo(n);return o?{scope:"project",projectRoot:o}:{scope:"global"}}function xc(e){return`.${e}`}function Vy(e){const t=We.homedir();if(process.platform==="darwin")return T.join(t,"Library","Application Support",e);if(process.platform==="win32"){const r=process.env.APPDATA??T.join(t,"AppData","Roaming");return T.join(r,e)}const n=process.env.XDG_DATA_HOME??T.join(t,".local","share");return T.join(n,e)}function Ky(e){const t=e.orgNamespace,n=e.adhdRoot??T.join(We.homedir(),xc(t)),r=e.adhdRoot??Vy(t),o={system:T.join(r,e.project,e.namespace),global:T.join(n,e.project,e.namespace)};return e.projectRoot&&(o.project=T.join(e.projectRoot,xc(t),e.project,e.namespace)),o}function Jl(e,t){return t==="project"?e.project??e.global:e[t]}function Gy(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function zy(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var o=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,o.get?o:{enumerable:!0,get:function(){return e[r]}})}),n}const oe={ANCHOR:"&",COMMENT:"#",TAG:"!",DIRECTIVES_END:"-",DOCUMENT_END:"."},k={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"},sr="tag:yaml.org,2002:",rt={MAP:"tag:yaml.org,2002:map",SEQ:"tag:yaml.org,2002:seq",STR:"tag:yaml.org,2002:str"};function Pc(e){const t=[0];let n=e.indexOf(`
|
|
8
8
|
`);for(;n!==-1;)n+=1,t.push(n),n=e.indexOf(`
|
|
9
|
-
`,n);return t}function
|
|
10
|
-
`;)--s;return r.slice(o,s)}function
|
|
11
|
-
${c}${u}${a}`}let te=class
|
|
9
|
+
`,n);return t}function Wl(e){let t,n;return typeof e=="string"?(t=Pc(e),n=e):(Array.isArray(e)&&(e=e[0]),e&&e.context&&(e.lineStarts||(e.lineStarts=Pc(e.context.src)),t=e.lineStarts,n=e.context.src)),{lineStarts:t,src:n}}function os(e,t){if(typeof e!="number"||e<0)return null;const{lineStarts:n,src:r}=Wl(t);if(!n||!r||e>r.length)return null;for(let s=0;s<n.length;++s){const i=n[s];if(e<i)return{line:s,col:e-n[s-1]+1};if(e===i)return{line:s+1,col:1}}const o=n.length;return{line:o,col:e-n[o-1]+1}}function Jy(e,t){const{lineStarts:n,src:r}=Wl(t);if(!n||!(e>=1)||e>n.length)return null;const o=n[e-1];let s=n[e];for(;s&&s>o&&r[s-1]===`
|
|
10
|
+
`;)--s;return r.slice(o,s)}function Wy({start:e,end:t},n,r=80){let o=Jy(e.line,n);if(!o)return null;let{col:s}=e;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="";t&&(t.line===e.line&&s+(t.col-e.col)<=r+1?i=t.col-e.col:(i=Math.min(o.length+1,r)-s,a="…"));const c=s>1?" ".repeat(s-1):"",u="^".repeat(i);return`${o}
|
|
11
|
+
${c}${u}${a}`}let te=class Hl{static copy(t){return new Hl(t.start,t.end)}constructor(t,n){this.start=t,this.end=n||t}isEmpty(){return typeof this.start!="number"||!this.end||this.end<=this.start}setOrigRange(t,n){const{start:r,end:o}=this;if(t.length===0||o<=t[0])return this.origStart=r,this.origEnd=o,n;let s=n;for(;s<t.length&&!(t[s]>r);)++s;this.origStart=r+s;const i=s;for(;s<t.length&&!(t[s]>=o);)++s;return this.origEnd=o+s,i}},I=class qe{static addStringTerminator(t,n,r){if(r[r.length-1]===`
|
|
12
12
|
`)return r;const o=qe.endOfWhiteSpace(t,n);return o>=t.length||t[o]===`
|
|
13
13
|
`?r+`
|
|
14
14
|
`:r}static atDocumentBoundary(t,n,r){const o=t[n];if(!o)return!0;const s=t[n-1];if(s&&s!==`
|
|
@@ -26,42 +26,42 @@ ${c}${u}${a}`}let te=class zl{static copy(t){return new zl(t.start,t.end)}constr
|
|
|
26
26
|
`;){switch(a){case`
|
|
27
27
|
`:o=0,n+=1,i+=`
|
|
28
28
|
`;break;case" ":o<=r&&(s=!0),n=qe.endOfWhiteSpace(t,n+2)-1;break;case" ":o+=1,n+=1;break}a=t[n+1]}return i||(i=" "),a&&o<=r&&(s=!0),{fold:i,offset:n,error:s}}constructor(t,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=t,this.value=null}getPropValue(t,n,r){if(!this.context)return null;const{src:o}=this.context,s=this.props[t];return s&&o[s.start]===n?o.slice(s.start+(r?1:0),s.end):null}get anchor(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,oe.ANCHOR,!0);if(n!=null)return n}return null}get comment(){const t=[];for(let n=0;n<this.props.length;++n){const r=this.getPropValue(n,oe.COMMENT,!0);r!=null&&t.push(r)}return t.length>0?t.join(`
|
|
29
|
-
`):null}commentHasRequiredWhitespace(t){const{src:n}=this.context;if(this.header&&t===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return t!==r||qe.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]===oe.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]!==oe.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[k.FLOW_MAP,k.FLOW_SEQ,k.QUOTE_DOUBLE,k.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const t=
|
|
30
|
-
`)return!0;return!1}parseComment(t){const{src:n}=this.context;if(n[t]===oe.COMMENT){const r=qe.endOfLine(n,t+1),o=new te(t,r);return this.props.push(o),r}return t}setOrigRanges(t,n){return this.range&&(n=this.range.setOrigRange(t,n)),this.valueRange&&this.valueRange.setOrigRange(t,n),this.props.forEach(r=>r.setOrigRange(t,n)),n}toString(){const{context:{src:t},range:n,value:r}=this;if(r!=null)return r;const o=t.slice(n.start,n.end);return qe.addStringTerminator(t,n.end,o)}},At=class extends Error{constructor(t,n,r){if(!r||!(n instanceof I))throw new Error(`Invalid arguments for new ${t}`);super(),this.name=t,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const t=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new te(this.offset,this.offset+1);const n=t&&
|
|
29
|
+
`):null}commentHasRequiredWhitespace(t){const{src:n}=this.context;if(this.header&&t===this.header.end||!this.valueRange)return!1;const{end:r}=this.valueRange;return t!==r||qe.atBlank(n,r-1)}get hasComment(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]===oe.COMMENT)return!0}return!1}get hasProps(){if(this.context){const{src:t}=this.context;for(let n=0;n<this.props.length;++n)if(t[this.props[n].start]!==oe.COMMENT)return!0}return!1}get includesTrailingLines(){return!1}get jsonLike(){return[k.FLOW_MAP,k.FLOW_SEQ,k.QUOTE_DOUBLE,k.QUOTE_SINGLE].indexOf(this.type)!==-1}get rangeAsLinePos(){if(!this.range||!this.context)return;const t=os(this.range.start,this.context.root);if(!t)return;const n=os(this.range.end,this.context.root);return{start:t,end:n}}get rawValue(){if(!this.valueRange||!this.context)return null;const{start:t,end:n}=this.valueRange;return this.context.src.slice(t,n)}get tag(){for(let t=0;t<this.props.length;++t){const n=this.getPropValue(t,oe.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:t,end:n}=this.valueRange,{src:r}=this.context;for(let o=t;o<n;++o)if(r[o]===`
|
|
30
|
+
`)return!0;return!1}parseComment(t){const{src:n}=this.context;if(n[t]===oe.COMMENT){const r=qe.endOfLine(n,t+1),o=new te(t,r);return this.props.push(o),r}return t}setOrigRanges(t,n){return this.range&&(n=this.range.setOrigRange(t,n)),this.valueRange&&this.valueRange.setOrigRange(t,n),this.props.forEach(r=>r.setOrigRange(t,n)),n}toString(){const{context:{src:t},range:n,value:r}=this;if(r!=null)return r;const o=t.slice(n.start,n.end);return qe.addStringTerminator(t,n.end,o)}},At=class extends Error{constructor(t,n,r){if(!r||!(n instanceof I))throw new Error(`Invalid arguments for new ${t}`);super(),this.name=t,this.message=r,this.source=n}makePretty(){if(!this.source)return;this.nodeType=this.source.type;const t=this.source.context&&this.source.context.root;if(typeof this.offset=="number"){this.range=new te(this.offset,this.offset+1);const n=t&&os(this.offset,t);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=t&&Wy(this.linePos,t);o&&(this.message+=`:
|
|
31
31
|
|
|
32
32
|
${o}
|
|
33
|
-
`)}delete this.source}},Nn=class extends At{constructor(t,n){super("YAMLReferenceError",t,n)}},F=class extends At{constructor(t,n){super("YAMLSemanticError",t,n)}},fe=class extends At{constructor(t,n){super("YAMLSyntaxError",t,n)}},en=class extends At{constructor(t,n){super("YAMLWarning",t,n)}};function he(e,t,n){return(t=
|
|
33
|
+
`)}delete this.source}},Nn=class extends At{constructor(t,n){super("YAMLReferenceError",t,n)}},F=class extends At{constructor(t,n){super("YAMLSemanticError",t,n)}},fe=class extends At{constructor(t,n){super("YAMLSyntaxError",t,n)}},en=class extends At{constructor(t,n){super("YAMLWarning",t,n)}};function he(e,t,n){return(t=Yy(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Hy(e,t){if(typeof e!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function Yy(e){var t=Hy(e,"string");return typeof t=="symbol"?t:t+""}let Yl=class ss extends I{static endOfLine(t,n,r){let o=t[n],s=n;for(;o&&o!==`
|
|
34
34
|
`&&!(r&&(o==="["||o==="]"||o==="{"||o==="}"||o===","));){const i=t[s+1];if(o===":"&&(!i||i===`
|
|
35
35
|
`||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:t,end:n}=this.valueRange;const{src:r}=this.context;let o=r[n-1];for(;t<n&&(o===`
|
|
36
36
|
`||o===" "||o===" ");)o=r[--n-1];let s="";for(let a=t;a<n;++a){const c=r[a];if(c===`
|
|
37
37
|
`){const{fold:u,offset:l}=I.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!==`
|
|
38
38
|
`&&(s+=a>u?r.slice(u,a+1):c)}else s+=c}const i=r[t];switch(i){case" ":{const a="Plain value cannot start with a tab character";return{errors:[new F(this,a)],str:s}}case"@":case"`":{const a=`Plain value cannot start with reserved character ${i}`;return{errors:[new F(this,a)],str:s}}default:return s}}parseBlockValue(t){const{indent:n,inFlow:r,src:o}=this.context;let s=t,i=t;for(let a=o[s];a===`
|
|
39
39
|
`&&!I.atDocumentBoundary(o,s+1);a=o[s]){const c=I.endOfBlockIndent(o,n,s+1);if(c===null||o[c]==="#")break;o[c]===`
|
|
40
|
-
`?s=c:(i=
|
|
41
|
-
`&&(s=
|
|
40
|
+
`?s=c:(i=ss.endOfLine(o,c,r),s=i)}return this.valueRange.isEmpty()&&(this.valueRange.start=t),this.valueRange.end=i,i}parse(t,n){this.context=t;const{inFlow:r,src:o}=t;let s=n;const i=o[s];return i&&i!=="#"&&i!==`
|
|
41
|
+
`&&(s=ss.endOfLine(o,n,r)),this.valueRange=new te(n,s),s=I.endOfWhiteSpace(o,s),s=this.parseComment(s),(!this.hasComment||this.valueRange.isEmpty())&&(s=this.parseBlockValue(s)),s}},_n=class extends I{constructor(){super(k.BLANK_LINE)}get includesTrailingLines(){return!0}parse(t,n){return this.context=t,this.range=new te(n,n+1),n+1}};class ci extends I{constructor(t,n){super(t,n),this.node=null}get includesTrailingLines(){return!!this.node&&this.node.includesTrailingLines}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{atLineStart:s,lineStart:i}=t;!s&&this.type===k.SEQ_ITEM&&(this.error=new F(this,"Sequence items must not have preceding content on the same line"));const a=s?n-i:t.indent;let c=I.endOfWhiteSpace(o,n+1),u=o[c];const l=u==="#",f=[];let p=null;for(;u===`
|
|
42
42
|
`||u==="#";){if(u==="#"){const d=I.endOfLine(o,c+1);f.push(new te(c,d)),c=d}else{s=!0,i=c+1;const d=I.endOfWhiteSpace(o,i);o[d]===`
|
|
43
|
-
`&&f.length===0&&(p=new _n,i=p.parse({src:o},i)),c=I.endOfIndent(o,i)}u=o[c]}if(I.nextNodeIsIndented(u,c-(i+a),this.type!==k.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(p){const d=t.parent.items||t.parent.contents;d&&d.push(p)}f.length&&Array.prototype.push.apply(this.props,f),c=this.node.range.end}else if(l){const d=f[0];this.props.push(d),c=d.end}else c=I.endOfLine(o,n+1);const h=this.node?this.node.valueRange.end:c;return this.valueRange=new te(n,h),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.node?this.node.setOrigRanges(t,n):n}toString(){const{context:{src:t},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?t.slice(r.start,n.range.start)+String(n):t.slice(r.start,r.end);return I.addStringTerminator(t,r.end,s)}}let mn=class extends I{constructor(){super(k.COMMENT)}parse(t,n){this.context=t;const r=this.parseComment(n);return this.range=new te(n,r),r}};function
|
|
44
|
-
`?!1:
|
|
43
|
+
`&&f.length===0&&(p=new _n,i=p.parse({src:o},i)),c=I.endOfIndent(o,i)}u=o[c]}if(I.nextNodeIsIndented(u,c-(i+a),this.type!==k.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(p){const d=t.parent.items||t.parent.contents;d&&d.push(p)}f.length&&Array.prototype.push.apply(this.props,f),c=this.node.range.end}else if(l){const d=f[0];this.props.push(d),c=d.end}else c=I.endOfLine(o,n+1);const h=this.node?this.node.valueRange.end:c;return this.valueRange=new te(n,h),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.node?this.node.setOrigRanges(t,n):n}toString(){const{context:{src:t},node:n,range:r,value:o}=this;if(o!=null)return o;const s=n?t.slice(r.start,n.range.start)+String(n):t.slice(r.start,r.end);return I.addStringTerminator(t,r.end,s)}}let mn=class extends I{constructor(){super(k.COMMENT)}parse(t,n){this.context=t;const r=this.parseComment(n);return this.range=new te(n,r),r}};function is(e){let t=e;for(;t instanceof ci;)t=t.node;if(!(t instanceof Ql))return null;const n=t.items.length;let r=-1;for(let i=n-1;i>=0;--i){const a=t.items[i];if(a.type===k.COMMENT){const{indent:c,lineStart:u}=a.context;if(c>0&&a.range.start>=u+c)break;r=i}else if(a.type===k.BLANK_LINE)r=i;else break}if(r===-1)return null;const o=t.items.splice(r,n-r),s=o[0].range.start;for(;t.range.end=s,t.valueRange&&t.valueRange.end>s&&(t.valueRange.end=s),t!==e;)t=t.context.parent;return o}let Ql=class as extends I{static nextContentHasIndent(t,n,r){const o=I.endOfLine(t,n)+1;n=I.endOfWhiteSpace(t,o);const s=t[n];return s?n>=o+r?!0:s!=="#"&&s!==`
|
|
44
|
+
`?!1:as.nextContentHasIndent(t,n,r):!1}constructor(t){super(t.type===k.SEQ_ITEM?k.SEQ:k.MAP);for(let r=t.props.length-1;r>=0;--r)if(t.props[r].start<t.context.lineStart){this.props=t.props.slice(0,r+1),t.props=t.props.slice(r+1);const o=t.props[0]||t.valueRange;t.range.start=o.start;break}this.items=[t];const n=is(t);n&&Array.prototype.push.apply(this.items,n)}get includesTrailingLines(){return this.items.length>0}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let s=I.startOfLine(o,n);const i=this.items[0];i.context.parent=this,this.valueRange=te.copy(i.valueRange);const a=i.range.start-i.context.lineStart;let c=n;c=I.normalizeOffset(o,c);let u=o[c],l=I.endOfWhiteSpace(o,s)===c,f=!1;for(;u;){for(;u===`
|
|
45
45
|
`||u==="#";){if(l&&u===`
|
|
46
|
-
`&&!f){const d=new _n;if(c=d.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(d),c-=1}else if(u==="#"){if(c<s+a&&!
|
|
47
|
-
`||
|
|
48
|
-
`||d===" "||d===" "){const
|
|
49
|
-
`&&(s=d+1,l=!0)}const h=
|
|
46
|
+
`&&!f){const d=new _n;if(c=d.parse({src:o},c),this.valueRange.end=c,c>=o.length){u=null;break}this.items.push(d),c-=1}else if(u==="#"){if(c<s+a&&!as.nextContentHasIndent(o,c,a))return c;const d=new mn;if(c=d.parse({indent:a,lineStart:s,src:o},c),this.items.push(d),this.valueRange.end=c,c>=o.length){u=null;break}}if(s=c+1,c=I.endOfIndent(o,s),I.atBlank(o,c)){const d=I.endOfWhiteSpace(o,c),m=o[d];(!m||m===`
|
|
47
|
+
`||m==="#")&&(c=d)}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 d="All collection items must start at the same column";this.error=new fe(this,d)}}if(i.type===k.SEQ_ITEM){if(u!=="-"){s>n&&(c=s);break}}else if(u==="-"&&!this.error){const d=o[c+1];if(!d||d===`
|
|
48
|
+
`||d===" "||d===" "){const m="A collection cannot be both a mapping and a sequence";this.error=new fe(this,m)}}const p=r({atLineStart:l,inCollection:!0,indent:a,lineStart:s,parent:this},c);if(!p)return c;if(this.items.push(p),this.valueRange.end=p.valueRange.end,c=I.normalizeOffset(o,p.range.end),u=o[c],l=!1,f=p.includesTrailingLines,u){let d=c-1,m=o[d];for(;m===" "||m===" ";)m=o[--d];m===`
|
|
49
|
+
`&&(s=d+1,l=!0)}const h=is(p);h&&Array.prototype.push.apply(this.items,h)}return c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{n=r.setOrigRanges(t,n)}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;let s=t.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 I.addStringTerminator(t,r.end,s)}};class Qy extends I{constructor(){super(k.DIRECTIVE),this.name=null}get parameters(){const t=this.rawValue;return t?t.trim().split(/[ \t]+/):[]}parseName(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
|
|
50
50
|
`&&o!==" "&&o!==" ";)o=n[r+=1];return this.name=n.slice(t,r),r}parseParameters(t){const{src:n}=this.context;let r=t,o=n[r];for(;o&&o!==`
|
|
51
|
-
`&&o!=="#";)o=n[r+=1];return this.valueRange=new te(t,r),r}parse(t,n){this.context=t;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new te(n,r),r}}let
|
|
52
|
-
`?r:n}constructor(){super(k.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(t){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=t;for(;!I.atDocumentBoundary(n,s,oe.DIRECTIVES_END);)switch(s=
|
|
53
|
-
`:if(r){const i=new _n;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new mn;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new
|
|
54
|
-
`:if(i){const a=new _n;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 mn;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=I.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=
|
|
51
|
+
`&&o!=="#";)o=n[r+=1];return this.valueRange=new te(t,r),r}parse(t,n){this.context=t;let r=this.parseName(n+1);return r=this.parseParameters(r),r=this.parseComment(r),this.range=new te(n,r),r}}let Zy=class cs extends I{static startCommentOrEndBlankLine(t,n){const r=I.endOfWhiteSpace(t,n),o=t[r];return o==="#"||o===`
|
|
52
|
+
`?r:n}constructor(){super(k.DOCUMENT),this.directives=null,this.contents=null,this.directivesEndMarker=null,this.documentEndMarker=null}parseDirectives(t){const{src:n}=this.context;this.directives=[];let r=!0,o=!1,s=t;for(;!I.atDocumentBoundary(n,s,oe.DIRECTIVES_END);)switch(s=cs.startCommentOrEndBlankLine(n,s),n[s]){case`
|
|
53
|
+
`:if(r){const i=new _n;s=i.parse({src:n},s),s<n.length&&this.directives.push(i)}else s+=1,r=!0;break;case"#":{const i=new mn;s=i.parse({src:n},s),this.directives.push(i),r=!1}break;case"%":{const i=new Qy;s=i.parse({parent:this,src:n},s),this.directives.push(i),o=!0,r=!1}break;default:return o?this.error=new F(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s}return n[s]?(this.directivesEndMarker=new te(s,s+3),s+3):(o?this.error=new F(this,"Missing directives-end indicator line"):this.directives.length>0&&(this.contents=this.directives,this.directives=[]),s)}parseContents(t){const{parseNode:n,src:r}=this.context;this.contents||(this.contents=[]);let o=t;for(;r[o-1]==="-";)o-=1;let s=I.endOfWhiteSpace(r,t),i=o===t;for(this.valueRange=new te(s);!I.atDocumentBoundary(r,s,oe.DOCUMENT_END);){switch(r[s]){case`
|
|
54
|
+
`:if(i){const a=new _n;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 mn;s=a.parse({src:r},s),this.contents.push(a),i=!1}break;default:{const a=I.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=is(c);u&&Array.prototype.push.apply(this.contents,u)}}s=cs.startCommentOrEndBlankLine(r,s)}if(this.valueRange.end=s,r[s]&&(this.documentEndMarker=new te(s,s+3),s+=3,r[s])){if(s=I.endOfWhiteSpace(r,s),r[s]==="#"){const a=new mn;s=a.parse({src:r},s),this.contents.push(a)}switch(r[s]){case`
|
|
55
55
|
`: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(t,n){t.root=this,this.context=t;const{src:r}=t;let o=r.charCodeAt(n)===65279?n+1:n;return o=this.parseDirectives(o),o=this.parseContents(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.directives.forEach(r=>{n=r.setOrigRanges(t,n)}),this.directivesEndMarker&&(n=this.directivesEndMarker.setOrigRange(t,n)),this.contents.forEach(r=>{n=r.setOrigRanges(t,n)}),this.documentEndMarker&&(n=this.documentEndMarker.setOrigRange(t,n)),n}toString(){const{contents:t,directives:n,value:r}=this;if(r!=null)return r;let o=n.join("");return t.length>0&&((n.length>0||t[0].type===k.COMMENT)&&(o+=`---
|
|
56
56
|
`),o+=t.join("")),o[o.length-1]!==`
|
|
57
57
|
`&&(o+=`
|
|
58
|
-
`),o}},
|
|
58
|
+
`),o}},Xy=class extends I{parse(e,t){this.context=e;const{src:n}=e;let r=I.endOfIdentifier(n,t+1);return this.valueRange=new te(t+1,r),r=I.endOfWhiteSpace(n,r),r=this.parseComment(r),r}};const Ze={CLIP:"CLIP",KEEP:"KEEP",STRIP:"STRIP"};class e$ extends I{constructor(t,n){super(t,n),this.blockIndent=null,this.chomping=Ze.CLIP,this.header=null}get includesTrailingLines(){return this.chomping===Ze.KEEP}get strValue(){if(!this.valueRange||!this.context)return null;let{start:t,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===`
|
|
59
59
|
`||i===" "||i===" ";){if(n-=1,n<=t){if(this.chomping===Ze.KEEP)break;return""}i===`
|
|
60
|
-
`&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===Ze.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===k.BLOCK_FOLDED;let l=!0,f="",p="",h=!1;for(let d=t;d<n;++d){for(let y=0;y<c&&o[d]===" ";++y)d+=1;const
|
|
60
|
+
`&&(s=n),i=o[n-1]}let a=n+1;s&&(this.chomping===Ze.KEEP?(a=s,n=this.valueRange.end):n=s);const c=r+this.blockIndent,u=this.type===k.BLOCK_FOLDED;let l=!0,f="",p="",h=!1;for(let d=t;d<n;++d){for(let y=0;y<c&&o[d]===" ";++y)d+=1;const m=o[d];if(m===`
|
|
61
61
|
`)p===`
|
|
62
62
|
`?f+=`
|
|
63
63
|
`:p=`
|
|
64
|
-
`;else{const y=I.endOfLine(o,d),$=o.slice(d,y);d=y,u&&(
|
|
64
|
+
`;else{const y=I.endOfLine(o,d),$=o.slice(d,y);d=y,u&&(m===" "||m===" ")&&d<a?(p===" "?p=`
|
|
65
65
|
`:!h&&!l&&p===`
|
|
66
66
|
`&&(p=`
|
|
67
67
|
|
|
@@ -71,7 +71,7 @@ ${o}
|
|
|
71
71
|
`&&(s+=1,!I.atDocumentBoundary(r,s));c=r[s]){const u=I.endOfBlockIndent(r,n,s);if(u===null)break;const l=r[u],f=u-(s+n);if(this.blockIndent){if(l&&l!==`
|
|
72
72
|
`&&f<this.blockIndent){if(r[u]==="#")break;if(!this.error){const p=`Block scalars must not be less indented than their ${o?"explicit indentation indicator":"first line"}`;this.error=new F(this,p)}}}else if(r[u]!==`
|
|
73
73
|
`){if(f<a){const p="Block scalars with more-indented leading empty lines must use an explicit indentation indicator";this.error=new F(this,p)}this.blockIndent=f}else f>a&&(a=f);r[u]===`
|
|
74
|
-
`?s=u:s=i=I.endOfLine(r,u)}return this.chomping!==Ze.KEEP&&(s=r[i]?i+1:i),this.valueRange=new te(t+1,s),s}parse(t,n){this.context=t;const{src:r}=t;let o=this.parseBlockHeader(n);return o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.header?this.header.setOrigRange(t,n):n}}class
|
|
74
|
+
`?s=u:s=i=I.endOfLine(r,u)}return this.chomping!==Ze.KEEP&&(s=r[i]?i+1:i),this.valueRange=new te(t+1,s),s}parse(t,n){this.context=t;const{src:r}=t;let o=this.parseBlockHeader(n);return o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o=this.parseBlockValue(o),o}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.header?this.header.setOrigRange(t,n):n}}class t$ extends I{constructor(t,n){super(t,n),this.items=null}prevNodeIsJsonLike(t=this.items.length){const n=this.items[t-1];return!!n&&(n.jsonLike||n.type===k.COMMENT&&this.prevNodeIsJsonLike(t-1))}parse(t,n){this.context=t;const{parseNode:r,src:o}=t;let{indent:s,lineStart:i}=t,a=o[n];this.items=[{char:a,offset:n}];let c=I.endOfWhiteSpace(o,n+1);for(a=o[c];a&&a!=="]"&&a!=="}";){switch(a){case`
|
|
75
75
|
`:{i=c+1;const u=I.endOfWhiteSpace(o,i);if(o[u]===`
|
|
76
76
|
`){const l=new _n;i=l.parse({src:o},i),this.items.push(l)}if(c=I.endOfIndent(o,i),c<=i+s&&(a=o[c],c<i+s||a!=="]"&&a!=="}")){const l="Insufficient indentation in flow collection";this.error=new F(this,l)}}break;case",":this.items.push({char:a,offset:c}),c+=1;break;case"#":{const u=new mn;c=u.parse({src:o},c),this.items.push(u)}break;case"?":case":":{const u=o[c+1];if(u===`
|
|
77
77
|
`||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 te(n,c),c;this.items.push(u),c=I.normalizeOffset(o,u.range.end)}}c=I.endOfWhiteSpace(o,c),a=o[c]}return this.valueRange=new te(n,c+1),a&&(this.items.push({char:a,offset:c}),c=I.endOfWhiteSpace(o,c+1),c=this.parseComment(c)),c}setOrigRanges(t,n){return n=super.setOrigRanges(t,n),this.items.forEach(r=>{if(r instanceof I)n=r.setOrigRanges(t,n);else if(t.length===0)r.origOffset=r.offset;else{let o=n;for(;o<t.length&&!(t[o]>r.offset);)++o;r.origOffset=r.offset+o,n=o}}),n}toString(){const{context:{src:t},items:n,range:r,value:o}=this;if(o!=null)return o;const s=n.filter(c=>c instanceof I);let i="",a=r.start;return s.forEach(c=>{const u=t.slice(a,c.range.start);a=c.range.end,i+=u+String(c),i[i.length-1]===`
|
|
@@ -83,126 +83,126 @@ ${o}
|
|
|
83
83
|
`:for(;s[a+1]===" "||s[a+1]===" ";)a+=1;break;default:t.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!==`
|
|
84
84
|
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parseCharCode(t,n,r){const{src:o}=this.context,s=o.substr(t,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(t-2,n+2)}`)),o.substr(t-2,n+2)):String.fromCodePoint(i)}parse(t,n){this.context=t;const{src:r}=t;let o=ui.endOfQuote(r,n+1);return this.valueRange=new te(n,o),o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}class li extends I{static endOfQuote(t,n){let r=t[n];for(;r;)if(r==="'"){if(t[n+1]!=="'")break;r=t[n+=2]}else r=t[n+=1];return n+1}get strValue(){if(!this.valueRange||!this.context)return null;const t=[],{start:n,end:r}=this.valueRange,{indent:o,src:s}=this.context;s[r-1]!=="'"&&t.push(new fe(this,"Missing closing 'quote"));let i="";for(let a=n+1;a<r-1;++a){const c=s[a];if(c===`
|
|
85
85
|
`){I.atDocumentBoundary(s,a+1)&&t.push(new F(this,"Document boundary indicators are not allowed within string values"));const{fold:u,offset:l,error:f}=I.foldNewline(s,a,o);i+=u,a=l,f&&t.push(new F(this,"Multi-line single-quoted string needs to be sufficiently indented"))}else if(c==="'")i+=c,a+=1,s[a]!=="'"&&t.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!==`
|
|
86
|
-
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parse(t,n){this.context=t;const{src:r}=t;let o=li.endOfQuote(r,n+1);return this.valueRange=new te(n,o),o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}function
|
|
86
|
+
`&&(i+=a>u?s.slice(u,a+1):c)}else i+=c}return t.length>0?{errors:t,str:i}:i}parse(t,n){this.context=t;const{src:r}=t;let o=li.endOfQuote(r,n+1);return this.valueRange=new te(n,o),o=I.endOfWhiteSpace(r,o),o=this.parseComment(o),o}}function n$(e,t){switch(e){case k.ALIAS:return new Xy(e,t);case k.BLOCK_FOLDED:case k.BLOCK_LITERAL:return new e$(e,t);case k.FLOW_MAP:case k.FLOW_SEQ:return new t$(e,t);case k.MAP_KEY:case k.MAP_VALUE:case k.SEQ_ITEM:return new ci(e,t);case k.COMMENT:case k.PLAIN:return new Yl(e,t);case k.QUOTE_DOUBLE:return new ui(e,t);case k.QUOTE_SINGLE:return new li(e,t);default:return null}}class gn{static parseType(t,n,r){switch(t[n]){case"*":return k.ALIAS;case">":return k.BLOCK_FOLDED;case"|":return k.BLOCK_LITERAL;case"{":return k.FLOW_MAP;case"[":return k.FLOW_SEQ;case"?":return!r&&I.atBlank(t,n+1,!0)?k.MAP_KEY:k.PLAIN;case":":return!r&&I.atBlank(t,n+1,!0)?k.MAP_VALUE:k.PLAIN;case"-":return!r&&I.atBlank(t,n+1,!0)?k.SEQ_ITEM:k.PLAIN;case'"':return k.QUOTE_DOUBLE;case"'":return k.QUOTE_SINGLE;default:return k.PLAIN}}constructor(t={},{atLineStart:n,inCollection:r,inFlow:o,indent:s,lineStart:i,parent:a}={}){he(this,"parseNode",(c,u)=>{if(I.atDocumentBoundary(this.src,u))return null;const l=new gn(this,c),{props:f,type:p,valueStart:h}=l.parseProps(u),d=n$(p,f);let m=u;try{m=d.parse(l,h)}catch(y){const $=y instanceof Error?y.message:String(y);d.error||(d.error=new fe(d,$))}if(d.range=new te(u,m),m<=u&&(d.error||(d.error=new Error("Node#parse consumed no characters")),d.error.parseEnd=m,d.error.source=d,d.range.end=u+1),l.nodeStartsCollection(d)){!d.error&&!l.atLineStart&&l.parent.type===k.DOCUMENT&&(d.error=new fe(d,"Block collection must not have preceding content here (e.g. directives-end indicator)"));const y=new Ql(d);return m=y.parse(new gn(l),m),y.range=new te(u,m),y}return d}),this.atLineStart=n??(t.atLineStart||!1),this.inCollection=r??(t.inCollection||!1),this.inFlow=o??(t.inFlow||!1),this.indent=s??t.indent,this.lineStart=i??t.lineStart,this.parent=a??(t.parent||{}),this.root=t.root,this.src=t.src}nodeStartsCollection(t){const{inCollection:n,inFlow:r,src:o}=this;if(n||r)return!1;if(t instanceof ci)return!0;let s=t.range.end;return o[s]===`
|
|
87
87
|
`||o[s-1]===`
|
|
88
88
|
`?!1:(s=I.endOfWhiteSpace(o,s),o[s]===":")}parseProps(t){const{inFlow:n,parent:r,src:o}=this,s=[];let i=!1;t=this.atLineStart?I.endOfIndent(o,t):I.endOfWhiteSpace(o,t);let a=o[t];for(;a===oe.ANCHOR||a===oe.COMMENT||a===oe.TAG||a===`
|
|
89
89
|
`;){if(a===`
|
|
90
90
|
`){let u=t,l;do l=u+1,u=I.endOfIndent(o,l);while(o[u]===`
|
|
91
91
|
`);const f=u-(l+this.indent),p=r.type===k.SEQ_ITEM&&r.context.atLineStart;if(o[u]!=="#"&&!I.nextNodeIsIndented(o[u],f,!p))break;this.atLineStart=!0,this.lineStart=l,i=!1,t=u}else if(a===oe.COMMENT){const u=I.endOfLine(o,t+1);s.push(new te(t,u)),t=u}else{let u=I.endOfIdentifier(o,t+1);a===oe.TAG&&o[u]===","&&/^[a-zA-Z0-9-]+\.[a-zA-Z0-9-]+,\d\d\d\d(-\d\d){0,2}\/\S/.test(o.slice(t+1,u+13))&&(u=I.endOfIdentifier(o,u+5)),s.push(new te(t,u)),i=!0,t=I.endOfWhiteSpace(o,u)}a=o[t]}i&&a===":"&&I.atBlank(o,t+1,!0)&&(t-=1);const c=gn.parseType(o,t,n);return{props:s,type:c,valueStart:t}}}function fi(e){const t=[];e.indexOf("\r")!==-1&&(e=e.replace(/\r\n?/g,(o,s)=>(o.length>1&&t.push(s),`
|
|
92
|
-
`)));const n=[];let r=0;do{const o=new
|
|
93
|
-
`),n}function
|
|
92
|
+
`)));const n=[];let r=0;do{const o=new Zy,s=new gn({src:e});r=o.parse(s,r),n.push(o)}while(r<e.length);return n.setOrigRanges=()=>{if(t.length===0)return!1;for(let s=1;s<t.length;++s)t[s]-=s;let o=0;for(let s=0;s<n.length;++s)o=n[s].setOrigRanges(t,o);return t.splice(0,t.length),!0},n.toString=()=>n.join(`...
|
|
93
|
+
`),n}function r$(e,t,n){return n?`#${n.replace(/[\s\S]^/gm,`$&${t}#`)}
|
|
94
94
|
${t}${e}`:e}function Gt(e,t,n){return n?n.indexOf(`
|
|
95
95
|
`)===-1?`${e} #${n}`:`${e}
|
|
96
|
-
`+n.replace(/^/gm,`${t||""}#`):e}let $e=class{};function xe(e,t,n){if(Array.isArray(e))return e.map((r,o)=>xe(r,String(o),n));if(e&&typeof e.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(e);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=e.toJSON(t,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof e=="bigint"?Number(e):e}let Y=class extends $e{constructor(t){super(),this.value=t}toJSON(t,n){return n&&n.keep?this.value:xe(this.value,t,n)}toString(){return String(this.value)}};function
|
|
97
|
-
`)&&(d=!0),f&&E<this.items.length-1&&(O+=","),O=Gt(O,s,b),h&&(b||f)&&(h=!1),$.push({type:"item",str:O}),$},[]);let y;if(
|
|
96
|
+
`+n.replace(/^/gm,`${t||""}#`):e}let $e=class{};function xe(e,t,n){if(Array.isArray(e))return e.map((r,o)=>xe(r,String(o),n));if(e&&typeof e.toJSON=="function"){const r=n&&n.anchors&&n.anchors.get(e);r&&(n.onCreate=s=>{r.res=s,delete n.onCreate});const o=e.toJSON(t,n);return r&&n.onCreate&&n.onCreate(o),o}return(!n||!n.keep)&&typeof e=="bigint"?Number(e):e}let Y=class extends $e{constructor(t){super(),this.value=t}toJSON(t,n){return n&&n.keep?this.value:xe(this.value,t,n)}toString(){return String(this.value)}};function Tc(e,t,n){let r=n;for(let o=t.length-1;o>=0;--o){const s=t[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 e.createNode(r,!1)}const fn=e=>e==null||typeof e=="object"&&e[Symbol.iterator]().next().done;let le=class mt extends $e{constructor(t){super(),he(this,"items",[]),this.schema=t}addIn(t,n){if(fn(t))this.add(n);else{const[r,...o]=t,s=this.get(r,!0);if(s instanceof mt)s.addIn(o,n);else if(s===void 0&&this.schema)this.set(r,Tc(this.schema,o,n));else throw new Error(`Expected YAML collection at ${r}. Remaining path: ${o}`)}}deleteIn([t,...n]){if(n.length===0)return this.delete(t);const r=this.get(t,!0);if(r instanceof mt)return r.deleteIn(n);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn([t,...n],r){const o=this.get(t,!0);return n.length===0?!r&&o instanceof Y?o.value:o:o instanceof mt?o.getIn(n,r):void 0}hasAllNullValues(){return this.items.every(t=>{if(!t||t.type!=="PAIR")return!1;const n=t.value;return n==null||n instanceof Y&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn([t,...n]){if(n.length===0)return this.has(t);const r=this.get(t,!0);return r instanceof mt?r.hasIn(n):!1}setIn([t,...n],r){if(n.length===0)this.set(t,r);else{const o=this.get(t,!0);if(o instanceof mt)o.setIn(n,r);else if(o===void 0&&this.schema)this.set(t,Tc(this.schema,n,r));else throw new Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}}toJSON(){return null}toString(t,{blockItem:n,flowChars:r,isMap:o,itemIndent:s},i,a){const{indent:c,indentStep:u,stringify:l}=t,f=this.type===k.FLOW_MAP||this.type===k.FLOW_SEQ||t.inFlow;f&&(s+=u);const p=o&&this.hasAllNullValues();t=Object.assign({},t,{allNullValues:p,indent:s,inFlow:f,type:null});let h=!1,d=!1;const m=this.items.reduce(($,v,E)=>{let b;v&&(!h&&v.spaceBefore&&$.push({type:"comment",str:""}),v.commentBefore&&v.commentBefore.match(/^.*$/gm).forEach(j=>{$.push({type:"comment",str:`#${j}`})}),v.comment&&(b=v.comment),f&&(!h&&v.spaceBefore||v.commentBefore||v.comment||v.key&&(v.key.commentBefore||v.key.comment)||v.value&&(v.value.commentBefore||v.value.comment))&&(d=!0)),h=!1;let O=l(v,t,()=>b=null,()=>h=!0);return f&&!d&&O.includes(`
|
|
97
|
+
`)&&(d=!0),f&&E<this.items.length-1&&(O+=","),O=Gt(O,s,b),h&&(b||f)&&(h=!1),$.push({type:"item",str:O}),$},[]);let y;if(m.length===0)y=r.start+r.end;else if(f){const{start:$,end:v}=r,E=m.map(b=>b.str);if(d||E.reduce((b,O)=>b+O.length+2,2)>mt.maxFlowStringSingleLineLength){y=$;for(const b of E)y+=b?`
|
|
98
98
|
${u}${c}${b}`:`
|
|
99
99
|
`;y+=`
|
|
100
|
-
${c}${v}`}else y=`${$} ${E.join(" ")} ${v}`}else{const $=
|
|
100
|
+
${c}${v}`}else y=`${$} ${E.join(" ")} ${v}`}else{const $=m.map(n);y=$.shift();for(const v of $)y+=v?`
|
|
101
101
|
${c}${v}`:`
|
|
102
102
|
`}return this.comment?(y+=`
|
|
103
|
-
`+this.comment.replace(/^/gm,`${c}#`),i&&i()):h&&a&&a(),y}};he(le,"maxFlowStringSingleLineLength",60);function Gn(e){let t=e instanceof Y?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),Number.isInteger(t)&&t>=0?t:null}let Le=class extends le{add(t){this.items.push(t)}delete(t){const n=Gn(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const r=Gn(t);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof Y?o.value:o}has(t){const n=Gn(t);return typeof n=="number"&&n<this.items.length}set(t,n){const r=Gn(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);this.items[r]=n}toJSON(t,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(xe(s,String(o++),n));return r}toString(t,n,r){return t?super.toString(t,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(t.indent||"")+" "},n,r):JSON.stringify(this)}};const
|
|
103
|
+
`+this.comment.replace(/^/gm,`${c}#`),i&&i()):h&&a&&a(),y}};he(le,"maxFlowStringSingleLineLength",60);function Gn(e){let t=e instanceof Y?e.value:e;return t&&typeof t=="string"&&(t=Number(t)),Number.isInteger(t)&&t>=0?t:null}let Le=class extends le{add(t){this.items.push(t)}delete(t){const n=Gn(t);return typeof n!="number"?!1:this.items.splice(n,1).length>0}get(t,n){const r=Gn(t);if(typeof r!="number")return;const o=this.items[r];return!n&&o instanceof Y?o.value:o}has(t){const n=Gn(t);return typeof n=="number"&&n<this.items.length}set(t,n){const r=Gn(t);if(typeof r!="number")throw new Error(`Expected a valid index, not ${t}.`);this.items[r]=n}toJSON(t,n){const r=[];n&&n.onCreate&&n.onCreate(r);let o=0;for(const s of this.items)r.push(xe(s,String(o++),n));return r}toString(t,n,r){return t?super.toString(t,{blockItem:o=>o.type==="comment"?o.str:`- ${o.str}`,flowChars:{start:"[",end:"]"},isMap:!1,itemIndent:(t.indent||"")+" "},n,r):JSON.stringify(this)}};const o$=(e,t,n)=>t===null?"":typeof t!="object"?String(t):e instanceof $e&&n&&n.doc?e.toString({anchors:Object.create(null),doc:n.doc,indent:"",indentStep:n.indentStep,inFlow:!0,inStringifyKey:!0,stringify:n.stringify}):JSON.stringify(t);let J=class Zl extends $e{constructor(t,n=null){super(),this.key=t,this.value=n,this.type=Zl.Type.PAIR}get commentBefore(){return this.key instanceof $e?this.key.commentBefore:void 0}set commentBefore(t){if(this.key==null&&(this.key=new Y(null)),this.key instanceof $e)this.key.commentBefore=t;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(t,n){const r=xe(this.key,"",t);if(n instanceof Map){const o=xe(this.value,r,t);n.set(r,o)}else if(n instanceof Set)n.add(r);else{const o=o$(this.key,r,t),s=xe(this.value,o,t);o in n?Object.defineProperty(n,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):n[o]=s}return n}toJSON(t,n){const r=n&&n.mapAsMap?new Map:{};return this.addToJSMap(n,r)}toString(t,n,r){if(!t||!t.doc)return JSON.stringify(this);const{indent:o,indentSeq:s,simpleKeys:i}=t.doc.options;let{key:a,value:c}=this,u=a instanceof $e&&a.comment;if(i){if(u)throw new Error("With simple keys, key nodes cannot have comments");if(a instanceof le){const O="With simple keys, collection cannot be used as a key value";throw new Error(O)}}let l=!i&&(!a||u||(a instanceof $e?a instanceof le||a.type===k.BLOCK_FOLDED||a.type===k.BLOCK_LITERAL:typeof a=="object"));const{doc:f,indent:p,indentStep:h,stringify:d}=t;t=Object.assign({},t,{implicitKey:!l,indent:p+h});let m=!1,y=d(a,t,()=>u=null,()=>m=!0);if(y=Gt(y,t.indent,u),!l&&y.length>1024){if(i)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");l=!0}if(t.allNullValues&&!i)return this.comment?(y=Gt(y,t.indent,this.comment),n&&n()):m&&!u&&r&&r(),t.inFlow&&!l?y:`? ${y}`;y=l?`? ${y}
|
|
104
104
|
${p}:`:`${y}:`,this.comment&&(y=Gt(y,t.indent,this.comment),n&&n());let $="",v=null;if(c instanceof $e){if(c.spaceBefore&&($=`
|
|
105
105
|
`),c.commentBefore){const O=c.commentBefore.replace(/^/gm,`${t.indent}#`);$+=`
|
|
106
|
-
${O}`}v=c.comment}else c&&typeof c=="object"&&(c=f.schema.createNode(c,!0));t.implicitKey=!1,!l&&!this.comment&&c instanceof Y&&(t.indentAtStart=y.length+1),
|
|
106
|
+
${O}`}v=c.comment}else c&&typeof c=="object"&&(c=f.schema.createNode(c,!0));t.implicitKey=!1,!l&&!this.comment&&c instanceof Y&&(t.indentAtStart=y.length+1),m=!1,!s&&o>=2&&!t.inFlow&&!l&&c instanceof Le&&c.type!==k.FLOW_SEQ&&!c.tag&&!f.anchors.getName(c)&&(t.indent=t.indent.substr(2));const E=d(c,t,()=>v=null,()=>m=!0);let b=" ";return $||this.comment?b=`${$}
|
|
107
107
|
${t.indent}`:!l&&c instanceof le?(!(E[0]==="["||E[0]==="{")||E.includes(`
|
|
108
108
|
`))&&(b=`
|
|
109
109
|
${t.indent}`):E[0]===`
|
|
110
|
-
`&&(b=""),
|
|
111
|
-
`);n=e[t+1]}return t};function Pr(e,t,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return e;const c=Math.max(1+s,1+o-t.length);if(e.length<=c)return e;const u=[],l={};let f=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):f=o-r);let p,h,d=!1,
|
|
112
|
-
`)n===
|
|
113
|
-
`&&h!==" "){const b=e[
|
|
114
|
-
`&&b!==" "&&(p=
|
|
110
|
+
`&&(b=""),m&&!v&&r&&r(),Gt(y+b+E,t.indent,v)}};he(J,"Type",{PAIR:"PAIR",MERGE_PAIR:"MERGE_PAIR"});const ir=(e,t)=>{if(e instanceof He){const n=t.get(e.source);return n.count*n.aliasCount}else if(e instanceof le){let n=0;for(const r of e.items){const o=ir(r,t);o>n&&(n=o)}return n}else if(e instanceof J){const n=ir(e.key,t),r=ir(e.value,t);return Math.max(n,r)}return 1};let He=class Xl extends $e{static stringify({range:t,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} [${t}]`)}constructor(t){super(),this.source=t,this.type=k.ALIAS}set tag(t){throw new Error("Alias nodes cannot have tags")}toJSON(t,n){if(!n)return xe(this.source,t,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 Nn(this.cstNode,i):new ReferenceError(i)}if(o>=0&&(s.count+=1,s.aliasCount===0&&(s.aliasCount=ir(this.source,r)),s.count*s.aliasCount>o)){const i="Excessive alias count indicates a resource exhaustion attack";throw this.cstNode?new Nn(this.cstNode,i):new ReferenceError(i)}return s.res}toString(t){return Xl.stringify(this,t)}};he(He,"default",!0);function Ot(e,t){const n=t instanceof Y?t.value:t;for(const r of e)if(r instanceof J&&(r.key===t||r.key===n||r.key&&r.key.value===n))return r}let ve=class extends le{add(t,n){t?t instanceof J||(t=new J(t.key||t,t.value)):t=new J(t);const r=Ot(this.items,t.key),o=this.schema&&this.schema.sortMapEntries;if(r)if(n)r.value=t.value;else throw new Error(`Key ${t.key} already set`);else if(o){const s=this.items.findIndex(i=>o(t,i)<0);s===-1?this.items.push(t):this.items.splice(s,0,t)}else this.items.push(t)}delete(t){const n=Ot(this.items,t);return n?this.items.splice(this.items.indexOf(n),1).length>0:!1}get(t,n){const r=Ot(this.items,t),o=r&&r.value;return!n&&o instanceof Y?o.value:o}has(t){return!!Ot(this.items,t)}set(t,n){this.add(new J(t,n),!0)}toJSON(t,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(t,n,r){if(!t)return JSON.stringify(this);for(const o of this.items)if(!(o instanceof J))throw new Error(`Map items must all be pairs; found ${JSON.stringify(o)} instead`);return super.toString(t,{blockItem:o=>o.str,flowChars:{start:"{",end:"}"},isMap:!0,itemIndent:t.indent||""},n,r)}};const ef="<<";class tf extends J{constructor(t){if(t instanceof J){let n=t.value;n instanceof Le||(n=new Le,n.items.push(t.value),n.range=t.value.range),super(t.key,n),this.range=t.range}else super(new Y(ef),new Le);this.type=J.Type.MERGE_PAIR}addToJSMap(t,n){for(const{source:r}of this.value.items){if(!(r instanceof ve))throw new Error("Merge sources must be maps");const o=r.toJSON(null,t,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(t,n){const r=this.value;if(r.items.length>1)return super.toString(t,n);this.value=r.items[0];const o=super.toString(t,n);return this.value=r,o}}const yn={defaultType:k.BLOCK_LITERAL,lineWidth:76},Ke={trueStr:"true",falseStr:"false"},at={asBigInt:!1},Yt={nullStr:"null"},Ye={defaultType:k.PLAIN,doubleQuoted:{jsonEncoding:!1,minMultiLineLength:40},fold:{lineWidth:80,minContentWidth:20}};function di(e,t,n){for(const{format:r,test:o,resolve:s}of t)if(o){const i=e.match(o);if(i){let a=s.apply(null,i);return a instanceof Y||(a=new Y(a)),r&&(a.format=r),a}}return n&&(e=n(e)),new Y(e)}const nf="flow",us="block",ar="quoted",Cc=(e,t)=>{let n=e[t+1];for(;n===" "||n===" ";){do n=e[t+=1];while(n&&n!==`
|
|
111
|
+
`);n=e[t+1]}return t};function Pr(e,t,n,{indentAtStart:r,lineWidth:o=80,minContentWidth:s=20,onFold:i,onOverflow:a}){if(!o||o<0)return e;const c=Math.max(1+s,1+o-t.length);if(e.length<=c)return e;const u=[],l={};let f=o-t.length;typeof r=="number"&&(r>o-Math.max(2,s)?u.push(0):f=o-r);let p,h,d=!1,m=-1,y=-1,$=-1;n===us&&(m=Cc(e,m),m!==-1&&(f=m+c));for(let E;E=e[m+=1];){if(n===ar&&E==="\\"){switch(y=m,e[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}$=m}if(E===`
|
|
112
|
+
`)n===us&&(m=Cc(e,m)),f=m+c,p=void 0;else{if(E===" "&&h&&h!==" "&&h!==`
|
|
113
|
+
`&&h!==" "){const b=e[m+1];b&&b!==" "&&b!==`
|
|
114
|
+
`&&b!==" "&&(p=m)}if(m>=f)if(p)u.push(p),f=p+c,p=void 0;else if(n===ar){for(;h===" "||h===" ";)h=E,E=e[m+=1],d=!0;const b=m>$+1?m-2:y-1;if(l[b])return e;u.push(b),l[b]=!0,f=b+c,p=void 0}else d=!0}h=E}if(d&&a&&a(),u.length===0)return e;i&&i();let v=e.slice(0,u[0]);for(let E=0;E<u.length;++E){const b=u[E],O=u[E+1]||e.length;b===0?v=`
|
|
115
115
|
${t}${e.slice(0,O)}`:(n===ar&&l[b]&&(v+=`${e[b]}\\`),v+=`
|
|
116
|
-
${t}${e.slice(b+1,O)}`)}return v}const pi=({indentAtStart:e})=>e?Object.assign({indentAtStart:e},Ye.fold):Ye.fold,Tr=e=>/^(%|---|\.\.\.)/m.test(e);function
|
|
116
|
+
${t}${e.slice(b+1,O)}`)}return v}const pi=({indentAtStart:e})=>e?Object.assign({indentAtStart:e},Ye.fold):Ye.fold,Tr=e=>/^(%|---|\.\.\.)/m.test(e);function s$(e,t,n){if(!t||t<0)return!1;const r=t-n,o=e.length;if(o<=r)return!1;for(let s=0,i=0;s<o;++s)if(e[s]===`
|
|
117
117
|
`){if(s-i>r)return!0;if(i=s+1,o-i<=r)return!1}return!0}function kt(e,t){const{implicitKey:n}=t,{jsonEncoding:r,minMultiLineLength:o}=Ye.doubleQuoted,s=JSON.stringify(e);if(r)return s;const i=t.indent||(Tr(e)?" ":"");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 f=s.substr(u+2,4);switch(f){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:f.substr(0,2)==="00"?a+="\\x"+f.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)+`
|
|
118
118
|
|
|
119
119
|
`;s[u+2]==="\\"&&s[u+3]==="n"&&s[u+4]!=='"';)a+=`
|
|
120
|
-
`,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:Pr(a,i,ar,pi(t))}function
|
|
121
|
-
${n}`)+"'";return t.implicitKey?r:Pr(r,n,
|
|
120
|
+
`,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:Pr(a,i,ar,pi(t))}function rf(e,t){if(t.implicitKey){if(/\n/.test(e))return kt(e,t)}else if(/[ \t]\n|\n[ \t]/.test(e))return kt(e,t);const n=t.indent||(Tr(e)?" ":""),r="'"+e.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
121
|
+
${n}`)+"'";return t.implicitKey?r:Pr(r,n,nf,pi(t))}function cr({comment:e,type:t,value:n},r,o,s){if(/\n[\t ]+$/.test(n)||/^\s*$/.test(n))return kt(n,r);const i=r.indent||(r.forceBlockIndent||Tr(n)?" ":""),a=i?"2":"1",c=t===k.BLOCK_FOLDED?!1:t===k.BLOCK_LITERAL?!0:!s$(n,Ye.fold.lineWidth,i.length);let u=c?"|":">";if(!n)return u+`
|
|
122
122
|
`;let l="",f="";if(n=n.replace(/[\n\t ]*$/,h=>{const d=h.indexOf(`
|
|
123
123
|
`);return d===-1?u+="-":(n===h||d!==h.length-1)&&(u+="+",s&&s()),f=h.replace(/\n$/,""),""}).replace(/^[\n ]*/,h=>{h.indexOf(" ")!==-1&&(u+=a);const d=h.match(/ +$/);return d?(l=h.slice(0,-d[0].length),d[0]):(l=h,"")}),f&&(f=f.replace(/\n+(?!\n|$)/g,`$&${i}`)),l&&(l=l.replace(/\n+/g,`$&${i}`)),e&&(u+=" #"+e.replace(/ ?[\r\n]+/g," "),o&&o()),!n)return`${u}${a}
|
|
124
124
|
${i}${f}`;if(c)return n=n.replace(/\n+/g,`$&${i}`),`${u}
|
|
125
125
|
${i}${l}${n}${f}`;n=n.replace(/\n+/g,`
|
|
126
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const p=Pr(`${l}${n}${f}`,i,
|
|
127
|
-
${i}${p}`}function
|
|
128
|
-
`)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?
|
|
126
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${i}`);const p=Pr(`${l}${n}${f}`,i,us,Ye.fold);return`${u}
|
|
127
|
+
${i}${p}`}function i$(e,t,n,r){const{comment:o,type:s,value:i}=e,{actualString:a,implicitKey:c,indent:u,inFlow:l}=t;if(c&&/[\n[\]{},]/.test(i)||l&&/[[\]{},]/.test(i))return kt(i,t);if(!i||/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return c||l||i.indexOf(`
|
|
128
|
+
`)===-1?i.indexOf('"')!==-1&&i.indexOf("'")===-1?rf(i,t):kt(i,t):cr(e,t,n,r);if(!c&&!l&&s!==k.PLAIN&&i.indexOf(`
|
|
129
129
|
`)!==-1)return cr(e,t,n,r);if(u===""&&Tr(i))return t.forceBlockIndent=!0,cr(e,t,n,r);const f=i.replace(/\n+/g,`$&
|
|
130
|
-
${u}`);if(a){const{tags:h}=t.doc.schema;if(typeof di(f,h,h.scalarFallback).value!="string")return kt(i,t)}const p=c?f:Pr(f,u,
|
|
130
|
+
${u}`);if(a){const{tags:h}=t.doc.schema;if(typeof di(f,h,h.scalarFallback).value!="string")return kt(i,t)}const p=c?f:Pr(f,u,nf,pi(t));return o&&!l&&(p.indexOf(`
|
|
131
131
|
`)!==-1||o.indexOf(`
|
|
132
|
-
`)!==-1)?(n&&n(),
|
|
133
|
-
`&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";e.push(new F(t,r))}}function
|
|
132
|
+
`)!==-1)?(n&&n(),r$(p,u,o)):p}function hi(e,t,n,r){const{defaultType:o}=Ye,{implicitKey:s,inFlow:i}=t;let{type:a,value:c}=e;typeof c!="string"&&(c=String(c),e=Object.assign({},e,{value:c}));const u=f=>{switch(f){case k.BLOCK_FOLDED:case k.BLOCK_LITERAL:return cr(e,t,n,r);case k.QUOTE_DOUBLE:return kt(c,t);case k.QUOTE_SINGLE:return rf(c,t);case k.PLAIN:return i$(e,t,n,r);default:return null}};(a!==k.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(c)||(s||i)&&(a===k.BLOCK_FOLDED||a===k.BLOCK_LITERAL))&&(a=k.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 Ge({format:e,minFractionDigits:t,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(!e&&t&&(!n||n==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let i=t-(o.length-s-1);for(;i-- >0;)o+="0"}return o}function of(e,t){let n,r;switch(t.type){case k.FLOW_MAP:n="}",r="flow map";break;case k.FLOW_SEQ:n="]",r="flow sequence";break;default:e.push(new F(t,"Not a flow collection!?"));return}let o;for(let s=t.items.length-1;s>=0;--s){const i=t.items[s];if(!i||i.type!==k.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 F(t,s),i.offset=o.offset+1):(i=new F(o,s),o.range&&o.range.end&&(i.offset=o.range.end-o.range.start)),e.push(i)}}function sf(e,t){const n=t.context.src[t.range.start-1];if(n!==`
|
|
133
|
+
`&&n!==" "&&n!==" "){const r="Comments must be separated from other tokens by white space characters";e.push(new F(t,r))}}function af(e,t){const n=String(t),r=n.substr(0,8)+"..."+n.substr(-8);return new F(e,`The "${r}" key is too long`)}function cf(e,t){for(const{afterKey:n,before:r,comment:o}of t){let s=e.items[r];s?(n&&s.value&&(s=s.value),o===void 0?(n||!s.commentBefore)&&(s.spaceBefore=!0):s.commentBefore?s.commentBefore+=`
|
|
134
134
|
`+o:s.commentBefore=o):o!==void 0&&(e.comment?e.comment+=`
|
|
135
|
-
`+o:e.comment=o)}}function Dn(e,t){const n=t.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=t),e.errors.push(r)}),n.str):""}function
|
|
135
|
+
`+o:e.comment=o)}}function Dn(e,t){const n=t.strValue;return n?typeof n=="string"?n:(n.errors.forEach(r=>{r.source||(r.source=t),e.errors.push(r)}),n.str):""}function a$(e,t){const{handle:n,suffix:r}=t.tag;let o=e.tagPrefixes.find(s=>s.handle===n);if(!o){const s=e.getDefaults().tagPrefixes;if(s&&(o=s.find(i=>i.handle===n)),!o)throw new F(t,`The ${n} tag handle is non-default and was not declared.`)}if(!r)throw new F(t,`The ${n} tag has no suffix.`);if(n==="!"&&(e.version||e.options.version)==="1.0"){if(r[0]==="^")return e.warnings.push(new en(t,"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 c$(e,t){const{tag:n,type:r}=t;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.`;e.errors.push(new F(t,c))}else if(s==="!"&&!i)o=!0;else try{return a$(e,t)}catch(c){e.errors.push(c)}}switch(r){case k.BLOCK_FOLDED:case k.BLOCK_LITERAL:case k.QUOTE_DOUBLE:case k.QUOTE_SINGLE:return rt.STR;case k.FLOW_MAP:case k.MAP:return rt.MAP;case k.FLOW_SEQ:case k.SEQ:return rt.SEQ;case k.PLAIN:return o?rt.STR:null;default:return null}}function Rc(e,t,n){const{tags:r}=e.schema,o=[];for(const i of r)if(i.tag===n)if(i.test)o.push(i);else{const a=i.resolve(e,t);return a instanceof le?a:new Y(a)}const s=Dn(e,t);return typeof s=="string"&&o.length>0?di(s,o,r.scalarFallback):null}function u$({type:e}){switch(e){case k.FLOW_MAP:case k.MAP:return rt.MAP;case k.FLOW_SEQ:case k.SEQ:return rt.SEQ;default:return rt.STR}}function l$(e,t,n){try{const r=Rc(e,t,n);if(r)return n&&t.tag&&(r.tag=n),r}catch(r){if(r instanceof At)r.source||(r.source=t),e.errors.push(r);else{const o=r instanceof Error?r.message:String(r);e.errors.push(new F(t,o))}return null}try{const r=u$(t);if(!r)throw new Error(`The tag ${n} is unavailable`);const o=`The tag ${n} is unavailable, falling back to ${r}`;e.warnings.push(new en(t,o));const s=Rc(e,t,r);return s.tag=n,s}catch(r){const o=new Nn(t,r.message);return o.stack=r.stack,e.errors.push(o),null}}const f$=e=>{if(!e)return!1;const{type:t}=e;return t===k.MAP_KEY||t===k.MAP_VALUE||t===k.SEQ_ITEM};function d$(e,t){const n={before:[],after:[]};let r=!1,o=!1;const s=f$(t.context.parent)?t.context.parent.props.concat(t.props):t.props;for(const{start:i,end:a}of s)switch(t.context.src[i]){case oe.COMMENT:{if(!t.commentHasRequiredWhitespace(i)){const l="Comments must be separated from other tokens by white space characters";e.push(new F(t,l))}const{header:c,valueRange:u}=t;(u&&(i>u.start||c&&i>c.start)?n.after:n.before).push(t.context.src.slice(i+1,a));break}case oe.ANCHOR:if(r){const c="A node can have at most one anchor";e.push(new F(t,c))}r=!0;break;case oe.TAG:if(o){const c="A node can have at most one tag";e.push(new F(t,c))}o=!0;break}return{comments:n,hasAnchor:r,hasTag:o}}function p$(e,t){const{anchors:n,errors:r,schema:o}=e;if(t.type===k.ALIAS){const i=t.rawValue,a=n.getNode(i);if(!a){const u=`Aliased anchor not found: ${i}`;return r.push(new Nn(t,u)),null}const c=new He(a);return n._cstAliases.push(c),c}const s=c$(e,t);if(s)return l$(e,t,s);if(t.type!==k.PLAIN){const i=`Failed to resolve ${t.type} node here`;return r.push(new fe(t,i)),null}try{const i=Dn(e,t);return di(i,o.tags,o.tags.scalarFallback)}catch(i){return i.source||(i.source=t),r.push(i),null}}function st(e,t){if(!t)return null;t.error&&e.errors.push(t.error);const{comments:n,hasAnchor:r,hasTag:o}=d$(e.errors,t);if(r){const{anchors:i}=e,a=t.anchor,c=i.getNode(a);c&&(i.map[i.newName(a)]=c),i.map[a]=t}if(t.type===k.ALIAS&&(r||o)){const i="An alias node must not specify any properties";e.errors.push(new F(t,i))}const s=p$(e,t);if(s){s.range=[t.range.start,t.range.end],e.options.keepCstNodes&&(s.cstNode=t),e.options.keepNodeTypes&&(s.type=t.type);const i=n.before.join(`
|
|
136
136
|
`);i&&(s.commentBefore=s.commentBefore?`${s.commentBefore}
|
|
137
137
|
${i}`:i);const a=n.after.join(`
|
|
138
138
|
`);a&&(s.comment=s.comment?`${s.comment}
|
|
139
|
-
${a}`:a)}return t.resolved=s}function
|
|
140
|
-
`)return!1;return!0};function
|
|
141
|
-
`){const y="Implicit keys of flow sequence pairs need to be on a single line";e.errors.push(new F(c,y));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||f!=="]"||u<t.items.length-1){const h=`Flow sequence contains an unexpected ${f}`,d=new fe(t,h);d.offset=p,e.errors.push(d)}}else if(l.type===k.BLANK_LINE)n.push({before:r.length});else if(l.type===k.COMMENT)
|
|
142
|
-
`:" ")}return hi({comment:e,type:t,value:n},r,o,s)}};function
|
|
139
|
+
${a}`:a)}return t.resolved=s}function uf(e,t){if(t.type!==k.MAP&&t.type!==k.FLOW_MAP){const i=`A ${t.type} node cannot be resolved as a mapping`;return e.errors.push(new fe(t,i)),null}const{comments:n,items:r}=t.type===k.FLOW_MAP?y$(e,t):g$(e,t),o=new ve;o.items=r,cf(o,n);let s=!1;for(let i=0;i<r.length;++i){const{key:a}=r[i];if(a instanceof le&&(s=!0),e.schema.merge&&a&&a.value===ef){r[i]=new tf(r[i]);const c=r[i].value.items;let u=null;c.some(l=>{if(l instanceof He){const{type:f}=l.source;return f===k.MAP||f===k.FLOW_MAP?!1:u="Merge nodes aliases can only point to maps"}return u="Merge nodes can only have Alias nodes as values"}),u&&e.errors.push(new F(t,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`;e.errors.push(new F(t,l));break}}}if(s&&!e.options.mapAsMap){const i="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new en(t,i))}return t.resolved=o,o}const h$=({context:{lineStart:e,node:t,src:n},props:r})=>{if(r.length===0)return!1;const{start:o}=r[0];if(t&&o>t.valueRange.start||n[o]!==oe.COMMENT)return!1;for(let s=e;s<o;++s)if(n[s]===`
|
|
140
|
+
`)return!1;return!0};function m$(e,t){if(!h$(e))return;const n=e.getPropValue(0,oe.COMMENT,!0);let r=!1;const o=t.value.commentBefore;if(o&&o.startsWith(n))t.value.commentBefore=o.substr(n.length+1),r=!0;else{const s=t.value.comment;!e.node&&s&&s.startsWith(n)&&(t.value.comment=s.substr(n.length+1),r=!0)}r&&(t.comment=n)}function g$(e,t){const n=[],r=[];let o,s=null;for(let i=0;i<t.items.length;++i){const a=t.items[i];switch(a.type){case k.BLANK_LINE:n.push({afterKey:!!o,before:r.length});break;case k.COMMENT:n.push({afterKey:!!o,before:r.length,comment:a.comment});break;case k.MAP_KEY:o!==void 0&&r.push(new J(o)),a.error&&e.errors.push(a.error),o=st(e,a.node),s=null;break;case k.MAP_VALUE:{if(o===void 0&&(o=null),a.error&&e.errors.push(a.error),!a.context.atLineStart&&a.node&&a.node.type===k.MAP&&!a.node.context.atLineStart){const l="Nested mappings are not allowed in compact mappings";e.errors.push(new F(a.node,l))}let c=a.node;if(!c&&a.props.length>0){c=new Yl(k.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 f=a.range.origStart+1;c.range.origStart=c.range.origEnd=f,c.valueRange.origStart=c.valueRange.origEnd=f}}const u=new J(o,st(e,c));m$(a,u),r.push(u),o&&typeof s=="number"&&a.range.start>s+1024&&e.errors.push(af(t,o)),o=void 0,s=null}break;default:o!==void 0&&r.push(new J(o)),o=st(e,a),s=a.range.start,a.error&&e.errors.push(a.error);e:for(let c=i+1;;++c){const u=t.items[c];switch(u&&u.type){case k.BLANK_LINE:case k.COMMENT:continue e;case k.MAP_VALUE:break e;default:{const l="Implicit map keys need to be followed by map values";e.errors.push(new F(a,l));break e}}}if(a.valueRangeContainsNewline){const c="Implicit map keys need to be on a single line";e.errors.push(new F(a,c))}}}return o!==void 0&&r.push(new J(o)),{comments:n,items:r}}function y$(e,t){const n=[],r=[];let o,s=!1,i="{";for(let a=0;a<t.items.length;++a){const c=t.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 J(o)),o=void 0,u===",")){i=":";continue}if(u==="}"){if(a===t.items.length-1)continue}else if(u===i){i=":";continue}const f=`Flow map contains an unexpected ${u}`,p=new fe(t,f);p.offset=l,e.errors.push(p)}else c.type===k.BLANK_LINE?n.push({afterKey:!!o,before:r.length}):c.type===k.COMMENT?(sf(e.errors,c),n.push({afterKey:!!o,before:r.length,comment:c.comment})):o===void 0?(i===","&&e.errors.push(new F(c,"Separator , missing in flow map")),o=st(e,c)):(i!==","&&e.errors.push(new F(c,"Indicator : missing in flow map entry")),r.push(new J(o,st(e,c))),o=void 0,s=!1)}return of(e.errors,t),o!==void 0&&r.push(new J(o)),{comments:n,items:r}}function lf(e,t){if(t.type!==k.SEQ&&t.type!==k.FLOW_SEQ){const s=`A ${t.type} node cannot be resolved as a sequence`;return e.errors.push(new fe(t,s)),null}const{comments:n,items:r}=t.type===k.FLOW_SEQ?v$(e,t):$$(e,t),o=new Le;if(o.items=r,cf(o,n),!e.options.mapAsMap&&r.some(s=>s instanceof J&&s.key instanceof le)){const s="Keys with collection values will be stringified as YAML due to JS Object restrictions. Use mapAsMap: true to avoid this.";e.warnings.push(new en(t,s))}return t.resolved=o,o}function $$(e,t){const n=[],r=[];for(let o=0;o<t.items.length;++o){const s=t.items[o];switch(s.type){case k.BLANK_LINE:n.push({before:r.length});break;case k.COMMENT:n.push({comment:s.comment,before:r.length});break;case k.SEQ_ITEM:if(s.error&&e.errors.push(s.error),r.push(st(e,s.node)),s.hasProps){const i="Sequence items cannot have tags or anchors before the - indicator";e.errors.push(new F(s,i))}break;default:s.error&&e.errors.push(s.error),e.errors.push(new fe(s,`Unexpected ${s.type} node in sequence`))}}return{comments:n,items:r}}function v$(e,t){const n=[],r=[];let o=!1,s,i=null,a="[",c=null;for(let u=0;u<t.items.length;++u){const l=t.items[u];if(typeof l.char=="string"){const{char:f,offset:p}=l;if(f!==":"&&(o||s!==void 0)&&(o&&s===void 0&&(s=a?r.pop():null),r.push(new J(s)),o=!1,s=void 0,i=null),f===a)a=null;else if(!a&&f==="?")o=!0;else if(a!=="["&&f===":"&&s===void 0){if(a===","){if(s=r.pop(),s instanceof J){const h="Chaining flow sequence pairs is invalid",d=new F(t,h);d.offset=p,e.errors.push(d)}if(!o&&typeof i=="number"){const h=l.range?l.range.start:l.offset;h>i+1024&&e.errors.push(af(t,s));const{src:d}=c.context;for(let m=i;m<h;++m)if(d[m]===`
|
|
141
|
+
`){const y="Implicit keys of flow sequence pairs need to be on a single line";e.errors.push(new F(c,y));break}}}else s=null;i=null,o=!1,a=null}else if(a==="["||f!=="]"||u<t.items.length-1){const h=`Flow sequence contains an unexpected ${f}`,d=new fe(t,h);d.offset=p,e.errors.push(d)}}else if(l.type===k.BLANK_LINE)n.push({before:r.length});else if(l.type===k.COMMENT)sf(e.errors,l),n.push({comment:l.comment,before:r.length});else{if(a){const p=`Expected a ${a} in flow sequence`;e.errors.push(new F(l,p))}const f=st(e,l);s===void 0?(r.push(f),c=l):(r.push(new J(s,f)),s=void 0),i=l.range.start,a=","}}return of(e.errors,t),s!==void 0&&r.push(new J(s)),{comments:n,items:r}}const ff={identify:e=>e instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve:(e,t)=>{const n=Dn(e,t);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 e.errors.push(new Nn(t,r)),null}},options:yn,stringify:({comment:e,type:t,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(t||(t=yn.defaultType),t===k.QUOTE_DOUBLE)n=i;else{const{lineWidth:a}=yn,c=Math.ceil(i.length/a),u=new Array(c);for(let l=0,f=0;l<c;++l,f+=a)u[l]=i.substr(f,a);n=u.join(t===k.BLOCK_LITERAL?`
|
|
142
|
+
`:" ")}return hi({comment:e,type:t,value:n},r,o,s)}};function df(e,t){const n=lf(e,t);for(let r=0;r<n.items.length;++r){let o=n.items[r];if(!(o instanceof J)){if(o instanceof ve){if(o.items.length>1){const i="Each pair must have its own sequence indicator";throw new F(t,i)}const s=o.items[0]||new J;o.commentBefore&&(s.commentBefore=s.commentBefore?`${o.commentBefore}
|
|
143
143
|
${s.commentBefore}`:o.commentBefore),o.comment&&(s.comment=s.comment?`${o.comment}
|
|
144
|
-
${s.comment}`:o.comment),o=s}n.items[r]=o instanceof J?o:new J(o)}}return n}function lf(e,t,n){const r=new Le(e);r.tag="tag:yaml.org,2002:pairs";for(const o of t){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=e.createPair(s,i,n);r.items.push(a)}return r}const ff={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:uf,createNode:lf};let Cr=class df extends Le{constructor(){super(),he(this,"add",ve.prototype.add.bind(this)),he(this,"delete",ve.prototype.delete.bind(this)),he(this,"get",ve.prototype.get.bind(this)),he(this,"has",ve.prototype.has.bind(this)),he(this,"set",ve.prototype.set.bind(this)),this.tag=df.tag}toJSON(t,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof J?(s=xe(o.key,"",n),i=xe(o.value,s,n)):s=xe(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};he(Cr,"tag","tag:yaml.org,2002:omap");function y$(e,t){const n=uf(e,t),r=[];for(const{key:o}of n.items)if(o instanceof Y)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new F(t,s)}else r.push(o.value);return Object.assign(new Cr,n)}function $$(e,t,n){const r=lf(e,t,n),o=new Cr;return o.items=r.items,o}const pf={identify:e=>e instanceof Map,nodeClass:Cr,default:!1,tag:"tag:yaml.org,2002:omap",resolve:y$,createNode:$$};let Rr=class hf extends ve{constructor(){super(),this.tag=hf.tag}add(t){const n=t instanceof J?t:new J(t);Ot(this.items,n.key)||this.items.push(n)}get(t,n){const r=Ot(this.items,t);return!n&&r instanceof J?r.key instanceof Y?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=Ot(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new J(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(t,n,r);throw new Error("Set items must all have null values")}};he(Rr,"tag","tag:yaml.org,2002:set");function v$(e,t){const n=sf(e,t);if(!n.hasAllNullValues())throw new F(t,"Set items must all have null values");return Object.assign(new Rr,n)}function w$(e,t,n){const r=new Rr;for(const o of t)r.items.push(e.createPair(o,null,n));return r}const mf={identify:e=>e instanceof Set,nodeClass:Rr,default:!1,tag:"tag:yaml.org,2002:set",resolve:v$,createNode:w$},mi=(e,t)=>{const n=t.split(":").reduce((r,o)=>r*60+Number(o),0);return e==="-"?-n:n},gf=({value:e})=>{if(isNaN(e)||!isFinite(e))return Ge(e);let t="";e<0&&(t="-",e=Math.abs(e));const n=[e%60];return e<60?n.unshift(0):(e=Math.round((e-n[0])/60),n.unshift(e%60),e>=60&&(e=Math.round((e-n[0])/60),n.unshift(e))),t+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},yf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(e,t,n)=>mi(t,n.replace(/_/g,"")),stringify:gf},$f={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(e,t,n)=>mi(t,n.replace(/_/g,"")),stringify:gf},vf={identify:e=>e 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:(e,t,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(t,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=mi(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function wf(e){const t=typeof process<"u"&&process.env||{};return e?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!t.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!t.YAML_SILENCE_WARNINGS}function bf(e,t){if(wf(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(e,t):console.warn(t?`${t}: ${e}`:e)}}const Rc={};function b$(e,t){if(!Rc[e]&&wf(!0)){Rc[e]=!0;let n=`The option '${e}' will be removed in a future release`;n+=`, use '${t}' instead.`,bf(n,"DeprecationWarning")}}function E$(e,t,n){const r=new ve(e);if(t instanceof Map)for(const[o,s]of t)r.items.push(e.createPair(o,s,n));else if(t&&typeof t=="object")for(const o of Object.keys(t))r.items.push(e.createPair(o,t[o],n));return typeof e.sortMapEntries=="function"&&r.items.sort(e.sortMapEntries),r}const kn={createNode:E$,default:!0,nodeClass:ve,tag:"tag:yaml.org,2002:map",resolve:sf};function S$(e,t,n){const r=new Le(e);if(t&&t[Symbol.iterator])for(const o of t){const s=e.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const Mr={createNode:S$,default:!0,nodeClass:Le,tag:"tag:yaml.org,2002:seq",resolve:af},O$={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Dn,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),hi(e,t,n,r)},options:Ye},gi=[kn,Mr,O$],Dr=e=>typeof e=="bigint"||Number.isInteger(e),yi=(e,t,n)=>at.asBigInt?BigInt(e):parseInt(t,n);function Ef(e,t,n){const{value:r}=e;return Dr(r)&&r>=0?n+r.toString(t):Ge(e)}const Sf={identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Yt,stringify:()=>Yt.nullStr},Of={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>e[0]==="t"||e[0]==="T",options:Ke,stringify:({value:e})=>e?Ke.trueStr:Ke.falseStr},Nf={identify:e=>Dr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(e,t)=>yi(e,t,8),options:at,stringify:e=>Ef(e,8,"0o")},_f={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:e=>yi(e,e,10),options:at,stringify:Ge},kf={identify:e=>Dr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(e,t)=>yi(e,t,16),options:at,stringify:e=>Ef(e,16,"0x")},Af={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ge},jf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify:({value:e})=>Number(e).toExponential()},If={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(e,t,n){const r=t||n,o=new Y(parseFloat(e));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:Ge},N$=gi.concat([Sf,Of,Nf,_f,kf,Af,jf,If]),Mc=e=>typeof e=="bigint"||Number.isInteger(e),zn=({value:e})=>JSON.stringify(e),xf=[kn,Mr,{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Dn,stringify:zn},{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:zn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:zn},{identify:Mc,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:e=>at.asBigInt?BigInt(e):parseInt(e,10),stringify:({value:e})=>Mc(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:zn}];xf.scalarFallback=e=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(e)}`)};const Dc=({value:e})=>e?Ke.trueStr:Ke.falseStr,dn=e=>typeof e=="bigint"||Number.isInteger(e);function Jn(e,t,n){let r=t.replace(/_/g,"");if(at.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 e==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return e==="-"?-1*o:o}function bo(e,t,n){const{value:r}=e;if(dn(r)){const o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return Ge(e)}const _$=gi.concat([{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Yt,stringify:()=>Yt.nullStr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:Ke,stringify:Dc},{identify:e=>typeof e=="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:Ke,stringify:Dc},{identify:dn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(e,t,n)=>Jn(t,n,2),stringify:e=>bo(e,2,"0b")},{identify:dn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(e,t,n)=>Jn(t,n,8),stringify:e=>bo(e,8,"0")},{identify:dn,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(e,t,n)=>Jn(t,n,10),stringify:Ge},{identify:dn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(e,t,n)=>Jn(t,n,16),stringify:e=>bo(e,16,"0x")},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ge},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify:({value:e})=>Number(e).toExponential()},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(e,t){const n=new Y(parseFloat(e.replace(/_/g,"")));if(t){const r=t.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:Ge}],cf,pf,ff,mf,yf,$f,vf),k$={core:N$,failsafe:gi,json:xf,yaml11:_$},A$={binary:cf,bool:Of,float:If,floatExp:jf,floatNaN:Af,floatTime:$f,int:_f,intHex:kf,intOct:Nf,intTime:yf,map:kn,null:Sf,omap:pf,pairs:ff,seq:Mr,set:mf,timestamp:vf};function j$(e,t,n){if(t){const r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>(r.identify&&r.identify(e)||r.class&&e instanceof r.class)&&!r.format)}function I$(e,t,n){if(e instanceof $e)return e;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;t&&t.startsWith("!!")&&(t=r+t.slice(2));let c=j$(e,t,i.tags);if(!c){if(typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object")return a?new Y(e):e;c=e instanceof Map?kn:e[Symbol.iterator]?Mr:kn}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(e&&typeof e=="object"&&s){const l=s.get(e);if(l){const f=new We(l);return n.aliasNodes.push(f),f}u.value=e,s.set(e,u)}return u.node=c.createNode?c.createNode(n.schema,e,n):a?new Y(e):e,t&&u.node instanceof $e&&(u.node.tag=t),u.node}function x$(e,t,n,r){let o=e[r.replace(/\W/g,"")];if(!o){const s=Object.keys(e).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=t[i];if(!a){const c=Object.keys(t).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const P$=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;let An=class Pf{constructor({customTags:t,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?P$:o||null,!t&&s&&b$("tags","customTags"),this.tags=x$(k$,A$,t||s,r)}createNode(t,n,r,o){const s={defaultPrefix:Pf.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return I$(t,r,i)}createPair(t,n,r){r||(r={wrapScalars:!0});const o=this.createNode(t,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new J(o,s)}};he(An,"defaultPrefix",sr);he(An,"defaultTags",rt);const vr={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"},T$={get binary(){return yn},set binary(e){Object.assign(yn,e)},get bool(){return Ke},set bool(e){Object.assign(Ke,e)},get int(){return at},set int(e){Object.assign(at,e)},get null(){return Yt},set null(e){Object.assign(Yt,e)},get str(){return Ye},set str(e){Object.assign(Ye,e)}},Tf={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:sr},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:sr}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:sr}]}};function Lc(e,t){if((e.version||e.options.version)==="1.0"){const o=t.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=t.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${t.replace(/^tag:/,"")}`}let n=e.tagPrefixes.find(o=>t.indexOf(o.prefix)===0);if(!n){const o=e.getDefaults().tagPrefixes;n=o&&o.find(s=>t.indexOf(s.prefix)===0)}if(!n)return t[0]==="!"?t:`!<${t}>`;const r=t.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function C$(e,t){if(t instanceof We)return We;if(t.tag){const o=e.filter(s=>s.tag===t.tag);if(o.length>0)return o.find(s=>s.format===t.format)||o[0]}let n,r;if(t instanceof Y){r=t.value;const o=e.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===t.format)||o.find(s=>!s.format)}else r=t,n=e.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 R$(e,t,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(e);return s&&(n[s]=e,o.push(`&${s}`)),e.tag?o.push(Lc(r,e.tag)):t.default||o.push(Lc(r,t.tag)),o.join(" ")}function Hn(e,t,n,r){const{anchors:o,schema:s}=t.doc;let i;if(!(e instanceof $e)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};e=s.createNode(e,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let f=o.getName(l.source);f||(f=o.newName(),o.map[f]=l.source)}}if(e instanceof J)return e.toString(t,n,r);i||(i=C$(s.tags,e));const a=R$(e,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(e,t,n,r):e instanceof Y?hi(e,t,n,r):e.toString(t,n,r);return a?e instanceof Y||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
|
|
145
|
-
${t.indent}${c}`:c}class $i{static validAnchorNode(t){return t instanceof Y||t instanceof Le||t instanceof ve}constructor(t){he(this,"map",Object.create(null)),this.prefix=t}createAlias(t,n){return this.setAnchor(t,n),new
|
|
144
|
+
${s.comment}`:o.comment),o=s}n.items[r]=o instanceof J?o:new J(o)}}return n}function pf(e,t,n){const r=new Le(e);r.tag="tag:yaml.org,2002:pairs";for(const o of t){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=e.createPair(s,i,n);r.items.push(a)}return r}const hf={default:!1,tag:"tag:yaml.org,2002:pairs",resolve:df,createNode:pf};let Cr=class mf extends Le{constructor(){super(),he(this,"add",ve.prototype.add.bind(this)),he(this,"delete",ve.prototype.delete.bind(this)),he(this,"get",ve.prototype.get.bind(this)),he(this,"has",ve.prototype.has.bind(this)),he(this,"set",ve.prototype.set.bind(this)),this.tag=mf.tag}toJSON(t,n){const r=new Map;n&&n.onCreate&&n.onCreate(r);for(const o of this.items){let s,i;if(o instanceof J?(s=xe(o.key,"",n),i=xe(o.value,s,n)):s=xe(o,"",n),r.has(s))throw new Error("Ordered maps must not include duplicate keys");r.set(s,i)}return r}};he(Cr,"tag","tag:yaml.org,2002:omap");function w$(e,t){const n=df(e,t),r=[];for(const{key:o}of n.items)if(o instanceof Y)if(r.includes(o.value)){const s="Ordered maps must not include duplicate keys";throw new F(t,s)}else r.push(o.value);return Object.assign(new Cr,n)}function b$(e,t,n){const r=pf(e,t,n),o=new Cr;return o.items=r.items,o}const gf={identify:e=>e instanceof Map,nodeClass:Cr,default:!1,tag:"tag:yaml.org,2002:omap",resolve:w$,createNode:b$};let Rr=class yf extends ve{constructor(){super(),this.tag=yf.tag}add(t){const n=t instanceof J?t:new J(t);Ot(this.items,n.key)||this.items.push(n)}get(t,n){const r=Ot(this.items,t);return!n&&r instanceof J?r.key instanceof Y?r.key.value:r.key:r}set(t,n){if(typeof n!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof n}`);const r=Ot(this.items,t);r&&!n?this.items.splice(this.items.indexOf(r),1):!r&&n&&this.items.push(new J(t))}toJSON(t,n){return super.toJSON(t,n,Set)}toString(t,n,r){if(!t)return JSON.stringify(this);if(this.hasAllNullValues())return super.toString(t,n,r);throw new Error("Set items must all have null values")}};he(Rr,"tag","tag:yaml.org,2002:set");function E$(e,t){const n=uf(e,t);if(!n.hasAllNullValues())throw new F(t,"Set items must all have null values");return Object.assign(new Rr,n)}function S$(e,t,n){const r=new Rr;for(const o of t)r.items.push(e.createPair(o,null,n));return r}const $f={identify:e=>e instanceof Set,nodeClass:Rr,default:!1,tag:"tag:yaml.org,2002:set",resolve:E$,createNode:S$},mi=(e,t)=>{const n=t.split(":").reduce((r,o)=>r*60+Number(o),0);return e==="-"?-n:n},vf=({value:e})=>{if(isNaN(e)||!isFinite(e))return Ge(e);let t="";e<0&&(t="-",e=Math.abs(e));const n=[e%60];return e<60?n.unshift(0):(e=Math.round((e-n[0])/60),n.unshift(e%60),e>=60&&(e=Math.round((e-n[0])/60),n.unshift(e))),t+n.map(r=>r<10?"0"+String(r):String(r)).join(":").replace(/000000\d*$/,"")},wf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+)$/,resolve:(e,t,n)=>mi(t,n.replace(/_/g,"")),stringify:vf},bf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^([-+]?)([0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*)$/,resolve:(e,t,n)=>mi(t,n.replace(/_/g,"")),stringify:vf},Ef={identify:e=>e 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:(e,t,n,r,o,s,i,a,c)=>{a&&(a=(a+"00").substr(1,3));let u=Date.UTC(t,n-1,r,o||0,s||0,i||0,a||0);if(c&&c!=="Z"){let l=mi(c[0],c.slice(1));Math.abs(l)<30&&(l*=60),u-=6e4*l}return new Date(u)},stringify:({value:e})=>e.toISOString().replace(/((T00:00)?:00)?\.000Z$/,"")};function Sf(e){const t=typeof process<"u"&&process.env||{};return e?typeof YAML_SILENCE_DEPRECATION_WARNINGS<"u"?!YAML_SILENCE_DEPRECATION_WARNINGS:!t.YAML_SILENCE_DEPRECATION_WARNINGS:typeof YAML_SILENCE_WARNINGS<"u"?!YAML_SILENCE_WARNINGS:!t.YAML_SILENCE_WARNINGS}function Of(e,t){if(Sf(!1)){const n=typeof process<"u"&&process.emitWarning;n?n(e,t):console.warn(t?`${t}: ${e}`:e)}}const Mc={};function O$(e,t){if(!Mc[e]&&Sf(!0)){Mc[e]=!0;let n=`The option '${e}' will be removed in a future release`;n+=`, use '${t}' instead.`,Of(n,"DeprecationWarning")}}function N$(e,t,n){const r=new ve(e);if(t instanceof Map)for(const[o,s]of t)r.items.push(e.createPair(o,s,n));else if(t&&typeof t=="object")for(const o of Object.keys(t))r.items.push(e.createPair(o,t[o],n));return typeof e.sortMapEntries=="function"&&r.items.sort(e.sortMapEntries),r}const kn={createNode:N$,default:!0,nodeClass:ve,tag:"tag:yaml.org,2002:map",resolve:uf};function _$(e,t,n){const r=new Le(e);if(t&&t[Symbol.iterator])for(const o of t){const s=e.createNode(o,n.wrapScalars,null,n);r.items.push(s)}return r}const Mr={createNode:_$,default:!0,nodeClass:Le,tag:"tag:yaml.org,2002:seq",resolve:lf},k$={identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Dn,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),hi(e,t,n,r)},options:Ye},gi=[kn,Mr,k$],Dr=e=>typeof e=="bigint"||Number.isInteger(e),yi=(e,t,n)=>at.asBigInt?BigInt(e):parseInt(t,n);function Nf(e,t,n){const{value:r}=e;return Dr(r)&&r>=0?n+r.toString(t):Ge(e)}const _f={identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Yt,stringify:()=>Yt.nullStr},kf={identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>e[0]==="t"||e[0]==="T",options:Ke,stringify:({value:e})=>e?Ke.trueStr:Ke.falseStr},Af={identify:e=>Dr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o([0-7]+)$/,resolve:(e,t)=>yi(e,t,8),options:at,stringify:e=>Nf(e,8,"0o")},jf={identify:Dr,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:e=>yi(e,e,10),options:at,stringify:Ge},If={identify:e=>Dr(e)&&e>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x([0-9a-fA-F]+)$/,resolve:(e,t)=>yi(e,t,16),options:at,stringify:e=>Nf(e,16,"0x")},xf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ge},Pf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify:({value:e})=>Number(e).toExponential()},Tf={identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.([0-9]+)|[0-9]+\.([0-9]*))$/,resolve(e,t,n){const r=t||n,o=new Y(parseFloat(e));return r&&r[r.length-1]==="0"&&(o.minFractionDigits=r.length),o},stringify:Ge},A$=gi.concat([_f,kf,Af,jf,If,xf,Pf,Tf]),Dc=e=>typeof e=="bigint"||Number.isInteger(e),zn=({value:e})=>JSON.stringify(e),Cf=[kn,Mr,{identify:e=>typeof e=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:Dn,stringify:zn},{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:zn},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true|false$/,resolve:e=>e==="true",stringify:zn},{identify:Dc,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:e=>at.asBigInt?BigInt(e):parseInt(e,10),stringify:({value:e})=>Dc(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:zn}];Cf.scalarFallback=e=>{throw new SyntaxError(`Unresolved plain scalar ${JSON.stringify(e)}`)};const Lc=({value:e})=>e?Ke.trueStr:Ke.falseStr,dn=e=>typeof e=="bigint"||Number.isInteger(e);function Jn(e,t,n){let r=t.replace(/_/g,"");if(at.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 e==="-"?BigInt(-1)*s:s}const o=parseInt(r,n);return e==="-"?-1*o:o}function bo(e,t,n){const{value:r}=e;if(dn(r)){const o=r.toString(t);return r<0?"-"+n+o.substr(1):n+o}return Ge(e)}const j$=gi.concat([{identify:e=>e==null,createNode:(e,t,n)=>n.wrapScalars?new Y(null):null,default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>null,options:Yt,stringify:()=>Yt.nullStr},{identify:e=>typeof e=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>!0,options:Ke,stringify:Lc},{identify:e=>typeof e=="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:Ke,stringify:Lc},{identify:dn,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^([-+]?)0b([0-1_]+)$/,resolve:(e,t,n)=>Jn(t,n,2),stringify:e=>bo(e,2,"0b")},{identify:dn,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^([-+]?)0([0-7_]+)$/,resolve:(e,t,n)=>Jn(t,n,8),stringify:e=>bo(e,8,"0")},{identify:dn,default:!0,tag:"tag:yaml.org,2002:int",test:/^([-+]?)([0-9][0-9_]*)$/,resolve:(e,t,n)=>Jn(t,n,10),stringify:Ge},{identify:dn,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^([-+]?)0x([0-9a-fA-F_]+)$/,resolve:(e,t,n)=>Jn(t,n,16),stringify:e=>bo(e,16,"0x")},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.inf|(\.nan))$/i,resolve:(e,t)=>t?NaN:e[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Ge},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?([0-9][0-9_]*)?(\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,"")),stringify:({value:e})=>Number(e).toExponential()},{identify:e=>typeof e=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.([0-9_]*)$/,resolve(e,t){const n=new Y(parseFloat(e.replace(/_/g,"")));if(t){const r=t.replace(/_/g,"");r[r.length-1]==="0"&&(n.minFractionDigits=r.length)}return n},stringify:Ge}],ff,gf,hf,$f,wf,bf,Ef),I$={core:A$,failsafe:gi,json:Cf,yaml11:j$},x$={binary:ff,bool:kf,float:Tf,floatExp:Pf,floatNaN:xf,floatTime:bf,int:jf,intHex:If,intOct:Af,intTime:wf,map:kn,null:_f,omap:gf,pairs:hf,seq:Mr,set:$f,timestamp:Ef};function P$(e,t,n){if(t){const r=n.filter(s=>s.tag===t),o=r.find(s=>!s.format)||r[0];if(!o)throw new Error(`Tag ${t} not found`);return o}return n.find(r=>(r.identify&&r.identify(e)||r.class&&e instanceof r.class)&&!r.format)}function T$(e,t,n){if(e instanceof $e)return e;const{defaultPrefix:r,onTagObj:o,prevObjects:s,schema:i,wrapScalars:a}=n;t&&t.startsWith("!!")&&(t=r+t.slice(2));let c=P$(e,t,i.tags);if(!c){if(typeof e.toJSON=="function"&&(e=e.toJSON()),!e||typeof e!="object")return a?new Y(e):e;c=e instanceof Map?kn:e[Symbol.iterator]?Mr:kn}o&&(o(c),delete n.onTagObj);const u={value:void 0,node:void 0};if(e&&typeof e=="object"&&s){const l=s.get(e);if(l){const f=new He(l);return n.aliasNodes.push(f),f}u.value=e,s.set(e,u)}return u.node=c.createNode?c.createNode(n.schema,e,n):a?new Y(e):e,t&&u.node instanceof $e&&(u.node.tag=t),u.node}function C$(e,t,n,r){let o=e[r.replace(/\W/g,"")];if(!o){const s=Object.keys(e).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=t[i];if(!a){const c=Object.keys(t).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag "${i}"; use one of ${c}`)}o[s]=a}}return o}const R$=(e,t)=>e.key<t.key?-1:e.key>t.key?1:0;let An=class Rf{constructor({customTags:t,merge:n,schema:r,sortMapEntries:o,tags:s}){this.merge=!!n,this.name=r,this.sortMapEntries=o===!0?R$:o||null,!t&&s&&O$("tags","customTags"),this.tags=C$(I$,x$,t||s,r)}createNode(t,n,r,o){const s={defaultPrefix:Rf.defaultPrefix,schema:this,wrapScalars:n},i=o?Object.assign(o,s):s;return T$(t,r,i)}createPair(t,n,r){r||(r={wrapScalars:!0});const o=this.createNode(t,r.wrapScalars,null,r),s=this.createNode(n,r.wrapScalars,null,r);return new J(o,s)}};he(An,"defaultPrefix",sr);he(An,"defaultTags",rt);const vr={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"},M$={get binary(){return yn},set binary(e){Object.assign(yn,e)},get bool(){return Ke},set bool(e){Object.assign(Ke,e)},get int(){return at},set int(e){Object.assign(at,e)},get null(){return Yt},set null(e){Object.assign(Yt,e)},get str(){return Ye},set str(e){Object.assign(Ye,e)}},Mf={"1.0":{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:sr},{handle:"!!",prefix:"tag:private.yaml.org,2002:"}]},1.1:{schema:"yaml-1.1",merge:!0,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:sr}]},1.2:{schema:"core",merge:!1,tagPrefixes:[{handle:"!",prefix:"!"},{handle:"!!",prefix:sr}]}};function Uc(e,t){if((e.version||e.options.version)==="1.0"){const o=t.match(/^tag:private\.yaml\.org,2002:([^:/]+)$/);if(o)return"!"+o[1];const s=t.match(/^tag:([a-zA-Z0-9-]+)\.yaml\.org,2002:(.*)/);return s?`!${s[1]}/${s[2]}`:`!${t.replace(/^tag:/,"")}`}let n=e.tagPrefixes.find(o=>t.indexOf(o.prefix)===0);if(!n){const o=e.getDefaults().tagPrefixes;n=o&&o.find(s=>t.indexOf(s.prefix)===0)}if(!n)return t[0]==="!"?t:`!<${t}>`;const r=t.substr(n.prefix.length).replace(/[!,[\]{}]/g,o=>({"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"})[o]);return n.handle+r}function D$(e,t){if(t instanceof He)return He;if(t.tag){const o=e.filter(s=>s.tag===t.tag);if(o.length>0)return o.find(s=>s.format===t.format)||o[0]}let n,r;if(t instanceof Y){r=t.value;const o=e.filter(s=>s.identify&&s.identify(r)||s.class&&r instanceof s.class);n=o.find(s=>s.format===t.format)||o.find(s=>!s.format)}else r=t,n=e.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 L$(e,t,{anchors:n,doc:r}){const o=[],s=r.anchors.getName(e);return s&&(n[s]=e,o.push(`&${s}`)),e.tag?o.push(Uc(r,e.tag)):t.default||o.push(Uc(r,t.tag)),o.join(" ")}function Wn(e,t,n,r){const{anchors:o,schema:s}=t.doc;let i;if(!(e instanceof $e)){const u={aliasNodes:[],onTagObj:l=>i=l,prevObjects:new Map};e=s.createNode(e,!0,null,u);for(const l of u.aliasNodes){l.source=l.source.node;let f=o.getName(l.source);f||(f=o.newName(),o.map[f]=l.source)}}if(e instanceof J)return e.toString(t,n,r);i||(i=D$(s.tags,e));const a=L$(e,i,t);a.length>0&&(t.indentAtStart=(t.indentAtStart||0)+a.length+1);const c=typeof i.stringify=="function"?i.stringify(e,t,n,r):e instanceof Y?hi(e,t,n,r):e.toString(t,n,r);return a?e instanceof Y||c[0]==="{"||c[0]==="["?`${a} ${c}`:`${a}
|
|
145
|
+
${t.indent}${c}`:c}class $i{static validAnchorNode(t){return t instanceof Y||t instanceof Le||t instanceof ve}constructor(t){he(this,"map",Object.create(null)),this.prefix=t}createAlias(t,n){return this.setAnchor(t,n),new He(t)}createMergePair(...t){const n=new tf;return n.value.items=t.map(r=>{if(r instanceof He){if(r.source instanceof ve)return r}else if(r instanceof ve)return this.createAlias(r);throw new Error("Merge sources must be Map nodes or their Aliases")}),n}getName(t){const{map:n}=this;return Object.keys(n).find(r=>n[r]===t)}getNames(){return Object.keys(this.map)}getNode(t){return this.map[t]}newName(t){t||(t=this.prefix);const n=Object.keys(this.map);for(let r=1;;++r){const o=`${t}${r}`;if(!n.includes(o))return o}}resolveNodes(){const{map:t,_cstAliases:n}=this;Object.keys(t).forEach(r=>{t[r]=t[r].resolved}),n.forEach(r=>{r.source=r.source.resolved}),delete this._cstAliases}setAnchor(t,n){if(t!=null&&!$i.validAnchorNode(t))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=t&&Object.keys(r).find(s=>r[s]===t);if(o)if(n)o!==n&&(delete r[o],r[n]=t);else return o;else{if(!n){if(!t)return null;n=this.newName()}r[n]=t}return n}}const ur=(e,t)=>{if(e&&typeof e=="object"){const{tag:n}=e;e instanceof le?(n&&(t[n]=!0),e.items.forEach(r=>ur(r,t))):e instanceof J?(ur(e.key,t),ur(e.value,t)):e instanceof Y&&n&&(t[n]=!0)}return t},U$=e=>Object.keys(ur(e,{}));function B$(e,t){const n={before:[],after:[]};let r,o=!1;for(const s of t)if(s.valueRange){if(r!==void 0){const a="Document contains trailing content not separated by a ... or --- line";e.errors.push(new fe(s,a));break}const i=st(e,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===k.BLANK_LINE&&(o=!0,r===void 0&&n.before.length>0&&!e.commentBefore&&(e.commentBefore=n.before.join(`
|
|
146
146
|
`),n.before=[]));if(e.contents=r||null,!r)e.comment=n.before.concat(n.after).join(`
|
|
147
147
|
`)||null;else{const s=n.before.join(`
|
|
148
148
|
`);if(s){const i=r instanceof le&&r.items[0]?r.items[0]:r;i.commentBefore=i.commentBefore?`${s}
|
|
149
149
|
${i.commentBefore}`:s}e.comment=n.after.join(`
|
|
150
|
-
`)||null}}function
|
|
151
|
-
`)||null}function Tt(e){if(e instanceof le)return!0;throw new Error("Expected a YAML collection as document contents")}let vi=class
|
|
150
|
+
`)||null}}function F$({tagPrefixes:e},t){const[n,r]=t.parameters;if(!n||!r){const o="Insufficient parameters given for %TAG directive";throw new F(t,o)}if(e.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 F(t,o)}return{handle:n,prefix:r}}function q$(e,t){let[n]=t.parameters;if(t.name==="YAML:1.0"&&(n="1.0"),!n){const r="Insufficient parameters given for %YAML directive";throw new F(t,r)}if(!Mf[n]){const r=`Document will be parsed as YAML ${e.version||e.options.version} rather than YAML ${n}`;e.warnings.push(new en(t,r))}return n}function V$(e,t,n){const r=[];let o=!1;for(const s of t){const{comment:i,name:a}=s;switch(a){case"TAG":try{e.tagPrefixes.push(F$(e,s))}catch(c){e.errors.push(c)}o=!0;break;case"YAML":case"YAML:1.0":if(e.version){const c="The %YAML directive must only be given at most once per document.";e.errors.push(new F(s,c))}try{e.version=q$(e,s)}catch(c){e.errors.push(c)}o=!0;break;default:if(a){const c=`YAML only supports %TAG and %YAML directives, and not %${a}`;e.warnings.push(new en(s,c))}}i&&r.push(i)}if(n&&!o&&(e.version||n.version||e.options.version)==="1.1"){const s=({handle:i,prefix:a})=>({handle:i,prefix:a});e.tagPrefixes=n.tagPrefixes.map(s),e.version=n.version}e.commentBefore=r.join(`
|
|
151
|
+
`)||null}function Tt(e){if(e instanceof le)return!0;throw new Error("Expected a YAML collection as document contents")}let vi=class ls{constructor(t){this.anchors=new $i(t.anchorPrefix),this.commentBefore=null,this.comment=null,this.contents=null,this.directivesEndMarker=null,this.errors=[],this.options=t,this.schema=null,this.tagPrefixes=[],this.version=null,this.warnings=[]}add(t){return Tt(this.contents),this.contents.add(t)}addIn(t,n){Tt(this.contents),this.contents.addIn(t,n)}delete(t){return Tt(this.contents),this.contents.delete(t)}deleteIn(t){return fn(t)?this.contents==null?!1:(this.contents=null,!0):(Tt(this.contents),this.contents.deleteIn(t))}getDefaults(){return ls.defaults[this.version]||ls.defaults[this.options.version]||{}}get(t,n){return this.contents instanceof le?this.contents.get(t,n):void 0}getIn(t,n){return fn(t)?!n&&this.contents instanceof Y?this.contents.value:this.contents:this.contents instanceof le?this.contents.getIn(t,n):void 0}has(t){return this.contents instanceof le?this.contents.has(t):!1}hasIn(t){return fn(t)?this.contents!==void 0:this.contents instanceof le?this.contents.hasIn(t):!1}set(t,n){Tt(this.contents),this.contents.set(t,n)}setIn(t,n){fn(t)?this.contents=n:(Tt(this.contents),this.contents.setIn(t,n))}setSchema(t,n){if(!t&&!n&&this.schema)return;typeof t=="number"&&(t=t.toFixed(1)),t==="1.0"||t==="1.1"||t==="1.2"?(this.version?this.version=t:this.options.version=t,delete this.options.schema):t&&typeof t=="string"&&(this.options.schema=t),Array.isArray(n)&&(this.options.customTags=n);const r=Object.assign({},this.getDefaults(),this.options);this.schema=new An(r)}parse(t,n){this.options.keepCstNodes&&(this.cstNode=t),this.options.keepNodeTypes&&(this.type="DOCUMENT");const{directives:r=[],contents:o=[],directivesEndMarker:s,error:i,valueRange:a}=t;if(i&&(i.source||(i.source=this),this.errors.push(i)),V$(this,r,n),s&&(this.directivesEndMarker=!0),this.range=a?[a.start,a.end]:null,this.setSchema(),this.anchors._cstAliases=[],B$(this,o),this.anchors.resolveNodes(),this.options.prettyErrors){for(const c of this.errors)c instanceof At&&c.makePretty();for(const c of this.warnings)c instanceof At&&c.makePretty()}return this}listNonDefaultTags(){return U$(this.contents).filter(t=>t.indexOf(An.defaultPrefix)!==0)}setTagPrefix(t,n){if(t[0]!=="!"||t[t.length-1]!=="!")throw new Error("Handle must start and end with !");if(n){const r=this.tagPrefixes.find(o=>o.handle===t);r?r.prefix=n:this.tagPrefixes.push({handle:t,prefix:n})}else this.tagPrefixes=this.tagPrefixes.filter(r=>r.handle!==t)}toJSON(t,n){const{keepBlobsInJSON:r,mapAsMap:o,maxAliasCount:s}=this.options,i=r&&(typeof t!="string"||!(this.contents instanceof Y)),a={doc:this,indentStep:" ",keep:i,mapAsMap:i&&!!o,maxAliasCount:s,stringify:Wn},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=xe(this.contents,t,a);if(typeof n=="function"&&a.anchors)for(const{count:l,res:f}of a.anchors.values())n(f,l);return u}toString(){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");const t=this.options.indent;if(!Number.isInteger(t)||t<=0){const c=JSON.stringify(t);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(t),stringify:Wn};let i=!1,a=null;if(this.contents){this.contents instanceof $e&&(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=Wn(this.contents,s,()=>a=null,c);n.push(Gt(u,"",a))}else this.contents!==void 0&&n.push(Wn(this.contents,s));return this.comment&&((!i||a)&&n[n.length-1]!==""&&n.push(""),n.push(this.comment.replace(/^/gm,"#"))),n.join(`
|
|
152
152
|
`)+`
|
|
153
|
-
`}};he(vi,"defaults",
|
|
154
|
-
`}return`sha256-${
|
|
155
|
-
`);return`sha256-${Mf(t)}`}function rv(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function ov(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function sv(e){const t={type:"object",properties:{}},n=e;for(const r of Object.keys(n)){const o=n[r],s=r.split(".");let i=t;s.forEach((a,c)=>{if(c===s.length-1){i.properties[a]=iv(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 t}function iv(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 av="adhd-env-ref:";function cv(e){return`${av}${e}`}const uv=[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],lv=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Te(e,t){return(e>>>t|e<<32-t)>>>0}function fv(e){const t=Uint32Array.from(lv),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 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 f=0;f<r;f+=64){for(let b=0;b<16;b++)c[b]=a.getUint32(f+b*4,!1);for(let b=16;b<64;b++){const O=c[b-15],j=c[b-2],C=Te(O,7)^Te(O,18)^O>>>3,z=Te(j,17)^Te(j,19)^j>>>10;c[b]=c[b-16]+C+c[b-7]+z>>>0}let p=t[0],h=t[1],d=t[2],g=t[3],y=t[4],$=t[5],v=t[6],E=t[7];for(let b=0;b<64;b++){const O=Te(y,6)^Te(y,11)^Te(y,25),j=y&$^~y&v,C=E+O+j+uv[b]+c[b]>>>0,z=Te(p,2)^Te(p,13)^Te(p,22),U=p&h^p&d^h&d,q=z+U>>>0;E=v,v=$,$=y,y=g+C>>>0,g=d,d=h,h=p,p=C+q>>>0}t[0]=t[0]+p>>>0,t[1]=t[1]+h>>>0,t[2]=t[2]+d>>>0,t[3]=t[3]+g>>>0,t[4]=t[4]+y>>>0,t[5]=t[5]+$>>>0,t[6]=t[6]+v>>>0,t[7]=t[7]+E>>>0}const u=new Uint8Array(32),l=new DataView(u.buffer);for(let f=0;f<8;f++)l.setUint32(f*4,t[f],!1);return u}function dv(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function Mf(e){const t=new TextEncoder().encode(e);return dv(fv(t))}function Df(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 s=t?`${t}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,Df(o,s)):n[s]=o}return n}function Wn(e){if(L.existsSync(e))try{const t=L.readFileSync(e,"utf8"),n=H$.parse(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:Df(n)}catch{return}}function pv(e){return{system:Wn(T.join(e.system,Eo)),global:Wn(T.join(e.global,Eo)),project:e.project?Wn(T.join(e.project,Eo)):void 0,local:e.project?Wn(T.join(e.project,X$)):void 0}}function hv(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function ls(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 Lf(e){const t={};for(const n of Object.keys(e)){const r=n.split(".");let o=t;r.forEach((s,i)=>{if(i===r.length-1){o[s]=e[n];return}const a=o[s];(typeof a!="object"||a===null||Array.isArray(a))&&(o[s]={}),o=o[s]})}return t}const mv=[["system","system"],["global","global"],["project","project"],["local","local"]];function gv(e,t,n,r){const o={},s={},i={},a={};for(const c of Object.keys(e)){const u=e[c],l=u.env&&u.env!==""?u.env:ov(r.prefix,c),f=u.at==="runtime"||u.secret===!0,p=u.scope??r.activeScope;let h=u.default,d="default";for(const[E,b]of mv){const O=t[E];O&&Object.prototype.hasOwnProperty.call(O,c)&&(h=ls(O[c],u.type),d=b)}const g=n[l];let y,$,v;g!==void 0?(y=ls(g,u.type),$="env",v=l):(y=h,$=d),o[c]=f?cv(l):y,s[c]=y,i[c]=hv(f?{source:"env",scope:p,env:l}:{source:$,scope:p,env:v}),a[c]={...u,env:l,live:f,fallbackValue:h}}return{raw:o,nested:Lf(o),typedRaw:s,provenance:i,fields:a}}function yv(e,t){return e.replace(/\$\{HOME\}/g,He.homedir()).replace(/\$HOME\b/g,He.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function $v(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=o.scope??t.activeScope,i=o.share??ev[o.kind],a=o.path?yv(o.path,t):T.join(Kl(t.roots,s),r),c=i==="per-instance"?T.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:s,share:i}}return n}function vv(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=t[o.in];if(!s)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:T.join(s.path,o.name),share:o.share??"shared"}}return n}var fs={exports:{}},Uf={},Pe={},Qt={},Ln={},G={},jn={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(v){if(super(),!e.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}}}e.Name=n;class r extends t{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((E,b)=>`${E}${b}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((E,b)=>(b instanceof n&&(E[b.str]=(E[b.str]||0)+1),E),{})}}e._Code=r,e.nil=new r("");function o($,...v){const E=[$[0]];let b=0;for(;b<v.length;)a(E,v[b]),E.push($[++b]);return new r(E)}e._=o;const s=new r("+");function i($,...v){const E=[h($[0])];let b=0;for(;b<v.length;)E.push(s),a(E,v[b]),E.push(s,h($[++b]));return c(E),new r(E)}e.str=i;function a($,v){v instanceof r?$.push(...v._items):v instanceof n?$.push(v):$.push(f(v))}e.addCodeArg=a;function c($){let v=1;for(;v<$.length-1;){if($[v]===s){const E=u($[v-1],$[v+1]);if(E!==void 0){$.splice(v-1,3,E);continue}$[v++]="+"}v++}}function u($,v){if(v==='""')return $;if($==='""')return v;if(typeof $=="string")return v instanceof n||$[$.length-1]!=='"'?void 0:typeof v!="string"?`${$.slice(0,-1)}${v}"`:v[0]==='"'?$.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!($ instanceof n))return`"${$}${v.slice(1)}`}function l($,v){return v.emptyStr()?$:$.emptyStr()?v:i`${$}${v}`}e.strConcat=l;function f($){return typeof $=="number"||typeof $=="boolean"||$===null?$:h(Array.isArray($)?$.join(","):$)}function p($){return new r(h($))}e.stringify=p;function h($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function d($){return typeof $=="string"&&e.IDENTIFIER.test($)?new r(`.${$}`):o`[${$}]`}e.getProperty=d;function g($){if(typeof $=="string"&&e.IDENTIFIER.test($))return new r(`${$}`);throw new Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}e.getEsmExportName=g;function y($){return new r($.toString())}e.regexpCode=y})(jn);var ds={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=jn;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||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,f;if(!((f=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||f===void 0)&&f.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}}}e.Scope=o;class s extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:f}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${f}]`}}e.ValueScopeName=s;const i=(0,t._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:t.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var f;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:h}=p,d=(f=l.key)!==null&&f!==void 0?f:l.ref;let g=this._values[h];if(g){const v=g.get(d);if(v)return v}else g=this._values[h]=new Map;g.set(d,p);const y=this._scope[h]||(this._scope[h]=[]),$=y.length;return y[$]=l.ref,p.setValue(l,{property:h,itemIndex:$}),p}getValue(u,l){const f=this._values[u];if(f)return f.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${u}${f.scopePath}`})}scopeCode(u=this._values,l,f){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,f)}_reduceValues(u,l,f={},p){let h=t.nil;for(const d in u){const g=u[d];if(!g)continue;const y=f[d]=f[d]||new Map;g.forEach($=>{if(y.has($))return;y.set($,r.Started);let v=l($);if(v){const E=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${E} ${$} = ${v};${this.opts._n}`}else if(v=p==null?void 0:p($))h=(0,t._)`${h}${v}${this.opts._n}`;else throw new n($);y.set($,r.Completed)})}return h}}e.ValueScope=a})(ds);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=jn,n=ds;var r=jn;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var o=ds;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(m,w){return this}}class i extends s{constructor(m,w,_){super(),this.varKind=m,this.name=w,this.rhs=_}render({es5:m,_n:w}){const _=m?n.varKinds.var:this.varKind,M=this.rhs===void 0?"":` = ${this.rhs}`;return`${_} ${this.name}${M};`+w}optimizeNames(m,w){if(m[this.name.str])return this.rhs&&(this.rhs=Ne(this.rhs,m,w)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(m,w,_){super(),this.lhs=m,this.rhs=w,this.sideEffects=_}render({_n:m}){return`${this.lhs} = ${this.rhs};`+m}optimizeNames(m,w){if(!(this.lhs instanceof t.Name&&!m[this.lhs.str]&&!this.sideEffects))return this.rhs=Ne(this.rhs,m,w),this}get names(){const m=this.lhs instanceof t.Name?{}:{...this.lhs.names};return me(m,this.rhs)}}class c extends a{constructor(m,w,_,M){super(m,_,M),this.op=w}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 f extends s{constructor(m){super(),this.error=m}render({_n:m}){return`throw ${this.error};`+m}get names(){return this.error.names}}class p extends s{constructor(m){super(),this.code=m}render({_n:m}){return`${this.code};`+m}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(m,w){return this.code=Ne(this.code,m,w),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(m=[]){super(),this.nodes=m}render(m){return this.nodes.reduce((w,_)=>w+_.render(m),"")}optimizeNodes(){const{nodes:m}=this;let w=m.length;for(;w--;){const _=m[w].optimizeNodes();Array.isArray(_)?m.splice(w,1,..._):_?m[w]=_:m.splice(w,1)}return m.length>0?this:void 0}optimizeNames(m,w){const{nodes:_}=this;let M=_.length;for(;M--;){const D=_[M];D.optimizeNames(m,w)||(Fe(m,D.names),_.splice(M,1))}return _.length>0?this:void 0}get names(){return this.nodes.reduce((m,w)=>Z(m,w.names),{})}}class d extends h{render(m){return"{"+m._n+super.render(m)+"}"+m._n}}class g extends h{}class y extends d{}y.kind="else";class $ extends d{constructor(m,w){super(w),this.condition=m}render(m){let w=`if(${this.condition})`+super.render(m);return this.else&&(w+="else "+this.else.render(m)),w}optimizeNodes(){super.optimizeNodes();const m=this.condition;if(m===!0)return this.nodes;let w=this.else;if(w){const _=w.optimizeNodes();w=this.else=Array.isArray(_)?new y(_):_}if(w)return m===!1?w instanceof $?w:w.nodes:this.nodes.length?this:new $(de(m),w instanceof $?[w]:w.nodes);if(!(m===!1||!this.nodes.length))return this}optimizeNames(m,w){var _;if(this.else=(_=this.else)===null||_===void 0?void 0:_.optimizeNames(m,w),!!(super.optimizeNames(m,w)||this.else))return this.condition=Ne(this.condition,m,w),this}get names(){const m=super.names;return me(m,this.condition),this.else&&Z(m,this.else.names),m}}$.kind="if";class v extends d{}v.kind="for";class E extends v{constructor(m){super(),this.iteration=m}render(m){return`for(${this.iteration})`+super.render(m)}optimizeNames(m,w){if(super.optimizeNames(m,w))return this.iteration=Ne(this.iteration,m,w),this}get names(){return Z(super.names,this.iteration.names)}}class b extends v{constructor(m,w,_,M){super(),this.varKind=m,this.name=w,this.from=_,this.to=M}render(m){const w=m.es5?n.varKinds.var:this.varKind,{name:_,from:M,to:D}=this;return`for(${w} ${_}=${M}; ${_}<${D}; ${_}++)`+super.render(m)}get names(){const m=me(super.names,this.from);return me(m,this.to)}}class O extends v{constructor(m,w,_,M){super(),this.loop=m,this.varKind=w,this.name=_,this.iterable=M}render(m){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(m)}optimizeNames(m,w){if(super.optimizeNames(m,w))return this.iterable=Ne(this.iterable,m,w),this}get names(){return Z(super.names,this.iterable.names)}}class j extends d{constructor(m,w,_){super(),this.name=m,this.args=w,this.async=_}render(m){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(m)}}j.kind="func";class C extends h{render(m){return"return "+super.render(m)}}C.kind="return";class z extends d{render(m){let w="try"+super.render(m);return this.catch&&(w+=this.catch.render(m)),this.finally&&(w+=this.finally.render(m)),w}optimizeNodes(){var m,w;return super.optimizeNodes(),(m=this.catch)===null||m===void 0||m.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(m,w){var _,M;return super.optimizeNames(m,w),(_=this.catch)===null||_===void 0||_.optimizeNames(m,w),(M=this.finally)===null||M===void 0||M.optimizeNames(m,w),this}get names(){const m=super.names;return this.catch&&Z(m,this.catch.names),this.finally&&Z(m,this.finally.names),m}}class U extends d{constructor(m){super(),this.error=m}render(m){return`catch(${this.error})`+super.render(m)}}U.kind="catch";class q extends d{render(m){return"finally"+super.render(m)}}q.kind="finally";class Q{constructor(m,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
156
|
-
`:""},this._extScope=m,this._scope=new n.Scope({parent:m}),this._nodes=[new g]}toString(){return this._root.render(this.opts)}name(m){return this._scope.name(m)}scopeName(m){return this._extScope.name(m)}scopeValue(m,w){const _=this._extScope.value(m,w);return(this._values[_.prefix]||(this._values[_.prefix]=new Set)).add(_),_}getScopeValue(m,w){return this._extScope.getValue(m,w)}scopeRefs(m){return this._extScope.scopeRefs(m,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(m,w,_,M){const D=this._scope.toName(w);return _!==void 0&&M&&(this._constants[D.str]=_),this._leafNode(new i(m,D,_)),D}const(m,w,_){return this._def(n.varKinds.const,m,w,_)}let(m,w,_){return this._def(n.varKinds.let,m,w,_)}var(m,w,_){return this._def(n.varKinds.var,m,w,_)}assign(m,w,_){return this._leafNode(new a(m,w,_))}add(m,w){return this._leafNode(new c(m,e.operators.ADD,w))}code(m){return typeof m=="function"?m():m!==t.nil&&this._leafNode(new p(m)),this}object(...m){const w=["{"];for(const[_,M]of m)w.length>1&&w.push(","),w.push(_),(_!==M||this.opts.es5)&&(w.push(":"),(0,t.addCodeArg)(w,M));return w.push("}"),new t._Code(w)}if(m,w,_){if(this._blockNode(new $(m)),w&&_)this.code(w).else().code(_).endIf();else if(w)this.code(w).endIf();else if(_)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(m){return this._elseNode(new $(m))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode($,y)}_for(m,w){return this._blockNode(m),w&&this.code(w).endFor(),this}for(m,w){return this._for(new E(m),w)}forRange(m,w,_,M,D=this.opts.es5?n.varKinds.var:n.varKinds.let){const W=this._scope.toName(m);return this._for(new b(D,W,w,_),()=>M(W))}forOf(m,w,_,M=n.varKinds.const){const D=this._scope.toName(m);if(this.opts.es5){const W=w instanceof t.Name?w:this.var("_arr",w);return this.forRange("_i",0,(0,t._)`${W}.length`,H=>{this.var(D,(0,t._)`${W}[${H}]`),_(D)})}return this._for(new O("of",M,D,w),()=>_(D))}forIn(m,w,_,M=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(m,(0,t._)`Object.keys(${w})`,_);const D=this._scope.toName(m);return this._for(new O("in",M,D,w),()=>_(D))}endFor(){return this._endBlockNode(v)}label(m){return this._leafNode(new u(m))}break(m){return this._leafNode(new l(m))}return(m){const w=new C;if(this._blockNode(w),this.code(m),w.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(m,w,_){if(!w&&!_)throw new Error('CodeGen: "try" without "catch" and "finally"');const M=new z;if(this._blockNode(M),this.code(m),w){const D=this.name("e");this._currNode=M.catch=new U(D),w(D)}return _&&(this._currNode=M.finally=new q,this.code(_)),this._endBlockNode(U,q)}throw(m){return this._leafNode(new f(m))}block(m,w){return this._blockStarts.push(this._nodes.length),m&&this.code(m).endBlock(w),this}endBlock(m){const w=this._blockStarts.pop();if(w===void 0)throw new Error("CodeGen: not in self-balancing block");const _=this._nodes.length-w;if(_<0||m!==void 0&&_!==m)throw new Error(`CodeGen: wrong number of nodes: ${_} vs ${m} expected`);return this._nodes.length=w,this}func(m,w=t.nil,_,M){return this._blockNode(new j(m,w,_)),M&&this.code(M).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,w){const _=this._currNode;if(_ instanceof m||w&&_ instanceof w)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${w?`${m.kind}/${w.kind}`:m.kind}"`)}_elseNode(m){const w=this._currNode;if(!(w instanceof $))throw new Error('CodeGen: "else" without "if"');return this._currNode=w.else=m,this}get _root(){return this._nodes[0]}get _currNode(){const m=this._nodes;return m[m.length-1]}set _currNode(m){const w=this._nodes;w[w.length-1]=m}}e.CodeGen=Q;function Z(N,m){for(const w in m)N[w]=(N[w]||0)+(m[w]||0);return N}function me(N,m){return m instanceof t._CodeOrName?Z(N,m.names):N}function Ne(N,m,w){if(N instanceof t.Name)return _(N);if(!M(N))return N;return new t._Code(N._items.reduce((D,W)=>(W instanceof t.Name&&(W=_(W)),W instanceof t._Code?D.push(...W._items):D.push(W),D),[]));function _(D){const W=w[D.str];return W===void 0||m[D.str]!==1?D:(delete m[D.str],W)}function M(D){return D instanceof t._Code&&D._items.some(W=>W instanceof t.Name&&m[W.str]===1&&w[W.str]!==void 0)}}function Fe(N,m){for(const w in m)N[w]=(N[w]||0)-(m[w]||0)}function de(N){return typeof N=="boolean"||typeof N=="number"||N===null?!N:(0,t._)`!${A(N)}`}e.not=de;const on=S(e.operators.AND);function Qr(...N){return N.reduce(on)}e.and=Qr;const Fn=S(e.operators.OR);function x(...N){return N.reduce(Fn)}e.or=x;function S(N){return(m,w)=>m===t.nil?w:w===t.nil?m:(0,t._)`${A(m)} ${N} ${A(w)}`}function A(N){return N instanceof t.Name?N:(0,t._)`(${N})`}})(G);var P={};Object.defineProperty(P,"__esModule",{value:!0});P.checkStrictMode=P.getErrorPath=P.Type=P.useFunc=P.setEvaluated=P.evaluatedPropsToName=P.mergeEvaluated=P.eachItem=P.unescapeJsonPointer=P.escapeJsonPointer=P.escapeFragment=P.unescapeFragment=P.schemaRefOrVal=P.schemaHasRulesButRef=P.schemaHasRules=P.checkUnknownRules=P.alwaysValidSchema=P.toHash=void 0;const X=G,wv=jn;function bv(e){const t={};for(const n of e)t[n]=!0;return t}P.toHash=bv;function Ev(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Bf(e,t),!Ff(t,e.self.RULES.all))}P.alwaysValidSchema=Ev;function Bf(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;const o=r.RULES.keywords;for(const s in t)o[s]||Kf(e,`unknown keyword: "${s}"`)}P.checkUnknownRules=Bf;function Ff(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}P.schemaHasRules=Ff;function Sv(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}P.schemaHasRulesButRef=Sv;function Ov({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,X._)`${n}`}return(0,X._)`${e}${t}${(0,X.getProperty)(r)}`}P.schemaRefOrVal=Ov;function Nv(e){return qf(decodeURIComponent(e))}P.unescapeFragment=Nv;function _v(e){return encodeURIComponent(wi(e))}P.escapeFragment=_v;function wi(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}P.escapeJsonPointer=wi;function qf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}P.unescapeJsonPointer=qf;function kv(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}P.eachItem=kv;function qc({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof X.Name?(s instanceof X.Name?e(o,s,i):t(o,s,i),i):s instanceof X.Name?(t(o,i,s),s):n(s,i);return a===X.Name&&!(c instanceof X.Name)?r(o,c):c}}P.mergeEvaluated={props:qc({mergeNames:(e,t,n)=>e.if((0,X._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,X._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,X._)`${n} || {}`).code((0,X._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,X._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,X._)`${n} || {}`),bi(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:Vf}),items:qc({mergeNames:(e,t,n)=>e.if((0,X._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,X._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,X._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,X._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function Vf(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,X._)`{}`);return t!==void 0&&bi(e,n,t),n}P.evaluatedPropsToName=Vf;function bi(e,t,n){Object.keys(n).forEach(r=>e.assign((0,X._)`${t}${(0,X.getProperty)(r)}`,!0))}P.setEvaluated=bi;const Vc={};function Av(e,t){return e.scopeValue("func",{ref:t,code:Vc[t.code]||(Vc[t.code]=new wv._Code(t.code))})}P.useFunc=Av;var ps;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(ps||(P.Type=ps={}));function jv(e,t,n){if(e instanceof X.Name){const r=t===ps.Num;return n?r?(0,X._)`"[" + ${e} + "]"`:(0,X._)`"['" + ${e} + "']"`:r?(0,X._)`"/" + ${e}`:(0,X._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,X.getProperty)(e).toString():"/"+wi(e)}P.getErrorPath=jv;function Kf(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}P.checkStrictMode=Kf;var Be={};Object.defineProperty(Be,"__esModule",{value:!0});const pe=G,Iv={data:new pe.Name("data"),valCxt:new pe.Name("valCxt"),instancePath:new pe.Name("instancePath"),parentData:new pe.Name("parentData"),parentDataProperty:new pe.Name("parentDataProperty"),rootData:new pe.Name("rootData"),dynamicAnchors:new pe.Name("dynamicAnchors"),vErrors:new pe.Name("vErrors"),errors:new pe.Name("errors"),this:new pe.Name("this"),self:new pe.Name("self"),scope:new pe.Name("scope"),json:new pe.Name("json"),jsonPos:new pe.Name("jsonPos"),jsonLen:new pe.Name("jsonLen"),jsonPart:new pe.Name("jsonPart")};Be.default=Iv;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=G,n=P,r=Be;e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:$})=>$?(0,t.str)`"${y}" keyword must be ${$} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,$=e.keywordError,v,E){const{it:b}=y,{gen:O,compositeRule:j,allErrors:C}=b,z=f(y,$,v);E??(j||C)?c(O,z):u(b,(0,t._)`[${z}]`)}e.reportError=o;function s(y,$=e.keywordError,v){const{it:E}=y,{gen:b,compositeRule:O,allErrors:j}=E,C=f(y,$,v);c(b,C),O||j||u(E,r.default.vErrors)}e.reportExtraError=s;function i(y,$){y.assign(r.default.errors,$),y.if((0,t._)`${r.default.vErrors} !== null`,()=>y.if($,()=>y.assign((0,t._)`${r.default.vErrors}.length`,$),()=>y.assign(r.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:y,keyword:$,schemaValue:v,data:E,errsCount:b,it:O}){if(b===void 0)throw new Error("ajv implementation error");const j=y.name("err");y.forRange("i",b,r.default.errors,C=>{y.const(j,(0,t._)`${r.default.vErrors}[${C}]`),y.if((0,t._)`${j}.instancePath === undefined`,()=>y.assign((0,t._)`${j}.instancePath`,(0,t.strConcat)(r.default.instancePath,O.errorPath))),y.assign((0,t._)`${j}.schemaPath`,(0,t.str)`${O.errSchemaPath}/${$}`),O.opts.verbose&&(y.assign((0,t._)`${j}.schema`,v),y.assign((0,t._)`${j}.data`,E))})}e.extendErrors=a;function c(y,$){const v=y.const("err",$);y.if((0,t._)`${r.default.vErrors} === null`,()=>y.assign(r.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${r.default.vErrors}.push(${v})`),y.code((0,t._)`${r.default.errors}++`)}function u(y,$){const{gen:v,validateName:E,schemaEnv:b}=y;b.$async?v.throw((0,t._)`new ${y.ValidationError}(${$})`):(v.assign((0,t._)`${E}.errors`,$),v.return(!1))}const l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function f(y,$,v){const{createErrors:E}=y.it;return E===!1?(0,t._)`{}`:p(y,$,v)}function p(y,$,v={}){const{gen:E,it:b}=y,O=[h(b,v),d(y,v)];return g(y,$,O),E.object(...O)}function h({errorPath:y},{instancePath:$}){const v=$?(0,t.str)`${y}${(0,n.getErrorPath)($,n.Type.Str)}`:y;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,v)]}function d({keyword:y,it:{errSchemaPath:$}},{schemaPath:v,parentSchema:E}){let b=E?$:(0,t.str)`${$}/${y}`;return v&&(b=(0,t.str)`${b}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,b]}function g(y,{params:$,message:v},E){const{keyword:b,data:O,schemaValue:j,it:C}=y,{opts:z,propertyName:U,topSchemaRef:q,schemaPath:Q}=C;E.push([l.keyword,b],[l.params,typeof $=="function"?$(y):$||(0,t._)`{}`]),z.messages&&E.push([l.message,typeof v=="function"?v(y):v]),z.verbose&&E.push([l.schema,j],[l.parentSchema,(0,t._)`${q}${Q}`],[r.default.data,O]),U&&E.push([l.propertyName,U])}})(Ln);Object.defineProperty(Qt,"__esModule",{value:!0});Qt.boolOrEmptySchema=Qt.topBoolOrEmptySchema=void 0;const xv=Ln,Pv=G,Tv=Be,Cv={message:"boolean schema is false"};function Rv(e){const{gen:t,schema:n,validateName:r}=e;n===!1?Gf(e,!1):typeof n=="object"&&n.$async===!0?t.return(Tv.default.data):(t.assign((0,Pv._)`${r}.errors`,null),t.return(!0))}Qt.topBoolOrEmptySchema=Rv;function Mv(e,t){const{gen:n,schema:r}=e;r===!1?(n.var(t,!1),Gf(e)):n.var(t,!0)}Qt.boolOrEmptySchema=Mv;function Gf(e,t){const{gen:n,data:r}=e,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,xv.reportError)(o,Cv,void 0,t)}var se={},jt={};Object.defineProperty(jt,"__esModule",{value:!0});jt.getRules=jt.isJSONType=void 0;const Dv=["string","number","integer","boolean","null","object","array"],Lv=new Set(Dv);function Uv(e){return typeof e=="string"&&Lv.has(e)}jt.isJSONType=Uv;function Bv(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}jt.getRules=Bv;var ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.shouldUseRule=ze.shouldUseGroup=ze.schemaHasRulesForType=void 0;function Fv({schema:e,self:t},n){const r=t.RULES.types[n];return r&&r!==!0&&zf(e,r)}ze.schemaHasRulesForType=Fv;function zf(e,t){return t.rules.some(n=>Jf(e,n))}ze.shouldUseGroup=zf;function Jf(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}ze.shouldUseRule=Jf;Object.defineProperty(se,"__esModule",{value:!0});se.reportTypeError=se.checkDataTypes=se.checkDataType=se.coerceAndCheckDataType=se.getJSONTypes=se.getSchemaTypes=se.DataType=void 0;const qv=jt,Vv=ze,Kv=Ln,V=G,Hf=P;var Jt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Jt||(se.DataType=Jt={}));function Gv(e){const t=Wf(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}se.getSchemaTypes=Gv;function Wf(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(qv.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}se.getJSONTypes=Wf;function zv(e,t){const{gen:n,data:r,opts:o}=e,s=Jv(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,Vv.schemaHasRulesForType)(e,t[0]));if(i){const a=Ei(t,r,o.strictNumbers,Jt.Wrong);n.if(a,()=>{s.length?Hv(e,t,s):Si(e)})}return i}se.coerceAndCheckDataType=zv;const Yf=new Set(["string","number","integer","boolean","null"]);function Jv(e,t){return t?e.filter(n=>Yf.has(n)||t==="array"&&n==="array"):[]}function Hv(e,t,n){const{gen:r,data:o,opts:s}=e,i=r.let("dataType",(0,V._)`typeof ${o}`),a=r.let("coerced",(0,V._)`undefined`);s.coerceTypes==="array"&&r.if((0,V._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,V._)`${o}[0]`).assign(i,(0,V._)`typeof ${o}`).if(Ei(t,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,V._)`${a} !== undefined`);for(const u of n)(Yf.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Si(e),r.endIf(),r.if((0,V._)`${a} !== undefined`,()=>{r.assign(o,a),Wv(e,a)});function c(u){switch(u){case"string":r.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${o}`).elseIf((0,V._)`${o} === null`).assign(a,(0,V._)`""`);return;case"number":r.elseIf((0,V._)`${i} == "boolean" || ${o} === null
|
|
153
|
+
`}};he(vi,"defaults",Mf);function K$(e,t=!0,n){n===void 0&&typeof t=="string"&&(n=t,t=!0);const r=Object.assign({},vi.defaults[vr.version],vr);return new An(r).createNode(e,t,n)}class Lr extends vi{constructor(t){super(Object.assign({},vr,t))}}function G$(e,t){const n=[];let r;for(const o of fi(e)){const s=new Lr(t);s.parse(o,r),n.push(s),r=s}return n}function Df(e,t){const n=fi(e),r=new Lr(t).parse(n[0]);if(n.length>1){const o="Source contains multiple documents; please use YAML.parseAllDocuments()";r.errors.unshift(new F(n[1],o))}return r}function z$(e,t){const n=Df(e,t);if(n.warnings.forEach(r=>Of(r)),n.errors.length>0)throw n.errors[0];return n.toJSON()}function J$(e,t){const n=new Lr(t);return n.contents=e,String(n)}const W$={createNode:K$,defaultOptions:vr,Document:Lr,parse:z$,parseAllDocuments:G$,parseCST:fi,parseDocument:Df,scalarOptions:M$,stringify:J$},H$=Object.freeze(Object.defineProperty({__proto__:null,YAML:W$},Symbol.toStringTag,{value:"Module"})),Y$=zy(H$);var Q$=Y$.YAML;const Z$="1.0.0-redesign.1",X$="adhd",ev="default",tv="adhd-environment.json",Eo="config.yaml",nv="config.local.yaml",rv={data:"shared",cache:"shared",state:"shared",config:"shared",run:"shared",logs:"per-instance",temp:"per-instance"};class Bc 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 Fc(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 Lf(e,t){const n=Array.from(e),r=Array.from(t),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 qc(e){return new TextEncoder().encode(e).length}function ov(e){const t=Object.keys(e).sort(Lf);let n="";for(const r of t){const o=e[r];if(Fc(r))throw new Bc("key",r);if(Fc(o))throw new Bc("value",o);n+=`${qc(r)}:${r}=${qc(o)}:${o}
|
|
154
|
+
`}return`sha256-${Uf(n)}`}function sv(e){const t=[...e].sort((n,r)=>Lf(n.name,r.name)).map(n=>`${n.name}:${n.kind}:${n.scope}`).join(`
|
|
155
|
+
`);return`sha256-${Uf(t)}`}function iv(e){return`ADHD_${e.toUpperCase().replace(/[.-]/g,"_")}`}function av(e,t){return`${e}_${t.toUpperCase().replace(/[.-]/g,"_")}`}function cv(e){const t={type:"object",properties:{}},n=e;for(const r of Object.keys(n)){const o=n[r],s=r.split(".");let i=t;s.forEach((a,c)=>{if(c===s.length-1){i.properties[a]=uv(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 t}function uv(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 lv="adhd-env-ref:";function fv(e){return`${lv}${e}`}const dv=[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],pv=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];function Te(e,t){return(e>>>t|e<<32-t)>>>0}function hv(e){const t=Uint32Array.from(pv),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 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 f=0;f<r;f+=64){for(let b=0;b<16;b++)c[b]=a.getUint32(f+b*4,!1);for(let b=16;b<64;b++){const O=c[b-15],j=c[b-2],C=Te(O,7)^Te(O,18)^O>>>3,z=Te(j,17)^Te(j,19)^j>>>10;c[b]=c[b-16]+C+c[b-7]+z>>>0}let p=t[0],h=t[1],d=t[2],m=t[3],y=t[4],$=t[5],v=t[6],E=t[7];for(let b=0;b<64;b++){const O=Te(y,6)^Te(y,11)^Te(y,25),j=y&$^~y&v,C=E+O+j+dv[b]+c[b]>>>0,z=Te(p,2)^Te(p,13)^Te(p,22),U=p&h^p&d^h&d,q=z+U>>>0;E=v,v=$,$=y,y=m+C>>>0,m=d,d=h,h=p,p=C+q>>>0}t[0]=t[0]+p>>>0,t[1]=t[1]+h>>>0,t[2]=t[2]+d>>>0,t[3]=t[3]+m>>>0,t[4]=t[4]+y>>>0,t[5]=t[5]+$>>>0,t[6]=t[6]+v>>>0,t[7]=t[7]+E>>>0}const u=new Uint8Array(32),l=new DataView(u.buffer);for(let f=0;f<8;f++)l.setUint32(f*4,t[f],!1);return u}function mv(e){let t="";for(const n of e)t+=n.toString(16).padStart(2,"0");return t}function Uf(e){const t=new TextEncoder().encode(e);return mv(hv(t))}function Bf(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 s=t?`${t}.${r}`:r;o!==null&&typeof o=="object"&&!Array.isArray(o)?Object.assign(n,Bf(o,s)):n[s]=o}return n}function Hn(e){if(L.existsSync(e))try{const t=L.readFileSync(e,"utf8"),n=Q$.parse(t);return n===null||typeof n!="object"||Array.isArray(n)?void 0:Bf(n)}catch{return}}function gv(e){return{system:Hn(T.join(e.system,Eo)),global:Hn(T.join(e.global,Eo)),project:e.project?Hn(T.join(e.project,Eo)):void 0,local:e.project?Hn(T.join(e.project,nv)):void 0}}function yv(e){const t={source:e.source,scope:e.scope};return e.source==="env"&&e.env!==void 0&&(t.env=e.env),t}function fs(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 Ff(e){const t={};for(const n of Object.keys(e)){const r=n.split(".");let o=t;r.forEach((s,i)=>{if(i===r.length-1){o[s]=e[n];return}const a=o[s];(typeof a!="object"||a===null||Array.isArray(a))&&(o[s]={}),o=o[s]})}return t}const $v=[["system","system"],["global","global"],["project","project"],["local","local"]];function vv(e,t,n,r){const o={},s={},i={},a={};for(const c of Object.keys(e)){const u=e[c],l=u.env&&u.env!==""?u.env:av(r.prefix,c),f=u.at==="runtime"||u.secret===!0,p=u.scope??r.activeScope;let h=u.default,d="default";for(const[E,b]of $v){const O=t[E];O&&Object.prototype.hasOwnProperty.call(O,c)&&(h=fs(O[c],u.type),d=b)}const m=n[l];let y,$,v;m!==void 0?(y=fs(m,u.type),$="env",v=l):(y=h,$=d),o[c]=f?fv(l):y,s[c]=y,i[c]=yv(f?{source:"env",scope:p,env:l}:{source:$,scope:p,env:v}),a[c]={...u,env:l,live:f,fallbackValue:h}}return{raw:o,nested:Ff(o),typedRaw:s,provenance:i,fields:a}}function wv(e,t){return e.replace(/\$\{HOME\}/g,We.homedir()).replace(/\$HOME\b/g,We.homedir()).replace(/\$\{PROJECT_ROOT\}/g,t.projectRoot??process.cwd()).replace(/\$\{NAMESPACE\}/g,t.namespace)}function bv(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=o.scope??t.activeScope,i=o.share??rv[o.kind],a=o.path?wv(o.path,t):T.join(Jl(t.roots,s),r),c=i==="per-instance"?T.join(a,t.instanceId):a;n[r]={name:r,kind:o.kind,path:c,scope:s,share:i}}return n}function Ev(e,t){const n={};for(const[r,o]of Object.entries(e??{})){const s=t[o.in];if(!s)throw new Error(`files.${r}.in references unknown dirs key "${o.in}"`);n[r]={name:r,in:o.in,path:T.join(s.path,o.name),share:o.share??"shared"}}return n}var ds={exports:{}},qf={},Pe={},Qt={},Ln={},G={},jn={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;class t{}e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class n extends t{constructor(v){if(super(),!e.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}}}e.Name=n;class r extends t{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((E,b)=>`${E}${b}`,"")}get names(){var v;return(v=this._names)!==null&&v!==void 0?v:this._names=this._items.reduce((E,b)=>(b instanceof n&&(E[b.str]=(E[b.str]||0)+1),E),{})}}e._Code=r,e.nil=new r("");function o($,...v){const E=[$[0]];let b=0;for(;b<v.length;)a(E,v[b]),E.push($[++b]);return new r(E)}e._=o;const s=new r("+");function i($,...v){const E=[h($[0])];let b=0;for(;b<v.length;)E.push(s),a(E,v[b]),E.push(s,h($[++b]));return c(E),new r(E)}e.str=i;function a($,v){v instanceof r?$.push(...v._items):v instanceof n?$.push(v):$.push(f(v))}e.addCodeArg=a;function c($){let v=1;for(;v<$.length-1;){if($[v]===s){const E=u($[v-1],$[v+1]);if(E!==void 0){$.splice(v-1,3,E);continue}$[v++]="+"}v++}}function u($,v){if(v==='""')return $;if($==='""')return v;if(typeof $=="string")return v instanceof n||$[$.length-1]!=='"'?void 0:typeof v!="string"?`${$.slice(0,-1)}${v}"`:v[0]==='"'?$.slice(0,-1)+v.slice(1):void 0;if(typeof v=="string"&&v[0]==='"'&&!($ instanceof n))return`"${$}${v.slice(1)}`}function l($,v){return v.emptyStr()?$:$.emptyStr()?v:i`${$}${v}`}e.strConcat=l;function f($){return typeof $=="number"||typeof $=="boolean"||$===null?$:h(Array.isArray($)?$.join(","):$)}function p($){return new r(h($))}e.stringify=p;function h($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}e.safeStringify=h;function d($){return typeof $=="string"&&e.IDENTIFIER.test($)?new r(`.${$}`):o`[${$}]`}e.getProperty=d;function m($){if(typeof $=="string"&&e.IDENTIFIER.test($))return new r(`${$}`);throw new Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}e.getEsmExportName=m;function y($){return new r($.toString())}e.regexpCode=y})(jn);var ps={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;const t=jn;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||(e.UsedValueState=r={})),e.varKinds={const:new t.Name("const"),let:new t.Name("let"),var:new t.Name("var")};class o{constructor({prefixes:u,parent:l}={}){this._names={},this._prefixes=u,this._parent=l}toName(u){return u instanceof t.Name?u:this.name(u)}name(u){return new t.Name(this._newName(u))}_newName(u){const l=this._names[u]||this._nameGroup(u);return`${u}${l.index++}`}_nameGroup(u){var l,f;if(!((f=(l=this._parent)===null||l===void 0?void 0:l._prefixes)===null||f===void 0)&&f.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}}}e.Scope=o;class s extends t.Name{constructor(u,l){super(l),this.prefix=u}setValue(u,{property:l,itemIndex:f}){this.value=u,this.scopePath=(0,t._)`.${new t.Name(l)}[${f}]`}}e.ValueScopeName=s;const i=(0,t._)`\n`;class a extends o{constructor(u){super(u),this._values={},this._scope=u.scope,this.opts={...u,_n:u.lines?i:t.nil}}get(){return this._scope}name(u){return new s(u,this._newName(u))}value(u,l){var f;if(l.ref===void 0)throw new Error("CodeGen: ref must be passed in value");const p=this.toName(u),{prefix:h}=p,d=(f=l.key)!==null&&f!==void 0?f:l.ref;let m=this._values[h];if(m){const v=m.get(d);if(v)return v}else m=this._values[h]=new Map;m.set(d,p);const y=this._scope[h]||(this._scope[h]=[]),$=y.length;return y[$]=l.ref,p.setValue(l,{property:h,itemIndex:$}),p}getValue(u,l){const f=this._values[u];if(f)return f.get(l)}scopeRefs(u,l=this._values){return this._reduceValues(l,f=>{if(f.scopePath===void 0)throw new Error(`CodeGen: name "${f}" has no value`);return(0,t._)`${u}${f.scopePath}`})}scopeCode(u=this._values,l,f){return this._reduceValues(u,p=>{if(p.value===void 0)throw new Error(`CodeGen: name "${p}" has no value`);return p.value.code},l,f)}_reduceValues(u,l,f={},p){let h=t.nil;for(const d in u){const m=u[d];if(!m)continue;const y=f[d]=f[d]||new Map;m.forEach($=>{if(y.has($))return;y.set($,r.Started);let v=l($);if(v){const E=this.opts.es5?e.varKinds.var:e.varKinds.const;h=(0,t._)`${h}${E} ${$} = ${v};${this.opts._n}`}else if(v=p==null?void 0:p($))h=(0,t._)`${h}${v}${this.opts._n}`;else throw new n($);y.set($,r.Completed)})}return h}}e.ValueScope=a})(ps);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;const t=jn,n=ps;var r=jn;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var o=ps;Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return o.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return o.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return o.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return o.varKinds}}),e.operators={GT:new t._Code(">"),GTE:new t._Code(">="),LT:new t._Code("<"),LTE:new t._Code("<="),EQ:new t._Code("==="),NEQ:new t._Code("!=="),NOT:new t._Code("!"),OR:new t._Code("||"),AND:new t._Code("&&"),ADD:new t._Code("+")};class s{optimizeNodes(){return this}optimizeNames(g,w){return this}}class i extends s{constructor(g,w,_){super(),this.varKind=g,this.name=w,this.rhs=_}render({es5:g,_n:w}){const _=g?n.varKinds.var:this.varKind,M=this.rhs===void 0?"":` = ${this.rhs}`;return`${_} ${this.name}${M};`+w}optimizeNames(g,w){if(g[this.name.str])return this.rhs&&(this.rhs=Ne(this.rhs,g,w)),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}}class a extends s{constructor(g,w,_){super(),this.lhs=g,this.rhs=w,this.sideEffects=_}render({_n:g}){return`${this.lhs} = ${this.rhs};`+g}optimizeNames(g,w){if(!(this.lhs instanceof t.Name&&!g[this.lhs.str]&&!this.sideEffects))return this.rhs=Ne(this.rhs,g,w),this}get names(){const g=this.lhs instanceof t.Name?{}:{...this.lhs.names};return me(g,this.rhs)}}class c extends a{constructor(g,w,_,M){super(g,_,M),this.op=w}render({_n:g}){return`${this.lhs} ${this.op}= ${this.rhs};`+g}}class u extends s{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`${this.label}:`+g}}class l extends s{constructor(g){super(),this.label=g,this.names={}}render({_n:g}){return`break${this.label?` ${this.label}`:""};`+g}}class f extends s{constructor(g){super(),this.error=g}render({_n:g}){return`throw ${this.error};`+g}get names(){return this.error.names}}class p extends s{constructor(g){super(),this.code=g}render({_n:g}){return`${this.code};`+g}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(g,w){return this.code=Ne(this.code,g,w),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}}class h extends s{constructor(g=[]){super(),this.nodes=g}render(g){return this.nodes.reduce((w,_)=>w+_.render(g),"")}optimizeNodes(){const{nodes:g}=this;let w=g.length;for(;w--;){const _=g[w].optimizeNodes();Array.isArray(_)?g.splice(w,1,..._):_?g[w]=_:g.splice(w,1)}return g.length>0?this:void 0}optimizeNames(g,w){const{nodes:_}=this;let M=_.length;for(;M--;){const D=_[M];D.optimizeNames(g,w)||(Fe(g,D.names),_.splice(M,1))}return _.length>0?this:void 0}get names(){return this.nodes.reduce((g,w)=>Z(g,w.names),{})}}class d extends h{render(g){return"{"+g._n+super.render(g)+"}"+g._n}}class m extends h{}class y extends d{}y.kind="else";class $ extends d{constructor(g,w){super(w),this.condition=g}render(g){let w=`if(${this.condition})`+super.render(g);return this.else&&(w+="else "+this.else.render(g)),w}optimizeNodes(){super.optimizeNodes();const g=this.condition;if(g===!0)return this.nodes;let w=this.else;if(w){const _=w.optimizeNodes();w=this.else=Array.isArray(_)?new y(_):_}if(w)return g===!1?w instanceof $?w:w.nodes:this.nodes.length?this:new $(de(g),w instanceof $?[w]:w.nodes);if(!(g===!1||!this.nodes.length))return this}optimizeNames(g,w){var _;if(this.else=(_=this.else)===null||_===void 0?void 0:_.optimizeNames(g,w),!!(super.optimizeNames(g,w)||this.else))return this.condition=Ne(this.condition,g,w),this}get names(){const g=super.names;return me(g,this.condition),this.else&&Z(g,this.else.names),g}}$.kind="if";class v extends d{}v.kind="for";class E extends v{constructor(g){super(),this.iteration=g}render(g){return`for(${this.iteration})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iteration=Ne(this.iteration,g,w),this}get names(){return Z(super.names,this.iteration.names)}}class b extends v{constructor(g,w,_,M){super(),this.varKind=g,this.name=w,this.from=_,this.to=M}render(g){const w=g.es5?n.varKinds.var:this.varKind,{name:_,from:M,to:D}=this;return`for(${w} ${_}=${M}; ${_}<${D}; ${_}++)`+super.render(g)}get names(){const g=me(super.names,this.from);return me(g,this.to)}}class O extends v{constructor(g,w,_,M){super(),this.loop=g,this.varKind=w,this.name=_,this.iterable=M}render(g){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(g)}optimizeNames(g,w){if(super.optimizeNames(g,w))return this.iterable=Ne(this.iterable,g,w),this}get names(){return Z(super.names,this.iterable.names)}}class j extends d{constructor(g,w,_){super(),this.name=g,this.args=w,this.async=_}render(g){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(g)}}j.kind="func";class C extends h{render(g){return"return "+super.render(g)}}C.kind="return";class z extends d{render(g){let w="try"+super.render(g);return this.catch&&(w+=this.catch.render(g)),this.finally&&(w+=this.finally.render(g)),w}optimizeNodes(){var g,w;return super.optimizeNodes(),(g=this.catch)===null||g===void 0||g.optimizeNodes(),(w=this.finally)===null||w===void 0||w.optimizeNodes(),this}optimizeNames(g,w){var _,M;return super.optimizeNames(g,w),(_=this.catch)===null||_===void 0||_.optimizeNames(g,w),(M=this.finally)===null||M===void 0||M.optimizeNames(g,w),this}get names(){const g=super.names;return this.catch&&Z(g,this.catch.names),this.finally&&Z(g,this.finally.names),g}}class U extends d{constructor(g){super(),this.error=g}render(g){return`catch(${this.error})`+super.render(g)}}U.kind="catch";class q extends d{render(g){return"finally"+super.render(g)}}q.kind="finally";class Q{constructor(g,w={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...w,_n:w.lines?`
|
|
156
|
+
`:""},this._extScope=g,this._scope=new n.Scope({parent:g}),this._nodes=[new m]}toString(){return this._root.render(this.opts)}name(g){return this._scope.name(g)}scopeName(g){return this._extScope.name(g)}scopeValue(g,w){const _=this._extScope.value(g,w);return(this._values[_.prefix]||(this._values[_.prefix]=new Set)).add(_),_}getScopeValue(g,w){return this._extScope.getValue(g,w)}scopeRefs(g){return this._extScope.scopeRefs(g,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(g,w,_,M){const D=this._scope.toName(w);return _!==void 0&&M&&(this._constants[D.str]=_),this._leafNode(new i(g,D,_)),D}const(g,w,_){return this._def(n.varKinds.const,g,w,_)}let(g,w,_){return this._def(n.varKinds.let,g,w,_)}var(g,w,_){return this._def(n.varKinds.var,g,w,_)}assign(g,w,_){return this._leafNode(new a(g,w,_))}add(g,w){return this._leafNode(new c(g,e.operators.ADD,w))}code(g){return typeof g=="function"?g():g!==t.nil&&this._leafNode(new p(g)),this}object(...g){const w=["{"];for(const[_,M]of g)w.length>1&&w.push(","),w.push(_),(_!==M||this.opts.es5)&&(w.push(":"),(0,t.addCodeArg)(w,M));return w.push("}"),new t._Code(w)}if(g,w,_){if(this._blockNode(new $(g)),w&&_)this.code(w).else().code(_).endIf();else if(w)this.code(w).endIf();else if(_)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(g){return this._elseNode(new $(g))}else(){return this._elseNode(new y)}endIf(){return this._endBlockNode($,y)}_for(g,w){return this._blockNode(g),w&&this.code(w).endFor(),this}for(g,w){return this._for(new E(g),w)}forRange(g,w,_,M,D=this.opts.es5?n.varKinds.var:n.varKinds.let){const H=this._scope.toName(g);return this._for(new b(D,H,w,_),()=>M(H))}forOf(g,w,_,M=n.varKinds.const){const D=this._scope.toName(g);if(this.opts.es5){const H=w instanceof t.Name?w:this.var("_arr",w);return this.forRange("_i",0,(0,t._)`${H}.length`,W=>{this.var(D,(0,t._)`${H}[${W}]`),_(D)})}return this._for(new O("of",M,D,w),()=>_(D))}forIn(g,w,_,M=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(g,(0,t._)`Object.keys(${w})`,_);const D=this._scope.toName(g);return this._for(new O("in",M,D,w),()=>_(D))}endFor(){return this._endBlockNode(v)}label(g){return this._leafNode(new u(g))}break(g){return this._leafNode(new l(g))}return(g){const w=new C;if(this._blockNode(w),this.code(g),w.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(C)}try(g,w,_){if(!w&&!_)throw new Error('CodeGen: "try" without "catch" and "finally"');const M=new z;if(this._blockNode(M),this.code(g),w){const D=this.name("e");this._currNode=M.catch=new U(D),w(D)}return _&&(this._currNode=M.finally=new q,this.code(_)),this._endBlockNode(U,q)}throw(g){return this._leafNode(new f(g))}block(g,w){return this._blockStarts.push(this._nodes.length),g&&this.code(g).endBlock(w),this}endBlock(g){const w=this._blockStarts.pop();if(w===void 0)throw new Error("CodeGen: not in self-balancing block");const _=this._nodes.length-w;if(_<0||g!==void 0&&_!==g)throw new Error(`CodeGen: wrong number of nodes: ${_} vs ${g} expected`);return this._nodes.length=w,this}func(g,w=t.nil,_,M){return this._blockNode(new j(g,w,_)),M&&this.code(M).endFunc(),this}endFunc(){return this._endBlockNode(j)}optimize(g=1){for(;g-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(g){return this._currNode.nodes.push(g),this}_blockNode(g){this._currNode.nodes.push(g),this._nodes.push(g)}_endBlockNode(g,w){const _=this._currNode;if(_ instanceof g||w&&_ instanceof w)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${w?`${g.kind}/${w.kind}`:g.kind}"`)}_elseNode(g){const w=this._currNode;if(!(w instanceof $))throw new Error('CodeGen: "else" without "if"');return this._currNode=w.else=g,this}get _root(){return this._nodes[0]}get _currNode(){const g=this._nodes;return g[g.length-1]}set _currNode(g){const w=this._nodes;w[w.length-1]=g}}e.CodeGen=Q;function Z(N,g){for(const w in g)N[w]=(N[w]||0)+(g[w]||0);return N}function me(N,g){return g instanceof t._CodeOrName?Z(N,g.names):N}function Ne(N,g,w){if(N instanceof t.Name)return _(N);if(!M(N))return N;return new t._Code(N._items.reduce((D,H)=>(H instanceof t.Name&&(H=_(H)),H instanceof t._Code?D.push(...H._items):D.push(H),D),[]));function _(D){const H=w[D.str];return H===void 0||g[D.str]!==1?D:(delete g[D.str],H)}function M(D){return D instanceof t._Code&&D._items.some(H=>H instanceof t.Name&&g[H.str]===1&&w[H.str]!==void 0)}}function Fe(N,g){for(const w in g)N[w]=(N[w]||0)-(g[w]||0)}function de(N){return typeof N=="boolean"||typeof N=="number"||N===null?!N:(0,t._)`!${A(N)}`}e.not=de;const on=S(e.operators.AND);function Qr(...N){return N.reduce(on)}e.and=Qr;const Fn=S(e.operators.OR);function x(...N){return N.reduce(Fn)}e.or=x;function S(N){return(g,w)=>g===t.nil?w:w===t.nil?g:(0,t._)`${A(g)} ${N} ${A(w)}`}function A(N){return N instanceof t.Name?N:(0,t._)`(${N})`}})(G);var P={};Object.defineProperty(P,"__esModule",{value:!0});P.checkStrictMode=P.getErrorPath=P.Type=P.useFunc=P.setEvaluated=P.evaluatedPropsToName=P.mergeEvaluated=P.eachItem=P.unescapeJsonPointer=P.escapeJsonPointer=P.escapeFragment=P.unescapeFragment=P.schemaRefOrVal=P.schemaHasRulesButRef=P.schemaHasRules=P.checkUnknownRules=P.alwaysValidSchema=P.toHash=void 0;const X=G,Sv=jn;function Ov(e){const t={};for(const n of e)t[n]=!0;return t}P.toHash=Ov;function Nv(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Vf(e,t),!Kf(t,e.self.RULES.all))}P.alwaysValidSchema=Nv;function Vf(e,t=e.schema){const{opts:n,self:r}=e;if(!n.strictSchema||typeof t=="boolean")return;const o=r.RULES.keywords;for(const s in t)o[s]||Jf(e,`unknown keyword: "${s}"`)}P.checkUnknownRules=Vf;function Kf(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(t[n])return!0;return!1}P.schemaHasRules=Kf;function _v(e,t){if(typeof e=="boolean")return!e;for(const n in e)if(n!=="$ref"&&t.all[n])return!0;return!1}P.schemaHasRulesButRef=_v;function kv({topSchemaRef:e,schemaPath:t},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,X._)`${n}`}return(0,X._)`${e}${t}${(0,X.getProperty)(r)}`}P.schemaRefOrVal=kv;function Av(e){return Gf(decodeURIComponent(e))}P.unescapeFragment=Av;function jv(e){return encodeURIComponent(wi(e))}P.escapeFragment=jv;function wi(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}P.escapeJsonPointer=wi;function Gf(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}P.unescapeJsonPointer=Gf;function Iv(e,t){if(Array.isArray(e))for(const n of e)t(n);else t(e)}P.eachItem=Iv;function Vc({mergeNames:e,mergeToName:t,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{const c=i===void 0?s:i instanceof X.Name?(s instanceof X.Name?e(o,s,i):t(o,s,i),i):s instanceof X.Name?(t(o,i,s),s):n(s,i);return a===X.Name&&!(c instanceof X.Name)?r(o,c):c}}P.mergeEvaluated={props:Vc({mergeNames:(e,t,n)=>e.if((0,X._)`${n} !== true && ${t} !== undefined`,()=>{e.if((0,X._)`${t} === true`,()=>e.assign(n,!0),()=>e.assign(n,(0,X._)`${n} || {}`).code((0,X._)`Object.assign(${n}, ${t})`))}),mergeToName:(e,t,n)=>e.if((0,X._)`${n} !== true`,()=>{t===!0?e.assign(n,!0):(e.assign(n,(0,X._)`${n} || {}`),bi(e,n,t))}),mergeValues:(e,t)=>e===!0?!0:{...e,...t},resultToName:zf}),items:Vc({mergeNames:(e,t,n)=>e.if((0,X._)`${n} !== true && ${t} !== undefined`,()=>e.assign(n,(0,X._)`${t} === true ? true : ${n} > ${t} ? ${n} : ${t}`)),mergeToName:(e,t,n)=>e.if((0,X._)`${n} !== true`,()=>e.assign(n,t===!0?!0:(0,X._)`${n} > ${t} ? ${n} : ${t}`)),mergeValues:(e,t)=>e===!0?!0:Math.max(e,t),resultToName:(e,t)=>e.var("items",t)})};function zf(e,t){if(t===!0)return e.var("props",!0);const n=e.var("props",(0,X._)`{}`);return t!==void 0&&bi(e,n,t),n}P.evaluatedPropsToName=zf;function bi(e,t,n){Object.keys(n).forEach(r=>e.assign((0,X._)`${t}${(0,X.getProperty)(r)}`,!0))}P.setEvaluated=bi;const Kc={};function xv(e,t){return e.scopeValue("func",{ref:t,code:Kc[t.code]||(Kc[t.code]=new Sv._Code(t.code))})}P.useFunc=xv;var hs;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(hs||(P.Type=hs={}));function Pv(e,t,n){if(e instanceof X.Name){const r=t===hs.Num;return n?r?(0,X._)`"[" + ${e} + "]"`:(0,X._)`"['" + ${e} + "']"`:r?(0,X._)`"/" + ${e}`:(0,X._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,X.getProperty)(e).toString():"/"+wi(e)}P.getErrorPath=Pv;function Jf(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw new Error(t);e.self.logger.warn(t)}}P.checkStrictMode=Jf;var Be={};Object.defineProperty(Be,"__esModule",{value:!0});const pe=G,Tv={data:new pe.Name("data"),valCxt:new pe.Name("valCxt"),instancePath:new pe.Name("instancePath"),parentData:new pe.Name("parentData"),parentDataProperty:new pe.Name("parentDataProperty"),rootData:new pe.Name("rootData"),dynamicAnchors:new pe.Name("dynamicAnchors"),vErrors:new pe.Name("vErrors"),errors:new pe.Name("errors"),this:new pe.Name("this"),self:new pe.Name("self"),scope:new pe.Name("scope"),json:new pe.Name("json"),jsonPos:new pe.Name("jsonPos"),jsonLen:new pe.Name("jsonLen"),jsonPart:new pe.Name("jsonPart")};Be.default=Tv;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;const t=G,n=P,r=Be;e.keywordError={message:({keyword:y})=>(0,t.str)`must pass "${y}" keyword validation`},e.keyword$DataError={message:({keyword:y,schemaType:$})=>$?(0,t.str)`"${y}" keyword must be ${$} ($data)`:(0,t.str)`"${y}" keyword is invalid ($data)`};function o(y,$=e.keywordError,v,E){const{it:b}=y,{gen:O,compositeRule:j,allErrors:C}=b,z=f(y,$,v);E??(j||C)?c(O,z):u(b,(0,t._)`[${z}]`)}e.reportError=o;function s(y,$=e.keywordError,v){const{it:E}=y,{gen:b,compositeRule:O,allErrors:j}=E,C=f(y,$,v);c(b,C),O||j||u(E,r.default.vErrors)}e.reportExtraError=s;function i(y,$){y.assign(r.default.errors,$),y.if((0,t._)`${r.default.vErrors} !== null`,()=>y.if($,()=>y.assign((0,t._)`${r.default.vErrors}.length`,$),()=>y.assign(r.default.vErrors,null)))}e.resetErrorsCount=i;function a({gen:y,keyword:$,schemaValue:v,data:E,errsCount:b,it:O}){if(b===void 0)throw new Error("ajv implementation error");const j=y.name("err");y.forRange("i",b,r.default.errors,C=>{y.const(j,(0,t._)`${r.default.vErrors}[${C}]`),y.if((0,t._)`${j}.instancePath === undefined`,()=>y.assign((0,t._)`${j}.instancePath`,(0,t.strConcat)(r.default.instancePath,O.errorPath))),y.assign((0,t._)`${j}.schemaPath`,(0,t.str)`${O.errSchemaPath}/${$}`),O.opts.verbose&&(y.assign((0,t._)`${j}.schema`,v),y.assign((0,t._)`${j}.data`,E))})}e.extendErrors=a;function c(y,$){const v=y.const("err",$);y.if((0,t._)`${r.default.vErrors} === null`,()=>y.assign(r.default.vErrors,(0,t._)`[${v}]`),(0,t._)`${r.default.vErrors}.push(${v})`),y.code((0,t._)`${r.default.errors}++`)}function u(y,$){const{gen:v,validateName:E,schemaEnv:b}=y;b.$async?v.throw((0,t._)`new ${y.ValidationError}(${$})`):(v.assign((0,t._)`${E}.errors`,$),v.return(!1))}const l={keyword:new t.Name("keyword"),schemaPath:new t.Name("schemaPath"),params:new t.Name("params"),propertyName:new t.Name("propertyName"),message:new t.Name("message"),schema:new t.Name("schema"),parentSchema:new t.Name("parentSchema")};function f(y,$,v){const{createErrors:E}=y.it;return E===!1?(0,t._)`{}`:p(y,$,v)}function p(y,$,v={}){const{gen:E,it:b}=y,O=[h(b,v),d(y,v)];return m(y,$,O),E.object(...O)}function h({errorPath:y},{instancePath:$}){const v=$?(0,t.str)`${y}${(0,n.getErrorPath)($,n.Type.Str)}`:y;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,v)]}function d({keyword:y,it:{errSchemaPath:$}},{schemaPath:v,parentSchema:E}){let b=E?$:(0,t.str)`${$}/${y}`;return v&&(b=(0,t.str)`${b}${(0,n.getErrorPath)(v,n.Type.Str)}`),[l.schemaPath,b]}function m(y,{params:$,message:v},E){const{keyword:b,data:O,schemaValue:j,it:C}=y,{opts:z,propertyName:U,topSchemaRef:q,schemaPath:Q}=C;E.push([l.keyword,b],[l.params,typeof $=="function"?$(y):$||(0,t._)`{}`]),z.messages&&E.push([l.message,typeof v=="function"?v(y):v]),z.verbose&&E.push([l.schema,j],[l.parentSchema,(0,t._)`${q}${Q}`],[r.default.data,O]),U&&E.push([l.propertyName,U])}})(Ln);Object.defineProperty(Qt,"__esModule",{value:!0});Qt.boolOrEmptySchema=Qt.topBoolOrEmptySchema=void 0;const Cv=Ln,Rv=G,Mv=Be,Dv={message:"boolean schema is false"};function Lv(e){const{gen:t,schema:n,validateName:r}=e;n===!1?Wf(e,!1):typeof n=="object"&&n.$async===!0?t.return(Mv.default.data):(t.assign((0,Rv._)`${r}.errors`,null),t.return(!0))}Qt.topBoolOrEmptySchema=Lv;function Uv(e,t){const{gen:n,schema:r}=e;r===!1?(n.var(t,!1),Wf(e)):n.var(t,!0)}Qt.boolOrEmptySchema=Uv;function Wf(e,t){const{gen:n,data:r}=e,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,Cv.reportError)(o,Dv,void 0,t)}var se={},jt={};Object.defineProperty(jt,"__esModule",{value:!0});jt.getRules=jt.isJSONType=void 0;const Bv=["string","number","integer","boolean","null","object","array"],Fv=new Set(Bv);function qv(e){return typeof e=="string"&&Fv.has(e)}jt.isJSONType=qv;function Vv(){const e={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}jt.getRules=Vv;var ze={};Object.defineProperty(ze,"__esModule",{value:!0});ze.shouldUseRule=ze.shouldUseGroup=ze.schemaHasRulesForType=void 0;function Kv({schema:e,self:t},n){const r=t.RULES.types[n];return r&&r!==!0&&Hf(e,r)}ze.schemaHasRulesForType=Kv;function Hf(e,t){return t.rules.some(n=>Yf(e,n))}ze.shouldUseGroup=Hf;function Yf(e,t){var n;return e[t.keyword]!==void 0||((n=t.definition.implements)===null||n===void 0?void 0:n.some(r=>e[r]!==void 0))}ze.shouldUseRule=Yf;Object.defineProperty(se,"__esModule",{value:!0});se.reportTypeError=se.checkDataTypes=se.checkDataType=se.coerceAndCheckDataType=se.getJSONTypes=se.getSchemaTypes=se.DataType=void 0;const Gv=jt,zv=ze,Jv=Ln,V=G,Qf=P;var Jt;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Jt||(se.DataType=Jt={}));function Wv(e){const t=Zf(e.type);if(t.includes("null")){if(e.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!t.length&&e.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');e.nullable===!0&&t.push("null")}return t}se.getSchemaTypes=Wv;function Zf(e){const t=Array.isArray(e)?e:e?[e]:[];if(t.every(Gv.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}se.getJSONTypes=Zf;function Hv(e,t){const{gen:n,data:r,opts:o}=e,s=Yv(t,o.coerceTypes),i=t.length>0&&!(s.length===0&&t.length===1&&(0,zv.schemaHasRulesForType)(e,t[0]));if(i){const a=Ei(t,r,o.strictNumbers,Jt.Wrong);n.if(a,()=>{s.length?Qv(e,t,s):Si(e)})}return i}se.coerceAndCheckDataType=Hv;const Xf=new Set(["string","number","integer","boolean","null"]);function Yv(e,t){return t?e.filter(n=>Xf.has(n)||t==="array"&&n==="array"):[]}function Qv(e,t,n){const{gen:r,data:o,opts:s}=e,i=r.let("dataType",(0,V._)`typeof ${o}`),a=r.let("coerced",(0,V._)`undefined`);s.coerceTypes==="array"&&r.if((0,V._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,V._)`${o}[0]`).assign(i,(0,V._)`typeof ${o}`).if(Ei(t,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,V._)`${a} !== undefined`);for(const u of n)(Xf.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),Si(e),r.endIf(),r.if((0,V._)`${a} !== undefined`,()=>{r.assign(o,a),Zv(e,a)});function c(u){switch(u){case"string":r.elseIf((0,V._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,V._)`"" + ${o}`).elseIf((0,V._)`${o} === null`).assign(a,(0,V._)`""`);return;case"number":r.elseIf((0,V._)`${i} == "boolean" || ${o} === null
|
|
157
157
|
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,V._)`+${o}`);return;case"integer":r.elseIf((0,V._)`${i} === "boolean" || ${o} === null
|
|
158
158
|
|| (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,V._)`+${o}`);return;case"boolean":r.elseIf((0,V._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,V._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,V._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,V._)`${i} === "string" || ${i} === "number"
|
|
159
|
-
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,V._)`[${o}]`)}}}function Wv({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,V._)`${t} !== undefined`,()=>e.assign((0,V._)`${t}[${n}]`,r))}function hs(e,t,n,r=Jt.Correct){const o=r===Jt.Correct?V.operators.EQ:V.operators.NEQ;let s;switch(e){case"null":return(0,V._)`${t} ${o} null`;case"array":s=(0,V._)`Array.isArray(${t})`;break;case"object":s=(0,V._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,V._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,V._)`typeof ${t} ${o} ${e}`}return r===Jt.Correct?s:(0,V.not)(s);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${t} == "number"`,a,n?(0,V._)`isFinite(${t})`:V.nil)}}se.checkDataType=hs;function Ei(e,t,n,r){if(e.length===1)return hs(e[0],t,n,r);let o;const s=(0,Hf.toHash)(e);if(s.array&&s.object){const i=(0,V._)`typeof ${t} != "object"`;o=s.null?i:(0,V._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=V.nil;s.number&&delete s.integer;for(const i in s)o=(0,V.and)(o,hs(i,t,n,r));return o}se.checkDataTypes=Ei;const Yv={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,V._)`{type: ${e}}`:(0,V._)`{type: ${t}}`};function Si(e){const t=Qv(e);(0,Kv.reportError)(t,Yv)}se.reportTypeError=Si;function Qv(e){const{gen:t,data:n,schema:r}=e,o=(0,Hf.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var Ur={};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.assignDefaults=void 0;const Ct=G,Zv=P;function Xv(e,t){const{properties:n,items:r}=e.schema;if(t==="object"&&n)for(const o in n)Kc(e,o,n[o].default);else t==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Kc(e,s,o.default))}Ur.assignDefaults=Xv;function Kc(e,t,n){const{gen:r,compositeRule:o,data:s,opts:i}=e;if(n===void 0)return;const a=(0,Ct._)`${s}${(0,Ct.getProperty)(t)}`;if(o){(0,Zv.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Ct._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ct._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Ct._)`${a} = ${(0,Ct.stringify)(n)}`)}var Re={},K={};Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;const ee=G,Oi=P,Xe=Be,e0=P;function t0(e,t){const{gen:n,data:r,it:o}=e;n.if(_i(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=t0;function n0({gen:e,data:t,it:{opts:n}},r,o){return(0,ee.or)(...r.map(s=>(0,ee.and)(_i(e,t,s,n.ownProperties),(0,ee._)`${o} = ${s}`)))}K.checkMissingProp=n0;function r0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=r0;function Qf(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=Qf;function Ni(e,t,n){return(0,ee._)`${Qf(e)}.call(${t}, ${n})`}K.isOwnProperty=Ni;function o0(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} !== undefined`;return r?(0,ee._)`${o} && ${Ni(e,t,n)}`:o}K.propertyInData=o0;function _i(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} === undefined`;return r?(0,ee.or)(o,(0,ee.not)(Ni(e,t,n))):o}K.noPropertyInData=_i;function Zf(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=Zf;function s0(e,t){return Zf(t).filter(n=>!(0,Oi.alwaysValidSchema)(e,t[n]))}K.schemaProperties=s0;function i0({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){const l=u?(0,ee._)`${e}, ${t}, ${r}${o}`:t,f=[[Xe.default.instancePath,(0,ee.strConcat)(Xe.default.instancePath,s)],[Xe.default.parentData,i.parentData],[Xe.default.parentDataProperty,i.parentDataProperty],[Xe.default.rootData,Xe.default.rootData]];i.opts.dynamicRef&&f.push([Xe.default.dynamicAnchors,Xe.default.dynamicAnchors]);const p=(0,ee._)`${l}, ${n.object(...f)}`;return c!==ee.nil?(0,ee._)`${a}.call(${c}, ${p})`:(0,ee._)`${a}(${p})`}K.callValidateCode=i0;const a0=(0,ee._)`new RegExp`;function c0({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(n,r);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ee._)`${o.code==="new RegExp"?a0:(0,e0.useFunc)(e,o)}(${n}, ${r})`})}K.usePattern=c0;function u0(e){const{gen:t,data:n,keyword:r,it:o}=e,s=t.name("valid");if(o.allErrors){const a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){const c=t.const("len",(0,ee._)`${n}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:r,dataProp:u,dataPropType:Oi.Type.Num},s),t.if((0,ee.not)(s),a)})}}K.validateArray=u0;function l0(e){const{gen:t,schema:n,keyword:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,Oi.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;const s=t.let("valid",!1),i=t.name("_valid");t.block(()=>n.forEach((a,c)=>{const u=e.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);t.assign(s,(0,ee._)`${s} || ${i}`),e.mergeValidEvaluated(u,i)||t.if((0,ee.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=l0;Object.defineProperty(Re,"__esModule",{value:!0});Re.validateKeywordUsage=Re.validSchemaType=Re.funcKeywordCode=Re.macroKeywordCode=void 0;const ge=G,yt=Be,f0=K,d0=Ln;function p0(e,t){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=Xf(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");e.subschema({schema:a,schemaPath:ge.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Re.macroKeywordCode=p0;function h0(e,t){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;g0(c,t);const u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,l=Xf(r,o,u),f=r.let("valid");e.block$data(f,p),e.ok((n=t.valid)!==null&&n!==void 0?n:f);function p(){if(t.errors===!1)g(),t.modifying&&Gc(e),y(()=>e.error());else{const $=t.async?h():d();t.modifying&&Gc(e),y(()=>m0(e,$))}}function h(){const $=r.let("ruleErrs",null);return r.try(()=>g((0,ge._)`await `),v=>r.assign(f,!1).if((0,ge._)`${v} instanceof ${c.ValidationError}`,()=>r.assign($,(0,ge._)`${v}.errors`),()=>r.throw(v))),$}function d(){const $=(0,ge._)`${l}.errors`;return r.assign($,null),g(ge.nil),$}function g($=t.async?(0,ge._)`await `:ge.nil){const v=c.opts.passContext?yt.default.this:yt.default.self,E=!("compile"in t&&!a||t.schema===!1);r.assign(f,(0,ge._)`${$}${(0,f0.callValidateCode)(e,l,v,E)}`,t.modifying)}function y($){var v;r.if((0,ge.not)((v=t.valid)!==null&&v!==void 0?v:f),$)}}Re.funcKeywordCode=h0;function Gc(e){const{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,ge._)`${r.parentData}[${r.parentDataProperty}]`))}function m0(e,t){const{gen:n}=e;n.if((0,ge._)`Array.isArray(${t})`,()=>{n.assign(yt.default.vErrors,(0,ge._)`${yt.default.vErrors} === null ? ${t} : ${yt.default.vErrors}.concat(${t})`).assign(yt.default.errors,(0,ge._)`${yt.default.vErrors}.length`),(0,d0.extendErrors)(e)},()=>e.error())}function g0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function Xf(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ge.stringify)(n)})}function y0(e,t,n=!1){return!t.length||t.some(r=>r==="array"?Array.isArray(e):r==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==r||n&&typeof e>"u")}Re.validSchemaType=y0;function $0({schema:e,opts:t,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(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){const a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}Re.validateKeywordUsage=$0;var it={};Object.defineProperty(it,"__esModule",{value:!0});it.extendSubschemaMode=it.extendSubschemaData=it.getSubschema=void 0;const Ce=G,ed=P;function v0(e,{keyword:t,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){const a=e.schema[t];return n===void 0?{schema:a,schemaPath:(0,Ce._)`${e.schemaPath}${(0,Ce.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,Ce._)`${e.schemaPath}${(0,Ce.getProperty)(t)}${(0,Ce.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,ed.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')}it.getSubschema=v0;function w0(e,t,{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}=t;if(n!==void 0){const{errorPath:u,dataPathArr:l,opts:f}=t,p=a.let("data",(0,Ce._)`${t.data}${(0,Ce.getProperty)(n)}`,!0);c(p),e.errorPath=(0,Ce.str)`${u}${(0,ed.getErrorPath)(n,r,f.jsPropertySyntax)}`,e.parentDataProperty=(0,Ce._)`${n}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){const u=o instanceof Ce.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}it.extendSubschemaData=w0;function b0(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(e.compositeRule=r),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}it.extendSubschemaMode=b0;var ue={},td=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),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(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n},nd={exports:{}},ot=nd.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};lr(t,r,o,e,"",e)};ot.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ot.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ot.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ot.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 lr(e,t,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,o,s,i,a,c,u);for(var l in r){var f=r[l];if(Array.isArray(f)){if(l in ot.arrayKeywords)for(var p=0;p<f.length;p++)lr(e,t,n,f[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in ot.propsKeywords){if(f&&typeof f=="object")for(var h in f)lr(e,t,n,f[h],o+"/"+l+"/"+E0(h),s,o,l,r,h)}else(l in ot.keywords||e.allKeys&&!(l in ot.skipKeywords))&&lr(e,t,n,f,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function E0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var S0=nd.exports;Object.defineProperty(ue,"__esModule",{value:!0});ue.getSchemaRefs=ue.resolveUrl=ue.normalizeId=ue._getFullPath=ue.getFullPath=ue.inlineRef=void 0;const O0=P,N0=td,_0=S0,k0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function A0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!ms(e):t?rd(e)<=t:!1}ue.inlineRef=A0;const j0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function ms(e){for(const t in e){if(j0.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(ms)||typeof n=="object"&&ms(n))return!0}return!1}function rd(e){let t=0;for(const n in e)if(n==="$ref"||(t++,!k0.has(n)&&(typeof e[n]=="object"&&(0,O0.eachItem)(e[n],r=>t+=rd(r)),t===1/0)))return 1/0;return t}function od(e,t="",n){n!==!1&&(t=Ht(t));const r=e.parse(t);return sd(e,r)}ue.getFullPath=od;function sd(e,t){return e.serialize(t).split("#")[0]+"#"}ue._getFullPath=sd;const I0=/#\/?$/;function Ht(e){return e?e.replace(I0,""):""}ue.normalizeId=Ht;function x0(e,t,n){return n=Ht(n),e.resolve(t,n)}ue.resolveUrl=x0;const P0=/^[a-z_][-a-z0-9._]*$/i;function T0(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Ht(e[n]||t),s={"":o},i=od(r,o,!1),a={},c=new Set;return _0(e,{allKeys:!0},(f,p,h,d)=>{if(d===void 0)return;const g=i+p;let y=s[d];typeof f[n]=="string"&&(y=$.call(this,f[n])),v.call(this,f.$anchor),v.call(this,f.$dynamicAnchor),s[p]=y;function $(E){const b=this.opts.uriResolver.resolve;if(E=Ht(y?b(y,E):E),c.has(E))throw l(E);c.add(E);let O=this.refs[E];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?u(f,O.schema,E):E!==Ht(g)&&(E[0]==="#"?(u(f,a[E],E),a[E]=f):this.refs[E]=g),E}function v(E){if(typeof E=="string"){if(!P0.test(E))throw new Error(`invalid anchor "${E}"`);$.call(this,`#${E}`)}}}),a;function u(f,p,h){if(p!==void 0&&!N0(f,p))throw l(h)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ue.getSchemaRefs=T0;Object.defineProperty(Pe,"__esModule",{value:!0});Pe.getData=Pe.KeywordCxt=Pe.validateFunctionCode=void 0;const id=Qt,zc=se,ki=ze,wr=se,C0=Ur,$n=Re,So=it,R=G,B=Be,R0=ue,Je=P,an=Ln;function M0(e){if(ud(e)&&(ld(e),cd(e))){U0(e);return}ad(e,()=>(0,id.topBoolOrEmptySchema)(e))}Pe.validateFunctionCode=M0;function ad({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},s){o.code.es5?e.func(t,(0,R._)`${B.default.data}, ${B.default.valCxt}`,r.$async,()=>{e.code((0,R._)`"use strict"; ${Jc(n,o)}`),L0(e,o),e.code(s)}):e.func(t,(0,R._)`${B.default.data}, ${D0(o)}`,r.$async,()=>e.code(Jc(n,o)).code(s))}function D0(e){return(0,R._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${e.dynamicRef?(0,R._)`, ${B.default.dynamicAnchors}={}`:R.nil}}={}`}function L0(e,t){e.if(B.default.valCxt,()=>{e.var(B.default.instancePath,(0,R._)`${B.default.valCxt}.${B.default.instancePath}`),e.var(B.default.parentData,(0,R._)`${B.default.valCxt}.${B.default.parentData}`),e.var(B.default.parentDataProperty,(0,R._)`${B.default.valCxt}.${B.default.parentDataProperty}`),e.var(B.default.rootData,(0,R._)`${B.default.valCxt}.${B.default.rootData}`),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,R._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{e.var(B.default.instancePath,(0,R._)`""`),e.var(B.default.parentData,(0,R._)`undefined`),e.var(B.default.parentDataProperty,(0,R._)`undefined`),e.var(B.default.rootData,B.default.data),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,R._)`{}`)})}function U0(e){const{schema:t,opts:n,gen:r}=e;ad(e,()=>{n.$comment&&t.$comment&&dd(e),K0(e),r.let(B.default.vErrors,null),r.let(B.default.errors,0),n.unevaluated&&B0(e),fd(e),J0(e)})}function B0(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,R._)`${n}.evaluated`),t.if((0,R._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,R._)`${e.evaluated}.props`,(0,R._)`undefined`)),t.if((0,R._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,R._)`${e.evaluated}.items`,(0,R._)`undefined`))}function Jc(e,t){const n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,R._)`/*# sourceURL=${n} */`:R.nil}function F0(e,t){if(ud(e)&&(ld(e),cd(e))){q0(e,t);return}(0,id.boolOrEmptySchema)(e,t)}function cd({schema:e,self:t}){if(typeof e=="boolean")return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function ud(e){return typeof e.schema!="boolean"}function q0(e,t){const{schema:n,gen:r,opts:o}=e;o.$comment&&n.$comment&&dd(e),G0(e),z0(e);const s=r.const("_errs",B.default.errors);fd(e,s),r.var(t,(0,R._)`${s} === ${B.default.errors}`)}function ld(e){(0,Je.checkUnknownRules)(e),V0(e)}function fd(e,t){if(e.opts.jtd)return Hc(e,[],!1,t);const n=(0,zc.getSchemaTypes)(e.schema),r=(0,zc.coerceAndCheckDataType)(e,n);Hc(e,n,!r,t)}function V0(e){const{schema:t,errSchemaPath:n,opts:r,self:o}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,Je.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function K0(e){const{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Je.checkStrictMode)(e,"default is ignored in the schema root")}function G0(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,R0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function z0(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function dd({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)e.code((0,R._)`${B.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,R.str)`${r}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,R._)`${B.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function J0(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=e;n.$async?t.if((0,R._)`${B.default.errors} === 0`,()=>t.return(B.default.data),()=>t.throw((0,R._)`new ${o}(${B.default.vErrors})`)):(t.assign((0,R._)`${r}.errors`,B.default.vErrors),s.unevaluated&&H0(e),t.return((0,R._)`${B.default.errors} === 0`))}function H0({gen:e,evaluated:t,props:n,items:r}){n instanceof R.Name&&e.assign((0,R._)`${t}.props`,n),r instanceof R.Name&&e.assign((0,R._)`${t}.items`,r)}function Hc(e,t,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Je.schemaHasRulesButRef)(s,l))){o.block(()=>md(e,"$ref",l.all.$ref.definition));return}c.jtd||W0(e,t),o.block(()=>{for(const p of l.rules)f(p);f(l.post)});function f(p){(0,ki.shouldUseGroup)(s,p)&&(p.type?(o.if((0,wr.checkDataType)(p.type,i,c.strictNumbers)),Wc(e,p),t.length===1&&t[0]===p.type&&n&&(o.else(),(0,wr.reportTypeError)(e)),o.endIf()):Wc(e,p),a||o.if((0,R._)`${B.default.errors} === ${r||0}`))}}function Wc(e,t){const{gen:n,schema:r,opts:{useDefaults:o}}=e;o&&(0,C0.assignDefaults)(e,t.type),n.block(()=>{for(const s of t.rules)(0,ki.shouldUseRule)(r,s)&&md(e,s.keyword,s.definition,t.type)})}function W0(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(Y0(e,t),e.opts.allowUnionTypes||Q0(e,t),Z0(e,e.dataTypes))}function Y0(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{pd(e.dataTypes,n)||Ai(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),ew(e,t)}}function Q0(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ai(e,"use allowUnionTypes to allow union type keyword")}function Z0(e,t){const n=e.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,ki.shouldUseRule)(e.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>X0(t,i))&&Ai(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function X0(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function pd(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function ew(e,t){const n=[];for(const r of e.dataTypes)pd(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function Ai(e,t){const n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,Je.checkStrictMode)(e,t,e.opts.strictTypes)}class hd{constructor(t,n,r){if((0,$n.validateKeywordUsage)(t,n,r),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=r,this.data=t.data,this.schema=t.schema[r],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Je.schemaRefOrVal)(t,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",gd(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,$n.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=t.gen.const("_errs",B.default.errors))}result(t,n,r){this.failResult((0,R.not)(t),n,r)}failResult(t,n,r){this.gen.if(t),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,R.not)(t),void 0,n)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);const{schemaCode:n}=this;this.fail((0,R._)`${n} !== undefined && (${(0,R.or)(this.invalid$data(),t)})`)}error(t,n,r){if(n){this.setParams(n),this._error(t,r),this.setParams({});return}this._error(t,r)}_error(t,n){(t?an.reportExtraError:an.reportError)(this,this.def.error,n)}$dataError(){(0,an.reportError)(this,this.def.$dataError||an.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,an.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,r=R.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=R.nil,n=R.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,R.or)((0,R._)`${o} === undefined`,n)),t!==R.nil&&r.assign(t,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==R.nil&&r.assign(t,!1)),r.else()}invalid$data(){const{gen:t,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,R.or)(i(),a());function i(){if(r.length){if(!(n instanceof R.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,R._)`${(0,wr.checkDataTypes)(c,n,s.opts.strictNumbers,wr.DataType.Wrong)}`}return R.nil}function a(){if(o.validateSchema){const c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,R._)`!${c}(${n})`}return R.nil}}subschema(t,n){const r=(0,So.getSubschema)(this.it,t);(0,So.extendSubschemaData)(r,this.it,t),(0,So.extendSubschemaMode)(r,t);const o={...this.it,...r,items:void 0,props:void 0};return F0(o,n),o}mergeEvaluated(t,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=Je.mergeEvaluated.props(o,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=Je.mergeEvaluated.items(o,t.items,r.items,n)))}mergeValidEvaluated(t,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(t,R.Name)),!0}}Pe.KeywordCxt=hd;function md(e,t,n,r){const o=new hd(e,n,t);"code"in n?n.code(o,r):o.$data&&n.validate?(0,$n.funcKeywordCode)(o,n):"macro"in n?(0,$n.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,$n.funcKeywordCode)(o,n)}const tw=/^\/(?:[^~]|~0|~1)*$/,nw=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function gd(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let o,s;if(e==="")return B.default.rootData;if(e[0]==="/"){if(!tw.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=B.default.rootData}else{const u=nw.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);const l=+u[1];if(o=u[2],o==="#"){if(l>=t)throw new Error(c("property/index",l));return r[t-l]}if(l>t)throw new Error(c("data",l));if(s=n[t-l],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,R._)`${s}${(0,R.getProperty)((0,Je.unescapeJsonPointer)(u))}`,i=(0,R._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}Pe.getData=gd;var Un={};Object.defineProperty(Un,"__esModule",{value:!0});let rw=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Un.default=rw;var tn={};Object.defineProperty(tn,"__esModule",{value:!0});const Oo=ue;class ow extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Oo.resolveUrl)(t,n,r),this.missingSchema=(0,Oo.normalizeId)((0,Oo.getFullPath)(t,this.missingRef))}}tn.default=ow;var we={};Object.defineProperty(we,"__esModule",{value:!0});we.resolveSchema=we.getCompilingSchema=we.resolveRef=we.compileSchema=we.SchemaEnv=void 0;const Ae=G,sw=Un,ft=Be,Ie=ue,Yc=P,iw=Pe;class Br{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Ie.normalizeId)(r==null?void 0:r[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}we.SchemaEnv=Br;function ji(e){const t=yd.call(this,e);if(t)return t;const n=(0,Ie.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ae.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:sw.default,code:(0,Ae._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:ft.default.data,parentData:ft.default.parentData,parentDataProperty:ft.default.parentDataProperty,dataNames:[ft.default.data],dataPathArr:[Ae.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ae.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ae.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ae._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,iw.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const f=i.toString();l=`${i.scopeRefs(ft.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const p=new Function(`${ft.default.self}`,`${ft.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){const{props:h,items:d}=u;p.evaluated={props:h instanceof Ae.Name?void 0:h,items:d instanceof Ae.Name?void 0:d,dynamicProps:h instanceof Ae.Name,dynamicItems:d instanceof Ae.Name},p.source&&(p.source.evaluated=(0,Ae.stringify)(p.evaluated))}return e.validate=p,e}catch(f){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),f}finally{this._compilations.delete(e)}}we.compileSchema=ji;function aw(e,t,n){var r;n=(0,Ie.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=lw.call(this,e,n);if(s===void 0){const i=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Br({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=cw.call(this,s)}we.resolveRef=aw;function cw(e){return(0,Ie.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ji.call(this,e)}function yd(e){for(const t of this._compilations)if(uw(t,e))return t}we.getCompilingSchema=yd;function uw(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function lw(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Fr.call(this,e,t)}function Fr(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Ie._getFullPath)(this.opts.uriResolver,n);let o=(0,Ie.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return No.call(this,n,e);const s=(0,Ie.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Fr.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:No.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||ji.call(this,i),s===(0,Ie.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Ie.resolveUrl)(this.opts.uriResolver,o,u)),new Br({schema:a,schemaId:c,root:e,baseId:o})}return No.call(this,n,i)}}we.resolveSchema=Fr;const fw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function No(e,{baseId:t,schema:n,root:r}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,Yc.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!fw.has(a)&&u&&(t=(0,Ie.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Yc.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Ie.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Fr.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Br({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}const dw="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",pw="Meta-schema for $data reference (JSON AnySchema extension proposal)",hw="object",mw=["$data"],gw={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},yw=!1,$w={$id:dw,description:pw,type:hw,required:mw,properties:gw,additionalProperties:yw};var Ii={},qr={exports:{}};const vw=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),$d=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),xi=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),vd=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),ww=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function wd(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const bw=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Qc(e){return e.length=0,!0}function Ew(e,t,n){if(e.length){const r=wd(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function Sw(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=Ew;for(let c=0;c<e.length;c++){const u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++t>7){n.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=Qc}else{o.push(u);continue}}return o.length&&(a===Qc?n.zone=o.join(""):i?r.push(o.join("")):r.push(wd(o))),n.address=r.join(""),n}function bd(e){if(Ow(e,":")<2)return{host:e,isIPV6:!1};const t=Sw(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,r=t.address;return t.zone&&(n+="%"+t.zone,r+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:r}}}function Ow(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function Nw(e){let t=e;const n=[];let r=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(o===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")}const _w={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},kw=/[@/?#:]/g,Aw=/[@/?#]/g;function Ed(e,t){const n=t?Aw:kw;return n.lastIndex=0,e.replace(n,r=>_w[r])}function jw(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){const o=e.slice(r+1,r+3);if(xi(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&vd(i)?n+=i:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function Iw(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(xi(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&vd(s)?t+=s:t+="%"+o,n+=2;continue}}ww(e[n])?t+=e[n]:t+=escape(e[n])}return t}function xw(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(xi(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function Pw(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!$d(n)){const r=bd(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Ed(n,!1)}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}var Sd={nonSimpleDomain:bw,recomposeAuthority:Pw,reescapeHostDelimiters:Ed,normalizePercentEncoding:jw,normalizePathEncoding:Iw,escapePreservingEscapes:xw,removeDotSegments:Nw,isIPv4:$d,isUUID:vw,normalizeIPv6:bd};const{isUUID:Tw}=Sd,Cw=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function Od(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Nd(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function _d(e){const t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function Rw(e){return e.secure=Od(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Mw(e){if((e.port===(Od(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function Dw(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(Cw);if(n){const r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const o=`${r}:${t.nid||e.nid}`,s=Pi(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Lw(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),o=`${n}:${t.nid||r}`,s=Pi(o);s&&(e=s.serialize(e,t));const i=e,a=e.nss;return i.path=`${r||t.nid}:${a}`,t.skipEscape=!0,i}function Uw(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!Tw(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Bw(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const kd={scheme:"http",domainHost:!0,parse:Nd,serialize:_d},Fw={scheme:"https",domainHost:kd.domainHost,parse:Nd,serialize:_d},fr={scheme:"ws",domainHost:!0,parse:Rw,serialize:Mw},qw={scheme:"wss",domainHost:fr.domainHost,parse:fr.parse,serialize:fr.serialize},Vw={scheme:"urn",parse:Dw,serialize:Lw,skipNormalize:!0},Kw={scheme:"urn:uuid",parse:Uw,serialize:Bw,skipNormalize:!0},br={http:kd,https:Fw,ws:fr,wss:qw,urn:Vw,"urn:uuid":Kw};Object.setPrototypeOf(br,null);function Pi(e){return e&&(br[e]||br[e.toLowerCase()])||void 0}var Gw={SCHEMES:br,getSchemeHandler:Pi};const{normalizeIPv6:zw,removeDotSegments:pn,recomposeAuthority:Jw,normalizePercentEncoding:Hw,normalizePathEncoding:Ww,escapePreservingEscapes:Yw,reescapeHostDelimiters:Qw,isIPv4:Zw,nonSimpleDomain:Xw}=Sd,{SCHEMES:eb,getSchemeHandler:Ad}=Gw;function tb(e,t){return typeof e=="string"?e=ab(e,t):typeof e=="object"&&(e=Zt(It(e,t),t)),e}function nb(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=jd(Zt(e,r),Zt(t,r),r,!0);return r.skipEscape=!0,It(o,r)}function jd(e,t,n,r){const o={};return r||(e=Zt(It(e,n),n),t=Zt(It(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=pn(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=pn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=pn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=pn(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function rb(e,t,n){const r=Zc(e,n),o=Zc(t,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function It(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},r=Object.assign({},t),o=[],s=Ad(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=Hw(n.path):(n.path=Yw(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=Jw(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=pn(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 ob=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,sb=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function ib(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Id(e,t){const n=Object.assign({},t),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?e=n.scheme+":"+e:e="//"+e);const i=e.match(sb);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);const a=e.match(ob);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=ib(r,a);if(c!==void 0&&(r.error=r.error||c,o=!0),r.host)if(Zw(r.host)===!1){const l=zw(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=Ad(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&s===!1&&Xw(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)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=Qw(unescape(r.host),s))),r.path&&(r.path=Ww(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 Zt(e,t){return Id(e,t).parsed}function ab(e,t){return xd(e,t).normalized}function xd(e,t){const{parsed:n,malformedAuthorityOrPort:r}=Id(e,t);return{normalized:r?e:It(n,t),malformedAuthorityOrPort:r}}function Zc(e,t){if(typeof e=="string"){const{normalized:n,malformedAuthorityOrPort:r}=xd(e,t);return r?void 0:n}if(typeof e=="object")return It(e,t)}const Ti={SCHEMES:eb,normalize:tb,resolve:nb,resolveComponent:jd,equal:rb,serialize:It,parse:Zt};qr.exports=Ti;qr.exports.default=Ti;qr.exports.fastUri=Ti;var cb=qr.exports;Object.defineProperty(Ii,"__esModule",{value:!0});const Pd=cb;Pd.code='require("ajv/dist/runtime/uri").default';Ii.default=Pd;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Pe;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=G;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=Un,o=tn,s=jt,i=we,a=G,c=ue,u=se,l=P,f=$w,p=Ii,h=(x,S)=>new RegExp(x,S);h.code="new RegExp";const d=["removeAdditional","useDefaults","coerceTypes"],g=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={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."},$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function E(x){var S,A,N,m,w,_,M,D,W,H,ae,Pt,Zr,Xr,eo,to,no,ro,oo,so,io,ao,co,uo,lo;const sn=x.strict,fo=(S=x.code)===null||S===void 0?void 0:S.optimize,Ga=fo===!0||fo===void 0?1:fo||0,za=(N=(A=x.code)===null||A===void 0?void 0:A.regExp)!==null&&N!==void 0?N:h,Wh=(m=x.uriResolver)!==null&&m!==void 0?m:p.default;return{strictSchema:(_=(w=x.strictSchema)!==null&&w!==void 0?w:sn)!==null&&_!==void 0?_:!0,strictNumbers:(D=(M=x.strictNumbers)!==null&&M!==void 0?M:sn)!==null&&D!==void 0?D:!0,strictTypes:(H=(W=x.strictTypes)!==null&&W!==void 0?W:sn)!==null&&H!==void 0?H:"log",strictTuples:(Pt=(ae=x.strictTuples)!==null&&ae!==void 0?ae:sn)!==null&&Pt!==void 0?Pt:"log",strictRequired:(Xr=(Zr=x.strictRequired)!==null&&Zr!==void 0?Zr:sn)!==null&&Xr!==void 0?Xr:!1,code:x.code?{...x.code,optimize:Ga,regExp:za}:{optimize:Ga,regExp:za},loopRequired:(eo=x.loopRequired)!==null&&eo!==void 0?eo:v,loopEnum:(to=x.loopEnum)!==null&&to!==void 0?to:v,meta:(no=x.meta)!==null&&no!==void 0?no:!0,messages:(ro=x.messages)!==null&&ro!==void 0?ro:!0,inlineRefs:(oo=x.inlineRefs)!==null&&oo!==void 0?oo:!0,schemaId:(so=x.schemaId)!==null&&so!==void 0?so:"$id",addUsedSchema:(io=x.addUsedSchema)!==null&&io!==void 0?io:!0,validateSchema:(ao=x.validateSchema)!==null&&ao!==void 0?ao:!0,validateFormats:(co=x.validateFormats)!==null&&co!==void 0?co:!0,unicodeRegExp:(uo=x.unicodeRegExp)!==null&&uo!==void 0?uo:!0,int32range:(lo=x.int32range)!==null&&lo!==void 0?lo:!0,uriResolver:Wh}}class b{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,...E(S)};const{es5:A,lines:N}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:g,es5:A,lines:N}),this.logger=Z(S.logger);const m=S.validateFormats;S.validateFormats=!1,this.RULES=(0,s.getRules)(),O.call(this,y,S,"NOT SUPPORTED"),O.call(this,$,S,"DEPRECATED","warn"),this._metaOpts=q.call(this),S.formats&&z.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&U.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),C.call(this),S.validateFormats=m}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:A,schemaId:N}=this.opts;let m=f;N==="id"&&(m={...f},m.id=m.$id,delete m.$id),A&&S&&this.addMetaSchema(m,m[N],!1)}defaultMeta(){const{meta:S,schemaId:A}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[A]||S:void 0}validate(S,A){let N;if(typeof S=="string"){if(N=this.getSchema(S),!N)throw new Error(`no schema with key or ref "${S}"`)}else N=this.compile(S);const m=N(A);return"$async"in N||(this.errors=N.errors),m}compile(S,A){const N=this._addSchema(S,A);return N.validate||this._compileSchemaEnv(N)}compileAsync(S,A){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:N}=this.opts;return m.call(this,S,A);async function m(H,ae){await w.call(this,H.$schema);const Pt=this._addSchema(H,ae);return Pt.validate||_.call(this,Pt)}async function w(H){H&&!this.getSchema(H)&&await m.call(this,{$ref:H},!0)}async function _(H){try{return this._compileSchemaEnv(H)}catch(ae){if(!(ae instanceof o.default))throw ae;return M.call(this,ae),await D.call(this,ae.missingSchema),_.call(this,H)}}function M({missingSchema:H,missingRef:ae}){if(this.refs[H])throw new Error(`AnySchema ${H} is loaded but ${ae} cannot be resolved`)}async function D(H){const ae=await W.call(this,H);this.refs[H]||await w.call(this,ae.$schema),this.refs[H]||this.addSchema(ae,H,A)}async function W(H){const ae=this._loading[H];if(ae)return ae;try{return await(this._loading[H]=N(H))}finally{delete this._loading[H]}}}addSchema(S,A,N,m=this.opts.validateSchema){if(Array.isArray(S)){for(const _ of S)this.addSchema(_,void 0,N,m);return this}let w;if(typeof S=="object"){const{schemaId:_}=this.opts;if(w=S[_],w!==void 0&&typeof w!="string")throw new Error(`schema ${_} must be string`)}return A=(0,c.normalizeId)(A||w),this._checkUnique(A),this.schemas[A]=this._addSchema(S,N,A,m,!0),this}addMetaSchema(S,A,N=this.opts.validateSchema){return this.addSchema(S,A,!0,N),this}validateSchema(S,A){if(typeof S=="boolean")return!0;let N;if(N=S.$schema,N!==void 0&&typeof N!="string")throw new Error("$schema must be a string");if(N=N||this.opts.defaultMeta||this.defaultMeta(),!N)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const m=this.validate(N,S);if(!m&&A){const w="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(w);else throw new Error(w)}return m}getSchema(S){let A;for(;typeof(A=j.call(this,S))=="string";)S=A;if(A===void 0){const{schemaId:N}=this.opts,m=new i.SchemaEnv({schema:{},schemaId:N});if(A=i.resolveSchema.call(this,m,S),!A)return;this.refs[S]=A}return A.validate||this._compileSchemaEnv(A)}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 A=j.call(this,S);return typeof A=="object"&&this._cache.delete(A.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const A=S;this._cache.delete(A);let N=S[this.opts.schemaId];return N&&(N=(0,c.normalizeId)(N),delete this.schemas[N],delete this.refs[N]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const A of S)this.addKeyword(A);return this}addKeyword(S,A){let N;if(typeof S=="string")N=S,typeof A=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),A.keyword=N);else if(typeof S=="object"&&A===void 0){if(A=S,N=A.keyword,Array.isArray(N)&&!N.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Ne.call(this,N,A),!A)return(0,l.eachItem)(N,w=>Fe.call(this,w)),this;on.call(this,A);const m={...A,type:(0,u.getJSONTypes)(A.type),schemaType:(0,u.getJSONTypes)(A.schemaType)};return(0,l.eachItem)(N,m.type.length===0?w=>Fe.call(this,w,m):w=>m.type.forEach(_=>Fe.call(this,w,m,_))),this}getKeyword(S){const A=this.RULES.all[S];return typeof A=="object"?A.definition:!!A}removeKeyword(S){const{RULES:A}=this;delete A.keywords[S],delete A.all[S];for(const N of A.rules){const m=N.rules.findIndex(w=>w.keyword===S);m>=0&&N.rules.splice(m,1)}return this}addFormat(S,A){return typeof A=="string"&&(A=new RegExp(A)),this.formats[S]=A,this}errorsText(S=this.errors,{separator:A=", ",dataVar:N="data"}={}){return!S||S.length===0?"No errors":S.map(m=>`${N}${m.instancePath} ${m.message}`).reduce((m,w)=>m+A+w)}$dataMetaSchema(S,A){const N=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const m of A){const w=m.split("/").slice(1);let _=S;for(const M of w)_=_[M];for(const M in N){const D=N[M];if(typeof D!="object")continue;const{$data:W}=D.definition,H=_[M];W&&H&&(_[M]=Fn(H))}}return S}_removeAllSchemas(S,A){for(const N in S){const m=S[N];(!A||A.test(N))&&(typeof m=="string"?delete S[N]:m&&!m.meta&&(this._cache.delete(m.schema),delete S[N]))}}_addSchema(S,A,N,m=this.opts.validateSchema,w=this.opts.addUsedSchema){let _;const{schemaId:M}=this.opts;if(typeof S=="object")_=S[M];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 D=this._cache.get(S);if(D!==void 0)return D;N=(0,c.normalizeId)(_||N);const W=c.getSchemaRefs.call(this,S,N);return D=new i.SchemaEnv({schema:S,schemaId:M,meta:A,baseId:N,localRefs:W}),this._cache.set(D.schema,D),w&&!N.startsWith("#")&&(N&&this._checkUnique(N),this.refs[N]=D),m&&this.validateSchema(S,!0),D}_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 A=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,S)}finally{this.opts=A}}}b.ValidationError=r.default,b.MissingRefError=o.default,e.default=b;function O(x,S,A,N="error"){for(const m in x){const w=m;w in S&&this.logger[N](`${A}: option ${m}. ${x[w]}`)}}function j(x){return x=(0,c.normalizeId)(x),this.schemas[x]||this.refs[x]}function C(){const x=this.opts.schemas;if(x)if(Array.isArray(x))this.addSchema(x);else for(const S in x)this.addSchema(x[S],S)}function z(){for(const x in this.opts.formats){const S=this.opts.formats[x];S&&this.addFormat(x,S)}}function U(x){if(Array.isArray(x)){this.addVocabulary(x);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in x){const A=x[S];A.keyword||(A.keyword=S),this.addKeyword(A)}}function q(){const x={...this.opts};for(const S of d)delete x[S];return x}const Q={log(){},warn(){},error(){}};function Z(x){if(x===!1)return Q;if(x===void 0)return console;if(x.log&&x.warn&&x.error)return x;throw new Error("logger must implement log, warn and error methods")}const me=/^[a-z_$][a-z0-9_$:-]*$/i;function Ne(x,S){const{RULES:A}=this;if((0,l.eachItem)(x,N=>{if(A.keywords[N])throw new Error(`Keyword ${N} is already defined`);if(!me.test(N))throw new Error(`Keyword ${N} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function Fe(x,S,A){var N;const m=S==null?void 0:S.post;if(A&&m)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:w}=this;let _=m?w.post:w.rules.find(({type:D})=>D===A);if(_||(_={type:A,rules:[]},w.rules.push(_)),w.keywords[x]=!0,!S)return;const M={keyword:x,definition:{...S,type:(0,u.getJSONTypes)(S.type),schemaType:(0,u.getJSONTypes)(S.schemaType)}};S.before?de.call(this,_,M,S.before):_.rules.push(M),w.all[x]=M,(N=S.implements)===null||N===void 0||N.forEach(D=>this.addKeyword(D))}function de(x,S,A){const N=x.rules.findIndex(m=>m.keyword===A);N>=0?x.rules.splice(N,0,S):(x.rules.push(S),this.logger.warn(`rule ${A} is not defined`))}function on(x){let{metaSchema:S}=x;S!==void 0&&(x.$data&&this.opts.$data&&(S=Fn(S)),x.validateSchema=this.compile(S,!0))}const Qr={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Fn(x){return{anyOf:[x,Qr]}}})(Uf);var Ci={},Ri={},Mi={};Object.defineProperty(Mi,"__esModule",{value:!0});const ub={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Mi.default=ub;var xt={};Object.defineProperty(xt,"__esModule",{value:!0});xt.callRef=xt.getValidate=void 0;const lb=tn,Xc=K,ye=G,Rt=Be,eu=we,Yn=P,fb={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return f();const l=eu.resolveRef.call(c,u,o,n);if(l===void 0)throw new lb.default(r.opts.uriResolver,o,n);if(l instanceof eu.SchemaEnv)return p(l);return h(l);function f(){if(s===u)return dr(e,i,s,s.$async);const d=t.scopeValue("root",{ref:u});return dr(e,(0,ye._)`${d}.validate`,u,u.$async)}function p(d){const g=Td(e,d);dr(e,g,d,d.$async)}function h(d){const g=t.scopeValue("schema",a.code.source===!0?{ref:d,code:(0,ye.stringify)(d)}:{ref:d}),y=t.name("valid"),$=e.subschema({schema:d,dataTypes:[],schemaPath:ye.nil,topSchemaRef:g,errSchemaPath:n},y);e.mergeEvaluated($),e.ok(y)}}};function Td(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,ye._)`${n.scopeValue("wrapper",{ref:t})}.validate`}xt.getValidate=Td;function dr(e,t,n,r){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Rt.default.this:ye.nil;r?l():f();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const d=o.let("valid");o.try(()=>{o.code((0,ye._)`await ${(0,Xc.callValidateCode)(e,t,u)}`),h(t),i||o.assign(d,!0)},g=>{o.if((0,ye._)`!(${g} instanceof ${s.ValidationError})`,()=>o.throw(g)),p(g),i||o.assign(d,!1)}),e.ok(d)}function f(){e.result((0,Xc.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(d){const g=(0,ye._)`${d}.errors`;o.assign(Rt.default.vErrors,(0,ye._)`${Rt.default.vErrors} === null ? ${g} : ${Rt.default.vErrors}.concat(${g})`),o.assign(Rt.default.errors,(0,ye._)`${Rt.default.vErrors}.length`)}function h(d){var g;if(!s.opts.unevaluated)return;const y=(g=n==null?void 0:n.validate)===null||g===void 0?void 0:g.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Yn.mergeEvaluated.props(o,y.props,s.props));else{const $=o.var("props",(0,ye._)`${d}.evaluated.props`);s.props=Yn.mergeEvaluated.props(o,$,s.props,ye.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Yn.mergeEvaluated.items(o,y.items,s.items));else{const $=o.var("items",(0,ye._)`${d}.evaluated.items`);s.items=Yn.mergeEvaluated.items(o,$,s.items,ye.Name)}}}xt.callRef=dr;xt.default=fb;Object.defineProperty(Ri,"__esModule",{value:!0});const db=Mi,pb=xt,hb=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",db.default,pb.default];Ri.default=hb;var Di={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});const Er=G,et=Er.operators,Sr={maximum:{okStr:"<=",ok:et.LTE,fail:et.GT},minimum:{okStr:">=",ok:et.GTE,fail:et.LT},exclusiveMaximum:{okStr:"<",ok:et.LT,fail:et.GTE},exclusiveMinimum:{okStr:">",ok:et.GT,fail:et.LTE}},mb={message:({keyword:e,schemaCode:t})=>(0,Er.str)`must be ${Sr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Er._)`{comparison: ${Sr[e].okStr}, limit: ${t}}`},gb={keyword:Object.keys(Sr),type:"number",schemaType:"number",$data:!0,error:mb,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,Er._)`${n} ${Sr[t].fail} ${r} || isNaN(${n})`)}};Li.default=gb;var Ui={};Object.defineProperty(Ui,"__esModule",{value:!0});const vn=G,yb={message:({schemaCode:e})=>(0,vn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,vn._)`{multipleOf: ${e}}`},$b={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:yb,code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,vn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,vn._)`${i} !== parseInt(${i})`;e.fail$data((0,vn._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Ui.default=$b;var Bi={},Fi={};Object.defineProperty(Fi,"__esModule",{value:!0});function Cd(e){const t=e.length;let n=0,r=0,o;for(;r<t;)n++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<t&&(o=e.charCodeAt(r),(o&64512)===56320&&r++);return n}Fi.default=Cd;Cd.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(Bi,"__esModule",{value:!0});const $t=G,vb=P,wb=Fi,bb={message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,$t.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,$t._)`{limit: ${e}}`},Eb={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:bb,code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?$t.operators.GT:$t.operators.LT,i=o.opts.unicode===!1?(0,$t._)`${n}.length`:(0,$t._)`${(0,vb.useFunc)(e.gen,wb.default)}(${n})`;e.fail$data((0,$t._)`${i} ${s} ${r}`)}};Bi.default=Eb;var qi={};Object.defineProperty(qi,"__esModule",{value:!0});const Sb=K,Ob=P,zt=G,Nb={message:({schemaCode:e})=>(0,zt.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,zt._)`{pattern: ${e}}`},_b={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Nb,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,zt._)`new RegExp`:(0,Ob.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,zt._)`${u}(${s}, ${a}).test(${n})`),()=>t.assign(l,!1)),e.fail$data((0,zt._)`!${l}`)}else{const c=(0,Sb.usePattern)(e,o);e.fail$data((0,zt._)`!${c}.test(${n})`)}}};qi.default=_b;var Vi={};Object.defineProperty(Vi,"__esModule",{value:!0});const wn=G,kb={message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,wn.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,wn._)`{limit: ${e}}`},Ab={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:kb,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?wn.operators.GT:wn.operators.LT;e.fail$data((0,wn._)`Object.keys(${n}).length ${o} ${r}`)}};Vi.default=Ab;var Ki={};Object.defineProperty(Ki,"__esModule",{value:!0});const cn=K,bn=G,jb=P,Ib={message:({params:{missingProperty:e}})=>(0,bn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,bn._)`{missingProperty: ${e}}`},xb={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Ib,code(e){const{gen:t,schema:n,schemaCode:r,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const h=e.parentSchema.properties,{definedProperties:d}=e.it;for(const g of n)if((h==null?void 0:h[g])===void 0&&!d.has(g)){const y=i.schemaEnv.baseId+i.errSchemaPath,$=`required property "${g}" is not defined at "${y}" (strictRequired)`;(0,jb.checkStrictMode)(i,$,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(bn.nil,f);else for(const h of n)(0,cn.checkReportMissingProp)(e,h)}function l(){const h=t.let("missing");if(c||s){const d=t.let("valid",!0);e.block$data(d,()=>p(h,d)),e.ok(d)}else t.if((0,cn.checkMissingProp)(e,n,h)),(0,cn.reportMissingProp)(e,h),t.else()}function f(){t.forOf("prop",r,h=>{e.setParams({missingProperty:h}),t.if((0,cn.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,d){e.setParams({missingProperty:h}),t.forOf(h,r,()=>{t.assign(d,(0,cn.propertyInData)(t,o,h,a.ownProperties)),t.if((0,bn.not)(d),()=>{e.error(),t.break()})},bn.nil)}}};Ki.default=xb;var Gi={};Object.defineProperty(Gi,"__esModule",{value:!0});const En=G,Pb={message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,En.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,En._)`{limit: ${e}}`},Tb={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Pb,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?En.operators.GT:En.operators.LT;e.fail$data((0,En._)`${n}.length ${o} ${r}`)}};Gi.default=Tb;var zi={},Bn={};Object.defineProperty(Bn,"__esModule",{value:!0});const Rd=td;Rd.code='require("ajv/dist/runtime/equal").default';Bn.default=Rd;Object.defineProperty(zi,"__esModule",{value:!0});const _o=se,ce=G,Cb=P,Rb=Bn,Mb={message:({params:{i:e,j:t}})=>(0,ce.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,ce._)`{i: ${e}, j: ${t}}`},Db={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Mb,code(e){const{gen:t,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!r&&!o)return;const c=t.let("valid"),u=s.items?(0,_o.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,ce._)`${i} === false`),e.ok(c);function l(){const d=t.let("i",(0,ce._)`${n}.length`),g=t.let("j");e.setParams({i:d,j:g}),t.assign(c,!0),t.if((0,ce._)`${d} > 1`,()=>(f()?p:h)(d,g))}function f(){return u.length>0&&!u.some(d=>d==="object"||d==="array")}function p(d,g){const y=t.name("item"),$=(0,_o.checkDataTypes)(u,y,a.opts.strictNumbers,_o.DataType.Wrong),v=t.const("indices",(0,ce._)`{}`);t.for((0,ce._)`;${d}--;`,()=>{t.let(y,(0,ce._)`${n}[${d}]`),t.if($,(0,ce._)`continue`),u.length>1&&t.if((0,ce._)`typeof ${y} == "string"`,(0,ce._)`${y} += "_"`),t.if((0,ce._)`typeof ${v}[${y}] == "number"`,()=>{t.assign(g,(0,ce._)`${v}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,ce._)`${v}[${y}] = ${d}`)})}function h(d,g){const y=(0,Cb.useFunc)(t,Rb.default),$=t.name("outer");t.label($).for((0,ce._)`;${d}--;`,()=>t.for((0,ce._)`${g} = ${d}; ${g}--;`,()=>t.if((0,ce._)`${y}(${n}[${d}], ${n}[${g}])`,()=>{e.error(),t.assign(c,!1).break($)})))}}};zi.default=Db;var Ji={};Object.defineProperty(Ji,"__esModule",{value:!0});const gs=G,Lb=P,Ub=Bn,Bb={message:"must be equal to constant",params:({schemaCode:e})=>(0,gs._)`{allowedValue: ${e}}`},Fb={keyword:"const",$data:!0,error:Bb,code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,gs._)`!${(0,Lb.useFunc)(t,Ub.default)}(${n}, ${o})`):e.fail((0,gs._)`${s} !== ${n}`)}};Ji.default=Fb;var Hi={};Object.defineProperty(Hi,"__esModule",{value:!0});const hn=G,qb=P,Vb=Bn,Kb={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,hn._)`{allowedValues: ${e}}`},Gb={keyword:"enum",schemaType:"array",$data:!0,error:Kb,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e;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,qb.useFunc)(t,Vb.default));let l;if(a||r)l=t.let("valid"),e.block$data(l,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const h=t.const("vSchema",s);l=(0,hn.or)(...o.map((d,g)=>p(h,g)))}e.pass(l);function f(){t.assign(l,!1),t.forOf("v",s,h=>t.if((0,hn._)`${u()}(${n}, ${h})`,()=>t.assign(l,!0).break()))}function p(h,d){const g=o[d];return typeof g=="object"&&g!==null?(0,hn._)`${u()}(${n}, ${h}[${d}])`:(0,hn._)`${n} === ${g}`}}};Hi.default=Gb;Object.defineProperty(Di,"__esModule",{value:!0});const zb=Li,Jb=Ui,Hb=Bi,Wb=qi,Yb=Vi,Qb=Ki,Zb=Gi,Xb=zi,eE=Ji,tE=Hi,nE=[zb.default,Jb.default,Hb.default,Wb.default,Yb.default,Qb.default,Zb.default,Xb.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},eE.default,tE.default];Di.default=nE;var Wi={},nn={};Object.defineProperty(nn,"__esModule",{value:!0});nn.validateAdditionalItems=void 0;const vt=G,ys=P,rE={message:({params:{len:e}})=>(0,vt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,vt._)`{limit: ${e}}`},oE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:rE,code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,ys.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Md(e,r)}};function Md(e,t){const{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;const a=n.const("len",(0,vt._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,vt._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,ys.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,vt._)`${a} <= ${t.length}`);n.if((0,vt.not)(u),()=>c(u)),e.ok(u)}function c(u){n.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:ys.Type.Num},u),i.allErrors||n.if((0,vt.not)(u),()=>n.break())})}}nn.validateAdditionalItems=Md;nn.default=oE;var Yi={},rn={};Object.defineProperty(rn,"__esModule",{value:!0});rn.validateTuple=void 0;const tu=G,pr=P,sE=K,iE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return Dd(e,"additionalItems",t);n.items=!0,!(0,pr.alwaysValidSchema)(n,t)&&e.ok((0,sE.validateArray)(e))}};function Dd(e,t,n=e.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=e;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=pr.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,tu._)`${s}.length`);n.forEach((f,p)=>{(0,pr.alwaysValidSchema)(a,f)||(r.if((0,tu._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function l(f){const{opts:p,errSchemaPath:h}=a,d=n.length,g=d===f.minItems&&(d===f.maxItems||f[t]===!1);if(p.strictTuples&&!g){const y=`"${i}" is ${d}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,pr.checkStrictMode)(a,y,p.strictTuples)}}}rn.validateTuple=Dd;rn.default=iE;Object.defineProperty(Yi,"__esModule",{value:!0});const aE=rn,cE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,aE.validateTuple)(e,"items")};Yi.default=cE;var Qi={};Object.defineProperty(Qi,"__esModule",{value:!0});const nu=G,uE=P,lE=K,fE=nn,dE={message:({params:{len:e}})=>(0,nu.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,nu._)`{limit: ${e}}`},pE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:dE,code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,uE.alwaysValidSchema)(r,t)&&(o?(0,fE.validateAdditionalItems)(e,o):e.ok((0,lE.validateArray)(e)))}};Qi.default=pE;var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0});const _e=G,Qn=P,hE={message:({params:{min:e,max:t}})=>t===void 0?(0,_e.str)`must contain at least ${e} valid item(s)`:(0,_e.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,_e._)`{minContains: ${e}}`:(0,_e._)`{minContains: ${e}, maxContains: ${t}}`},mE={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:hE,code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=t.const("len",(0,_e._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Qn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Qn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Qn.alwaysValidSchema)(s,n)){let g=(0,_e._)`${l} >= ${i}`;a!==void 0&&(g=(0,_e._)`${g} && ${l} <= ${a}`),e.pass(g);return}s.items=!0;const f=t.name("valid");a===void 0&&i===1?h(f,()=>t.if(f,()=>t.break())):i===0?(t.let(f,!0),a!==void 0&&t.if((0,_e._)`${o}.length > 0`,p)):(t.let(f,!1),p()),e.result(f,()=>e.reset());function p(){const g=t.name("_valid"),y=t.let("count",0);h(g,()=>t.if(g,()=>d(y)))}function h(g,y){t.forRange("i",0,l,$=>{e.subschema({keyword:"contains",dataProp:$,dataPropType:Qn.Type.Num,compositeRule:!0},g),y()})}function d(g){t.code((0,_e._)`${g}++`),a===void 0?t.if((0,_e._)`${g} >= ${i}`,()=>t.assign(f,!0).break()):(t.if((0,_e._)`${g} > ${a}`,()=>t.assign(f,!1).break()),i===1?t.assign(f,!0):t.if((0,_e._)`${g} >= ${i}`,()=>t.assign(f,!0)))}}};Zi.default=mE;var Ld={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=G,n=P,r=K;e.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const f=u===1?"property":"properties";return(0,t.str)`must have ${f} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:f}})=>(0,t._)`{property: ${c},
|
|
159
|
+
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,V._)`[${o}]`)}}}function Zv({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,V._)`${t} !== undefined`,()=>e.assign((0,V._)`${t}[${n}]`,r))}function ms(e,t,n,r=Jt.Correct){const o=r===Jt.Correct?V.operators.EQ:V.operators.NEQ;let s;switch(e){case"null":return(0,V._)`${t} ${o} null`;case"array":s=(0,V._)`Array.isArray(${t})`;break;case"object":s=(0,V._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":s=i((0,V._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":s=i();break;default:return(0,V._)`typeof ${t} ${o} ${e}`}return r===Jt.Correct?s:(0,V.not)(s);function i(a=V.nil){return(0,V.and)((0,V._)`typeof ${t} == "number"`,a,n?(0,V._)`isFinite(${t})`:V.nil)}}se.checkDataType=ms;function Ei(e,t,n,r){if(e.length===1)return ms(e[0],t,n,r);let o;const s=(0,Qf.toHash)(e);if(s.array&&s.object){const i=(0,V._)`typeof ${t} != "object"`;o=s.null?i:(0,V._)`!${t} || ${i}`,delete s.null,delete s.array,delete s.object}else o=V.nil;s.number&&delete s.integer;for(const i in s)o=(0,V.and)(o,ms(i,t,n,r));return o}se.checkDataTypes=Ei;const Xv={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e=="string"?(0,V._)`{type: ${e}}`:(0,V._)`{type: ${t}}`};function Si(e){const t=e0(e);(0,Jv.reportError)(t,Xv)}se.reportTypeError=Si;function e0(e){const{gen:t,data:n,schema:r}=e,o=(0,Qf.schemaRefOrVal)(e,r,"type");return{gen:t,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:e}}var Ur={};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.assignDefaults=void 0;const Ct=G,t0=P;function n0(e,t){const{properties:n,items:r}=e.schema;if(t==="object"&&n)for(const o in n)Gc(e,o,n[o].default);else t==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Gc(e,s,o.default))}Ur.assignDefaults=n0;function Gc(e,t,n){const{gen:r,compositeRule:o,data:s,opts:i}=e;if(n===void 0)return;const a=(0,Ct._)`${s}${(0,Ct.getProperty)(t)}`;if(o){(0,t0.checkStrictMode)(e,`default is ignored for: ${a}`);return}let c=(0,Ct._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ct._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Ct._)`${a} = ${(0,Ct.stringify)(n)}`)}var Re={},K={};Object.defineProperty(K,"__esModule",{value:!0});K.validateUnion=K.validateArray=K.usePattern=K.callValidateCode=K.schemaProperties=K.allSchemaProperties=K.noPropertyInData=K.propertyInData=K.isOwnProperty=K.hasPropFunc=K.reportMissingProp=K.checkMissingProp=K.checkReportMissingProp=void 0;const ee=G,Oi=P,Xe=Be,r0=P;function o0(e,t){const{gen:n,data:r,it:o}=e;n.if(_i(n,r,t,o.opts.ownProperties),()=>{e.setParams({missingProperty:(0,ee._)`${t}`},!0),e.error()})}K.checkReportMissingProp=o0;function s0({gen:e,data:t,it:{opts:n}},r,o){return(0,ee.or)(...r.map(s=>(0,ee.and)(_i(e,t,s,n.ownProperties),(0,ee._)`${o} = ${s}`)))}K.checkMissingProp=s0;function i0(e,t){e.setParams({missingProperty:t},!0),e.error()}K.reportMissingProp=i0;function ed(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ee._)`Object.prototype.hasOwnProperty`})}K.hasPropFunc=ed;function Ni(e,t,n){return(0,ee._)`${ed(e)}.call(${t}, ${n})`}K.isOwnProperty=Ni;function a0(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} !== undefined`;return r?(0,ee._)`${o} && ${Ni(e,t,n)}`:o}K.propertyInData=a0;function _i(e,t,n,r){const o=(0,ee._)`${t}${(0,ee.getProperty)(n)} === undefined`;return r?(0,ee.or)(o,(0,ee.not)(Ni(e,t,n))):o}K.noPropertyInData=_i;function td(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}K.allSchemaProperties=td;function c0(e,t){return td(t).filter(n=>!(0,Oi.alwaysValidSchema)(e,t[n]))}K.schemaProperties=c0;function u0({schemaCode:e,data:t,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){const l=u?(0,ee._)`${e}, ${t}, ${r}${o}`:t,f=[[Xe.default.instancePath,(0,ee.strConcat)(Xe.default.instancePath,s)],[Xe.default.parentData,i.parentData],[Xe.default.parentDataProperty,i.parentDataProperty],[Xe.default.rootData,Xe.default.rootData]];i.opts.dynamicRef&&f.push([Xe.default.dynamicAnchors,Xe.default.dynamicAnchors]);const p=(0,ee._)`${l}, ${n.object(...f)}`;return c!==ee.nil?(0,ee._)`${a}.call(${c}, ${p})`:(0,ee._)`${a}(${p})`}K.callValidateCode=u0;const l0=(0,ee._)`new RegExp`;function f0({gen:e,it:{opts:t}},n){const r=t.unicodeRegExp?"u":"",{regExp:o}=t.code,s=o(n,r);return e.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,ee._)`${o.code==="new RegExp"?l0:(0,r0.useFunc)(e,o)}(${n}, ${r})`})}K.usePattern=f0;function d0(e){const{gen:t,data:n,keyword:r,it:o}=e,s=t.name("valid");if(o.allErrors){const a=t.let("valid",!0);return i(()=>t.assign(a,!1)),a}return t.var(s,!0),i(()=>t.break()),s;function i(a){const c=t.const("len",(0,ee._)`${n}.length`);t.forRange("i",0,c,u=>{e.subschema({keyword:r,dataProp:u,dataPropType:Oi.Type.Num},s),t.if((0,ee.not)(s),a)})}}K.validateArray=d0;function p0(e){const{gen:t,schema:n,keyword:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(a=>(0,Oi.alwaysValidSchema)(o,a))&&!o.opts.unevaluated)return;const s=t.let("valid",!1),i=t.name("_valid");t.block(()=>n.forEach((a,c)=>{const u=e.subschema({keyword:r,schemaProp:c,compositeRule:!0},i);t.assign(s,(0,ee._)`${s} || ${i}`),e.mergeValidEvaluated(u,i)||t.if((0,ee.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}K.validateUnion=p0;Object.defineProperty(Re,"__esModule",{value:!0});Re.validateKeywordUsage=Re.validSchemaType=Re.funcKeywordCode=Re.macroKeywordCode=void 0;const ge=G,yt=Be,h0=K,m0=Ln;function g0(e,t){const{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=e,a=t.macro.call(i.self,o,s,i),c=nd(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);const u=n.name("valid");e.subschema({schema:a,schemaPath:ge.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),e.pass(u,()=>e.error(!0))}Re.macroKeywordCode=g0;function y0(e,t){var n;const{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=e;v0(c,t);const u=!a&&t.compile?t.compile.call(c.self,s,i,c):t.validate,l=nd(r,o,u),f=r.let("valid");e.block$data(f,p),e.ok((n=t.valid)!==null&&n!==void 0?n:f);function p(){if(t.errors===!1)m(),t.modifying&&zc(e),y(()=>e.error());else{const $=t.async?h():d();t.modifying&&zc(e),y(()=>$0(e,$))}}function h(){const $=r.let("ruleErrs",null);return r.try(()=>m((0,ge._)`await `),v=>r.assign(f,!1).if((0,ge._)`${v} instanceof ${c.ValidationError}`,()=>r.assign($,(0,ge._)`${v}.errors`),()=>r.throw(v))),$}function d(){const $=(0,ge._)`${l}.errors`;return r.assign($,null),m(ge.nil),$}function m($=t.async?(0,ge._)`await `:ge.nil){const v=c.opts.passContext?yt.default.this:yt.default.self,E=!("compile"in t&&!a||t.schema===!1);r.assign(f,(0,ge._)`${$}${(0,h0.callValidateCode)(e,l,v,E)}`,t.modifying)}function y($){var v;r.if((0,ge.not)((v=t.valid)!==null&&v!==void 0?v:f),$)}}Re.funcKeywordCode=y0;function zc(e){const{gen:t,data:n,it:r}=e;t.if(r.parentData,()=>t.assign(n,(0,ge._)`${r.parentData}[${r.parentDataProperty}]`))}function $0(e,t){const{gen:n}=e;n.if((0,ge._)`Array.isArray(${t})`,()=>{n.assign(yt.default.vErrors,(0,ge._)`${yt.default.vErrors} === null ? ${t} : ${yt.default.vErrors}.concat(${t})`).assign(yt.default.errors,(0,ge._)`${yt.default.vErrors}.length`),(0,m0.extendErrors)(e)},()=>e.error())}function v0({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}function nd(e,t,n){if(n===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,ge.stringify)(n)})}function w0(e,t,n=!1){return!t.length||t.some(r=>r==="array"?Array.isArray(e):r==="object"?e&&typeof e=="object"&&!Array.isArray(e):typeof e==r||n&&typeof e>"u")}Re.validSchemaType=w0;function b0({schema:e,opts:t,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(e,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(e[s])){const a=`keyword "${s}" value is invalid at path "${r}": `+n.errorsText(o.validateSchema.errors);if(t.validateSchema==="log")n.logger.error(a);else throw new Error(a)}}Re.validateKeywordUsage=b0;var it={};Object.defineProperty(it,"__esModule",{value:!0});it.extendSubschemaMode=it.extendSubschemaData=it.getSubschema=void 0;const Ce=G,rd=P;function E0(e,{keyword:t,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(t!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){const a=e.schema[t];return n===void 0?{schema:a,schemaPath:(0,Ce._)`${e.schemaPath}${(0,Ce.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:a[n],schemaPath:(0,Ce._)`${e.schemaPath}${(0,Ce.getProperty)(t)}${(0,Ce.getProperty)(n)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,rd.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')}it.getSubschema=E0;function S0(e,t,{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}=t;if(n!==void 0){const{errorPath:u,dataPathArr:l,opts:f}=t,p=a.let("data",(0,Ce._)`${t.data}${(0,Ce.getProperty)(n)}`,!0);c(p),e.errorPath=(0,Ce.str)`${u}${(0,rd.getErrorPath)(n,r,f.jsPropertySyntax)}`,e.parentDataProperty=(0,Ce._)`${n}`,e.dataPathArr=[...l,e.parentDataProperty]}if(o!==void 0){const u=o instanceof Ce.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(e.propertyName=i)}s&&(e.dataTypes=s);function c(u){e.data=u,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,u]}}it.extendSubschemaData=S0;function O0(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(e.compositeRule=r),o!==void 0&&(e.createErrors=o),s!==void 0&&(e.allErrors=s),e.jtdDiscriminator=t,e.jtdMetadata=n}it.extendSubschemaMode=O0;var ue={},od=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!e(t[o],n[o]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(s=Object.keys(t),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(!e(t[i],n[i]))return!1}return!0}return t!==t&&n!==n},sd={exports:{}},ot=sd.exports=function(e,t,n){typeof t=="function"&&(n=t,t={}),n=t.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};lr(t,r,o,e,"",e)};ot.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ot.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ot.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ot.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 lr(e,t,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){t(r,o,s,i,a,c,u);for(var l in r){var f=r[l];if(Array.isArray(f)){if(l in ot.arrayKeywords)for(var p=0;p<f.length;p++)lr(e,t,n,f[p],o+"/"+l+"/"+p,s,o,l,r,p)}else if(l in ot.propsKeywords){if(f&&typeof f=="object")for(var h in f)lr(e,t,n,f[h],o+"/"+l+"/"+N0(h),s,o,l,r,h)}else(l in ot.keywords||e.allKeys&&!(l in ot.skipKeywords))&&lr(e,t,n,f,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function N0(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var _0=sd.exports;Object.defineProperty(ue,"__esModule",{value:!0});ue.getSchemaRefs=ue.resolveUrl=ue.normalizeId=ue._getFullPath=ue.getFullPath=ue.inlineRef=void 0;const k0=P,A0=od,j0=_0,I0=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function x0(e,t=!0){return typeof e=="boolean"?!0:t===!0?!gs(e):t?id(e)<=t:!1}ue.inlineRef=x0;const P0=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gs(e){for(const t in e){if(P0.has(t))return!0;const n=e[t];if(Array.isArray(n)&&n.some(gs)||typeof n=="object"&&gs(n))return!0}return!1}function id(e){let t=0;for(const n in e)if(n==="$ref"||(t++,!I0.has(n)&&(typeof e[n]=="object"&&(0,k0.eachItem)(e[n],r=>t+=id(r)),t===1/0)))return 1/0;return t}function ad(e,t="",n){n!==!1&&(t=Wt(t));const r=e.parse(t);return cd(e,r)}ue.getFullPath=ad;function cd(e,t){return e.serialize(t).split("#")[0]+"#"}ue._getFullPath=cd;const T0=/#\/?$/;function Wt(e){return e?e.replace(T0,""):""}ue.normalizeId=Wt;function C0(e,t,n){return n=Wt(n),e.resolve(t,n)}ue.resolveUrl=C0;const R0=/^[a-z_][-a-z0-9._]*$/i;function M0(e,t){if(typeof e=="boolean")return{};const{schemaId:n,uriResolver:r}=this.opts,o=Wt(e[n]||t),s={"":o},i=ad(r,o,!1),a={},c=new Set;return j0(e,{allKeys:!0},(f,p,h,d)=>{if(d===void 0)return;const m=i+p;let y=s[d];typeof f[n]=="string"&&(y=$.call(this,f[n])),v.call(this,f.$anchor),v.call(this,f.$dynamicAnchor),s[p]=y;function $(E){const b=this.opts.uriResolver.resolve;if(E=Wt(y?b(y,E):E),c.has(E))throw l(E);c.add(E);let O=this.refs[E];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?u(f,O.schema,E):E!==Wt(m)&&(E[0]==="#"?(u(f,a[E],E),a[E]=f):this.refs[E]=m),E}function v(E){if(typeof E=="string"){if(!R0.test(E))throw new Error(`invalid anchor "${E}"`);$.call(this,`#${E}`)}}}),a;function u(f,p,h){if(p!==void 0&&!A0(f,p))throw l(h)}function l(f){return new Error(`reference "${f}" resolves to more than one schema`)}}ue.getSchemaRefs=M0;Object.defineProperty(Pe,"__esModule",{value:!0});Pe.getData=Pe.KeywordCxt=Pe.validateFunctionCode=void 0;const ud=Qt,Jc=se,ki=ze,wr=se,D0=Ur,$n=Re,So=it,R=G,B=Be,L0=ue,Je=P,an=Ln;function U0(e){if(dd(e)&&(pd(e),fd(e))){q0(e);return}ld(e,()=>(0,ud.topBoolOrEmptySchema)(e))}Pe.validateFunctionCode=U0;function ld({gen:e,validateName:t,schema:n,schemaEnv:r,opts:o},s){o.code.es5?e.func(t,(0,R._)`${B.default.data}, ${B.default.valCxt}`,r.$async,()=>{e.code((0,R._)`"use strict"; ${Wc(n,o)}`),F0(e,o),e.code(s)}):e.func(t,(0,R._)`${B.default.data}, ${B0(o)}`,r.$async,()=>e.code(Wc(n,o)).code(s))}function B0(e){return(0,R._)`{${B.default.instancePath}="", ${B.default.parentData}, ${B.default.parentDataProperty}, ${B.default.rootData}=${B.default.data}${e.dynamicRef?(0,R._)`, ${B.default.dynamicAnchors}={}`:R.nil}}={}`}function F0(e,t){e.if(B.default.valCxt,()=>{e.var(B.default.instancePath,(0,R._)`${B.default.valCxt}.${B.default.instancePath}`),e.var(B.default.parentData,(0,R._)`${B.default.valCxt}.${B.default.parentData}`),e.var(B.default.parentDataProperty,(0,R._)`${B.default.valCxt}.${B.default.parentDataProperty}`),e.var(B.default.rootData,(0,R._)`${B.default.valCxt}.${B.default.rootData}`),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,R._)`${B.default.valCxt}.${B.default.dynamicAnchors}`)},()=>{e.var(B.default.instancePath,(0,R._)`""`),e.var(B.default.parentData,(0,R._)`undefined`),e.var(B.default.parentDataProperty,(0,R._)`undefined`),e.var(B.default.rootData,B.default.data),t.dynamicRef&&e.var(B.default.dynamicAnchors,(0,R._)`{}`)})}function q0(e){const{schema:t,opts:n,gen:r}=e;ld(e,()=>{n.$comment&&t.$comment&&md(e),J0(e),r.let(B.default.vErrors,null),r.let(B.default.errors,0),n.unevaluated&&V0(e),hd(e),Y0(e)})}function V0(e){const{gen:t,validateName:n}=e;e.evaluated=t.const("evaluated",(0,R._)`${n}.evaluated`),t.if((0,R._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,R._)`${e.evaluated}.props`,(0,R._)`undefined`)),t.if((0,R._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,R._)`${e.evaluated}.items`,(0,R._)`undefined`))}function Wc(e,t){const n=typeof e=="object"&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,R._)`/*# sourceURL=${n} */`:R.nil}function K0(e,t){if(dd(e)&&(pd(e),fd(e))){G0(e,t);return}(0,ud.boolOrEmptySchema)(e,t)}function fd({schema:e,self:t}){if(typeof e=="boolean")return!e;for(const n in e)if(t.RULES.all[n])return!0;return!1}function dd(e){return typeof e.schema!="boolean"}function G0(e,t){const{schema:n,gen:r,opts:o}=e;o.$comment&&n.$comment&&md(e),W0(e),H0(e);const s=r.const("_errs",B.default.errors);hd(e,s),r.var(t,(0,R._)`${s} === ${B.default.errors}`)}function pd(e){(0,Je.checkUnknownRules)(e),z0(e)}function hd(e,t){if(e.opts.jtd)return Hc(e,[],!1,t);const n=(0,Jc.getSchemaTypes)(e.schema),r=(0,Jc.coerceAndCheckDataType)(e,n);Hc(e,n,!r,t)}function z0(e){const{schema:t,errSchemaPath:n,opts:r,self:o}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,Je.schemaHasRulesButRef)(t,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function J0(e){const{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Je.checkStrictMode)(e,"default is ignored in the schema root")}function W0(e){const t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,L0.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function H0(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}function md({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:o}){const s=n.$comment;if(o.$comment===!0)e.code((0,R._)`${B.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){const i=(0,R.str)`${r}/$comment`,a=e.scopeValue("root",{ref:t.root});e.code((0,R._)`${B.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function Y0(e){const{gen:t,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=e;n.$async?t.if((0,R._)`${B.default.errors} === 0`,()=>t.return(B.default.data),()=>t.throw((0,R._)`new ${o}(${B.default.vErrors})`)):(t.assign((0,R._)`${r}.errors`,B.default.vErrors),s.unevaluated&&Q0(e),t.return((0,R._)`${B.default.errors} === 0`))}function Q0({gen:e,evaluated:t,props:n,items:r}){n instanceof R.Name&&e.assign((0,R._)`${t}.props`,n),r instanceof R.Name&&e.assign((0,R._)`${t}.items`,r)}function Hc(e,t,n,r){const{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=e,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Je.schemaHasRulesButRef)(s,l))){o.block(()=>$d(e,"$ref",l.all.$ref.definition));return}c.jtd||Z0(e,t),o.block(()=>{for(const p of l.rules)f(p);f(l.post)});function f(p){(0,ki.shouldUseGroup)(s,p)&&(p.type?(o.if((0,wr.checkDataType)(p.type,i,c.strictNumbers)),Yc(e,p),t.length===1&&t[0]===p.type&&n&&(o.else(),(0,wr.reportTypeError)(e)),o.endIf()):Yc(e,p),a||o.if((0,R._)`${B.default.errors} === ${r||0}`))}}function Yc(e,t){const{gen:n,schema:r,opts:{useDefaults:o}}=e;o&&(0,D0.assignDefaults)(e,t.type),n.block(()=>{for(const s of t.rules)(0,ki.shouldUseRule)(r,s)&&$d(e,s.keyword,s.definition,t.type)})}function Z0(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(X0(e,t),e.opts.allowUnionTypes||ew(e,t),tw(e,e.dataTypes))}function X0(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(n=>{gd(e.dataTypes,n)||Ai(e,`type "${n}" not allowed by context "${e.dataTypes.join(",")}"`)}),rw(e,t)}}function ew(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Ai(e,"use allowUnionTypes to allow union type keyword")}function tw(e,t){const n=e.self.RULES.all;for(const r in n){const o=n[r];if(typeof o=="object"&&(0,ki.shouldUseRule)(e.schema,o)){const{type:s}=o.definition;s.length&&!s.some(i=>nw(t,i))&&Ai(e,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function nw(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}function gd(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}function rw(e,t){const n=[];for(const r of e.dataTypes)gd(t,r)?n.push(r):t.includes("integer")&&r==="number"&&n.push("integer");e.dataTypes=n}function Ai(e,t){const n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,Je.checkStrictMode)(e,t,e.opts.strictTypes)}class yd{constructor(t,n,r){if((0,$n.validateKeywordUsage)(t,n,r),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=r,this.data=t.data,this.schema=t.schema[r],this.$data=n.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Je.schemaRefOrVal)(t,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=n,this.$data)this.schemaCode=t.gen.const("vSchema",vd(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,$n.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=t.gen.const("_errs",B.default.errors))}result(t,n,r){this.failResult((0,R.not)(t),n,r)}failResult(t,n,r){this.gen.if(t),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,n){this.failResult((0,R.not)(t),void 0,n)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);const{schemaCode:n}=this;this.fail((0,R._)`${n} !== undefined && (${(0,R.or)(this.invalid$data(),t)})`)}error(t,n,r){if(n){this.setParams(n),this._error(t,r),this.setParams({});return}this._error(t,r)}_error(t,n){(t?an.reportExtraError:an.reportError)(this,this.def.error,n)}$dataError(){(0,an.reportError)(this,this.def.$dataError||an.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,an.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,n){n?Object.assign(this.params,t):this.params=t}block$data(t,n,r=R.nil){this.gen.block(()=>{this.check$data(t,r),n()})}check$data(t=R.nil,n=R.nil){if(!this.$data)return;const{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,R.or)((0,R._)`${o} === undefined`,n)),t!==R.nil&&r.assign(t,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),t!==R.nil&&r.assign(t,!1)),r.else()}invalid$data(){const{gen:t,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,R.or)(i(),a());function i(){if(r.length){if(!(n instanceof R.Name))throw new Error("ajv implementation error");const c=Array.isArray(r)?r:[r];return(0,R._)`${(0,wr.checkDataTypes)(c,n,s.opts.strictNumbers,wr.DataType.Wrong)}`}return R.nil}function a(){if(o.validateSchema){const c=t.scopeValue("validate$data",{ref:o.validateSchema});return(0,R._)`!${c}(${n})`}return R.nil}}subschema(t,n){const r=(0,So.getSubschema)(this.it,t);(0,So.extendSubschemaData)(r,this.it,t),(0,So.extendSubschemaMode)(r,t);const o={...this.it,...r,items:void 0,props:void 0};return K0(o,n),o}mergeEvaluated(t,n){const{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&t.props!==void 0&&(r.props=Je.mergeEvaluated.props(o,t.props,r.props,n)),r.items!==!0&&t.items!==void 0&&(r.items=Je.mergeEvaluated.items(o,t.items,r.items,n)))}mergeValidEvaluated(t,n){const{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(t,R.Name)),!0}}Pe.KeywordCxt=yd;function $d(e,t,n,r){const o=new yd(e,n,t);"code"in n?n.code(o,r):o.$data&&n.validate?(0,$n.funcKeywordCode)(o,n):"macro"in n?(0,$n.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,$n.funcKeywordCode)(o,n)}const ow=/^\/(?:[^~]|~0|~1)*$/,sw=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function vd(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let o,s;if(e==="")return B.default.rootData;if(e[0]==="/"){if(!ow.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);o=e,s=B.default.rootData}else{const u=sw.exec(e);if(!u)throw new Error(`Invalid JSON-pointer: ${e}`);const l=+u[1];if(o=u[2],o==="#"){if(l>=t)throw new Error(c("property/index",l));return r[t-l]}if(l>t)throw new Error(c("data",l));if(s=n[t-l],!o)return s}let i=s;const a=o.split("/");for(const u of a)u&&(s=(0,R._)`${s}${(0,R.getProperty)((0,Je.unescapeJsonPointer)(u))}`,i=(0,R._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${t}`}}Pe.getData=vd;var Un={};Object.defineProperty(Un,"__esModule",{value:!0});let iw=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Un.default=iw;var tn={};Object.defineProperty(tn,"__esModule",{value:!0});const Oo=ue;class aw extends Error{constructor(t,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Oo.resolveUrl)(t,n,r),this.missingSchema=(0,Oo.normalizeId)((0,Oo.getFullPath)(t,this.missingRef))}}tn.default=aw;var we={};Object.defineProperty(we,"__esModule",{value:!0});we.resolveSchema=we.getCompilingSchema=we.resolveRef=we.compileSchema=we.SchemaEnv=void 0;const Ae=G,cw=Un,ft=Be,Ie=ue,Qc=P,uw=Pe;class Br{constructor(t){var n;this.refs={},this.dynamicAnchors={};let r;typeof t.schema=="object"&&(r=t.schema),this.schema=t.schema,this.schemaId=t.schemaId,this.root=t.root||this,this.baseId=(n=t.baseId)!==null&&n!==void 0?n:(0,Ie.normalizeId)(r==null?void 0:r[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=r==null?void 0:r.$async,this.refs={}}}we.SchemaEnv=Br;function ji(e){const t=wd.call(this,e);if(t)return t;const n=(0,Ie.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Ae.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s});let a;e.$async&&(a=i.scopeValue("Error",{ref:cw.default,code:(0,Ae._)`require("ajv/dist/runtime/validation_error").default`}));const c=i.scopeName("validate");e.validateName=c;const u={gen:i,allErrors:this.opts.allErrors,data:ft.default.data,parentData:ft.default.parentData,parentDataProperty:ft.default.parentDataProperty,dataNames:[ft.default.data],dataPathArr:[Ae.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Ae.stringify)(e.schema)}:{ref:e.schema}),validateName:c,ValidationError:a,schema:e.schema,schemaEnv:e,rootId:n,baseId:e.baseId||n,schemaPath:Ae.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Ae._)`""`,opts:this.opts,self:this};let l;try{this._compilations.add(e),(0,uw.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);const f=i.toString();l=`${i.scopeRefs(ft.default.scope)}return ${f}`,this.opts.code.process&&(l=this.opts.code.process(l,e));const p=new Function(`${ft.default.self}`,`${ft.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:p}),p.errors=null,p.schema=e.schema,p.schemaEnv=e,e.$async&&(p.$async=!0),this.opts.code.source===!0&&(p.source={validateName:c,validateCode:f,scopeValues:i._values}),this.opts.unevaluated){const{props:h,items:d}=u;p.evaluated={props:h instanceof Ae.Name?void 0:h,items:d instanceof Ae.Name?void 0:d,dynamicProps:h instanceof Ae.Name,dynamicItems:d instanceof Ae.Name},p.source&&(p.source.evaluated=(0,Ae.stringify)(p.evaluated))}return e.validate=p,e}catch(f){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),f}finally{this._compilations.delete(e)}}we.compileSchema=ji;function lw(e,t,n){var r;n=(0,Ie.resolveUrl)(this.opts.uriResolver,t,n);const o=e.refs[n];if(o)return o;let s=pw.call(this,e,n);if(s===void 0){const i=(r=e.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Br({schema:i,schemaId:a,root:e,baseId:t}))}if(s!==void 0)return e.refs[n]=fw.call(this,s)}we.resolveRef=lw;function fw(e){return(0,Ie.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:ji.call(this,e)}function wd(e){for(const t of this._compilations)if(dw(t,e))return t}we.getCompilingSchema=wd;function dw(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function pw(e,t){let n;for(;typeof(n=this.refs[t])=="string";)t=n;return n||this.schemas[t]||Fr.call(this,e,t)}function Fr(e,t){const n=this.opts.uriResolver.parse(t),r=(0,Ie._getFullPath)(this.opts.uriResolver,n);let o=(0,Ie.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===o)return No.call(this,n,e);const s=(0,Ie.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){const a=Fr.call(this,e,i);return typeof(a==null?void 0:a.schema)!="object"?void 0:No.call(this,n,a)}if(typeof(i==null?void 0:i.schema)=="object"){if(i.validate||ji.call(this,i),s===(0,Ie.normalizeId)(t)){const{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Ie.resolveUrl)(this.opts.uriResolver,o,u)),new Br({schema:a,schemaId:c,root:e,baseId:o})}return No.call(this,n,i)}}we.resolveSchema=Fr;const hw=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function No(e,{baseId:t,schema:n,root:r}){var o;if(((o=e.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(const a of e.fragment.slice(1).split("/")){if(typeof n=="boolean")return;const c=n[(0,Qc.unescapeFragment)(a)];if(c===void 0)return;n=c;const u=typeof n=="object"&&n[this.opts.schemaId];!hw.has(a)&&u&&(t=(0,Ie.resolveUrl)(this.opts.uriResolver,t,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Qc.schemaHasRulesButRef)(n,this.RULES)){const a=(0,Ie.resolveUrl)(this.opts.uriResolver,t,n.$ref);s=Fr.call(this,r,a)}const{schemaId:i}=this.opts;if(s=s||new Br({schema:n,schemaId:i,root:r,baseId:t}),s.schema!==s.root.schema)return s}const mw="https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",gw="Meta-schema for $data reference (JSON AnySchema extension proposal)",yw="object",$w=["$data"],vw={$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},ww=!1,bw={$id:mw,description:gw,type:yw,required:$w,properties:vw,additionalProperties:ww};var Ii={},qr={exports:{}};const Ew=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),bd=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),xi=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Ed=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Sw=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function Sd(e){let t="",n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";t+=e[r]}return t}const Ow=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Zc(e){return e.length=0,!0}function Nw(e,t,n){if(e.length){const r=Sd(e);if(r!=="")t.push(r);else return n.error=!0,!1;e.length=0}return!0}function _w(e){let t=0;const n={error:!1,address:"",zone:""},r=[],o=[];let s=!1,i=!1,a=Nw;for(let c=0;c<e.length;c++){const u=e[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++t>7){n.error=!0;break}c>0&&e[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=Zc}else{o.push(u);continue}}return o.length&&(a===Zc?n.zone=o.join(""):i?r.push(o.join("")):r.push(Sd(o))),n.address=r.join(""),n}function Od(e){if(kw(e,":")<2)return{host:e,isIPV6:!1};const t=_w(e);if(t.error)return{host:e,isIPV6:!1};{let n=t.address,r=t.address;return t.zone&&(n+="%"+t.zone,r+="%25"+t.zone),{host:n,isIPV6:!0,escapedHost:r}}}function kw(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function Aw(e){let t=e;const n=[];let r=-1,o=0;for(;o=t.length;){if(o===1){if(t===".")break;if(t==="/"){n.push("/");break}else{n.push(t);break}}else if(o===2){if(t[0]==="."){if(t[1]===".")break;if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&(t[1]==="."||t[1]==="/")){n.push("/");break}}else if(o===3&&t==="/.."){n.length!==0&&n.pop(),n.push("/");break}if(t[0]==="."){if(t[1]==="."){if(t[2]==="/"){t=t.slice(3);continue}}else if(t[1]==="/"){t=t.slice(2);continue}}else if(t[0]==="/"&&t[1]==="."){if(t[2]==="/"){t=t.slice(2);continue}else if(t[2]==="."&&t[3]==="/"){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf("/",1))===-1){n.push(t);break}else n.push(t.slice(0,r)),t=t.slice(r)}return n.join("")}const jw={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Iw=/[@/?#:]/g,xw=/[@/?#]/g;function Nd(e,t){const n=t?xw:Iw;return n.lastIndex=0,e.replace(n,r=>jw[r])}function Pw(e,t=!1){if(e.indexOf("%")===-1)return e;let n="";for(let r=0;r<e.length;r++){if(e[r]==="%"&&r+2<e.length){const o=e.slice(r+1,r+3);if(xi(o)){const s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));t&&Ed(i)?n+=i:n+="%"+s,r+=2;continue}}n+=e[r]}return n}function Tw(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(xi(r)){const o=r.toUpperCase(),s=String.fromCharCode(parseInt(o,16));s!=="."&&Ed(s)?t+=s:t+="%"+o,n+=2;continue}}Sw(e[n])?t+=e[n]:t+=escape(e[n])}return t}function Cw(e){let t="";for(let n=0;n<e.length;n++){if(e[n]==="%"&&n+2<e.length){const r=e.slice(n+1,n+3);if(xi(r)){t+="%"+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function Rw(e){const t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let n=unescape(e.host);if(!bd(n)){const r=Od(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=Nd(n,!1)}t.push(n)}return(typeof e.port=="number"||typeof e.port=="string")&&(t.push(":"),t.push(String(e.port))),t.length?t.join(""):void 0}var _d={nonSimpleDomain:Ow,recomposeAuthority:Rw,reescapeHostDelimiters:Nd,normalizePercentEncoding:Pw,normalizePathEncoding:Tw,escapePreservingEscapes:Cw,removeDotSegments:Aw,isIPv4:bd,isUUID:Ew,normalizeIPv6:Od};const{isUUID:Mw}=_d,Dw=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;function kd(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}function Ad(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}function jd(e){const t=String(e.scheme).toLowerCase()==="https";return(e.port===(t?443:80)||e.port==="")&&(e.port=void 0),e.path||(e.path="/"),e}function Lw(e){return e.secure=kd(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}function Uw(e){if((e.port===(kd(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){const[t,n]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function Bw(e,t){if(!e.path)return e.error="URN can not be parsed",e;const n=e.path.match(Dw);if(n){const r=t.scheme||e.scheme||"urn";e.nid=n[1].toLowerCase(),e.nss=n[2];const o=`${r}:${t.nid||e.nid}`,s=Pi(o);e.path=void 0,s&&(e=s.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}function Fw(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");const n=t.scheme||e.scheme||"urn",r=e.nid.toLowerCase(),o=`${n}:${t.nid||r}`,s=Pi(o);s&&(e=s.serialize(e,t));const i=e,a=e.nss;return i.path=`${r||t.nid}:${a}`,t.skipEscape=!0,i}function qw(e,t){const n=e;return n.uuid=n.nss,n.nss=void 0,!t.tolerant&&(!n.uuid||!Mw(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function Vw(e){const t=e;return t.nss=(e.uuid||"").toLowerCase(),t}const Id={scheme:"http",domainHost:!0,parse:Ad,serialize:jd},Kw={scheme:"https",domainHost:Id.domainHost,parse:Ad,serialize:jd},fr={scheme:"ws",domainHost:!0,parse:Lw,serialize:Uw},Gw={scheme:"wss",domainHost:fr.domainHost,parse:fr.parse,serialize:fr.serialize},zw={scheme:"urn",parse:Bw,serialize:Fw,skipNormalize:!0},Jw={scheme:"urn:uuid",parse:qw,serialize:Vw,skipNormalize:!0},br={http:Id,https:Kw,ws:fr,wss:Gw,urn:zw,"urn:uuid":Jw};Object.setPrototypeOf(br,null);function Pi(e){return e&&(br[e]||br[e.toLowerCase()])||void 0}var Ww={SCHEMES:br,getSchemeHandler:Pi};const{normalizeIPv6:Hw,removeDotSegments:pn,recomposeAuthority:Yw,normalizePercentEncoding:Qw,normalizePathEncoding:Zw,escapePreservingEscapes:Xw,reescapeHostDelimiters:eb,isIPv4:tb,nonSimpleDomain:nb}=_d,{SCHEMES:rb,getSchemeHandler:xd}=Ww;function ob(e,t){return typeof e=="string"?e=lb(e,t):typeof e=="object"&&(e=Zt(It(e,t),t)),e}function sb(e,t,n){const r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=Pd(Zt(e,r),Zt(t,r),r,!0);return r.skipEscape=!0,It(o,r)}function Pd(e,t,n,r){const o={};return r||(e=Zt(It(e,n),n),t=Zt(It(t,n),n)),n=n||{},!n.tolerant&&t.scheme?(o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=pn(t.path||""),o.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=pn(t.path||""),o.query=t.query):(t.path?(t.path[0]==="/"?o.path=pn(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?o.path="/"+t.path:e.path?o.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:o.path=t.path,o.path=pn(o.path)),o.query=t.query):(o.path=e.path,t.query!==void 0?o.query=t.query:o.query=e.query),o.userinfo=e.userinfo,o.host=e.host,o.port=e.port),o.scheme=e.scheme),o.fragment=t.fragment,o}function ib(e,t,n){const r=Xc(e,n),o=Xc(t,n);return r!==void 0&&o!==void 0&&r.toLowerCase()===o.toLowerCase()}function It(e,t){const n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},r=Object.assign({},t),o=[],s=xd(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=Qw(n.path):(n.path=Xw(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");const i=Yw(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=pn(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 ab=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,cb=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function ub(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof e.port=="number"&&(e.port<0||e.port>65535))return"URI port is malformed."}function Td(e,t){const n=Object.assign({},t),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?e=n.scheme+":"+e:e="//"+e);const i=e.match(cb);i!==null&&i[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);const a=e.match(ab);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=ub(r,a);if(c!==void 0&&(r.error=r.error||c,o=!0),r.host)if(tb(r.host)===!1){const l=Hw(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=xd(n.scheme||r.scheme);if(!n.unicodeSupport&&(!u||!u.unicodeSupport)&&r.host&&(n.domainHost||u&&u.domainHost)&&s===!1&&nb(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)&&(e.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=eb(unescape(r.host),s))),r.path&&(r.path=Zw(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 Zt(e,t){return Td(e,t).parsed}function lb(e,t){return Cd(e,t).normalized}function Cd(e,t){const{parsed:n,malformedAuthorityOrPort:r}=Td(e,t);return{normalized:r?e:It(n,t),malformedAuthorityOrPort:r}}function Xc(e,t){if(typeof e=="string"){const{normalized:n,malformedAuthorityOrPort:r}=Cd(e,t);return r?void 0:n}if(typeof e=="object")return It(e,t)}const Ti={SCHEMES:rb,normalize:ob,resolve:sb,resolveComponent:Pd,equal:ib,serialize:It,parse:Zt};qr.exports=Ti;qr.exports.default=Ti;qr.exports.fastUri=Ti;var fb=qr.exports;Object.defineProperty(Ii,"__esModule",{value:!0});const Rd=fb;Rd.code='require("ajv/dist/runtime/uri").default';Ii.default=Rd;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Pe;Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=G;Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});const r=Un,o=tn,s=jt,i=we,a=G,c=ue,u=se,l=P,f=bw,p=Ii,h=(x,S)=>new RegExp(x,S);h.code="new RegExp";const d=["removeAdditional","useDefaults","coerceTypes"],m=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),y={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."},$={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},v=200;function E(x){var S,A,N,g,w,_,M,D,H,W,ae,Pt,Zr,Xr,eo,to,no,ro,oo,so,io,ao,co,uo,lo;const sn=x.strict,fo=(S=x.code)===null||S===void 0?void 0:S.optimize,za=fo===!0||fo===void 0?1:fo||0,Ja=(N=(A=x.code)===null||A===void 0?void 0:A.regExp)!==null&&N!==void 0?N:h,Zh=(g=x.uriResolver)!==null&&g!==void 0?g:p.default;return{strictSchema:(_=(w=x.strictSchema)!==null&&w!==void 0?w:sn)!==null&&_!==void 0?_:!0,strictNumbers:(D=(M=x.strictNumbers)!==null&&M!==void 0?M:sn)!==null&&D!==void 0?D:!0,strictTypes:(W=(H=x.strictTypes)!==null&&H!==void 0?H:sn)!==null&&W!==void 0?W:"log",strictTuples:(Pt=(ae=x.strictTuples)!==null&&ae!==void 0?ae:sn)!==null&&Pt!==void 0?Pt:"log",strictRequired:(Xr=(Zr=x.strictRequired)!==null&&Zr!==void 0?Zr:sn)!==null&&Xr!==void 0?Xr:!1,code:x.code?{...x.code,optimize:za,regExp:Ja}:{optimize:za,regExp:Ja},loopRequired:(eo=x.loopRequired)!==null&&eo!==void 0?eo:v,loopEnum:(to=x.loopEnum)!==null&&to!==void 0?to:v,meta:(no=x.meta)!==null&&no!==void 0?no:!0,messages:(ro=x.messages)!==null&&ro!==void 0?ro:!0,inlineRefs:(oo=x.inlineRefs)!==null&&oo!==void 0?oo:!0,schemaId:(so=x.schemaId)!==null&&so!==void 0?so:"$id",addUsedSchema:(io=x.addUsedSchema)!==null&&io!==void 0?io:!0,validateSchema:(ao=x.validateSchema)!==null&&ao!==void 0?ao:!0,validateFormats:(co=x.validateFormats)!==null&&co!==void 0?co:!0,unicodeRegExp:(uo=x.unicodeRegExp)!==null&&uo!==void 0?uo:!0,int32range:(lo=x.int32range)!==null&&lo!==void 0?lo:!0,uriResolver:Zh}}class b{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,...E(S)};const{es5:A,lines:N}=this.opts.code;this.scope=new a.ValueScope({scope:{},prefixes:m,es5:A,lines:N}),this.logger=Z(S.logger);const g=S.validateFormats;S.validateFormats=!1,this.RULES=(0,s.getRules)(),O.call(this,y,S,"NOT SUPPORTED"),O.call(this,$,S,"DEPRECATED","warn"),this._metaOpts=q.call(this),S.formats&&z.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),S.keywords&&U.call(this,S.keywords),typeof S.meta=="object"&&this.addMetaSchema(S.meta),C.call(this),S.validateFormats=g}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){const{$data:S,meta:A,schemaId:N}=this.opts;let g=f;N==="id"&&(g={...f},g.id=g.$id,delete g.$id),A&&S&&this.addMetaSchema(g,g[N],!1)}defaultMeta(){const{meta:S,schemaId:A}=this.opts;return this.opts.defaultMeta=typeof S=="object"?S[A]||S:void 0}validate(S,A){let N;if(typeof S=="string"){if(N=this.getSchema(S),!N)throw new Error(`no schema with key or ref "${S}"`)}else N=this.compile(S);const g=N(A);return"$async"in N||(this.errors=N.errors),g}compile(S,A){const N=this._addSchema(S,A);return N.validate||this._compileSchemaEnv(N)}compileAsync(S,A){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");const{loadSchema:N}=this.opts;return g.call(this,S,A);async function g(W,ae){await w.call(this,W.$schema);const Pt=this._addSchema(W,ae);return Pt.validate||_.call(this,Pt)}async function w(W){W&&!this.getSchema(W)&&await g.call(this,{$ref:W},!0)}async function _(W){try{return this._compileSchemaEnv(W)}catch(ae){if(!(ae instanceof o.default))throw ae;return M.call(this,ae),await D.call(this,ae.missingSchema),_.call(this,W)}}function M({missingSchema:W,missingRef:ae}){if(this.refs[W])throw new Error(`AnySchema ${W} is loaded but ${ae} cannot be resolved`)}async function D(W){const ae=await H.call(this,W);this.refs[W]||await w.call(this,ae.$schema),this.refs[W]||this.addSchema(ae,W,A)}async function H(W){const ae=this._loading[W];if(ae)return ae;try{return await(this._loading[W]=N(W))}finally{delete this._loading[W]}}}addSchema(S,A,N,g=this.opts.validateSchema){if(Array.isArray(S)){for(const _ of S)this.addSchema(_,void 0,N,g);return this}let w;if(typeof S=="object"){const{schemaId:_}=this.opts;if(w=S[_],w!==void 0&&typeof w!="string")throw new Error(`schema ${_} must be string`)}return A=(0,c.normalizeId)(A||w),this._checkUnique(A),this.schemas[A]=this._addSchema(S,N,A,g,!0),this}addMetaSchema(S,A,N=this.opts.validateSchema){return this.addSchema(S,A,!0,N),this}validateSchema(S,A){if(typeof S=="boolean")return!0;let N;if(N=S.$schema,N!==void 0&&typeof N!="string")throw new Error("$schema must be a string");if(N=N||this.opts.defaultMeta||this.defaultMeta(),!N)return this.logger.warn("meta-schema not available"),this.errors=null,!0;const g=this.validate(N,S);if(!g&&A){const w="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(w);else throw new Error(w)}return g}getSchema(S){let A;for(;typeof(A=j.call(this,S))=="string";)S=A;if(A===void 0){const{schemaId:N}=this.opts,g=new i.SchemaEnv({schema:{},schemaId:N});if(A=i.resolveSchema.call(this,g,S),!A)return;this.refs[S]=A}return A.validate||this._compileSchemaEnv(A)}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 A=j.call(this,S);return typeof A=="object"&&this._cache.delete(A.schema),delete this.schemas[S],delete this.refs[S],this}case"object":{const A=S;this._cache.delete(A);let N=S[this.opts.schemaId];return N&&(N=(0,c.normalizeId)(N),delete this.schemas[N],delete this.refs[N]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(S){for(const A of S)this.addKeyword(A);return this}addKeyword(S,A){let N;if(typeof S=="string")N=S,typeof A=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),A.keyword=N);else if(typeof S=="object"&&A===void 0){if(A=S,N=A.keyword,Array.isArray(N)&&!N.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(Ne.call(this,N,A),!A)return(0,l.eachItem)(N,w=>Fe.call(this,w)),this;on.call(this,A);const g={...A,type:(0,u.getJSONTypes)(A.type),schemaType:(0,u.getJSONTypes)(A.schemaType)};return(0,l.eachItem)(N,g.type.length===0?w=>Fe.call(this,w,g):w=>g.type.forEach(_=>Fe.call(this,w,g,_))),this}getKeyword(S){const A=this.RULES.all[S];return typeof A=="object"?A.definition:!!A}removeKeyword(S){const{RULES:A}=this;delete A.keywords[S],delete A.all[S];for(const N of A.rules){const g=N.rules.findIndex(w=>w.keyword===S);g>=0&&N.rules.splice(g,1)}return this}addFormat(S,A){return typeof A=="string"&&(A=new RegExp(A)),this.formats[S]=A,this}errorsText(S=this.errors,{separator:A=", ",dataVar:N="data"}={}){return!S||S.length===0?"No errors":S.map(g=>`${N}${g.instancePath} ${g.message}`).reduce((g,w)=>g+A+w)}$dataMetaSchema(S,A){const N=this.RULES.all;S=JSON.parse(JSON.stringify(S));for(const g of A){const w=g.split("/").slice(1);let _=S;for(const M of w)_=_[M];for(const M in N){const D=N[M];if(typeof D!="object")continue;const{$data:H}=D.definition,W=_[M];H&&W&&(_[M]=Fn(W))}}return S}_removeAllSchemas(S,A){for(const N in S){const g=S[N];(!A||A.test(N))&&(typeof g=="string"?delete S[N]:g&&!g.meta&&(this._cache.delete(g.schema),delete S[N]))}}_addSchema(S,A,N,g=this.opts.validateSchema,w=this.opts.addUsedSchema){let _;const{schemaId:M}=this.opts;if(typeof S=="object")_=S[M];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 D=this._cache.get(S);if(D!==void 0)return D;N=(0,c.normalizeId)(_||N);const H=c.getSchemaRefs.call(this,S,N);return D=new i.SchemaEnv({schema:S,schemaId:M,meta:A,baseId:N,localRefs:H}),this._cache.set(D.schema,D),w&&!N.startsWith("#")&&(N&&this._checkUnique(N),this.refs[N]=D),g&&this.validateSchema(S,!0),D}_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 A=this.opts;this.opts=this._metaOpts;try{i.compileSchema.call(this,S)}finally{this.opts=A}}}b.ValidationError=r.default,b.MissingRefError=o.default,e.default=b;function O(x,S,A,N="error"){for(const g in x){const w=g;w in S&&this.logger[N](`${A}: option ${g}. ${x[w]}`)}}function j(x){return x=(0,c.normalizeId)(x),this.schemas[x]||this.refs[x]}function C(){const x=this.opts.schemas;if(x)if(Array.isArray(x))this.addSchema(x);else for(const S in x)this.addSchema(x[S],S)}function z(){for(const x in this.opts.formats){const S=this.opts.formats[x];S&&this.addFormat(x,S)}}function U(x){if(Array.isArray(x)){this.addVocabulary(x);return}this.logger.warn("keywords option as map is deprecated, pass array");for(const S in x){const A=x[S];A.keyword||(A.keyword=S),this.addKeyword(A)}}function q(){const x={...this.opts};for(const S of d)delete x[S];return x}const Q={log(){},warn(){},error(){}};function Z(x){if(x===!1)return Q;if(x===void 0)return console;if(x.log&&x.warn&&x.error)return x;throw new Error("logger must implement log, warn and error methods")}const me=/^[a-z_$][a-z0-9_$:-]*$/i;function Ne(x,S){const{RULES:A}=this;if((0,l.eachItem)(x,N=>{if(A.keywords[N])throw new Error(`Keyword ${N} is already defined`);if(!me.test(N))throw new Error(`Keyword ${N} has invalid name`)}),!!S&&S.$data&&!("code"in S||"validate"in S))throw new Error('$data keyword must have "code" or "validate" function')}function Fe(x,S,A){var N;const g=S==null?void 0:S.post;if(A&&g)throw new Error('keyword with "post" flag cannot have "type"');const{RULES:w}=this;let _=g?w.post:w.rules.find(({type:D})=>D===A);if(_||(_={type:A,rules:[]},w.rules.push(_)),w.keywords[x]=!0,!S)return;const M={keyword:x,definition:{...S,type:(0,u.getJSONTypes)(S.type),schemaType:(0,u.getJSONTypes)(S.schemaType)}};S.before?de.call(this,_,M,S.before):_.rules.push(M),w.all[x]=M,(N=S.implements)===null||N===void 0||N.forEach(D=>this.addKeyword(D))}function de(x,S,A){const N=x.rules.findIndex(g=>g.keyword===A);N>=0?x.rules.splice(N,0,S):(x.rules.push(S),this.logger.warn(`rule ${A} is not defined`))}function on(x){let{metaSchema:S}=x;S!==void 0&&(x.$data&&this.opts.$data&&(S=Fn(S)),x.validateSchema=this.compile(S,!0))}const Qr={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Fn(x){return{anyOf:[x,Qr]}}})(qf);var Ci={},Ri={},Mi={};Object.defineProperty(Mi,"__esModule",{value:!0});const db={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Mi.default=db;var xt={};Object.defineProperty(xt,"__esModule",{value:!0});xt.callRef=xt.getValidate=void 0;const pb=tn,eu=K,ye=G,Rt=Be,tu=we,Yn=P,hb={keyword:"$ref",schemaType:"string",code(e){const{gen:t,schema:n,it:r}=e,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return f();const l=tu.resolveRef.call(c,u,o,n);if(l===void 0)throw new pb.default(r.opts.uriResolver,o,n);if(l instanceof tu.SchemaEnv)return p(l);return h(l);function f(){if(s===u)return dr(e,i,s,s.$async);const d=t.scopeValue("root",{ref:u});return dr(e,(0,ye._)`${d}.validate`,u,u.$async)}function p(d){const m=Md(e,d);dr(e,m,d,d.$async)}function h(d){const m=t.scopeValue("schema",a.code.source===!0?{ref:d,code:(0,ye.stringify)(d)}:{ref:d}),y=t.name("valid"),$=e.subschema({schema:d,dataTypes:[],schemaPath:ye.nil,topSchemaRef:m,errSchemaPath:n},y);e.mergeEvaluated($),e.ok(y)}}};function Md(e,t){const{gen:n}=e;return t.validate?n.scopeValue("validate",{ref:t.validate}):(0,ye._)`${n.scopeValue("wrapper",{ref:t})}.validate`}xt.getValidate=Md;function dr(e,t,n,r){const{gen:o,it:s}=e,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Rt.default.this:ye.nil;r?l():f();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");const d=o.let("valid");o.try(()=>{o.code((0,ye._)`await ${(0,eu.callValidateCode)(e,t,u)}`),h(t),i||o.assign(d,!0)},m=>{o.if((0,ye._)`!(${m} instanceof ${s.ValidationError})`,()=>o.throw(m)),p(m),i||o.assign(d,!1)}),e.ok(d)}function f(){e.result((0,eu.callValidateCode)(e,t,u),()=>h(t),()=>p(t))}function p(d){const m=(0,ye._)`${d}.errors`;o.assign(Rt.default.vErrors,(0,ye._)`${Rt.default.vErrors} === null ? ${m} : ${Rt.default.vErrors}.concat(${m})`),o.assign(Rt.default.errors,(0,ye._)`${Rt.default.vErrors}.length`)}function h(d){var m;if(!s.opts.unevaluated)return;const y=(m=n==null?void 0:n.validate)===null||m===void 0?void 0:m.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Yn.mergeEvaluated.props(o,y.props,s.props));else{const $=o.var("props",(0,ye._)`${d}.evaluated.props`);s.props=Yn.mergeEvaluated.props(o,$,s.props,ye.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Yn.mergeEvaluated.items(o,y.items,s.items));else{const $=o.var("items",(0,ye._)`${d}.evaluated.items`);s.items=Yn.mergeEvaluated.items(o,$,s.items,ye.Name)}}}xt.callRef=dr;xt.default=hb;Object.defineProperty(Ri,"__esModule",{value:!0});const mb=Mi,gb=xt,yb=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",mb.default,gb.default];Ri.default=yb;var Di={},Li={};Object.defineProperty(Li,"__esModule",{value:!0});const Er=G,et=Er.operators,Sr={maximum:{okStr:"<=",ok:et.LTE,fail:et.GT},minimum:{okStr:">=",ok:et.GTE,fail:et.LT},exclusiveMaximum:{okStr:"<",ok:et.LT,fail:et.GTE},exclusiveMinimum:{okStr:">",ok:et.GT,fail:et.LTE}},$b={message:({keyword:e,schemaCode:t})=>(0,Er.str)`must be ${Sr[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,Er._)`{comparison: ${Sr[e].okStr}, limit: ${t}}`},vb={keyword:Object.keys(Sr),type:"number",schemaType:"number",$data:!0,error:$b,code(e){const{keyword:t,data:n,schemaCode:r}=e;e.fail$data((0,Er._)`${n} ${Sr[t].fail} ${r} || isNaN(${n})`)}};Li.default=vb;var Ui={};Object.defineProperty(Ui,"__esModule",{value:!0});const vn=G,wb={message:({schemaCode:e})=>(0,vn.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,vn._)`{multipleOf: ${e}}`},bb={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:wb,code(e){const{gen:t,data:n,schemaCode:r,it:o}=e,s=o.opts.multipleOfPrecision,i=t.let("res"),a=s?(0,vn._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,vn._)`${i} !== parseInt(${i})`;e.fail$data((0,vn._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Ui.default=bb;var Bi={},Fi={};Object.defineProperty(Fi,"__esModule",{value:!0});function Dd(e){const t=e.length;let n=0,r=0,o;for(;r<t;)n++,o=e.charCodeAt(r++),o>=55296&&o<=56319&&r<t&&(o=e.charCodeAt(r),(o&64512)===56320&&r++);return n}Fi.default=Dd;Dd.code='require("ajv/dist/runtime/ucs2length").default';Object.defineProperty(Bi,"__esModule",{value:!0});const $t=G,Eb=P,Sb=Fi,Ob={message({keyword:e,schemaCode:t}){const n=e==="maxLength"?"more":"fewer";return(0,$t.str)`must NOT have ${n} than ${t} characters`},params:({schemaCode:e})=>(0,$t._)`{limit: ${e}}`},Nb={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Ob,code(e){const{keyword:t,data:n,schemaCode:r,it:o}=e,s=t==="maxLength"?$t.operators.GT:$t.operators.LT,i=o.opts.unicode===!1?(0,$t._)`${n}.length`:(0,$t._)`${(0,Eb.useFunc)(e.gen,Sb.default)}(${n})`;e.fail$data((0,$t._)`${i} ${s} ${r}`)}};Bi.default=Nb;var qi={};Object.defineProperty(qi,"__esModule",{value:!0});const _b=K,kb=P,zt=G,Ab={message:({schemaCode:e})=>(0,zt.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,zt._)`{pattern: ${e}}`},jb={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Ab,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e,a=i.opts.unicodeRegExp?"u":"";if(r){const{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,zt._)`new RegExp`:(0,kb.useFunc)(t,c),l=t.let("valid");t.try(()=>t.assign(l,(0,zt._)`${u}(${s}, ${a}).test(${n})`),()=>t.assign(l,!1)),e.fail$data((0,zt._)`!${l}`)}else{const c=(0,_b.usePattern)(e,o);e.fail$data((0,zt._)`!${c}.test(${n})`)}}};qi.default=jb;var Vi={};Object.defineProperty(Vi,"__esModule",{value:!0});const wn=G,Ib={message({keyword:e,schemaCode:t}){const n=e==="maxProperties"?"more":"fewer";return(0,wn.str)`must NOT have ${n} than ${t} properties`},params:({schemaCode:e})=>(0,wn._)`{limit: ${e}}`},xb={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Ib,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxProperties"?wn.operators.GT:wn.operators.LT;e.fail$data((0,wn._)`Object.keys(${n}).length ${o} ${r}`)}};Vi.default=xb;var Ki={};Object.defineProperty(Ki,"__esModule",{value:!0});const cn=K,bn=G,Pb=P,Tb={message:({params:{missingProperty:e}})=>(0,bn.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,bn._)`{missingProperty: ${e}}`},Cb={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Tb,code(e){const{gen:t,schema:n,schemaCode:r,data:o,$data:s,it:i}=e,{opts:a}=i;if(!s&&n.length===0)return;const c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){const h=e.parentSchema.properties,{definedProperties:d}=e.it;for(const m of n)if((h==null?void 0:h[m])===void 0&&!d.has(m)){const y=i.schemaEnv.baseId+i.errSchemaPath,$=`required property "${m}" is not defined at "${y}" (strictRequired)`;(0,Pb.checkStrictMode)(i,$,i.opts.strictRequired)}}function u(){if(c||s)e.block$data(bn.nil,f);else for(const h of n)(0,cn.checkReportMissingProp)(e,h)}function l(){const h=t.let("missing");if(c||s){const d=t.let("valid",!0);e.block$data(d,()=>p(h,d)),e.ok(d)}else t.if((0,cn.checkMissingProp)(e,n,h)),(0,cn.reportMissingProp)(e,h),t.else()}function f(){t.forOf("prop",r,h=>{e.setParams({missingProperty:h}),t.if((0,cn.noPropertyInData)(t,o,h,a.ownProperties),()=>e.error())})}function p(h,d){e.setParams({missingProperty:h}),t.forOf(h,r,()=>{t.assign(d,(0,cn.propertyInData)(t,o,h,a.ownProperties)),t.if((0,bn.not)(d),()=>{e.error(),t.break()})},bn.nil)}}};Ki.default=Cb;var Gi={};Object.defineProperty(Gi,"__esModule",{value:!0});const En=G,Rb={message({keyword:e,schemaCode:t}){const n=e==="maxItems"?"more":"fewer";return(0,En.str)`must NOT have ${n} than ${t} items`},params:({schemaCode:e})=>(0,En._)`{limit: ${e}}`},Mb={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Rb,code(e){const{keyword:t,data:n,schemaCode:r}=e,o=t==="maxItems"?En.operators.GT:En.operators.LT;e.fail$data((0,En._)`${n}.length ${o} ${r}`)}};Gi.default=Mb;var zi={},Bn={};Object.defineProperty(Bn,"__esModule",{value:!0});const Ld=od;Ld.code='require("ajv/dist/runtime/equal").default';Bn.default=Ld;Object.defineProperty(zi,"__esModule",{value:!0});const _o=se,ce=G,Db=P,Lb=Bn,Ub={message:({params:{i:e,j:t}})=>(0,ce.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,ce._)`{i: ${e}, j: ${t}}`},Bb={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:Ub,code(e){const{gen:t,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=e;if(!r&&!o)return;const c=t.let("valid"),u=s.items?(0,_o.getSchemaTypes)(s.items):[];e.block$data(c,l,(0,ce._)`${i} === false`),e.ok(c);function l(){const d=t.let("i",(0,ce._)`${n}.length`),m=t.let("j");e.setParams({i:d,j:m}),t.assign(c,!0),t.if((0,ce._)`${d} > 1`,()=>(f()?p:h)(d,m))}function f(){return u.length>0&&!u.some(d=>d==="object"||d==="array")}function p(d,m){const y=t.name("item"),$=(0,_o.checkDataTypes)(u,y,a.opts.strictNumbers,_o.DataType.Wrong),v=t.const("indices",(0,ce._)`{}`);t.for((0,ce._)`;${d}--;`,()=>{t.let(y,(0,ce._)`${n}[${d}]`),t.if($,(0,ce._)`continue`),u.length>1&&t.if((0,ce._)`typeof ${y} == "string"`,(0,ce._)`${y} += "_"`),t.if((0,ce._)`typeof ${v}[${y}] == "number"`,()=>{t.assign(m,(0,ce._)`${v}[${y}]`),e.error(),t.assign(c,!1).break()}).code((0,ce._)`${v}[${y}] = ${d}`)})}function h(d,m){const y=(0,Db.useFunc)(t,Lb.default),$=t.name("outer");t.label($).for((0,ce._)`;${d}--;`,()=>t.for((0,ce._)`${m} = ${d}; ${m}--;`,()=>t.if((0,ce._)`${y}(${n}[${d}], ${n}[${m}])`,()=>{e.error(),t.assign(c,!1).break($)})))}}};zi.default=Bb;var Ji={};Object.defineProperty(Ji,"__esModule",{value:!0});const ys=G,Fb=P,qb=Bn,Vb={message:"must be equal to constant",params:({schemaCode:e})=>(0,ys._)`{allowedValue: ${e}}`},Kb={keyword:"const",$data:!0,error:Vb,code(e){const{gen:t,data:n,$data:r,schemaCode:o,schema:s}=e;r||s&&typeof s=="object"?e.fail$data((0,ys._)`!${(0,Fb.useFunc)(t,qb.default)}(${n}, ${o})`):e.fail((0,ys._)`${s} !== ${n}`)}};Ji.default=Kb;var Wi={};Object.defineProperty(Wi,"__esModule",{value:!0});const hn=G,Gb=P,zb=Bn,Jb={message:"must be equal to one of the allowed values",params:({schemaCode:e})=>(0,hn._)`{allowedValues: ${e}}`},Wb={keyword:"enum",schemaType:"array",$data:!0,error:Jb,code(e){const{gen:t,data:n,$data:r,schema:o,schemaCode:s,it:i}=e;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,Gb.useFunc)(t,zb.default));let l;if(a||r)l=t.let("valid"),e.block$data(l,f);else{if(!Array.isArray(o))throw new Error("ajv implementation error");const h=t.const("vSchema",s);l=(0,hn.or)(...o.map((d,m)=>p(h,m)))}e.pass(l);function f(){t.assign(l,!1),t.forOf("v",s,h=>t.if((0,hn._)`${u()}(${n}, ${h})`,()=>t.assign(l,!0).break()))}function p(h,d){const m=o[d];return typeof m=="object"&&m!==null?(0,hn._)`${u()}(${n}, ${h}[${d}])`:(0,hn._)`${n} === ${m}`}}};Wi.default=Wb;Object.defineProperty(Di,"__esModule",{value:!0});const Hb=Li,Yb=Ui,Qb=Bi,Zb=qi,Xb=Vi,eE=Ki,tE=Gi,nE=zi,rE=Ji,oE=Wi,sE=[Hb.default,Yb.default,Qb.default,Zb.default,Xb.default,eE.default,tE.default,nE.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},rE.default,oE.default];Di.default=sE;var Hi={},nn={};Object.defineProperty(nn,"__esModule",{value:!0});nn.validateAdditionalItems=void 0;const vt=G,$s=P,iE={message:({params:{len:e}})=>(0,vt.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,vt._)`{limit: ${e}}`},aE={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:iE,code(e){const{parentSchema:t,it:n}=e,{items:r}=t;if(!Array.isArray(r)){(0,$s.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Ud(e,r)}};function Ud(e,t){const{gen:n,schema:r,data:o,keyword:s,it:i}=e;i.items=!0;const a=n.const("len",(0,vt._)`${o}.length`);if(r===!1)e.setParams({len:t.length}),e.pass((0,vt._)`${a} <= ${t.length}`);else if(typeof r=="object"&&!(0,$s.alwaysValidSchema)(i,r)){const u=n.var("valid",(0,vt._)`${a} <= ${t.length}`);n.if((0,vt.not)(u),()=>c(u)),e.ok(u)}function c(u){n.forRange("i",t.length,a,l=>{e.subschema({keyword:s,dataProp:l,dataPropType:$s.Type.Num},u),i.allErrors||n.if((0,vt.not)(u),()=>n.break())})}}nn.validateAdditionalItems=Ud;nn.default=aE;var Yi={},rn={};Object.defineProperty(rn,"__esModule",{value:!0});rn.validateTuple=void 0;const nu=G,pr=P,cE=K,uE={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){const{schema:t,it:n}=e;if(Array.isArray(t))return Bd(e,"additionalItems",t);n.items=!0,!(0,pr.alwaysValidSchema)(n,t)&&e.ok((0,cE.validateArray)(e))}};function Bd(e,t,n=e.schema){const{gen:r,parentSchema:o,data:s,keyword:i,it:a}=e;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=pr.mergeEvaluated.items(r,n.length,a.items));const c=r.name("valid"),u=r.const("len",(0,nu._)`${s}.length`);n.forEach((f,p)=>{(0,pr.alwaysValidSchema)(a,f)||(r.if((0,nu._)`${u} > ${p}`,()=>e.subschema({keyword:i,schemaProp:p,dataProp:p},c)),e.ok(c))});function l(f){const{opts:p,errSchemaPath:h}=a,d=n.length,m=d===f.minItems&&(d===f.maxItems||f[t]===!1);if(p.strictTuples&&!m){const y=`"${i}" is ${d}-tuple, but minItems or maxItems/${t} are not specified or different at path "${h}"`;(0,pr.checkStrictMode)(a,y,p.strictTuples)}}}rn.validateTuple=Bd;rn.default=uE;Object.defineProperty(Yi,"__esModule",{value:!0});const lE=rn,fE={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:e=>(0,lE.validateTuple)(e,"items")};Yi.default=fE;var Qi={};Object.defineProperty(Qi,"__esModule",{value:!0});const ru=G,dE=P,pE=K,hE=nn,mE={message:({params:{len:e}})=>(0,ru.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,ru._)`{limit: ${e}}`},gE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:mE,code(e){const{schema:t,parentSchema:n,it:r}=e,{prefixItems:o}=n;r.items=!0,!(0,dE.alwaysValidSchema)(r,t)&&(o?(0,hE.validateAdditionalItems)(e,o):e.ok((0,pE.validateArray)(e)))}};Qi.default=gE;var Zi={};Object.defineProperty(Zi,"__esModule",{value:!0});const _e=G,Qn=P,yE={message:({params:{min:e,max:t}})=>t===void 0?(0,_e.str)`must contain at least ${e} valid item(s)`:(0,_e.str)`must contain at least ${e} and no more than ${t} valid item(s)`,params:({params:{min:e,max:t}})=>t===void 0?(0,_e._)`{minContains: ${e}}`:(0,_e._)`{minContains: ${e}, maxContains: ${t}}`},$E={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:yE,code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;let i,a;const{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;const l=t.const("len",(0,_e._)`${o}.length`);if(e.setParams({min:i,max:a}),a===void 0&&i===0){(0,Qn.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Qn.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,Qn.alwaysValidSchema)(s,n)){let m=(0,_e._)`${l} >= ${i}`;a!==void 0&&(m=(0,_e._)`${m} && ${l} <= ${a}`),e.pass(m);return}s.items=!0;const f=t.name("valid");a===void 0&&i===1?h(f,()=>t.if(f,()=>t.break())):i===0?(t.let(f,!0),a!==void 0&&t.if((0,_e._)`${o}.length > 0`,p)):(t.let(f,!1),p()),e.result(f,()=>e.reset());function p(){const m=t.name("_valid"),y=t.let("count",0);h(m,()=>t.if(m,()=>d(y)))}function h(m,y){t.forRange("i",0,l,$=>{e.subschema({keyword:"contains",dataProp:$,dataPropType:Qn.Type.Num,compositeRule:!0},m),y()})}function d(m){t.code((0,_e._)`${m}++`),a===void 0?t.if((0,_e._)`${m} >= ${i}`,()=>t.assign(f,!0).break()):(t.if((0,_e._)`${m} > ${a}`,()=>t.assign(f,!1).break()),i===1?t.assign(f,!0):t.if((0,_e._)`${m} >= ${i}`,()=>t.assign(f,!0)))}}};Zi.default=$E;var Fd={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;const t=G,n=P,r=K;e.error={message:({params:{property:c,depsCount:u,deps:l}})=>{const f=u===1?"property":"properties";return(0,t.str)`must have ${f} ${l} when property ${c} is present`},params:({params:{property:c,depsCount:u,deps:l,missingProperty:f}})=>(0,t._)`{property: ${c},
|
|
160
160
|
missingProperty: ${f},
|
|
161
161
|
depsCount: ${u},
|
|
162
|
-
deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const f in c){if(f==="__proto__")continue;const p=Array.isArray(c[f])?u:l;p[f]=c[f]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:f,it:p}=c;if(Object.keys(u).length===0)return;const h=l.let("missing");for(const d in u){const g=u[d];if(g.length===0)continue;const y=(0,r.propertyInData)(l,f,d,p.opts.ownProperties);c.setParams({property:d,depsCount:g.length,deps:g.join(", ")}),p.allErrors?l.if(y,()=>{for(const $ of g)(0,r.checkReportMissingProp)(c,$)}):(l.if((0,t._)`${y} && (${(0,r.checkMissingProp)(c,g,h)})`),(0,r.reportMissingProp)(c,h),l.else())}}e.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:f,keyword:p,it:h}=c,d=l.name("valid");for(const g in u)(0,n.alwaysValidSchema)(h,u[g])||(l.if((0,r.propertyInData)(l,f,g,h.opts.ownProperties),()=>{const y=c.subschema({keyword:p,schemaProp:g},d);c.mergeValidEvaluated(y,d)},()=>l.var(d,!0)),c.ok(d))}e.validateSchemaDeps=a,e.default=o})(Ld);var Xi={};Object.defineProperty(Xi,"__esModule",{value:!0});const Ud=G,gE=P,yE={message:"property name must be valid",params:({params:e})=>(0,Ud._)`{propertyName: ${e.propertyName}}`},$E={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:yE,code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,gE.alwaysValidSchema)(o,n))return;const s=t.name("valid");t.forIn("key",r,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,Ud.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Xi.default=$E;var Vr={};Object.defineProperty(Vr,"__esModule",{value:!0});const Zn=K,je=G,vE=Be,Xn=P,wE={message:"must NOT have additional properties",params:({params:e})=>(0,je._)`{additionalProperty: ${e.additionalProperty}}`},bE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:wE,code(e){const{gen:t,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Xn.alwaysValidSchema)(i,n))return;const u=(0,Zn.allSchemaProperties)(r.properties),l=(0,Zn.allSchemaProperties)(r.patternProperties);f(),e.ok((0,je._)`${s} === ${vE.default.errors}`);function f(){t.forIn("key",o,y=>{!u.length&&!l.length?d(y):t.if(p(y),()=>d(y))})}function p(y){let $;if(u.length>8){const v=(0,Xn.schemaRefOrVal)(i,r.properties,"properties");$=(0,Zn.isOwnProperty)(t,v,y)}else u.length?$=(0,je.or)(...u.map(v=>(0,je._)`${y} === ${v}`)):$=je.nil;return l.length&&($=(0,je.or)($,...l.map(v=>(0,je._)`${(0,Zn.usePattern)(e,v)}.test(${y})`))),(0,je.not)($)}function h(y){t.code((0,je._)`delete ${o}[${y}]`)}function d(y){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(y);return}if(n===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,Xn.alwaysValidSchema)(i,n)){const $=t.name("valid");c.removeAdditional==="failing"?(g(y,$,!1),t.if((0,je.not)($),()=>{e.reset(),h(y)})):(g(y,$),a||t.if((0,je.not)($),()=>t.break()))}}function g(y,$,v){const E={keyword:"additionalProperties",dataProp:y,dataPropType:Xn.Type.Str};v===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(E,$)}}};Vr.default=bE;var ea={};Object.defineProperty(ea,"__esModule",{value:!0});const EE=Pe,ru=K,ko=P,ou=Vr,SE={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&ou.default.code(new EE.KeywordCxt(s,ou.default,"additionalProperties"));const i=(0,ru.allSchemaProperties)(n);for(const f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=ko.mergeEvaluated.props(t,(0,ko.toHash)(i),s.props));const a=i.filter(f=>!(0,ko.alwaysValidSchema)(s,n[f]));if(a.length===0)return;const c=t.name("valid");for(const f of a)u(f)?l(f):(t.if((0,ru.propertyInData)(t,o,f,s.opts.ownProperties)),l(f),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function u(f){return s.opts.useDefaults&&!s.compositeRule&&n[f].default!==void 0}function l(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};ea.default=SE;var ta={};Object.defineProperty(ta,"__esModule",{value:!0});const su=K,er=G,iu=P,au=P,OE={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:r,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,su.allSchemaProperties)(n),c=a.filter(g=>(0,iu.alwaysValidSchema)(s,n[g]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof er.Name)&&(s.props=(0,au.evaluatedPropsToName)(t,s.props));const{props:f}=s;p();function p(){for(const g of a)u&&h(g),s.allErrors?d(g):(t.var(l,!0),d(g),t.if(l))}function h(g){for(const y in u)new RegExp(g).test(y)&&(0,iu.checkStrictMode)(s,`property ${y} matches pattern ${g} (use allowMatchingProperties)`)}function d(g){t.forIn("key",r,y=>{t.if((0,er._)`${(0,su.usePattern)(e,g)}.test(${y})`,()=>{const $=c.includes(g);$||e.subschema({keyword:"patternProperties",schemaProp:g,dataProp:y,dataPropType:au.Type.Str},l),s.opts.unevaluated&&f!==!0?t.assign((0,er._)`${f}[${y}]`,!0):!$&&!s.allErrors&&t.if((0,er.not)(l),()=>t.break())})})}}};ta.default=OE;var na={};Object.defineProperty(na,"__esModule",{value:!0});const NE=P,_E={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,NE.alwaysValidSchema)(r,n)){e.fail();return}const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};na.default=_E;var ra={};Object.defineProperty(ra,"__esModule",{value:!0});const kE=K,AE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kE.validateUnion,error:{message:"must match a schema in anyOf"}};ra.default=AE;var oa={};Object.defineProperty(oa,"__esModule",{value:!0});const hr=G,jE=P,IE={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,hr._)`{passingSchemas: ${e.passing}}`},xE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:IE,code(e){const{gen:t,schema:n,parentSchema:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,f)=>{let p;(0,jE.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,hr._)`${c} && ${i}`).assign(i,!1).assign(a,(0,hr._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,f),p&&e.mergeEvaluated(p,hr.Name)})})}}};oa.default=xE;var sa={};Object.defineProperty(sa,"__esModule",{value:!0});const PE=P,TE={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=t.name("valid");n.forEach((s,i)=>{if((0,PE.alwaysValidSchema)(r,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};sa.default=TE;var ia={};Object.defineProperty(ia,"__esModule",{value:!0});const Or=G,Bd=P,CE={message:({params:e})=>(0,Or.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Or._)`{failingKeyword: ${e.ifClause}}`},RE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:CE,code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,Bd.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=cu(r,"then"),s=cu(r,"else");if(!o&&!s)return;const i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){const l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,Or.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){const l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,f){return()=>{const p=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(p,i),f?t.assign(f,(0,Or._)`${l}`):e.setParams({ifClause:l})}}}};function cu(e,t){const n=e.schema[t];return n!==void 0&&!(0,Bd.alwaysValidSchema)(e,n)}ia.default=RE;var aa={};Object.defineProperty(aa,"__esModule",{value:!0});const ME=P,DE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,ME.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};aa.default=DE;Object.defineProperty(Wi,"__esModule",{value:!0});const LE=nn,UE=Yi,BE=rn,FE=Qi,qE=Zi,VE=Ld,KE=Xi,GE=Vr,zE=ea,JE=ta,HE=na,WE=ra,YE=oa,QE=sa,ZE=ia,XE=aa;function eS(e=!1){const t=[HE.default,WE.default,YE.default,QE.default,ZE.default,XE.default,KE.default,GE.default,VE.default,zE.default,JE.default];return e?t.push(UE.default,FE.default):t.push(LE.default,BE.default),t.push(qE.default),t}Wi.default=eS;var ca={},ua={};Object.defineProperty(ua,"__esModule",{value:!0});const ne=G,tS={message:({schemaCode:e})=>(0,ne.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ne._)`{format: ${e}}`},nS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:tS,code(e,t){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:f}=a;if(!c.validateFormats)return;o?p():h();function p(){const d=n.scopeValue("formats",{ref:f.formats,code:c.code.formats}),g=n.const("fDef",(0,ne._)`${d}[${i}]`),y=n.let("fType"),$=n.let("format");n.if((0,ne._)`typeof ${g} == "object" && !(${g} instanceof RegExp)`,()=>n.assign(y,(0,ne._)`${g}.type || "string"`).assign($,(0,ne._)`${g}.validate`),()=>n.assign(y,(0,ne._)`"string"`).assign($,g)),e.fail$data((0,ne.or)(v(),E()));function v(){return c.strictSchema===!1?ne.nil:(0,ne._)`${i} && !${$}`}function E(){const b=l.$async?(0,ne._)`(${g}.async ? await ${$}(${r}) : ${$}(${r}))`:(0,ne._)`${$}(${r})`,O=(0,ne._)`(typeof ${$} == "function" ? ${b} : ${$}.test(${r}))`;return(0,ne._)`${$} && ${$} !== true && ${y} === ${t} && !${O}`}}function h(){const d=f.formats[s];if(!d){v();return}if(d===!0)return;const[g,y,$]=E(d);g===t&&e.pass(b());function v(){if(c.strictSchema===!1){f.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function E(O){const j=O instanceof RegExp?(0,ne.regexpCode)(O):c.code.formats?(0,ne._)`${c.code.formats}${(0,ne.getProperty)(s)}`:void 0,C=n.scopeValue("formats",{key:s,ref:O,code:j});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,ne._)`${C}.validate`]:["string",O,C]}function b(){if(typeof d=="object"&&!(d instanceof RegExp)&&d.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ne._)`await ${$}(${r})`}return typeof y=="function"?(0,ne._)`${$}(${r})`:(0,ne._)`${$}.test(${r})`}}}};ua.default=nS;Object.defineProperty(ca,"__esModule",{value:!0});const rS=ua,oS=[rS.default];ca.default=oS;var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.contentVocabulary=Xt.metadataVocabulary=void 0;Xt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Xt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(Ci,"__esModule",{value:!0});const sS=Ri,iS=Di,aS=Wi,cS=ca,uu=Xt,uS=[sS.default,iS.default,(0,aS.default)(),cS.default,uu.metadataVocabulary,uu.contentVocabulary];Ci.default=uS;var la={},Kr={};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.DiscrError=void 0;var lu;(function(e){e.Tag="tag",e.Mapping="mapping"})(lu||(Kr.DiscrError=lu={}));Object.defineProperty(la,"__esModule",{value:!0});const Bt=G,$s=Kr,fu=we,lS=tn,fS=P,dS={message:({params:{discrError:e,tagName:t}})=>e===$s.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Bt._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},pS={keyword:"discriminator",type:"object",schemaType:"object",error:dS,code(e){const{gen:t,data:n,schema:r,parentSchema:o,it:s}=e,{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=t.let("valid",!1),u=t.const("tag",(0,Bt._)`${n}${(0,Bt.getProperty)(a)}`);t.if((0,Bt._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:$s.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){const h=p();t.if(!1);for(const d in h)t.elseIf((0,Bt._)`${u} === ${d}`),t.assign(c,f(h[d]));t.else(),e.error(!1,{discrError:$s.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function f(h){const d=t.name("valid"),g=e.subschema({keyword:"oneOf",schemaProp:h},d);return e.mergeEvaluated(g,Bt.Name),d}function p(){var h;const d={},g=$(o);let y=!0;for(let b=0;b<i.length;b++){let O=i[b];if(O!=null&&O.$ref&&!(0,fS.schemaHasRulesButRef)(O,s.self.RULES)){const C=O.$ref;if(O=fu.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,C),O instanceof fu.SchemaEnv&&(O=O.schema),O===void 0)throw new lS.default(s.opts.uriResolver,s.baseId,C)}const j=(h=O==null?void 0:O.properties)===null||h===void 0?void 0:h[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(g||$(O)),v(j,b)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return d;function $({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,O){if(b.const)E(b.const,O);else if(b.enum)for(const j of b.enum)E(j,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(b,O){if(typeof b!="string"||b in d)throw new Error(`discriminator: "${a}" values must be unique strings`);d[b]=O}}}};la.default=pS;const hS="http://json-schema.org/draft-07/schema#",mS="http://json-schema.org/draft-07/schema#",gS="Core schema meta-schema",yS={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:[]}},$S=["object","boolean"],vS={$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:"#"}},wS={$schema:hS,$id:mS,title:gS,definitions:yS,type:$S,properties:vS,default:!0};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=Uf,r=Ci,o=la,s=wS,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(d=>this.addVocabulary(d)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const d=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(d,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Pe;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=G;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var f=Un;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=tn;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(fs,fs.exports);var bS=fs.exports;const ES=qy(bS);class Fd 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 SS(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new ES({allErrors:!0,strict:!1}).compile(n);if(!o(e))throw new Fd(OS(o.errors??[]))}function OS(e){return e.map(t=>({field:NS(t),message:t.message??"is invalid",keyword:t.keyword}))}function NS(e){var t;return(e.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((t=e.params)==null?void 0:t.missingProperty)??"(root)")}function _S(e,t){return T.join(Kl(e,t),Z$)}const kS=384,AS=448;function jS(e,t,n={}){const r=n.mode??kS,o=n.dirMode??AS,s=T.dirname(e);L.mkdirSync(s,{recursive:!0,mode:o}),L.chmodSync(s,o);const i=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{L.writeFileSync(i,a,{encoding:"utf8",mode:r}),L.chmodSync(i,r),L.renameSync(i,e),L.chmodSync(e,r)}catch(c){try{L.existsSync(i)&&L.unlinkSync(i)}catch{}throw c}}const IS="0.1.0";function du(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 xS(){return`${process.pid}-${Mn.randomBytes(3).toString("hex")}`}function qd(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");du(e,"project");const r=t.orgNamespace??Y$,o=t.envPrefixOverride??rv(e),s=t.namespaces&&t.namespaces.length>0?t.namespaces:[Q$],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${e}" (declared: ${s.join(", ")})`);du(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=Uy({scope:n.scope,cwd:n.cwd},a),l=Fy({project:e,namespace:i,orgNamespace:r,projectRoot:u,adhdRoot:n.adhdRoot});return{project:e,namespace:i,orgNamespace:r,envPrefix:o,scope:c,projectRoot:u,roots:l}}function PS(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=qd(e,t,n),u=n.processEnv??process.env,l=pv(c),f=n.instanceId??xS(),{raw:p,nested:h,typedRaw:d,provenance:g,fields:y}=gv(t.config,l,u,{prefix:s,activeScope:i}),$={};for(const O of Object.keys(y)){const j=y[O];j.live&&($[O]={env:j.env,type:j.type,fallback:j.secret===!0?void 0:j.fallbackValue})}const v=sv(t.config);SS(Lf(d),v);const E=$v(t.dirs,{roots:c,activeScope:i,instanceId:f,projectRoot:a,namespace:r}),b=vv(t.files,E);return{version:W$,libraryVersion:IS,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:f,config:h,raw:p,liveFields:$,fieldSchema:v,configHash:tv(Object.fromEntries(Object.entries(d).map(([O,j])=>[O,String(j)]))),structureHash:nv(Object.values(E).map(O=>({name:O.name,kind:O.kind,scope:O.scope}))),dirs:Object.values(E),files:Object.values(b),provenance:g}}let In=class extends Error{constructor(t){super(t),this.name="EnvironmentError"}};class TS extends In{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class CS extends In{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function RS(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 vs(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>vs(n));const t={};for(const[n,r]of Object.entries(e))t[n]=vs(r);return t}function MS(e,t){const n=vs(e);for(const r of Object.keys(t)){const o=t[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?ls(c,o.type):o.fallback}})}return n}function DS(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new In(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class fa{constructor(t,n,r={}){let o,s;try{o=PS(t,n,r);const i=qd(t,n,r);s=_S(i.roots,o.scope)}catch(i){throw i instanceof Fd||i instanceof In?i:new In(i instanceof Error?i.message:String(i))}return pu(this,o,s)}static fromSnapshot(t){if(!L.existsSync(t))throw new TS(t);const n=JSON.parse(L.readFileSync(t,"utf8")),r=Object.create(fa.prototype);return pu(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 RS(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"){DS(t);const n=this.paths.run??this._runDirFallback();L.mkdirSync(n,{recursive:!0});const r=T.join(n,`${t}.lock`);let o;try{o=L.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new CS(t,r):i}L.writeSync(o,`${process.pid}
|
|
162
|
+
deps: ${l}}`};const o={keyword:"dependencies",type:"object",schemaType:"object",error:e.error,code(c){const[u,l]=s(c);i(c,u),a(c,l)}};function s({schema:c}){const u={},l={};for(const f in c){if(f==="__proto__")continue;const p=Array.isArray(c[f])?u:l;p[f]=c[f]}return[u,l]}function i(c,u=c.schema){const{gen:l,data:f,it:p}=c;if(Object.keys(u).length===0)return;const h=l.let("missing");for(const d in u){const m=u[d];if(m.length===0)continue;const y=(0,r.propertyInData)(l,f,d,p.opts.ownProperties);c.setParams({property:d,depsCount:m.length,deps:m.join(", ")}),p.allErrors?l.if(y,()=>{for(const $ of m)(0,r.checkReportMissingProp)(c,$)}):(l.if((0,t._)`${y} && (${(0,r.checkMissingProp)(c,m,h)})`),(0,r.reportMissingProp)(c,h),l.else())}}e.validatePropertyDeps=i;function a(c,u=c.schema){const{gen:l,data:f,keyword:p,it:h}=c,d=l.name("valid");for(const m in u)(0,n.alwaysValidSchema)(h,u[m])||(l.if((0,r.propertyInData)(l,f,m,h.opts.ownProperties),()=>{const y=c.subschema({keyword:p,schemaProp:m},d);c.mergeValidEvaluated(y,d)},()=>l.var(d,!0)),c.ok(d))}e.validateSchemaDeps=a,e.default=o})(Fd);var Xi={};Object.defineProperty(Xi,"__esModule",{value:!0});const qd=G,vE=P,wE={message:"property name must be valid",params:({params:e})=>(0,qd._)`{propertyName: ${e.propertyName}}`},bE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:wE,code(e){const{gen:t,schema:n,data:r,it:o}=e;if((0,vE.alwaysValidSchema)(o,n))return;const s=t.name("valid");t.forIn("key",r,i=>{e.setParams({propertyName:i}),e.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),t.if((0,qd.not)(s),()=>{e.error(!0),o.allErrors||t.break()})}),e.ok(s)}};Xi.default=bE;var Vr={};Object.defineProperty(Vr,"__esModule",{value:!0});const Zn=K,je=G,EE=Be,Xn=P,SE={message:"must NOT have additional properties",params:({params:e})=>(0,je._)`{additionalProperty: ${e.additionalProperty}}`},OE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:SE,code(e){const{gen:t,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=e;if(!s)throw new Error("ajv implementation error");const{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Xn.alwaysValidSchema)(i,n))return;const u=(0,Zn.allSchemaProperties)(r.properties),l=(0,Zn.allSchemaProperties)(r.patternProperties);f(),e.ok((0,je._)`${s} === ${EE.default.errors}`);function f(){t.forIn("key",o,y=>{!u.length&&!l.length?d(y):t.if(p(y),()=>d(y))})}function p(y){let $;if(u.length>8){const v=(0,Xn.schemaRefOrVal)(i,r.properties,"properties");$=(0,Zn.isOwnProperty)(t,v,y)}else u.length?$=(0,je.or)(...u.map(v=>(0,je._)`${y} === ${v}`)):$=je.nil;return l.length&&($=(0,je.or)($,...l.map(v=>(0,je._)`${(0,Zn.usePattern)(e,v)}.test(${y})`))),(0,je.not)($)}function h(y){t.code((0,je._)`delete ${o}[${y}]`)}function d(y){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){h(y);return}if(n===!1){e.setParams({additionalProperty:y}),e.error(),a||t.break();return}if(typeof n=="object"&&!(0,Xn.alwaysValidSchema)(i,n)){const $=t.name("valid");c.removeAdditional==="failing"?(m(y,$,!1),t.if((0,je.not)($),()=>{e.reset(),h(y)})):(m(y,$),a||t.if((0,je.not)($),()=>t.break()))}}function m(y,$,v){const E={keyword:"additionalProperties",dataProp:y,dataPropType:Xn.Type.Str};v===!1&&Object.assign(E,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(E,$)}}};Vr.default=OE;var ea={};Object.defineProperty(ea,"__esModule",{value:!0});const NE=Pe,ou=K,ko=P,su=Vr,_E={keyword:"properties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,parentSchema:r,data:o,it:s}=e;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&su.default.code(new NE.KeywordCxt(s,su.default,"additionalProperties"));const i=(0,ou.allSchemaProperties)(n);for(const f of i)s.definedProperties.add(f);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=ko.mergeEvaluated.props(t,(0,ko.toHash)(i),s.props));const a=i.filter(f=>!(0,ko.alwaysValidSchema)(s,n[f]));if(a.length===0)return;const c=t.name("valid");for(const f of a)u(f)?l(f):(t.if((0,ou.propertyInData)(t,o,f,s.opts.ownProperties)),l(f),s.allErrors||t.else().var(c,!0),t.endIf()),e.it.definedProperties.add(f),e.ok(c);function u(f){return s.opts.useDefaults&&!s.compositeRule&&n[f].default!==void 0}function l(f){e.subschema({keyword:"properties",schemaProp:f,dataProp:f},c)}}};ea.default=_E;var ta={};Object.defineProperty(ta,"__esModule",{value:!0});const iu=K,er=G,au=P,cu=P,kE={keyword:"patternProperties",type:"object",schemaType:"object",code(e){const{gen:t,schema:n,data:r,parentSchema:o,it:s}=e,{opts:i}=s,a=(0,iu.allSchemaProperties)(n),c=a.filter(m=>(0,au.alwaysValidSchema)(s,n[m]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;const u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=t.name("valid");s.props!==!0&&!(s.props instanceof er.Name)&&(s.props=(0,cu.evaluatedPropsToName)(t,s.props));const{props:f}=s;p();function p(){for(const m of a)u&&h(m),s.allErrors?d(m):(t.var(l,!0),d(m),t.if(l))}function h(m){for(const y in u)new RegExp(m).test(y)&&(0,au.checkStrictMode)(s,`property ${y} matches pattern ${m} (use allowMatchingProperties)`)}function d(m){t.forIn("key",r,y=>{t.if((0,er._)`${(0,iu.usePattern)(e,m)}.test(${y})`,()=>{const $=c.includes(m);$||e.subschema({keyword:"patternProperties",schemaProp:m,dataProp:y,dataPropType:cu.Type.Str},l),s.opts.unevaluated&&f!==!0?t.assign((0,er._)`${f}[${y}]`,!0):!$&&!s.allErrors&&t.if((0,er.not)(l),()=>t.break())})})}}};ta.default=kE;var na={};Object.defineProperty(na,"__esModule",{value:!0});const AE=P,jE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){const{gen:t,schema:n,it:r}=e;if((0,AE.alwaysValidSchema)(r,n)){e.fail();return}const o=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),e.failResult(o,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};na.default=jE;var ra={};Object.defineProperty(ra,"__esModule",{value:!0});const IE=K,xE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:IE.validateUnion,error:{message:"must match a schema in anyOf"}};ra.default=xE;var oa={};Object.defineProperty(oa,"__esModule",{value:!0});const hr=G,PE=P,TE={message:"must match exactly one schema in oneOf",params:({params:e})=>(0,hr._)`{passingSchemas: ${e.passing}}`},CE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:TE,code(e){const{gen:t,schema:n,parentSchema:r,it:o}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;const s=n,i=t.let("valid",!1),a=t.let("passing",null),c=t.name("_valid");e.setParams({passing:a}),t.block(u),e.result(i,()=>e.reset(),()=>e.error(!0));function u(){s.forEach((l,f)=>{let p;(0,PE.alwaysValidSchema)(o,l)?t.var(c,!0):p=e.subschema({keyword:"oneOf",schemaProp:f,compositeRule:!0},c),f>0&&t.if((0,hr._)`${c} && ${i}`).assign(i,!1).assign(a,(0,hr._)`[${a}, ${f}]`).else(),t.if(c,()=>{t.assign(i,!0),t.assign(a,f),p&&e.mergeEvaluated(p,hr.Name)})})}}};oa.default=CE;var sa={};Object.defineProperty(sa,"__esModule",{value:!0});const RE=P,ME={keyword:"allOf",schemaType:"array",code(e){const{gen:t,schema:n,it:r}=e;if(!Array.isArray(n))throw new Error("ajv implementation error");const o=t.name("valid");n.forEach((s,i)=>{if((0,RE.alwaysValidSchema)(r,s))return;const a=e.subschema({keyword:"allOf",schemaProp:i},o);e.ok(o),e.mergeEvaluated(a)})}};sa.default=ME;var ia={};Object.defineProperty(ia,"__esModule",{value:!0});const Or=G,Vd=P,DE={message:({params:e})=>(0,Or.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,Or._)`{failingKeyword: ${e.ifClause}}`},LE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:DE,code(e){const{gen:t,parentSchema:n,it:r}=e;n.then===void 0&&n.else===void 0&&(0,Vd.checkStrictMode)(r,'"if" without "then" and "else" is ignored');const o=uu(r,"then"),s=uu(r,"else");if(!o&&!s)return;const i=t.let("valid",!0),a=t.name("_valid");if(c(),e.reset(),o&&s){const l=t.let("ifClause");e.setParams({ifClause:l}),t.if(a,u("then",l),u("else",l))}else o?t.if(a,u("then")):t.if((0,Or.not)(a),u("else"));e.pass(i,()=>e.error(!0));function c(){const l=e.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);e.mergeEvaluated(l)}function u(l,f){return()=>{const p=e.subschema({keyword:l},a);t.assign(i,a),e.mergeValidEvaluated(p,i),f?t.assign(f,(0,Or._)`${l}`):e.setParams({ifClause:l})}}}};function uu(e,t){const n=e.schema[t];return n!==void 0&&!(0,Vd.alwaysValidSchema)(e,n)}ia.default=LE;var aa={};Object.defineProperty(aa,"__esModule",{value:!0});const UE=P,BE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:n}){t.if===void 0&&(0,UE.checkStrictMode)(n,`"${e}" without "if" is ignored`)}};aa.default=BE;Object.defineProperty(Hi,"__esModule",{value:!0});const FE=nn,qE=Yi,VE=rn,KE=Qi,GE=Zi,zE=Fd,JE=Xi,WE=Vr,HE=ea,YE=ta,QE=na,ZE=ra,XE=oa,eS=sa,tS=ia,nS=aa;function rS(e=!1){const t=[QE.default,ZE.default,XE.default,eS.default,tS.default,nS.default,JE.default,WE.default,zE.default,HE.default,YE.default];return e?t.push(qE.default,KE.default):t.push(FE.default,VE.default),t.push(GE.default),t}Hi.default=rS;var ca={},ua={};Object.defineProperty(ua,"__esModule",{value:!0});const ne=G,oS={message:({schemaCode:e})=>(0,ne.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,ne._)`{format: ${e}}`},sS={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:oS,code(e,t){const{gen:n,data:r,$data:o,schema:s,schemaCode:i,it:a}=e,{opts:c,errSchemaPath:u,schemaEnv:l,self:f}=a;if(!c.validateFormats)return;o?p():h();function p(){const d=n.scopeValue("formats",{ref:f.formats,code:c.code.formats}),m=n.const("fDef",(0,ne._)`${d}[${i}]`),y=n.let("fType"),$=n.let("format");n.if((0,ne._)`typeof ${m} == "object" && !(${m} instanceof RegExp)`,()=>n.assign(y,(0,ne._)`${m}.type || "string"`).assign($,(0,ne._)`${m}.validate`),()=>n.assign(y,(0,ne._)`"string"`).assign($,m)),e.fail$data((0,ne.or)(v(),E()));function v(){return c.strictSchema===!1?ne.nil:(0,ne._)`${i} && !${$}`}function E(){const b=l.$async?(0,ne._)`(${m}.async ? await ${$}(${r}) : ${$}(${r}))`:(0,ne._)`${$}(${r})`,O=(0,ne._)`(typeof ${$} == "function" ? ${b} : ${$}.test(${r}))`;return(0,ne._)`${$} && ${$} !== true && ${y} === ${t} && !${O}`}}function h(){const d=f.formats[s];if(!d){v();return}if(d===!0)return;const[m,y,$]=E(d);m===t&&e.pass(b());function v(){if(c.strictSchema===!1){f.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function E(O){const j=O instanceof RegExp?(0,ne.regexpCode)(O):c.code.formats?(0,ne._)`${c.code.formats}${(0,ne.getProperty)(s)}`:void 0,C=n.scopeValue("formats",{key:s,ref:O,code:j});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,ne._)`${C}.validate`]:["string",O,C]}function b(){if(typeof d=="object"&&!(d instanceof RegExp)&&d.async){if(!l.$async)throw new Error("async format in sync schema");return(0,ne._)`await ${$}(${r})`}return typeof y=="function"?(0,ne._)`${$}(${r})`:(0,ne._)`${$}.test(${r})`}}}};ua.default=sS;Object.defineProperty(ca,"__esModule",{value:!0});const iS=ua,aS=[iS.default];ca.default=aS;var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0});Xt.contentVocabulary=Xt.metadataVocabulary=void 0;Xt.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Xt.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"];Object.defineProperty(Ci,"__esModule",{value:!0});const cS=Ri,uS=Di,lS=Hi,fS=ca,lu=Xt,dS=[cS.default,uS.default,(0,lS.default)(),fS.default,lu.metadataVocabulary,lu.contentVocabulary];Ci.default=dS;var la={},Kr={};Object.defineProperty(Kr,"__esModule",{value:!0});Kr.DiscrError=void 0;var fu;(function(e){e.Tag="tag",e.Mapping="mapping"})(fu||(Kr.DiscrError=fu={}));Object.defineProperty(la,"__esModule",{value:!0});const Bt=G,vs=Kr,du=we,pS=tn,hS=P,mS={message:({params:{discrError:e,tagName:t}})=>e===vs.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:t,tagName:n}})=>(0,Bt._)`{error: ${e}, tag: ${n}, tagValue: ${t}}`},gS={keyword:"discriminator",type:"object",schemaType:"object",error:mS,code(e){const{gen:t,data:n,schema:r,parentSchema:o,it:s}=e,{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=t.let("valid",!1),u=t.const("tag",(0,Bt._)`${n}${(0,Bt.getProperty)(a)}`);t.if((0,Bt._)`typeof ${u} == "string"`,()=>l(),()=>e.error(!1,{discrError:vs.DiscrError.Tag,tag:u,tagName:a})),e.ok(c);function l(){const h=p();t.if(!1);for(const d in h)t.elseIf((0,Bt._)`${u} === ${d}`),t.assign(c,f(h[d]));t.else(),e.error(!1,{discrError:vs.DiscrError.Mapping,tag:u,tagName:a}),t.endIf()}function f(h){const d=t.name("valid"),m=e.subschema({keyword:"oneOf",schemaProp:h},d);return e.mergeEvaluated(m,Bt.Name),d}function p(){var h;const d={},m=$(o);let y=!0;for(let b=0;b<i.length;b++){let O=i[b];if(O!=null&&O.$ref&&!(0,hS.schemaHasRulesButRef)(O,s.self.RULES)){const C=O.$ref;if(O=du.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,C),O instanceof du.SchemaEnv&&(O=O.schema),O===void 0)throw new pS.default(s.opts.uriResolver,s.baseId,C)}const j=(h=O==null?void 0:O.properties)===null||h===void 0?void 0:h[a];if(typeof j!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(m||$(O)),v(j,b)}if(!y)throw new Error(`discriminator: "${a}" must be required`);return d;function $({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,O){if(b.const)E(b.const,O);else if(b.enum)for(const j of b.enum)E(j,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function E(b,O){if(typeof b!="string"||b in d)throw new Error(`discriminator: "${a}" values must be unique strings`);d[b]=O}}}};la.default=gS;const yS="http://json-schema.org/draft-07/schema#",$S="http://json-schema.org/draft-07/schema#",vS="Core schema meta-schema",wS={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:[]}},bS=["object","boolean"],ES={$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:"#"}},SS={$schema:yS,$id:$S,title:vS,definitions:wS,type:bS,properties:ES,default:!0};(function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.MissingRefError=t.ValidationError=t.CodeGen=t.Name=t.nil=t.stringify=t.str=t._=t.KeywordCxt=t.Ajv=void 0;const n=qf,r=Ci,o=la,s=SS,i=["/properties"],a="http://json-schema.org/draft-07/schema";class c extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(d=>this.addVocabulary(d)),this.opts.discriminator&&this.addKeyword(o.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;const d=this.opts.$data?this.$dataMetaSchema(s,i):s;this.addMetaSchema(d,a,!1),this.refs["http://json-schema.org/schema"]=a}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(a)?a:void 0)}}t.Ajv=c,e.exports=t=c,e.exports.Ajv=c,Object.defineProperty(t,"__esModule",{value:!0}),t.default=c;var u=Pe;Object.defineProperty(t,"KeywordCxt",{enumerable:!0,get:function(){return u.KeywordCxt}});var l=G;Object.defineProperty(t,"_",{enumerable:!0,get:function(){return l._}}),Object.defineProperty(t,"str",{enumerable:!0,get:function(){return l.str}}),Object.defineProperty(t,"stringify",{enumerable:!0,get:function(){return l.stringify}}),Object.defineProperty(t,"nil",{enumerable:!0,get:function(){return l.nil}}),Object.defineProperty(t,"Name",{enumerable:!0,get:function(){return l.Name}}),Object.defineProperty(t,"CodeGen",{enumerable:!0,get:function(){return l.CodeGen}});var f=Un;Object.defineProperty(t,"ValidationError",{enumerable:!0,get:function(){return f.default}});var p=tn;Object.defineProperty(t,"MissingRefError",{enumerable:!0,get:function(){return p.default}})})(ds,ds.exports);var OS=ds.exports;const NS=Gy(OS);class Kd 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 _S(e,t){if(!t)return;const n=t,r=n.properties;if(r!==void 0&&Object.keys(r).length===0)return;const o=new NS({allErrors:!0,strict:!1}).compile(n);if(!o(e))throw new Kd(kS(o.errors??[]))}function kS(e){return e.map(t=>({field:AS(t),message:t.message??"is invalid",keyword:t.keyword}))}function AS(e){var t;return(e.instancePath??"").replace(/^\//,"").replace(/\//g,".")||(((t=e.params)==null?void 0:t.missingProperty)??"(root)")}function jS(e,t){return T.join(Jl(e,t),tv)}const IS=384,xS=448;function PS(e,t,n={}){const r=n.mode??IS,o=n.dirMode??xS,s=T.dirname(e);L.mkdirSync(s,{recursive:!0,mode:o}),L.chmodSync(s,o);const i=`${e}.tmp`,a=typeof t=="string"?t:JSON.stringify(t,null,2);try{L.writeFileSync(i,a,{encoding:"utf8",mode:r}),L.chmodSync(i,r),L.renameSync(i,e),L.chmodSync(e,r)}catch(c){try{L.existsSync(i)&&L.unlinkSync(i)}catch{}throw c}}const TS="0.1.0";function pu(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 CS(){return`${process.pid}-${Mn.randomBytes(3).toString("hex")}`}function Gd(e,t,n={}){if(!e)throw new Error("Environment requires a non-empty 'project' name");pu(e,"project");const r=t.orgNamespace??X$,o=t.envPrefixOverride??iv(e),s=t.namespaces&&t.namespaces.length>0?t.namespaces:[ev],i=n.namespace??s[0];if(!s.includes(i))throw new Error(`Namespace "${i}" is not declared for project "${e}" (declared: ${s.join(", ")})`);pu(i,"namespace");const a=n.processEnv??process.env,{scope:c,projectRoot:u}=qy({scope:n.scope,cwd:n.cwd},a),l=Ky({project:e,namespace:i,orgNamespace:r,projectRoot:u,adhdRoot:n.adhdRoot});return{project:e,namespace:i,orgNamespace:r,envPrefix:o,scope:c,projectRoot:u,roots:l}}function RS(e,t,n={}){const{namespace:r,orgNamespace:o,envPrefix:s,scope:i,projectRoot:a,roots:c}=Gd(e,t,n),u=n.processEnv??process.env,l=gv(c),f=n.instanceId??CS(),{raw:p,nested:h,typedRaw:d,provenance:m,fields:y}=vv(t.config,l,u,{prefix:s,activeScope:i}),$={};for(const O of Object.keys(y)){const j=y[O];j.live&&($[O]={env:j.env,type:j.type,fallback:j.secret===!0?void 0:j.fallbackValue})}const v=cv(t.config);_S(Ff(d),v);const E=bv(t.dirs,{roots:c,activeScope:i,instanceId:f,projectRoot:a,namespace:r}),b=Ev(t.files,E);return{version:Z$,libraryVersion:TS,generatedAt:new Date().toISOString(),project:e,namespace:r,orgNamespace:o,envPrefix:s,scope:i,instanceId:f,config:h,raw:p,liveFields:$,fieldSchema:v,configHash:ov(Object.fromEntries(Object.entries(d).map(([O,j])=>[O,String(j)]))),structureHash:sv(Object.values(E).map(O=>({name:O.name,kind:O.kind,scope:O.scope}))),dirs:Object.values(E),files:Object.values(b),provenance:m}}let In=class extends Error{constructor(t){super(t),this.name="EnvironmentError"}};class MS extends In{constructor(t){super(`adhd-environment snapshot not found: ${t}`),this.snapshotPath=t,this.name="SnapshotNotFoundError"}}class DS extends In{constructor(t,n){super(`lock "${t}" is already held (${n})`),this.lockName=t,this.lockPath=n,this.name="LockHeldError"}}function LS(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 ws(e){if(e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(n=>ws(n));const t={};for(const[n,r]of Object.entries(e))t[n]=ws(r);return t}function US(e,t){const n=ws(e);for(const r of Object.keys(t)){const o=t[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?fs(c,o.type):o.fallback}})}return n}function BS(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw new In(`lock name must be a non-empty path segment with no path separators: ${JSON.stringify(e)}`)}class fa{constructor(t,n,r={}){let o,s;try{o=RS(t,n,r);const i=Gd(t,n,r);s=jS(i.roots,o.scope)}catch(i){throw i instanceof Kd||i instanceof In?i:new In(i instanceof Error?i.message:String(i))}return hu(this,o,s)}static fromSnapshot(t){if(!L.existsSync(t))throw new MS(t);const n=JSON.parse(L.readFileSync(t,"utf8")),r=Object.create(fa.prototype);return hu(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 LS(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"){BS(t);const n=this.paths.run??this._runDirFallback();L.mkdirSync(n,{recursive:!0});const r=T.join(n,`${t}.lock`);let o;try{o=L.openSync(r,"wx")}catch(i){throw(i==null?void 0:i.code)==="EEXIST"?new DS(t,r):i}L.writeSync(o,`${process.pid}
|
|
163
163
|
${this.instanceId}
|
|
164
|
-
`),L.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{L.unlinkSync(r)}catch{}}}}_runDirFallback(){return T.join(T.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))L.mkdirSync(t,{recursive:!0})}write(){return jS(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function pu(e,t,n){const r={};for(const i of t.dirs)r[i.name]=i.path;const o={};for(const i of t.files)o[i.name]=i.path;const s=MS(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:s,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:t,enumerable:!1}}),new Proxy(e,{get(i,a,c){return typeof a=="string"&&!(a in i)?i.get(a):Reflect.get(i,a,c)}})}const Vd={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production"],dirs:{data:{kind:"data"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"SQLite 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:"SQLite `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"]},"migration.phase":{type:"string",env:"ADHD_BACKLOG_MIGRATION_PHASE",default:"not-started",enum:["not-started","phase-1","phase-2","phase-3","phase-4","phase-5","complete"],description:"MIGRATION.md §4.4 — a queried signal (never hardcoded prose) for whether BACKLOG.md or the tool is authoritative right now. Read via `migrationStatus(ctx)`/`backlog migration-status`. NOT yet per-repo-keyed (MIGRATION.md §9 open decision 6) — one global value."}}};function Kd(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 da(e={}){const t={namespace:"production",scope:Kd(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 fa("backlog",Vd,t)}function LS(e,t){return`${e}:${t}`}const Gd=Symbol.for("adhd.apigen.extraction-session");function zd(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{}zd(r,t)}}}function Jd(e){try{const t=L.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const mr=new Map,hu=new Map;function US(e,t,n){const r=t??"",o=mr.get(r);let s=n;if(o&&o.fileVersions.size>0){const c=[n],u=[...o.fileVersions.entries()].sort(([l],[f])=>l.localeCompare(f));for(const[l,f]of u)l!==e&&c.push(`${l}:${f}`);s=c.join("|")}const i=`${e}\0${t??""}`;let a=hu.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},hu.set(i,a)),a.schemas}function BS(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[Gd]:!0,stats:e,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=mr.get(o);return i&&i.tsconfigVersion!==s&&(i=void 0),i||(i={project:r?new Sn.Project({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new Sn.Project({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},mr.set(o,i),e.projectsBuilt++),i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=mr.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]);zd(c,u);for(const l of u)l!==r&&i.fileVersions.set(l,this.statVersion(l))}return c},statVersion(r){let o=t.get(r);return o===void 0&&(o=Jd(r),t.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function FS(e){const t=e;if(t[Gd]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const Nr="x-apigen-logical";function mu(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 s=o.$ref;if(typeof s=="string"){if(t){const f=t[s];if(!f){const p=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${s}" cannot be resolved. Available $defs: ${p}`)}r.push(f)}continue}const i=o.oneOf;if(Array.isArray(i))for(const f of i)typeof f=="object"&&f!==null&&r.push(f);const a=o.properties;if(a)for(const f of Object.values(a))r.push(f);const c=o.items;if(Array.isArray(c))for(const f of c)typeof f=="object"&&f!==null&&r.push(f);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 gu=new Set(["string","number","boolean","integer"]);function qS(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"?gu.has(n):Array.isArray(n)?n.every(r=>gu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function VS(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(qS)}function KS(e){const t={},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}`;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{mu(o.input,t),mu(o.output,t)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function GS(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 zS(e,t,n){KS(e);const r={};for(const[o,s]of Object.entries(e.schemas)){const i={},a=s.input.properties??{},c=s.input.required??[],u={},l=[],f={};for(const y of t)if(y.envelope&&i[y.id]!==!1)for(const[$,v]of Object.entries(y.envelope))u[$]=v,f[$]=y.id,l.includes($)||l.push($);const p={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},h=s.safe===!0||VS(s.input),d=s.input.definitions,g=s.input.$defs;r[o]={input:{type:"object",properties:{...u,data:p},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:GS(Object.keys(u),Object.keys(a).length>0),...d?{definitions:d}:{},...g?{$defs:g}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":h,...Object.keys(f).length>0?{"x-apigen-envelope":f}:{}}}return r}const JS=8;function HS(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let WS=0;async function YS(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${WS++}`;let s;try{s=t.addTypeAlias({name:o,type:n});const i=s.getType();return await r(i)}catch{return}finally{try{s==null||s.remove()}catch{}}}async function Hd(e,t,n){if(n>JS)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"};if(e.isNull()||e.isUndefined()||e.isVoid())return{type:"null"};if(e.isUnion()){const r=e.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=>Hd(i,t,n+1))),s=pa(o);return{oneOf:o,...s?{discriminator:s}:{},[Nr]:"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(s=>t(s.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const r=e.getStringIndexType(),o=e.getNumberIndexType(),s=r??o,i=e.getProperties();if(s&&i.length===0)return{type:"object",additionalProperties:await t(s.getText())};const a={},c=[];for(const u of i){const l=u.getName(),f=u.getDeclarations()[0];let p;if(f)try{p=u.getTypeAtLocation(f)}catch{p=void 0}if(p!==void 0&&p.getCallSignatures().length>0)continue;const h=p!==void 0?HS(p,f):void 0;a[l]=h!==void 0?await t(h):{},u.isOptional()||c.push(l)}return Object.keys(a).length>0?{type:"object",properties:a,...c.length>0?{required:c}:{}}:{}}return{}}function pa(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 s=!0;for(const a of t){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 gr(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=ws[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=ws[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:gr(r.slice(0,-2),t+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=>gr(c,t+1,n)),a=pa(i);return{oneOf:i,...a?{discriminator:a}:{},[Nr]:"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("?","")]=gr(u,t+1,n))}return{type:"object",properties:i}}return{}}function Wd(e){const t=[];let n=0,r=0;for(let s=0;s<e.length;s++){const i=e[s];i==="<"||i==="["||i==="{"||i==="("?n++:i===">"||i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,s).trim()),r=s+1)}const o=e.slice(r).trim();return o.length>0&&t.push(o),t}function QS(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function ZS(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function XS(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 Wd(n)}async function eO(e,t){const n=e.trim(),r=QS(n);if(r!==void 0){const i=Wd(r);if(i.length===2){const[a,c]=await Promise.all([t(i[0]),t(i[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=ZS(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const s=XS(n);if(s!==void 0){const i=await Promise.all(s.map(a=>t(a)));return{type:"array",items:i,minItems:i.length,maxItems:i.length}}}const Yd={"decimal.js":"Decimal"},ws={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"}},yu={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function $u(e){var t;const n=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=Yd[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=((t=a.getAliasNode())==null?void 0:t.getText())??a.getName();c!==s&&n.set(c,s)}}return n}function tO(e,t){return n=>{n.addNodeParser({supportsNode(r){var o,s,i;if(r.kind!==t)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(yu,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);return new wt.AnnotatedType(new wt.StringType,{format:yu[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){return new wt.AnnotatedType(new wt.StringType,{format:"int64"},!1)}})}}let un;function nO(){if(un)return un;try{const e=T.dirname(require.resolve("ts-json-schema-generator/package.json"));un=require(require.resolve("typescript",{paths:[e]}))}catch{un=require("typescript")}return un}const nt=new Map;function rO(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function oO(e){const t=nt.get(e);return t&&(nt.delete(e),nt.set(e,t)),t}function sO(e,t){const n=rO();if(n!==0)for(nt.delete(e),nt.set(e,t);nt.size>n;){const r=nt.keys().next().value;nt.delete(r)}}function iO(e,t){return`${e}\0${t??""}`}const aO=new Set(["zod",/^zod\/./]);function cO(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of aO)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function uO(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(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]}bs(e)}function bs(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&&bs(o,n);else bs(r,n)}}function lO(e){const t=new Set;for(const r of["$defs","definitions"]){const o=e[r];if(o&&typeof o=="object")for(const s of Object.keys(o))t.add(s)}const n=Es(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 Es(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 s=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);s&&!t.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(...Es(s,t));else n.push(...Es(o,t));return n}function fO(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=pa(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[Nr]:o[Nr]??"union"}}function dO(e,t,n){const{DEFAULT_CONFIG:r}=require("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},s=o.path,i=iO(s,o.tsconfig);let a;a=n?n.statVersion(s):Jd(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??oO(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=require("ts-json-schema-generator/dist/factory/program.js"),f=nO(),p=tO(f.SyntaxKind.BigIntKeyword,f.SyntaxKind.TypeReference),h=l(o),d=wt.createParser(h,o,p),g=wt.createFormatter(o);if(c=new wt.SchemaGenerator(h,d,g,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const y={version:a,gen:c};sO(i,y),n==null||n.generatorCache.set(i,y)}}const u=c.createSchema(o.type);return uO(u),lO(u),u}function pO(e,t){let n=e.trim();if(n=Zd(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 Qd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const hO=Object.entries(Yd).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Qd(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Zd(e){let t=e;for(const{pattern:n,key:r}of hO)t=t.replace(n,r);return t}function mO(e,t){let n=Zd(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${Qd(r)}\\b`,"g"),o);return n}async function xn(e,t,n,r,o,s){const i=t.getFilePath(),a=`${i}\0${r??""}\0${n}`,c=s??new Set;if(c.has(a))return{};if(!o){const d=new Set(c);return d.add(a),vu(e,t,n,r,void 0,d)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=US(i,r,o.statVersion(i)),f=l.get(n);if(f!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(f)),f;o.stats.schemaCacheMisses++;const p=new Set(c);p.add(a);const h=vu(e,t,n,r,o,p).then(d=>(l.set(n,d),d)).catch(d=>{throw o.schemaCache.delete(a),d});return o.schemaCache.set(a,h),h}async function vu(e,t,n,r,o,s){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let i;if(o){const p=o.aliasCache.get(t);i=p??$u(t),p||o.aliasCache.set(t,i)}else i=$u(t);const a=pO(n,i),c=ws[a];if(c!==void 0)return c;const u=await eO(a,p=>xn(e,t,p,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(t))??cO(t);if(o&&o.zodImportCache.set(t,l),!l)try{const p={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},h=dO(p,!0,o);return fO(h)}catch{}try{const p=await YS(e,t,a,h=>Hd(h,d=>xn(e,t,d,r,o,s),0));if(p!==void 0)return p}catch{}const f=mO(a,i);return gr(f,0,i)}function ha(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return gO(n,t)}function gO(e,t){var n;const r=e,o=((n=r==null?void 0:r.getJsDocs)==null?void 0:n.call(r))??[],s=t.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 yO(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 $O(e,t){const n=yO(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})`}function Gr(e){try{if(!e||e.getKind()!==Sn.SyntaxKind.TypeReference)return;const t=e;if(t.getTypeArguments().length>0)return;const n=t.getTypeName();if(n.getKind()!==Sn.SyntaxKind.Identifier)return;const r=n.getSymbol();if(!r)return;const o=r.getDeclarations().find(c=>c.getKindName()==="TypeAliasDeclaration");if(!o)return;const s=o,i=s.getType();if(!(i.isString()||i.isNumber()||i.isBoolean()))return;const a=s.getJsDocs();for(const c of a)for(const u of c.getTags())if(u.getTagName()==="format"){const l=u.getCommentText();if(l!==void 0)return l.trim()}return}catch{return}}async function vO(e){const t=e.session===void 0,n=FS(e.session??BS());try{return await wO(e,n)}finally{t&&n.dispose()}}async function wO(e,t){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:s}=e,i=t.projectFor(s),a=t.sourceFileFor(n,s),c=T.basename(n),u=Ve(OO(c)),l=o?null:u,f=Ve(r),p=[];for(const[g,y]of a.getExportedDeclarations()){if(g==="default"||nr(g))continue;const $=_O(y);if($){const O=$.getSignature(),j=bu(O,$),C=O.getReturnType().getText(),z=dt(O);p.push(await tr(i,a,f,l,g,j,C,$.isAsync(),s,t,z));continue}const v=y.find(O=>O.getKindName()==="VariableDeclaration");if(!v)continue;const E=v.getInitializer(),b=E==null?void 0:E.getKindName();if(E&&["ArrowFunction","FunctionExpression"].includes(b??"")){const O=v.getType().getCallSignatures();if(O.length===0)continue;const j=O[0],C=Eu(j,v,v.getVariableStatement()),z=j.getReturnType().getText(),U=dt(j),q=E.isAsync();p.push(await tr(i,a,f,l,g,C,z,q,s,t,U))}else if(b==="ObjectLiteralExpression"){const O=v.getType();for(const j of O.getProperties()){const C=j.getName();if(nr(C))continue;const z=j.getTypeAtLocation(v).getCallSignatures();if(z.length===0)continue;const U=z[0],q=Eu(U,v,v.getVariableStatement()),Q=U.getReturnType().getText(),Z=dt(U),me=[...l?[l]:[],Ve(g),Ve(C)];p.push(await yr(i,a,f,me,C,q,Q,!1,s,t,Z))}}else{const O=v.getType(),j=O.getText();if(gt(O,v)){const C=await xn(i,a,j,s,t);p.push(EO(f,l,g,C))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${g}`)}}const h=a.getDefaultExportSymbol();if(h){const g=a.getExportAssignment(y=>!y.isExportEquals());if(g){const y=g.getExpression(),$=y.getKindName();if(["ArrowFunction","FunctionExpression"].includes($)){const v=y.getType().getCallSignatures();if(v.length>0){const E=v[0],b=Ao(E,g),O=E.getReturnType().getText(),j=dt(E),C=y.isAsync();p.push(await tr(i,a,f,l,"default",b,O,C,s,t,j))}}else{const v=y.getType();for(const E of v.getProperties()){const b=E.getName();if(nr(b))continue;const O=E.getTypeAtLocation(g).getCallSignatures();if(O.length===0)continue;const j=O[0],C=Ao(j,g),z=j.getReturnType().getText(),U=dt(j),q=[...l?[l]:[],Ve("default"),Ve(b)];p.push(await yr(i,a,f,q,b,C,z,!1,s,t,U))}}}else{const y=h.getDeclarations();for(const $ of y){if($.getKindName()!=="FunctionDeclaration")continue;const v=$,E=v.getName(),b=E&&E.length>0?E:"default",O=v.getSignature(),j=bu(O,v),C=O.getReturnType().getText(),z=dt(O);p.push(await tr(i,a,f,l,b,j,C,v.isAsync(),s,t,z))}}}const d=NO(a);if(d.length>0)for(const{name:g,sig:y}of d){if(nr(g))continue;const $=Ao(y),v=y.getReturnType().getText(),E=dt(y),b=[...l?[l]:[],Ve(g)];p.push(await yr(i,a,f,b,g,$,v,!1,s,t,E))}return p}function bO(e,t,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 f=u,p=t[f];for(const[h,d]of Object.entries(l)){const g=s(d),y=p[h];if(y!==void 0&&JSON.stringify(y)!==JSON.stringify(g))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${f}.${h}" 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.`);p[h]=g}continue}c[u]=s(l)}return c}finally{o.delete(i)}};return s(e)}function wu(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 dt(e){var t;try{return Gr((t=e.getDeclaration())==null?void 0:t.getReturnTypeNode())}catch{return}}async function tr(e,t,n,r,o,s,i,a,c,u,l){const f=Ve(o);return yr(e,t,n,r?[r,f]:[f],o,s,i,a,c,u,l)}async function yr(e,t,n,r,o,s,i,a,c,u,l){const f=s.length>0&&s[0].name==="ctx",p=s.filter(b=>b.name!=="ctx"),h=p.filter(b=>!b.optional).map(b=>b.name),d={},g={definitions:{},$defs:{}};for(const b of p){const O=await xn(e,t,b.type,c,u),j=bO(O,g,o,b.name);b.defaultValue!==void 0&&$O(j,b.defaultValue),wu(j,b.format),d[b.name]=j}const y=i.replace(/^Promise<(.+)>$/,"$1").trim(),$=await xn(e,t,y,c,u),v=l?{...$}:$;wu(v,l);const E={type:"object",properties:d,required:h,...Object.keys(g.definitions).length>0?{definitions:g.definitions}:{},...Object.keys(g.$defs).length>0?{$defs:g.$defs}:{}};return{id:Xd(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:!1,safe:!1,input:E,output:v,envelope:{},typeText:{lang:"ts",input:kO(s),output:y},...f?{hasCtx:!0}:{}}}function EO(e,t,n,r){const o=Ve(n),s=t?[t,o]:[o];return{id:Xd(e,s),host:"ts",namespace:e,path:s,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function Xd(e,t){return(e.raw?[e,...t]:t).map(n=>n.words.join("-")).join("/")}function SO(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 Ve(e){return{raw:e,words:SO(e)}}function OO(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function NO(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(),i=s.getType();for(const a of i.getProperties()){const c=a.getTypeAtLocation(s).getCallSignatures();c.length!==0&&t.push({name:a.getName(),sig:c[0]})}}return t}function _O(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 bu(e,t){return e.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(e.getDeclaration()).getText(),optional:i,defaultValue:ha(s,n.getName(),t),format:Gr(s==null?void 0:s.getTypeNode())}})}function Eu(e,t,n){return e.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(t).getText(),optional:a,defaultValue:ha(i,r.getName(),n??t),format:Gr(i==null?void 0:i.getTypeNode())}})}function Ao(e,t){return e.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:ha(a,n.getName(),t),format:Gr(a==null?void 0:a.getTypeNode())}})}function kO(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function nr(e){return!!(e==="__samples__"||e.startsWith("__"))}function gt(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?gt(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>gt(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>gt(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>gt(r,t,n));if(e.isObject()){const r=e.getText(t);if(n.has(r))return!0;n.add(r);const o=e.getStringIndexType(),s=e.getNumberIndexType();if(o||s)return[o,s].every(a=>!a||gt(a,t,n));const i=e.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(t);return gt(c,t,n)})}return!1}function AO(e,t){return async n=>{let r=()=>t(n);for(let o=e.length-1;o>=0;o--){const s=e[o],i=r;r=()=>s(n,i)}return r()}}function jO(e,t){return AO(e,t)}function IO(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 jO(r,t)}function ep(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{}ep(r,t)}}}let jo;function xO(){return jo||(jo=new Sn.Project({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})),jo}function tp(e){const t=xO(),n=t.getSourceFile(e),r=n??t.addSourceFileAtPath(e);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([e]);return ep(r,o),[...o].sort()}const PO={"decimal.js":"Decimal"};function TO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(PO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${TO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));async function CO(e,t){await bt.mkdir(T.dirname(e),{recursive:!0});const n=`${e}.${process.pid}.${Mn.randomUUID()}.tmp`;try{await bt.writeFile(n,JSON.stringify(t),"utf8"),await bt.rename(n,e)}catch(r){throw await bt.unlink(n).catch(()=>{}),r}}function RO(e){return{async get(){try{const t=await bt.readFile(e,"utf8");return JSON.parse(t)}catch{return}},async put(t,n){await CO(e,n)}}}const Ss=1;function MO(e){return Mn.createHash("sha256").update(e).digest("hex")}async function Su(e){return MO(await bt.readFile(e,"utf8"))}async function _r(e){try{return(await bt.stat(e)).mtimeMs}catch{return}}async function Ou(e,t){const n=await Su(e.source),r=Mn.createHash("sha256");r.update(`formatVersion:${Ss}
|
|
164
|
+
`),L.closeSync(o);let s=!1;return()=>{if(!s){s=!0;try{L.unlinkSync(r)}catch{}}}}_runDirFallback(){return T.join(T.dirname(this.snapshotPath),"run")}ensureDirs(){for(const t of Object.values(this.paths))L.mkdirSync(t,{recursive:!0})}write(){return PS(this.snapshotPath,this._data),this.snapshotPath}toJSON(){return Object.freeze(JSON.parse(JSON.stringify(this._data)))}}function hu(e,t,n){const r={};for(const i of t.dirs)r[i.name]=i.path;const o={};for(const i of t.files)o[i.name]=i.path;const s=US(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:s,enumerable:!0},paths:{value:r,enumerable:!0},files:{value:o,enumerable:!0},_data:{value:t,enumerable:!1}}),new Proxy(e,{get(i,a,c){return typeof a=="string"&&!(a in i)?i.get(a):Reflect.get(i,a,c)}})}const zd={envPrefixOverride:"ADHD_BACKLOG",namespaces:["production"],dirs:{data:{kind:"data"}},files:{db:{in:"data",name:"backlog.db"}},config:{"db.path":{type:"string",env:"ADHD_BACKLOG_DATABASE_PATH",description:"SQLite 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:"SQLite `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"]},"migration.phase":{type:"string",env:"ADHD_BACKLOG_MIGRATION_PHASE",default:"not-started",enum:["not-started","phase-1","phase-2","phase-3","phase-4","phase-5","complete"],description:"MIGRATION.md §4.4 — a queried signal (never hardcoded prose) for whether BACKLOG.md or the tool is authoritative right now. Read via `migrationStatus(ctx)`/`backlog migration-status`. NOT yet per-repo-keyed (MIGRATION.md §9 open decision 6) — one global value."}}};function Jd(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 da(e={}){const t={namespace:"production",scope:Jd(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 fa("backlog",zd,t)}function pa(e){return e.config.db.path??e.files.db}function FS(e,t){return`${e}:${t}`}const Wd=Symbol.for("adhd.apigen.extraction-session");function Hd(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{}Hd(r,t)}}}function Yd(e){try{const t=L.statSync(e);return`${t.mtimeMs}:${t.size}`}catch{return"nostat"}}const mr=new Map,mu=new Map;function qS(e,t,n){const r=t??"",o=mr.get(r);let s=n;if(o&&o.fileVersions.size>0){const c=[n],u=[...o.fileVersions.entries()].sort(([l],[f])=>l.localeCompare(f));for(const[l,f]of u)l!==e&&c.push(`${l}:${f}`);s=c.join("|")}const i=`${e}\0${t??""}`;let a=mu.get(i);return(!a||a.version!==s)&&(a={version:s,schemas:new Map},mu.set(i,a)),a.schemas}function VS(){const e={projectsBuilt:0,generatorsBuilt:0,schemaCacheHits:0,schemaCacheMisses:0},t=new Map;let n=!1;return{[Wd]:!0,stats:e,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=mr.get(o);return i&&i.tsconfigVersion!==s&&(i=void 0),i||(i={project:r?new Sn.Project({tsConfigFilePath:r,skipAddingFilesFromTsConfig:!0}):new Sn.Project({skipAddingFilesFromTsConfig:!0}),tsconfigVersion:s,fileVersions:new Map},mr.set(o,i),e.projectsBuilt++),i.project},sourceFileFor(r,o){const s=this.projectFor(o),i=mr.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]);Hd(c,u);for(const l of u)l!==r&&i.fileVersions.set(l,this.statVersion(l))}return c},statVersion(r){let o=t.get(r);return o===void 0&&(o=Yd(r),t.set(r,o)),o},dispose(){n=!0,this.schemaCache.clear(),this.generatorCache.clear(),t.clear()}}}function KS(e){const t=e;if(t[Wd]!==!0)throw new Error("apigen-core: unknown ExtractionSession implementation — create sessions with createExtractionSession()");return t}const Nr="x-apigen-logical";function gu(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 s=o.$ref;if(typeof s=="string"){if(t){const f=t[s];if(!f){const p=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${s}" cannot be resolved. Available $defs: ${p}`)}r.push(f)}continue}const i=o.oneOf;if(Array.isArray(i))for(const f of i)typeof f=="object"&&f!==null&&r.push(f);const a=o.properties;if(a)for(const f of Object.values(a))r.push(f);const c=o.items;if(Array.isArray(c))for(const f of c)typeof f=="object"&&f!==null&&r.push(f);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 yu=new Set(["string","number","boolean","integer"]);function GS(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"?yu.has(n):Array.isArray(n)?n.every(r=>yu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function zS(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(GS)}function JS(e){const t={},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}`;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{gu(o.input,t),gu(o.output,t)}catch(s){throw new Error(`[apigen-core-client] Schema validation failed for function "${r}": ${s.message}`)}}function WS(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 HS(e,t,n){JS(e);const r={};for(const[o,s]of Object.entries(e.schemas)){const i={},a=s.input.properties??{},c=s.input.required??[],u={},l=[],f={};for(const y of t)if(y.envelope&&i[y.id]!==!1)for(const[$,v]of Object.entries(y.envelope))u[$]=v,f[$]=y.id,l.includes($)||l.push($);const p={type:"object",properties:a,additionalProperties:!1,...c.length>0?{required:c}:{}},h=s.safe===!0||zS(s.input),d=s.input.definitions,m=s.input.$defs;r[o]={input:{type:"object",properties:{...u,data:p},required:[...l,...c.length>0?["data"]:[]],additionalProperties:!1,description:WS(Object.keys(u),Object.keys(a).length>0),...d?{definitions:d}:{},...m?{$defs:m}:{}},output:s.output,...s.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":h,...Object.keys(f).length>0?{"x-apigen-envelope":f}:{}}}return r}const YS=8;function QS(e,t){try{return t?e.getText(t):e.getText()}catch{try{return e.getText()}catch{return}}}let ZS=0;async function XS(e,t,n,r){const o=`__ApigenProbe_${process.pid}_${ZS++}`;let s;try{s=t.addTypeAlias({name:o,type:n});const i=s.getType();return await r(i)}catch{return}finally{try{s==null||s.remove()}catch{}}}async function Qd(e,t,n){if(n>YS)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"};if(e.isNull()||e.isUndefined()||e.isVoid())return{type:"null"};if(e.isUnion()){const r=e.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=>Qd(i,t,n+1))),s=ha(o);return{oneOf:o,...s?{discriminator:s}:{},[Nr]:"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(s=>t(s.getText())));return{type:"array",items:o,minItems:o.length,maxItems:o.length}}if(e.isObject()){const r=e.getStringIndexType(),o=e.getNumberIndexType(),s=r??o,i=e.getProperties();if(s&&i.length===0)return{type:"object",additionalProperties:await t(s.getText())};const a={},c=[];for(const u of i){const l=u.getName(),f=u.getDeclarations()[0];let p;if(f)try{p=u.getTypeAtLocation(f)}catch{p=void 0}if(p!==void 0&&p.getCallSignatures().length>0)continue;const h=p!==void 0?QS(p,f):void 0;a[l]=h!==void 0?await t(h):{},u.isOptional()||c.push(l)}return Object.keys(a).length>0?{type:"object",properties:a,...c.length>0?{required:c}:{}}:{}}return{}}function ha(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 s=!0;for(const a of t){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 gr(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=bs[r];if(o!==void 0)return o;if(n!=null&&n.size){const s=n.get(r);if(s!==void 0){const i=bs[s];if(i!==void 0)return i}}if(r.endsWith("[]"))return{type:"array",items:gr(r.slice(0,-2),t+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=>gr(c,t+1,n)),a=ha(i);return{oneOf:i,...a?{discriminator:a}:{},[Nr]:"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("?","")]=gr(u,t+1,n))}return{type:"object",properties:i}}return{}}function Zd(e){const t=[];let n=0,r=0;for(let s=0;s<e.length;s++){const i=e[s];i==="<"||i==="["||i==="{"||i==="("?n++:i===">"||i==="]"||i==="}"||i===")"?n--:i===","&&n===0&&(t.push(e.slice(r,s).trim()),r=s+1)}const o=e.slice(r).trim();return o.length>0&&t.push(o),t}function eO(e){const t=/^(?:Readonly)?Map<(.+)>$/.exec(e);return t?t[1]:void 0}function tO(e){const t=/^(?:Readonly)?Set<(.+)>$/.exec(e);return t?t[1]:void 0}function nO(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 Zd(n)}async function rO(e,t){const n=e.trim(),r=eO(n);if(r!==void 0){const i=Zd(r);if(i.length===2){const[a,c]=await Promise.all([t(i[0]),t(i[1])]);return{type:"array",items:{type:"array",items:[a,c],minItems:2,maxItems:2}}}}const o=tO(n);if(o!==void 0)return{type:"array",items:await t(o),uniqueItems:!0};const s=nO(n);if(s!==void 0){const i=await Promise.all(s.map(a=>t(a)));return{type:"array",items:i,minItems:i.length,maxItems:i.length}}}const Xd={"decimal.js":"Decimal"},bs={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"}},$u={Uint8Array:"byte",Buffer:"byte",Decimal:"decimal"};function vu(e){var t;const n=new Map;for(const r of e.getImportDeclarations()){const o=r.getModuleSpecifierValue(),s=Xd[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=((t=a.getAliasNode())==null?void 0:t.getText())??a.getName();c!==s&&n.set(c,s)}}return n}function oO(e,t){return n=>{n.addNodeParser({supportsNode(r){var o,s,i;if(r.kind!==t)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($u,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);return new wt.AnnotatedType(new wt.StringType,{format:$u[a]},!1)}}),n.addNodeParser({supportsNode(r){return r.kind===e},createType(){return new wt.AnnotatedType(new wt.StringType,{format:"int64"},!1)}})}}let un;function sO(){if(un)return un;try{const e=T.dirname(require.resolve("ts-json-schema-generator/package.json"));un=require(require.resolve("typescript",{paths:[e]}))}catch{un=require("typescript")}return un}const nt=new Map;function iO(){const e=process.env.APIGEN_PROGRAM_CACHE,t=e===void 0?NaN:Number(e);return Number.isFinite(t)&&t>=0?t:8}function aO(e){const t=nt.get(e);return t&&(nt.delete(e),nt.set(e,t)),t}function cO(e,t){const n=iO();if(n!==0)for(nt.delete(e),nt.set(e,t);nt.size>n;){const r=nt.keys().next().value;nt.delete(r)}}function uO(e,t){return`${e}\0${t??""}`}const lO=new Set(["zod",/^zod\/./]);function fO(e){for(const t of e.getImportDeclarations()){const n=t.getModuleSpecifierValue();for(const r of lO)if(typeof r=="string"){if(n===r)return!0}else if(r.test(n))return!0}return!1}function dO(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(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]}Es(e)}function Es(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&&Es(o,n);else Es(r,n)}}function pO(e){const t=new Set;for(const r of["$defs","definitions"]){const o=e[r];if(o&&typeof o=="object")for(const s of Object.keys(o))t.add(s)}const n=Ss(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 Ss(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 s=o.match(/#\/(?:\$defs|definitions)\/(.+)$/);s&&!t.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(...Ss(s,t));else n.push(...Ss(o,t));return n}function hO(e){const t=e.anyOf;if(!Array.isArray(t)||t.length<2)return e;const n=t,r=ha(n),o={...e};return delete o.anyOf,{...o,oneOf:n,...r?{discriminator:r}:{},[Nr]:o[Nr]??"union"}}function mO(e,t,n){const{DEFAULT_CONFIG:r}=require("ts-json-schema-generator/dist/src/Config.js"),o={...r,...e},s=o.path,i=uO(s,o.tsconfig);let a;a=n?n.statVersion(s):Yd(s);let c;if(i!==void 0){const l=(n==null?void 0:n.generatorCache.get(i))??aO(i);l&&l.version===a&&(c=l.gen)}if(!c){const{createProgram:l}=require("ts-json-schema-generator/dist/factory/program.js"),f=sO(),p=oO(f.SyntaxKind.BigIntKeyword,f.SyntaxKind.TypeReference),h=l(o),d=wt.createParser(h,o,p),m=wt.createFormatter(o);if(c=new wt.SchemaGenerator(h,d,m,o),n&&n.stats.generatorsBuilt++,i!==void 0&&a!==void 0){const y={version:a,gen:c};cO(i,y),n==null||n.generatorCache.set(i,y)}}const u=c.createSchema(o.type);return dO(u),pO(u),u}function gO(e,t){let n=e.trim();if(n=tp(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 ep(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const yO=Object.entries(Xd).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${ep(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function tp(e){let t=e;for(const{pattern:n,key:r}of yO)t=t.replace(n,r);return t}function $O(e,t){let n=tp(e);for(const[r,o]of t)n=n.replace(new RegExp(`\\b${ep(r)}\\b`,"g"),o);return n}async function xn(e,t,n,r,o,s){const i=t.getFilePath(),a=`${i}\0${r??""}\0${n}`,c=s??new Set;if(c.has(a))return{};if(!o){const d=new Set(c);return d.add(a),wu(e,t,n,r,void 0,d)}const u=o.schemaCache.get(a);if(u!==void 0)return o.stats.schemaCacheHits++,u;const l=qS(i,r,o.statVersion(i)),f=l.get(n);if(f!==void 0)return o.stats.schemaCacheHits++,o.schemaCache.set(a,Promise.resolve(f)),f;o.stats.schemaCacheMisses++;const p=new Set(c);p.add(a);const h=wu(e,t,n,r,o,p).then(d=>(l.set(n,d),d)).catch(d=>{throw o.schemaCache.delete(a),d});return o.schemaCache.set(a,h),h}async function wu(e,t,n,r,o,s){if(["void","undefined","null","Promise<void>"].includes(n))return{type:"null"};let i;if(o){const p=o.aliasCache.get(t);i=p??vu(t),p||o.aliasCache.set(t,i)}else i=vu(t);const a=gO(n,i),c=bs[a];if(c!==void 0)return c;const u=await rO(a,p=>xn(e,t,p,r,o,s));if(u!==void 0)return u;const l=(o==null?void 0:o.zodImportCache.get(t))??fO(t);if(o&&o.zodImportCache.set(t,l),!l)try{const p={path:t.getFilePath(),type:a,skipTypeCheck:!0,tsconfig:r,topRef:!1},h=mO(p,!0,o);return hO(h)}catch{}try{const p=await XS(e,t,a,h=>Qd(h,d=>xn(e,t,d,r,o,s),0));if(p!==void 0)return p}catch{}const f=$O(a,i);return gr(f,0,i)}function ma(e,t,n){if(e!=null&&e.hasInitializer()){const r=e.getInitializer();if(r)return r.getText()}return vO(n,t)}function vO(e,t){var n;const r=e,o=((n=r==null?void 0:r.getJsDocs)==null?void 0:n.call(r))??[],s=t.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 wO(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 bO(e,t){const n=wO(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})`}function Gr(e){try{if(!e||e.getKind()!==Sn.SyntaxKind.TypeReference)return;const t=e;if(t.getTypeArguments().length>0)return;const n=t.getTypeName();if(n.getKind()!==Sn.SyntaxKind.Identifier)return;const r=n.getSymbol();if(!r)return;const o=r.getDeclarations().find(c=>c.getKindName()==="TypeAliasDeclaration");if(!o)return;const s=o,i=s.getType();if(!(i.isString()||i.isNumber()||i.isBoolean()))return;const a=s.getJsDocs();for(const c of a)for(const u of c.getTags())if(u.getTagName()==="format"){const l=u.getCommentText();if(l!==void 0)return l.trim()}return}catch{return}}async function EO(e){const t=e.session===void 0,n=KS(e.session??VS());try{return await SO(e,n)}finally{t&&n.dispose()}}async function SO(e,t){const{sourceFile:n,namespace:r="",dropFileSegment:o=!1,tsconfig:s}=e,i=t.projectFor(s),a=t.sourceFileFor(n,s),c=T.basename(n),u=Ve(kO(c)),l=o?null:u,f=Ve(r),p=[];for(const[m,y]of a.getExportedDeclarations()){if(m==="default"||nr(m))continue;const $=jO(y);if($){const O=$.getSignature(),j=Eu(O,$),C=O.getReturnType().getText(),z=dt(O);p.push(await tr(i,a,f,l,m,j,C,$.isAsync(),s,t,z));continue}const v=y.find(O=>O.getKindName()==="VariableDeclaration");if(!v)continue;const E=v.getInitializer(),b=E==null?void 0:E.getKindName();if(E&&["ArrowFunction","FunctionExpression"].includes(b??"")){const O=v.getType().getCallSignatures();if(O.length===0)continue;const j=O[0],C=Su(j,v,v.getVariableStatement()),z=j.getReturnType().getText(),U=dt(j),q=E.isAsync();p.push(await tr(i,a,f,l,m,C,z,q,s,t,U))}else if(b==="ObjectLiteralExpression"){const O=v.getType();for(const j of O.getProperties()){const C=j.getName();if(nr(C))continue;const z=j.getTypeAtLocation(v).getCallSignatures();if(z.length===0)continue;const U=z[0],q=Su(U,v,v.getVariableStatement()),Q=U.getReturnType().getText(),Z=dt(U),me=[...l?[l]:[],Ve(m),Ve(C)];p.push(await yr(i,a,f,me,C,q,Q,!1,s,t,Z))}}else{const O=v.getType(),j=O.getText();if(gt(O,v)){const C=await xn(i,a,j,s,t);p.push(NO(f,l,m,C))}else console.warn(`[apigen-core] Skipping non-callable, non-serializable export: ${m}`)}}const h=a.getDefaultExportSymbol();if(h){const m=a.getExportAssignment(y=>!y.isExportEquals());if(m){const y=m.getExpression(),$=y.getKindName();if(["ArrowFunction","FunctionExpression"].includes($)){const v=y.getType().getCallSignatures();if(v.length>0){const E=v[0],b=Ao(E,m),O=E.getReturnType().getText(),j=dt(E),C=y.isAsync();p.push(await tr(i,a,f,l,"default",b,O,C,s,t,j))}}else{const v=y.getType();for(const E of v.getProperties()){const b=E.getName();if(nr(b))continue;const O=E.getTypeAtLocation(m).getCallSignatures();if(O.length===0)continue;const j=O[0],C=Ao(j,m),z=j.getReturnType().getText(),U=dt(j),q=[...l?[l]:[],Ve("default"),Ve(b)];p.push(await yr(i,a,f,q,b,C,z,!1,s,t,U))}}}else{const y=h.getDeclarations();for(const $ of y){if($.getKindName()!=="FunctionDeclaration")continue;const v=$,E=v.getName(),b=E&&E.length>0?E:"default",O=v.getSignature(),j=Eu(O,v),C=O.getReturnType().getText(),z=dt(O);p.push(await tr(i,a,f,l,b,j,C,v.isAsync(),s,t,z))}}}const d=AO(a);if(d.length>0)for(const{name:m,sig:y}of d){if(nr(m))continue;const $=Ao(y),v=y.getReturnType().getText(),E=dt(y),b=[...l?[l]:[],Ve(m)];p.push(await yr(i,a,f,b,m,$,v,!1,s,t,E))}return p}function OO(e,t,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 f=u,p=t[f];for(const[h,d]of Object.entries(l)){const m=s(d),y=p[h];if(y!==void 0&&JSON.stringify(y)!==JSON.stringify(m))throw new Error(`[apigen-core-client] Function "${n}": param "${r}" contributes a "${f}.${h}" 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.`);p[h]=m}continue}c[u]=s(l)}return c}finally{o.delete(i)}};return s(e)}function bu(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 dt(e){var t;try{return Gr((t=e.getDeclaration())==null?void 0:t.getReturnTypeNode())}catch{return}}async function tr(e,t,n,r,o,s,i,a,c,u,l){const f=Ve(o);return yr(e,t,n,r?[r,f]:[f],o,s,i,a,c,u,l)}async function yr(e,t,n,r,o,s,i,a,c,u,l){const f=s.length>0&&s[0].name==="ctx",p=s.filter(b=>b.name!=="ctx"),h=p.filter(b=>!b.optional).map(b=>b.name),d={},m={definitions:{},$defs:{}};for(const b of p){const O=await xn(e,t,b.type,c,u),j=OO(O,m,o,b.name);b.defaultValue!==void 0&&bO(j,b.defaultValue),bu(j,b.format),d[b.name]=j}const y=i.replace(/^Promise<(.+)>$/,"$1").trim(),$=await xn(e,t,y,c,u),v=l?{...$}:$;bu(v,l);const E={type:"object",properties:d,required:h,...Object.keys(m.definitions).length>0?{definitions:m.definitions}:{},...Object.keys(m.$defs).length>0?{$defs:m.$defs}:{}};return{id:np(n,r),host:"ts",namespace:n,path:r,kind:"action",async:a,streaming:!1,safe:!1,input:E,output:v,envelope:{},typeText:{lang:"ts",input:IO(s),output:y},...f?{hasCtx:!0}:{}}}function NO(e,t,n,r){const o=Ve(n),s=t?[t,o]:[o];return{id:np(e,s),host:"ts",namespace:e,path:s,kind:"query",async:!1,streaming:!1,safe:!0,input:{type:"object",properties:{},required:[]},output:r,envelope:{},typeText:null}}function np(e,t){return(e.raw?[e,...t]:t).map(n=>n.words.join("-")).join("/")}function _O(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 Ve(e){return{raw:e,words:_O(e)}}function kO(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function AO(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(),i=s.getType();for(const a of i.getProperties()){const c=a.getTypeAtLocation(s).getCallSignatures();c.length!==0&&t.push({name:a.getName(),sig:c[0]})}}return t}function jO(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 Eu(e,t){return e.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(e.getDeclaration()).getText(),optional:i,defaultValue:ma(s,n.getName(),t),format:Gr(s==null?void 0:s.getTypeNode())}})}function Su(e,t,n){return e.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(t).getText(),optional:a,defaultValue:ma(i,r.getName(),n??t),format:Gr(i==null?void 0:i.getTypeNode())}})}function Ao(e,t){return e.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:ma(a,n.getName(),t),format:Gr(a==null?void 0:a.getTypeNode())}})}function IO(e){const t=e.filter(n=>n.name!=="ctx");return t.length===0?"()":"("+t.map(n=>`${n.name}${n.optional?"?":""}: ${n.type}`).join(", ")+")"}function nr(e){return!!(e==="__samples__"||e.startsWith("__"))}function gt(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?gt(r,t,n):!1}if(e.isTuple())return e.getTupleElements().every(r=>gt(r,t,n));if(e.isUnion())return e.getUnionTypes().every(r=>gt(r,t,n));if(e.isIntersection())return e.getIntersectionTypes().every(r=>gt(r,t,n));if(e.isObject()){const r=e.getText(t);if(n.has(r))return!0;n.add(r);const o=e.getStringIndexType(),s=e.getNumberIndexType();if(o||s)return[o,s].every(a=>!a||gt(a,t,n));const i=e.getProperties();return i.length===0?!0:i.every(a=>{const c=a.getTypeAtLocation(t);return gt(c,t,n)})}return!1}function xO(e,t){return async n=>{let r=()=>t(n);for(let o=e.length-1;o>=0;o--){const s=e[o],i=r;r=()=>s(n,i)}return r()}}function PO(e,t){return xO(e,t)}function TO(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 PO(r,t)}function rp(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{}rp(r,t)}}}let jo;function CO(){return jo||(jo=new Sn.Project({skipAddingFilesFromTsConfig:!0,compilerOptions:{noLib:!0}})),jo}function op(e){const t=CO(),n=t.getSourceFile(e),r=n??t.addSourceFileAtPath(e);if(n)try{n.refreshFromFileSystemSync()}catch{}const o=new Set([e]);return rp(r,o),[...o].sort()}const RO={"decimal.js":"Decimal"};function MO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(RO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${MO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));async function DO(e,t){await bt.mkdir(T.dirname(e),{recursive:!0});const n=`${e}.${process.pid}.${Mn.randomUUID()}.tmp`;try{await bt.writeFile(n,JSON.stringify(t),"utf8"),await bt.rename(n,e)}catch(r){throw await bt.unlink(n).catch(()=>{}),r}}function LO(e){return{async get(){try{const t=await bt.readFile(e,"utf8");return JSON.parse(t)}catch{return}},async put(t,n){await DO(e,n)}}}const Os=1;function UO(e){return Mn.createHash("sha256").update(e).digest("hex")}async function Ou(e){return UO(await bt.readFile(e,"utf8"))}async function _r(e){try{return(await bt.stat(e)).mtimeMs}catch{return}}async function Nu(e,t){const n=await Ou(e.source),r=Mn.createHash("sha256");r.update(`formatVersion:${Os}
|
|
165
165
|
`),r.update(`extractorVersion:${t}
|
|
166
166
|
`),r.update(`host:${e.host}
|
|
167
167
|
`),r.update(`namespace:${e.namespace??""}
|
|
168
168
|
`),r.update(`source:${n}
|
|
169
|
-
`);for(const o of
|
|
170
|
-
`);return r.digest("hex")}async function Nu(e,t){const n=await _r(e.source)??0,r=[];for(const o of tp(e.source)){if(o===e.source)continue;const s=await _r(o);s!==void 0&&r.push({path:o,mtimeMs:s})}return{contentKey:t,source:{path:e.source,mtimeMs:n},deps:r}}async function DO(e,t){if(t.source.path!==e.source)return!1;const n=await _r(t.source.path);if(n===void 0||n!==t.source.mtimeMs)return!1;for(const r of t.deps){const o=await _r(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function LO(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=RO(e.cache),n=e.extractorVersion;async function r(o,s,i){const a=i??await Ou(o,n),c=await Nu(o,a);await t.put(e.cache,{formatVersion:Ss,operations:s,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,s)=>{const i=await t.get(e.cache);if(!i||i.formatVersion!==Ss||i.extractorVersion!==n||!i.staleness){const u=await s();return r(o,u).catch(()=>{}),u}if(await DO(o,i.staleness))return i.operations;const a=await Ou(o,n);if(a===i.staleness.contentKey)return Nu(o,a).then(u=>t.put(e.cache,{...i,staleness:u})).catch(()=>{}),i.operations;const c=await s();return r(o,c,a).catch(()=>{}),c}}bl.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href);const UO={"decimal.js":"Decimal"};function BO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(UO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${BO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const FO=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],qO={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let VO=class 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 ma(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&FO.includes(e.code)&&typeof e.toJSON=="function"}const Os="$apigen";let _u=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function KO(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new _u(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new _u("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 ga="x-apigen-logical",ya="x-apigen-codec",Ns="x-apigen-ctor",_s="x-apigen-tojson",GO="0.1.0";function ku(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 Ft(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 Ft(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=np(e,s,t);return Ft(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Io(e,t,n);const a=t.items;if(!a)return e.map(u=>Nt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Nt(u):Ft(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ft(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Io(e,t,n);const a=t.properties;if(!a)return Nt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Ft(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Io(e,t,n):Nt(e)}function qt(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 qt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=np(e,s,t);return qt(e,a,n)}const i=t.type;if(i==="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((u,l)=>{const f=a[l];return f===void 0?u:qt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>qt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=qt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?zO(e,n):e}function np(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Io(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Os]:r,v:s}}catch{}}return Nt(e)}function zO(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Os in e){const n=e,r=n[Os],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Nt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Nt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Nt(r));return t}return null}function JO(e){return{encode(t,n,r){const o=ku(e,r);return Ft(t,n,o)},decode(t,n,r){const o=ku(e,r);return qt(t,n,o)}}}const $a={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},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)}},va={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},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)}},wa={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}},ba={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},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"))}},HO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Ea={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"&&!HO.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},ks="NaN",As="Infinity",js="-Infinity",WO=new Set([ks,As,js]),Sa={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?ks:e===1/0?As:e===-1/0?js:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===ks)return NaN;if(e===As)return 1/0;if(e===js)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 ${[...WO].join(", ")}.`);return NaN}},YO=[$a,va,wa,ba,Ea,Sa];function QO(e,t={}){for(const n of YO)e.register(n,{override:t.override??!1})}const ZO=12;function XO(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function Au(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function eN(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 tN(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 ju(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?Pn(a,t,n+1):`<${i}>`}return s}function nN(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Pn(r,t,n+1)]:[]}function Pn(e,t=e??{},n=0){if(!e||n>ZO)return null;if(typeof e.$ref=="string"){const o=XO(e.$ref,t);return o!==void 0?Pn(o,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 o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return ju({...e,properties:o,required:s},t,n)}const r=Au(e.oneOf)??Au(e.anyOf);if(r)return Pn(r,t,n+1);switch(eN(e)){case"object":return ju(e,t,n);case"array":return nN(e,t,n);case"string":return tN(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function rN(e){if(!e)return;const t=Pn(e);return`Example: ${JSON.stringify(t)}`}$a.id,va.id,wa.id,ba.id,Ea.id,Sa.id;const rp=KO();QO(rp);const op=JO(rp.freeze());function oN(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function sN(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function iN(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function aN(e,t){return t===void 0||e===void 0?e:op.decode(e,t)}function xo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:op.encode(e,n)}async function cN(e,t,n,r,o,s){const i=sN(n).map(c=>aN(s[c],iN(n,c)));if(oN(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return xo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return xo(u,n)}const a=await e[r](...i);return xo(a,n)}let sp=class{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 uN(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>cN(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const lN={"decimal.js":"Decimal"};function fN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(lN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${fN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function dN(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"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},ke(s);const i=n?ke.destination({dest:e.destination,mkdir:!0,sync:!0}):ke.destination(2);return ke(s,i)}function ip(e){return e?e.type==="array"?`${ip(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function ap(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.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:ip(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function pN(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function hN(e,t){var n,r;const o=((r=(n=((t==null?void 0:t.input)??{}).properties)==null?void 0:n.data)==null?void 0:r.properties)??{},s={...e};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=pN(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 mN=class 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}};const zr=new jr({allErrors:!0});Ir(zr);for(const e of[ga,ya,Ns,_s,"discriminator"])zr.addKeyword({keyword:e,valid:!0});zr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function gN(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function yN(e,t){const n=rN(t),r=[`Validation failed: ${gN(e)}`];return n&&r.push(n),r.join(" — ")}function $N(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=zr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new mN("invalid_argument",yN(a,o.input),a)}return n()}}function vN(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class pt extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Po(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 cp(e,t){const n=e[ya];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function wN(e,t,n){const r=cp(t,n);return r?r.encode(e,t,n):e}function bN(e,t,n){const r=cp(t,n);return r?r.decode(e,t,n):e}function EN(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[ga]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Po(r)!==void 0},encode(r,o,s){const i=Po(o);if(!i)throw new pt("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 pt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new pt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return wN(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new pt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Po(o);if(!a)throw new pt("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 pt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new pt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return bN(r,h,{...s,path:`${s.path}[${f}]`})}}}const SN="x-apigen-instances";let rr=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function Iu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ON(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function xu(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function NN(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function _N(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[ga]==="nominal"?!0:o[ya]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new rr("E_NOMINAL_CYCLE",`[${t}] 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=Iu(s),c=typeof s[_s]=="string"?s[_s]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const g={};for(const[y,$]of Object.entries(d))g[y]=xu($,a[y],{...i,path:`${i.path}/${y}`});return g}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const g=p[d];g!==void 0&&(l[d]=xu(g,a[d],{...i,path:`${i.path}/${d}`}))}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 rr("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of ON(s))if(!(l in a))throw new rr("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[SN]===!1)throw new rr("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=Iu(s),u={};for(const[l,f]of Object.entries(a))u[l]=NN(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Ns]=="string"?s[Ns]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const kN=[$a,va,wa,ba,Ea,Sa],AN={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Pu=_N({id:"ts.NominalSentinel",schema:AN}),jN={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Tu=EN({id:"ts.UnionSentinel",schema:jN});function IN(){const e=[...kN.map(t=>[t.id,t]),[Pu.id,Pu],[Tu.id,Tu]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:GO,codecs:IN()});const Cu=new Set(["string","number","boolean","integer"]);function xN(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"?Cu.has(n):Array.isArray(n)?n.every(r=>Cu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function PN(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(xN)}const TN={"decimal.js":"Decimal"};function CN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(TN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${CN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ru(e){return e.words.join("-")}function Mu(e){return e.words.map(UN).join("")}function Du(e){return e.words.join("_")}function RN(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||PN(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Ru(h)).join("/"),c=o.map(h=>Du(h)).join("_"),u=o.map(h=>Du(h)).slice(0,-1).join("."),l=Mu(o[o.length-2]??o[0]),f=Mu(o[o.length-1]),p=o.map(h=>Ru(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function MN(e,t){return`x-${e}-${t}`}function DN(e,t){return`--${e}-${t}`}function LN(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function UN(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Oa(e){return e.anyOf??e.oneOf}function BN(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Oa(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 FN(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Oa(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function qN(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Oa(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 VN(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function KN(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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 Lu(e){return typeof e.handler=="function"}function GN(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["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=MN(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:DN(i,s),envVar:LN(i,s)})}return o}function zN(e,t){const n=new Map,{props:r}=KN(e);for(const[o,s]of Object.entries(r)){let i="string";FN(s)?i="boolean":(BN(s)||qN(s))&&(i="json"),n.set(VN(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Uu(e){const{op:t,schema:n,transport:r,projection:o}=e,s=RN(t,o),i=n?GN(n):[],a=n?zN(n,i):new Map,c=n?ap(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:Lu(t)};if(Lu(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function JN(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function HN(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function WN(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function To(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(WN(s))}return r.push($N(e)),uN(r)}function YN(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const QN={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Bu(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new sp};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:YN(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:QN}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const ZN={"decimal.js":"Decimal"};function XN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ZN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${XN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Is(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 Fu(e){return{raw:e,words:Is(e)}}function e_(e,t,n,r){for(const o of r??[]){const s=o.path[o.path.length-1];if(o.namespace.raw===e&&(s==null?void 0:s.raw)===t)return o}return{id:`${Is(e).join("-")}/${Is(t).join("-")}`,host:"ts",namespace:Fu(e),path:[Fu(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function t_(e){return`data: ${e}
|
|
169
|
+
`);for(const o of op(e.source))o!==e.source&&r.update(`dep:${o}:${await Ou(o)}
|
|
170
|
+
`);return r.digest("hex")}async function _u(e,t){const n=await _r(e.source)??0,r=[];for(const o of op(e.source)){if(o===e.source)continue;const s=await _r(o);s!==void 0&&r.push({path:o,mtimeMs:s})}return{contentKey:t,source:{path:e.source,mtimeMs:n},deps:r}}async function BO(e,t){if(t.source.path!==e.source)return!1;const n=await _r(t.source.path);if(n===void 0||n!==t.source.mtimeMs)return!1;for(const r of t.deps){const o=await _r(r.path);if(o===void 0||o!==r.mtimeMs)return!1}return!0}function FO(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=LO(e.cache),n=e.extractorVersion;async function r(o,s,i){const a=i??await Nu(o,n),c=await _u(o,a);await t.put(e.cache,{formatVersion:Os,operations:s,extractorVersion:n,createdAt:new Date().toISOString(),staleness:c})}return async(o,s)=>{const i=await t.get(e.cache);if(!i||i.formatVersion!==Os||i.extractorVersion!==n||!i.staleness){const u=await s();return r(o,u).catch(()=>{}),u}if(await BO(o,i.staleness))return i.operations;const a=await Nu(o,n);if(a===i.staleness.contentKey)return _u(o,a).then(u=>t.put(e.cache,{...i,staleness:u})).catch(()=>{}),i.operations;const c=await s();return r(o,c,a).catch(()=>{}),c}}El.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href);const qO={"decimal.js":"Decimal"};function VO(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(qO).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${VO(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const KO=["invalid_argument","unauthenticated","permission_denied","not_found","internal"],GO={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};let zO=class 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 ga(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&KO.includes(e.code)&&typeof e.toJSON=="function"}const Ns="$apigen";let ku=class extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}};function JO(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new ku(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new ku("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 ya="x-apigen-logical",$a="x-apigen-codec",_s="x-apigen-ctor",ks="x-apigen-tojson",WO="0.1.0";function Au(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 Ft(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 Ft(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=sp(e,s,t);return Ft(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Io(e,t,n);const a=t.items;if(!a)return e.map(u=>Nt(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?Nt(u):Ft(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Ft(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Io(e,t,n);const a=t.properties;if(!a)return Nt(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Ft(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Io(e,t,n):Nt(e)}function qt(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 qt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=sp(e,s,t);return qt(e,a,n)}const i=t.type;if(i==="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((u,l)=>{const f=a[l];return f===void 0?u:qt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>qt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=qt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?HO(e,n):e}function sp(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Io(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Ns]:r,v:s}}catch{}}return Nt(e)}function HO(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Ns in e){const n=e,r=n[Ns],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function Nt(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(Nt);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=Nt(r));return t}return null}function YO(e){return{encode(t,n,r){const o=Au(e,r);return Ft(t,n,o)},decode(t,n,r){const o=Au(e,r);return qt(t,n,o)}}}const va={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},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)}},wa={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},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)}},ba={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}},Ea={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},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"))}},QO=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Sa={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"&&!QO.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},As="NaN",js="Infinity",Is="-Infinity",ZO=new Set([As,js,Is]),Oa={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?As:e===1/0?js:e===-1/0?Is:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===As)return NaN;if(e===js)return 1/0;if(e===Is)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 ${[...ZO].join(", ")}.`);return NaN}},XO=[va,wa,ba,Ea,Sa,Oa];function eN(e,t={}){for(const n of XO)e.register(n,{override:t.override??!1})}const tN=12;function nN(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function ju(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function rN(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 oN(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 Iu(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?Pn(a,t,n+1):`<${i}>`}return s}function sN(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Pn(r,t,n+1)]:[]}function Pn(e,t=e??{},n=0){if(!e||n>tN)return null;if(typeof e.$ref=="string"){const o=nN(e.$ref,t);return o!==void 0?Pn(o,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 o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return Iu({...e,properties:o,required:s},t,n)}const r=ju(e.oneOf)??ju(e.anyOf);if(r)return Pn(r,t,n+1);switch(rN(e)){case"object":return Iu(e,t,n);case"array":return sN(e,t,n);case"string":return oN(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function iN(e){if(!e)return;const t=Pn(e);return`Example: ${JSON.stringify(t)}`}va.id,wa.id,ba.id,Ea.id,Sa.id,Oa.id;const ip=JO();eN(ip);const ap=YO(ip.freeze());function aN(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function cN(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function uN(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function lN(e,t){return t===void 0||e===void 0?e:ap.decode(e,t)}function xo(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:ap.encode(e,n)}async function fN(e,t,n,r,o,s){const i=cN(n).map(c=>lN(s[c],uN(n,c)));if(aN(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return xo(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return xo(u,n)}const a=await e[r](...i);return xo(a,n)}let cp=class{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 dN(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>fN(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const pN={"decimal.js":"Decimal"};function hN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(pN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${hN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function mN(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"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},ke(s);const i=n?ke.destination({dest:e.destination,mkdir:!0,sync:!0}):ke.destination(2);return ke(s,i)}function up(e){return e?e.type==="array"?`${up(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function lp(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.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:up(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}function gN(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(n=>n==="number"||n==="integer"||n==="boolean")}function yN(e,t){var n,r;const o=((r=(n=((t==null?void 0:t.input)??{}).properties)==null?void 0:n.data)==null?void 0:r.properties)??{},s={...e};for(const[i,a]of Object.entries(o)){const c=s[i];if(typeof c!="string")continue;const u=gN(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 $N=class 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}};const zr=new jr({allErrors:!0});Ir(zr);for(const e of[ya,$a,_s,ks,"discriminator"])zr.addKeyword({keyword:e,valid:!0});zr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function vN(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function wN(e,t){const n=iN(t),r=[`Validation failed: ${vN(e)}`];return n&&r.push(n),r.join(" — ")}function bN(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=zr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new $N("invalid_argument",wN(a,o.input),a)}return n()}}function EN(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class pt extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Po(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 fp(e,t){const n=e[$a];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function SN(e,t,n){const r=fp(t,n);return r?r.encode(e,t,n):e}function ON(e,t,n){const r=fp(t,n);return r?r.decode(e,t,n):e}function NN(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[ya]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Po(r)!==void 0},encode(r,o,s){const i=Po(o);if(!i)throw new pt("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 pt("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new pt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return SN(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new pt("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Po(o);if(!a)throw new pt("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 pt("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new pt("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return ON(r,h,{...s,path:`${s.path}[${f}]`})}}}const _N="x-apigen-instances";let rr=class extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}};function xu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function kN(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Pu(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function AN(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function jN(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[ya]==="nominal"?!0:o[$a]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new rr("E_NOMINAL_CYCLE",`[${t}] 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=xu(s),c=typeof s[ks]=="string"?s[ks]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=Pu($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=Pu(m,a[d],{...i,path:`${i.path}/${d}`}))}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 rr("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of kN(s))if(!(l in a))throw new rr("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[_N]===!1)throw new rr("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=xu(s),u={};for(const[l,f]of Object.entries(a))u[l]=AN(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[_s]=="string"?s[_s]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const IN=[va,wa,ba,Ea,Sa,Oa],xN={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},Tu=jN({id:"ts.NominalSentinel",schema:xN}),PN={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},Cu=NN({id:"ts.UnionSentinel",schema:PN});function TN(){const e=[...IN.map(t=>[t.id,t]),[Tu.id,Tu],[Cu.id,Cu]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:WO,codecs:TN()});const Ru=new Set(["string","number","boolean","integer"]);function CN(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"?Ru.has(n):Array.isArray(n)?n.every(r=>Ru.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function RN(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(CN)}const MN={"decimal.js":"Decimal"};function DN(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(MN).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${DN(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Mu(e){return e.words.join("-")}function Du(e){return e.words.map(qN).join("")}function Lu(e){return e.words.join("_")}function LN(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||RN(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Mu(h)).join("/"),c=o.map(h=>Lu(h)).join("_"),u=o.map(h=>Lu(h)).slice(0,-1).join("."),l=Du(o[o.length-2]??o[0]),f=Du(o[o.length-1]),p=o.map(h=>Mu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function UN(e,t){return`x-${e}-${t}`}function BN(e,t){return`--${e}-${t}`}function FN(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function qN(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Na(e){return e.anyOf??e.oneOf}function VN(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Na(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 KN(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Na(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function GN(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Na(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 zN(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function JN(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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 Uu(e){return typeof e.handler=="function"}function WN(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["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=UN(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:BN(i,s),envVar:FN(i,s)})}return o}function HN(e,t){const n=new Map,{props:r}=JN(e);for(const[o,s]of Object.entries(r)){let i="string";KN(s)?i="boolean":(VN(s)||GN(s))&&(i="json"),n.set(zN(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function Bu(e){const{op:t,schema:n,transport:r,projection:o}=e,s=LN(t,o),i=n?WN(n):[],a=n?HN(n,i):new Map,c=n?lp(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:Uu(t)};if(Uu(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function YN(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function QN(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function ZN(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function To(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(ZN(s))}return r.push(bN(e)),dN(r)}function XN(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const e_={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function Fu(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new cp};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:XN(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:e_}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const t_={"decimal.js":"Decimal"};function n_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(t_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${n_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function xs(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 qu(e){return{raw:e,words:xs(e)}}function r_(e,t,n,r){for(const o of r??[]){const s=o.path[o.path.length-1];if(o.namespace.raw===e&&(s==null?void 0:s.raw)===t)return o}return{id:`${xs(e).join("-")}/${xs(t).join("-")}`,host:"ts",namespace:qu(e),path:[qu(t)],kind:"action",async:!1,streaming:!1,safe:n["x-apigen-safe"]??!1,input:n.input??{},output:n.output??{},envelope:{},typeText:null}}function o_(e){return`data: ${e}
|
|
171
171
|
|
|
172
|
-
`}function
|
|
172
|
+
`}function s_(e){return`event: error
|
|
173
173
|
data: ${e}
|
|
174
174
|
|
|
175
|
-
`}async function r_(e,t,n){const r=new AbortController;t.raw.once("close",()=>r.abort());const o=n.raw;let s=!1;try{for await(const i of e){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(t_(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=ma(i)?i:new VO("internal",i instanceof Error?i.message:String(i));if(s)o.write(n_(JSON.stringify(a.toJSON()))),o.end();else{const c=s_(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const o_={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function s_(e){return o_[e]??500}function up(e){return ma(e)?qO[e.code]??500:500}function lp(e){return ma(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function i_(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)}}let a_=class{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(s,i)=>{const a={req:s,reply:i};try{const c=await this.readCall(a,t),u=await n(c);await this.writeResult(a,u,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,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?hN(c,a):c}else{const{data:c={}}=r.body??{};i=c}}return{envelope:s,domainArgs:i,signal:this.signal}}async writeResult(t,n,r){const{req:o,reply:s}=t;if(vN(n)){await r_(n,o,s);return}s.type("application/json"),s.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){const{reply:o}=t;o.status(up(n)).send(lp(n))}};function c_(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("http")||i.push(f)}return i}async function u_(e){var t,n;const r=e.options.port??3e3,o=e.options.host??"127.0.0.1",s=e.options.routePrefix??"",i=e.options.projection??{},a=JN(e.options),c=HN(e.options),u=e.logger??dN(),l=im({logger:u});l.setErrorHandler((E,b,O)=>{O.status(up(E)).send(lp(E))});const f=new a_(l,s,e.signal),p=[],h={},d={};for(const E of e.packages){if(!E.fns)throw new Error(`Package "${E.id}" is missing fns`);const b=E.fns,O=Object.entries(E.schemas).map(([q,Q])=>({fnName:q,fnSchema:Q,op:e_(E.id,q,Q,e.operations)})),j={},C={};for(const{fnName:q,fnSchema:Q,op:Z}of O)j[Z.id]=Q,C[Z.id]=b[q],h[Z.id]=Q,d[Z.id]=b[q];const z=To(j,a),U={fns:C,createClient:E.createClient,schemas:j};for(const{fnSchema:q,op:Q}of O){const Z=Uu({op:Q,schema:q,transport:"http",projection:i});f.bindSchema(Q.id,q),f.registerRoute(Z,Fe=>Bu(Z,z,Fe,U));const{params:me,text:Ne}=ap(q);p.push({method:Z.http.verb,route:s+Z.http.route,text:Ne,params:me})}}const g=((t=e.packages[0])==null?void 0:t.id)??"ts",y=To(h,a),$={invoke:(E,b,O)=>y(E,{operation:{id:E},ctx:new sp,domainArgs:b.domainArgs,envelope:b.envelope,signal:b.signal},O),invokeOptions:{fns:d,schemas:h,createClient:(n=e.packages[0])==null?void 0:n.createClient}},v=c_(a,c,g,e.operations??[],$);if(v.length>0){const E=To({},a),b={fns:{},schemas:{}};for(const O of v){const j=Uu({op:O,transport:"http",projection:i});f.registerRoute(j,C=>Bu(j,E,C,b)),p.push({method:j.http.verb,route:`${s}/${O.id}`,text:"",params:[]})}}return await l.listen({port:r,host:o}),u.info({host:o,port:r},`listening on http://${o}:${r}`),i_(u,p),new Promise(E=>{e.signal&&e.signal.addEventListener("abort",async()=>{await l.close(),E()})})}const l_={id:"api-fastify",run(e){return u_(e)}};function qu(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function f_(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:qu(i),path:s.map(qu),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 d_={"decimal.js":"Decimal"};function p_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(d_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${p_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const Vu=new Set(["string","number","boolean","integer"]);function h_(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"?Vu.has(n):Array.isArray(n)?n.every(r=>Vu.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function m_(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(h_)}const g_={"decimal.js":"Decimal"};function y_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(g_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${y_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Ku(e){return e.words.join("-")}function Gu(e){return e.words.map(v_).join("")}function zu(e){return e.words.join("_")}function $_(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||m_(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Ku(h)).join("/"),c=o.map(h=>zu(h)).join("_"),u=o.map(h=>zu(h)).slice(0,-1).join("."),l=Gu(o[o.length-2]??o[0]),f=Gu(o[o.length-1]),p=o.map(h=>Ku(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function v_(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function w_(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const s of e){const i=$_(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:b_(s.output)}};if(a==="GET")l.parameters=E_(s.input);else{const f=s.input;typeof f=="object"&&f!==null&&Object.keys(f).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:f}}})}o[c]===void 0&&(o[c]={}),o[c][u]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function b_(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function E_(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 S_(e,t={}){return[{...f_("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>w_(e.operations,{title:t.title,version:t.version})}]}const O_={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 S_(e,t)}}}},xs="$apigen";class Ju extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function N_(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Ju(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new Ju("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 Na="x-apigen-logical",_a="x-apigen-codec",Ps="x-apigen-ctor",Ts="x-apigen-tojson",__="0.1.0";function Hu(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 Vt(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 Vt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=fp(e,s,t);return Vt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Co(e,t,n);const a=t.items;if(!a)return e.map(u=>_t(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?_t(u):Vt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Vt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Co(e,t,n);const a=t.properties;if(!a)return _t(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Vt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Co(e,t,n):_t(e)}function Kt(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 Kt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=fp(e,s,t);return Kt(e,a,n)}const i=t.type;if(i==="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((u,l)=>{const f=a[l];return f===void 0?u:Kt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Kt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Kt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?k_(e,n):e}function fp(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Co(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[xs]:r,v:s}}catch{}}return _t(e)}function k_(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&xs in e){const n=e,r=n[xs],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function _t(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(_t);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=_t(r));return t}return null}function A_(e){return{encode(t,n,r){const o=Hu(e,r);return Vt(t,n,o)},decode(t,n,r){const o=Hu(e,r);return Kt(t,n,o)}}}const ka={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},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)}},Aa={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},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)}},ja={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}},Ia={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},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"))}},j_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,xa={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"&&!j_.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Cs="NaN",Rs="Infinity",Ms="-Infinity",I_=new Set([Cs,Rs,Ms]),Pa={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Cs:e===1/0?Rs:e===-1/0?Ms:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Cs)return NaN;if(e===Rs)return 1/0;if(e===Ms)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 ${[...I_].join(", ")}.`);return NaN}},x_=[ka,Aa,ja,Ia,xa,Pa];function P_(e,t={}){for(const n of x_)e.register(n,{override:t.override??!1})}const T_=12;function C_(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function Wu(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function R_(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 M_(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 Yu(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?Tn(a,t,n+1):`<${i}>`}return s}function D_(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Tn(r,t,n+1)]:[]}function Tn(e,t=e??{},n=0){if(!e||n>T_)return null;if(typeof e.$ref=="string"){const o=C_(e.$ref,t);return o!==void 0?Tn(o,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 o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return Yu({...e,properties:o,required:s},t,n)}const r=Wu(e.oneOf)??Wu(e.anyOf);if(r)return Tn(r,t,n+1);switch(R_(e)){case"object":return Yu(e,t,n);case"array":return D_(e,t,n);case"string":return M_(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function dp(e){if(!e)return;const t=Tn(e);return`Example: ${JSON.stringify(t)}`}ka.id,Aa.id,ja.id,Ia.id,xa.id,Pa.id;const pp=N_();P_(pp);const hp=A_(pp.freeze());function L_(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function U_(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function B_(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function F_(e,t){return t===void 0||e===void 0?e:hp.decode(e,t)}function Ro(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:hp.encode(e,n)}async function q_(e,t,n,r,o,s){const i=U_(n).map(c=>F_(s[c],B_(n,c)));if(L_(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Ro(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Ro(u,n)}const a=await e[r](...i);return Ro(a,n)}let mp=class{constructor(){this._map=new Map}set(e,t){this._map.set(e,t)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};function V_(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>q_(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const K_={"decimal.js":"Decimal"};function G_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(K_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${G_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function z_(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"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},ke(s);const i=n?ke.destination({dest:e.destination,mkdir:!0,sync:!0}):ke.destination(2);return ke(s,i)}function gp(e){return e?e.type==="array"?`${gp(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function J_(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.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:gp(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const H_=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class yp 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 W_(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&H_.includes(e.code)&&typeof e.toJSON=="function"}function Qu(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Jr=new jr({allErrors:!0});Ir(Jr);for(const e of[Na,_a,Ps,Ts,"discriminator"])Jr.addKeyword({keyword:e,valid:!0});Jr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function Y_(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Q_(e,t){const n=dp(t),r=[`Validation failed: ${Y_(e)}`];return n&&r.push(n),r.join(" — ")}function Z_(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Jr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new yp("invalid_argument",Q_(a,o.input),a)}return n()}}async function X_(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=W_(n)?n:new yp("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:Qu("before-first-chunk",r)}:{ok:!1,carrier:Qu("after-first-chunk",r,t.length)}}}function ek(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class ht extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Mo(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 $p(e,t){const n=e[_a];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function tk(e,t,n){const r=$p(t,n);return r?r.encode(e,t,n):e}function nk(e,t,n){const r=$p(t,n);return r?r.decode(e,t,n):e}function rk(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[Na]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Mo(r)!==void 0},encode(r,o,s){const i=Mo(o);if(!i)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 ht("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return tk(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ht("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Mo(o);if(!a)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 ht("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return nk(r,h,{...s,path:`${s.path}[${f}]`})}}}const ok="x-apigen-instances";class or extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function Zu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function sk(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function Xu(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function ik(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function ak(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[Na]==="nominal"?!0:o[_a]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new or("E_NOMINAL_CYCLE",`[${t}] 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=Zu(s),c=typeof s[Ts]=="string"?s[Ts]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const g={};for(const[y,$]of Object.entries(d))g[y]=Xu($,a[y],{...i,path:`${i.path}/${y}`});return g}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const g=p[d];g!==void 0&&(l[d]=Xu(g,a[d],{...i,path:`${i.path}/${d}`}))}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 or("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of sk(s))if(!(l in a))throw new or("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[ok]===!1)throw new or("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=Zu(s),u={};for(const[l,f]of Object.entries(a))u[l]=ik(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Ps]=="string"?s[Ps]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const ck=[ka,Aa,ja,Ia,xa,Pa],uk={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},el=ak({id:"ts.NominalSentinel",schema:uk}),lk={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},tl=rk({id:"ts.UnionSentinel",schema:lk});function fk(){const e=[...ck.map(t=>[t.id,t]),[el.id,el],[tl.id,tl]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:__,codecs:fk()});function nl(e,t,n){var r;const o=typeof((r=t==null?void 0:t.input)==null?void 0:r.description)=="string"?t.input.description:void 0,s=dp(t==null?void 0:t.input),i=[n,o,s].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):e}function vp(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:!1}:{outputSchema:{type:"object",properties:{result:t},required:["result"]},wrapped:!0}}function dk(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const rl=new Set(["string","number","boolean","integer"]);function pk(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"?rl.has(n):Array.isArray(n)?n.every(r=>rl.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function hk(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(pk)}const mk={"decimal.js":"Decimal"};function gk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(mk).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${gk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ol(e){return e.words.join("-")}function sl(e){return e.words.map(bk).join("")}function il(e){return e.words.join("_")}function yk(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||hk(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>ol(h)).join("/"),c=o.map(h=>il(h)).join("_"),u=o.map(h=>il(h)).slice(0,-1).join("."),l=sl(o[o.length-2]??o[0]),f=sl(o[o.length-1]),p=o.map(h=>ol(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function $k(e,t){return`x-${e}-${t}`}function vk(e,t){return`--${e}-${t}`}function wk(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function bk(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Ta(e){return e.anyOf??e.oneOf}function Ek(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Ta(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 Sk(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Ta(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function Ok(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Ta(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 Nk(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function _k(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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 al(e){return typeof e.handler=="function"}function kk(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["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=$k(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:vk(i,s),envVar:wk(i,s)})}return o}function Ak(e,t){const n=new Map,{props:r}=_k(e);for(const[o,s]of Object.entries(r)){let i="string";Sk(s)?i="boolean":(Ek(s)||Ok(s))&&(i="json"),n.set(Nk(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function cl(e){const{op:t,schema:n,transport:r,projection:o}=e,s=yk(t,o),i=n?kk(n):[],a=n?Ak(n,i):new Map,c=n?J_(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:al(t)};if(al(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function jk(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Ik(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function xk(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function Do(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(xk(s))}return r.push(Z_(e)),V_(r)}function Pk(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const Tk={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function ul(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new mp};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:Pk(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:Tk}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const Ck={"decimal.js":"Decimal"};function Rk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ck).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Rk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Mk(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)}const Dk={"decimal.js":"Decimal"};function Lk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Dk).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Lk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Uk(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Ds(e){return{raw:e,words:Mk(e)}}function Bk(e){return Ds(Uk(Uo.basename(e)))}function Fk(e,t,n){if(n){const o=n.find(s=>{var i;return s.kind==="action"&&s.namespace.raw===e.id&&((i=s.path[s.path.length-1])==null?void 0:i.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=Ds(t);return{id:`${e.id}/${t}`,host:"ts",namespace:Ds(e.id),path:e.dropFileSegment?[r]:[Bk(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}const qk=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function Vk(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&qk.includes(e.code)&&typeof e.toJSON=="function"}async function Kk(e){const t=await X_(e);if(t.ok){const o=t.chunks.map(s=>({type:"text",text:JSON.stringify(s)}));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}}class Gk{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.toolMeta.set(t,n)}registerRoute(t,n){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(){return[...this.plans.keys()].map(t=>{const n=this.toolMeta.get(t);return{name:t,description:(n==null?void 0:n.description)??t,inputSchema:(n==null?void 0:n.inputSchema)??{type:"object",properties:{}},...n!=null&&n.outputSchema?{outputSchema:n.outputSchema}:{}}})}readCall(t,n){const r={};for(const s of n.envelope){const i=t.meta[s.mcpMetaKey];i!==void 0&&(r[s.field]=i)}const o=n.isMount?t.args:t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(ek(n)){t.output=await Kk(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=vp(o==null?void 0:o.output),i=dk(s,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(t,n,r){throw Vk(n)&&n.code,n}}function zk(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 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{...e,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function Jk(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("mcp")||i.push(f)}return i}function Hk(e,t){var n,r;const o=e.options.projection??{},s=e.options.toolDescriptions??{},i=jk(e.options),a=Ik(e.options),c={},u={};for(const d of e.packages){if(!d.fns)throw new Error(`Package "${d.id}" is missing fns`);const g=d.fns,y=Object.entries(d.schemas).map(([O,j])=>({fnName:O,fnSchema:j,op:Fk({id:d.id,importPath:d.importPath},O,e.operations)})),$={},v={};for(const{fnName:O,fnSchema:j,op:C}of y)$[C.id]=j,v[C.id]=g[O],c[C.id]=j,u[C.id]=g[O];const E=Do($,i),b={fns:v,createClient:d.createClient,schemas:$};for(const{fnName:O,fnSchema:j,op:C}of y){const z=cl({op:C,schema:j,transport:"mcp",projection:o});t.bindSchema(C.id,j);const{outputSchema:U}=vp(j.output),q=nl(z.mcp.name,j,s[z.mcp.name]??s[O]);t.bindToolMeta(z.mcp.name,{description:q,inputSchema:j.input,outputSchema:U}),t.registerRoute(z,Q=>ul(z,E,Q,b))}}const l=((n=e.packages[0])==null?void 0:n.id)??"ts",f=Do(c,i),p={invoke:(d,g,y)=>f(d,{operation:{id:d},ctx:new mp,domainArgs:g.domainArgs,envelope:g.envelope,signal:g.signal},y),invokeOptions:{fns:u,schemas:c,createClient:(r=e.packages[0])==null?void 0:r.createClient}},h=Jk(i,a,l,e.operations??[],p);if(h.length>0){const d=Do({},i),g={fns:{},schemas:{}};for(const y of h){const $=cl({op:y,transport:"mcp",projection:o}),v=zk(y.input),E=nl($.mcp.name,{input:v},s[$.mcp.name]);t.bindToolMeta($.mcp.name,{description:E,inputSchema:v}),t.registerRoute($,b=>ul($,d,b,g))}}}function Lo(e,t){const n=new am.Server({name:"apigen-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(Wa.ListToolsRequestSchema,async()=>({tools:e.listTools()})),n.setRequestHandler(Wa.CallToolRequestSchema,async r=>{const{name:o,arguments:s={}}=r.params,i=e.getPlan(o),a=e.getDispatch(o);if(!i||!a)throw new Error(`Unknown tool: ${o}`);const c=s,u=c._meta??{},l={args:c,meta:u},f=Date.now();try{const p=await e.readCall(l,i),h=await a(p);return await e.writeResult(l,h,i),t.info({tool:o,ms:Date.now()-f},`→ ${o}`),l.output}catch(p){throw t.error({tool:o,ms:Date.now()-f,err:p},`✗ ${o}`),e.writeError(l,p,i),p}}),n}function ll(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")}}}async function Wk(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??z_();o.info(`mcp server starting (${t})`);const s=new Gk;Hk(e,s);const i=s.listTools().map(c=>c.name);o.info({tools:i},`${i.length} tools available`);for(const c of i){const u=s.getPlan(c),l=(u==null?void 0:u.params)??[],f=l.map(p=>`${p.name}${p.required?"":"?"}: ${p.type}`).join(", ");o.info({tool:c,args:{data:l}},`tool: ${c} args { data: {${f?` ${f} `:""}} }`)}if(t==="stdio"){const c=Lo(s,o),u=new cm.StdioServerTransport;return await c.connect(u),o.info("stdio transport ready"),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),l()})})}if(t==="sse"){const c=new Map,u=Ha.createServer(ll(o,async(l,f)=>{const p=l.url??"";if(l.method==="GET"&&p==="/sse"){const h=Lo(s,o),d=new um.SSEServerTransport("/messages",f);c.set(d.sessionId,d),d.onclose=()=>c.delete(d.sessionId),await h.connect(d)}else if(l.method==="POST"&&p.startsWith("/messages")){const h=new URLSearchParams(p.split("?")[1]??"").get("sessionId"),d=h?c.get(h):void 0;if(!d){f.writeHead(404),f.end("Session not found");return}await d.handlePostMessage(l,f)}else f.writeHead(404),f.end("Not found")}));return u.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),u.close(()=>l())})})}const a=Ha.createServer(ll(o,async(c,u)=>{const l=Lo(s,o),f=new lm.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await l.connect(f),await f.handleRequest(c,u)}));return a.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(c=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),a.close(()=>c())})})}const Yk={id:"mcp",run(e){return Wk(e)}},wp=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED"]),bp=new Set(["MITIGATED"]),Ep=new Set(["SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]),Ca=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Ue(e){return Ca.has(e)}function kr(e){return wp.has(e)||bp.has(e)}function Ar(e){return Ep.has(e)}class Sp extends Error{constructor(t,n,r=[]){const o=r.length>0?` - did you mean repo ${r.map(s=>`'${s}'`).join(" or ")}?`:"";super(`backlog item not found: ${t}::${n}${o}`),this.foundInRepos=r,this.name="BacklogItemNotFoundError"}}class Op extends Error{constructor(t){super(`transition to terminal status "${t}" requires at least one citation (either already attached via addCitation or passed inline to transitionStatus/resolveItem) — per the global CLAUDE.md rule "No citation, no claim."`),this.name="CitationRequiredError"}}class Np extends Error{constructor(t){super(`transition to terminal-dismissed status "${t}" requires a reason string`),this.name="ReasonRequiredError"}}class _p extends Error{constructor(t,n){super(`item is claimed by "${t}" since ${n} (not stale) — cannot start work`),this.heldBy=t,this.heldSince=n,this.name="ClaimHeldError"}}class Qk extends Error{constructor(t){super(`dependency cycle detected: ${t.join(" -> ")}`),this.cycle=t,this.name="DependencyCycleError"}}class Me extends Error{constructor(t,n){super(n),this.argument=t,this.name="InvalidArgumentError"}}class Ra extends Error{constructor(t,n,r){super(`backlog: ambiguous lookup — ${r.length} live items share the same (repo, humanId) key "${t}"::"${n}" (nodeIds: ${r.join(", ")}). Refusing to silently pick one — this is a data-integrity defect (see BUG-BACKLOG-HUMANID-COLLISION-001); repair the collision (e.g. rename one of these nodeIds to a distinct humanId) before retrying this operation.`),this.nodeIds=r,this.name="AmbiguousHumanIdError"}}function Zk(e,t){const n=t??T.join(He.homedir(),`.${e.orgNamespace}`);return T.join(n,e.project,e.namespace,"config.yaml")}function Xk(e,t,n){const r=Zk(e,n);let o={};if(L.existsSync(r))try{const a=Ya.parse(L.readFileSync(r,"utf8"));a!==null&&typeof a=="object"&&!Array.isArray(a)&&(o=a)}catch{o={}}const s=o.migration&&typeof o.migration=="object"&&!Array.isArray(o.migration)?o.migration:{},i={...o,migration:{...s,phase:t}};return L.mkdirSync(T.dirname(r),{recursive:!0}),L.writeFileSync(r,Ya.stringify(i),"utf8"),r}const be="backlog-item",fl="backlog-plan",dl="backlog-assignee",eA="adhd-backlog:";function tA(e){return Mn.createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Ma(e){return e.replace(/[^\p{L}\p{N}_\s]/gu," ").trim().replace(/\s+/g," ")}function Hr(e){return e.split("-")[0]??e}function Wr(e){return e.replace(/-\d+$/,"")}function Da(e,t,n,r){return`${n}
|
|
175
|
+
`}async function i_(e,t,n){const r=new AbortController;t.raw.once("close",()=>r.abort());const o=n.raw;let s=!1;try{for await(const i of e){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(o_(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=ga(i)?i:new zO("internal",i instanceof Error?i.message:String(i));if(s)o.write(s_(JSON.stringify(a.toJSON()))),o.end();else{const c=c_(a.code);o.writeHead(c,{"Content-Type":"application/json"}),o.end(JSON.stringify(a.toJSON()))}}n.hijack()}const a_={invalid_argument:400,unauthenticated:401,permission_denied:403,not_found:404,internal:500};function c_(e){return a_[e]??500}function dp(e){return ga(e)?GO[e.code]??500:500}function pp(e){return ga(e)?e.toJSON():{code:"internal",message:e instanceof Error?e.message:"Internal error"}}function u_(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)}}let l_=class{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(s,i)=>{const a={req:s,reply:i};try{const c=await this.readCall(a,t),u=await n(c);await this.writeResult(a,u,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,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?yN(c,a):c}else{const{data:c={}}=r.body??{};i=c}}return{envelope:s,domainArgs:i,signal:this.signal}}async writeResult(t,n,r){const{req:o,reply:s}=t;if(EN(n)){await i_(n,o,s);return}s.type("application/json"),s.send(JSON.stringify(n===void 0?null:n))}writeError(t,n,r){const{reply:o}=t;o.status(dp(n)).send(pp(n))}};function f_(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("http")||i.push(f)}return i}async function d_(e){var t,n;const r=e.options.port??3e3,o=e.options.host??"127.0.0.1",s=e.options.routePrefix??"",i=e.options.projection??{},a=YN(e.options),c=QN(e.options),u=e.logger??mN(),l=um({logger:u});l.setErrorHandler((E,b,O)=>{O.status(dp(E)).send(pp(E))});const f=new l_(l,s,e.signal),p=[],h={},d={};for(const E of e.packages){if(!E.fns)throw new Error(`Package "${E.id}" is missing fns`);const b=E.fns,O=Object.entries(E.schemas).map(([q,Q])=>({fnName:q,fnSchema:Q,op:r_(E.id,q,Q,e.operations)})),j={},C={};for(const{fnName:q,fnSchema:Q,op:Z}of O)j[Z.id]=Q,C[Z.id]=b[q],h[Z.id]=Q,d[Z.id]=b[q];const z=To(j,a),U={fns:C,createClient:E.createClient,schemas:j};for(const{fnSchema:q,op:Q}of O){const Z=Bu({op:Q,schema:q,transport:"http",projection:i});f.bindSchema(Q.id,q),f.registerRoute(Z,Fe=>Fu(Z,z,Fe,U));const{params:me,text:Ne}=lp(q);p.push({method:Z.http.verb,route:s+Z.http.route,text:Ne,params:me})}}const m=((t=e.packages[0])==null?void 0:t.id)??"ts",y=To(h,a),$={invoke:(E,b,O)=>y(E,{operation:{id:E},ctx:new cp,domainArgs:b.domainArgs,envelope:b.envelope,signal:b.signal},O),invokeOptions:{fns:d,schemas:h,createClient:(n=e.packages[0])==null?void 0:n.createClient}},v=f_(a,c,m,e.operations??[],$);if(v.length>0){const E=To({},a),b={fns:{},schemas:{}};for(const O of v){const j=Bu({op:O,transport:"http",projection:i});f.registerRoute(j,C=>Fu(j,E,C,b)),p.push({method:j.http.verb,route:`${s}/${O.id}`,text:"",params:[]})}}return await l.listen({port:r,host:o}),u.info({host:o,port:r},`listening on http://${o}:${r}`),u_(u,p),new Promise(E=>{e.signal&&e.signal.addEventListener("abort",async()=>{await l.close(),E()})})}const p_={id:"api-fastify",run(e){return d_(e)}};function Vu(e){return{raw:e,words:e.split(/(?=[A-Z])|[-_]/).map(t=>t.toLowerCase()).filter(Boolean)}}function h_(e,t,n={}){const r=e.split("/");if(r.length<2||r.some(u=>u.length===0))throw new Error(`syntheticOp: id "${e}" must be "<namespace>/<path...>" with non-empty segments`);const[o,...s]=r,i=o.replace(/^_+/,""),a=n.kind??"action",c={id:e,host:t.host,namespace:Vu(i),path:s.map(Vu),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 m_={"decimal.js":"Decimal"};function g_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(m_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${g_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));const Ku=new Set(["string","number","boolean","integer"]);function y_(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"?Ku.has(n):Array.isArray(n)?n.every(r=>Ku.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function $_(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(y_)}const v_={"decimal.js":"Decimal"};function w_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(v_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${w_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Gu(e){return e.words.join("-")}function zu(e){return e.words.map(E_).join("")}function Ju(e){return e.words.join("_")}function b_(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||$_(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>Gu(h)).join("/"),c=o.map(h=>Ju(h)).join("_"),u=o.map(h=>Ju(h)).slice(0,-1).join("."),l=zu(o[o.length-2]??o[0]),f=zu(o[o.length-1]),p=o.map(h=>Gu(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function E_(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function S_(e,t={}){const n=t.title??"API",r=t.version??"0.0.0",o={};for(const s of e){const i=b_(s),{verb:a,route:c}=i.http,u=a.toLowerCase(),l={operationId:s.id,summary:s.id,responses:{200:O_(s.output)}};if(a==="GET")l.parameters=N_(s.input);else{const f=s.input;typeof f=="object"&&f!==null&&Object.keys(f).length>0&&(l.requestBody={required:!0,content:{"application/json":{schema:f}}})}o[c]===void 0&&(o[c]={}),o[c][u]=l}return{openapi:"3.1.0",info:{title:n,version:r},paths:o}}function O_(e){return typeof e=="object"&&e!==null&&Object.keys(e).length>0?{description:"Success",content:{"application/json":{schema:e}}}:{description:"Success"}}function N_(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 __(e,t={}){return[{...h_("_meta/openapi",e,{kind:"query",safe:!0,output:{type:"object"},transports:["http"]}),handler:n=>S_(e.operations,{title:t.title,version:t.version})}]}const k_={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 __(e,t)}}}},Ps="$apigen";class Wu extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function A_(e){const t=new Map;return{register(n,r){if(t.has(n.id)&&!(r!=null&&r.override))throw new Wu(`E_DUP_CODEC: a codec is already registered for id "${n.id}"`);t.set(n.id,n)},resolve(n){for(const r of t.values())if(r.matches(n))return r},get(n){return t.get(n)},ids(){return[...t.keys()]},freeze(){const n=new Map(t),r={register(){throw new Wu("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 _a="x-apigen-logical",ka="x-apigen-codec",Ts="x-apigen-ctor",Cs="x-apigen-tojson",j_="0.1.0";function Hu(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 Vt(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 Vt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=hp(e,s,t);return Vt(e,a,n)}const i=t.type;if(i==="array"){if(!Array.isArray(e))return Co(e,t,n);const a=t.items;if(!a)return e.map(u=>_t(u));const c=n.path;return Array.isArray(a)?e.map((u,l)=>{const f=a[l];return f===void 0?_t(u):Vt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Vt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return Co(e,t,n);const a=t.properties;if(!a)return _t(e);const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Vt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?Co(e,t,n):_t(e)}function Kt(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 Kt(e,a,n)}const s=t.oneOf;if(Array.isArray(s)){const a=hp(e,s,t);return Kt(e,a,n)}const i=t.type;if(i==="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((u,l)=>{const f=a[l];return f===void 0?u:Kt(u,f,{...n,path:`${c}/${l}`})}):e.map((u,l)=>Kt(u,a,{...n,path:`${c}/${l}`}))}if(i==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const c=n.path,u={};for(const[l,f]of Object.entries(a)){const p=e[l];p!==void 0&&(u[l]=Kt(p,f,{...n,path:`${c}/${l}`}))}return u}return i==null?I_(e,n):e}function hp(e,t,n,r){const o=n.discriminator;if(o!=null&&o.propertyName){const s=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof s=="string"&&o.mapping){const i=o.mapping[s];if(i){const a=t.find(c=>c.$ref===i);if(a)return a}}}return t[0]??{}}function Co(e,t,n){for(const r of n.registry.ids()){const o=n.registry.get(r);if(o)try{const s=o.encode(e,o.schema,n);return{[Ps]:r,v:s}}catch{}}return _t(e)}function I_(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Ps in e){const n=e,r=n[Ps],o=t.registry.get(r);if(o)return o.decode(n.v,o.schema,t)}return e}function _t(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(_t);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))r!==void 0&&(t[n]=_t(r));return t}return null}function x_(e){return{encode(t,n,r){const o=Hu(e,r);return Vt(t,n,o)},decode(t,n,r){const o=Hu(e,r);return Kt(t,n,o)}}}const Aa={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},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)}},ja={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},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)}},Ia={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}},xa={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},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"))}},P_=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Pa={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"&&!P_.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},Rs="NaN",Ms="Infinity",Ds="-Infinity",T_=new Set([Rs,Ms,Ds]),Ta={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,n){return Number.isNaN(e)?Rs:e===1/0?Ms:e===-1/0?Ds:e},decode(e,t,n){if(typeof e=="number")return e;if(typeof e=="string"){if(e===Rs)return NaN;if(e===Ms)return 1/0;if(e===Ds)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 ${[...T_].join(", ")}.`);return NaN}},C_=[Aa,ja,Ia,xa,Pa,Ta];function R_(e,t={}){for(const n of C_)e.register(n,{override:t.override??!1})}const M_=12;function D_(e,t){const n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;const[,r,o]=n,s=r==="$defs"?t.$defs:t.definitions;return s==null?void 0:s[decodeURIComponent(o)]}function Yu(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function L_(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 U_(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 Qu(e,t,n){const r=e.properties??{},o=e.required??[],s={};for(const i of o){const a=r[i];s[i]=a!==void 0?Tn(a,t,n+1):`<${i}>`}return s}function B_(e,t,n){const r=Array.isArray(e.items)?e.items[0]:e.items;return r?[Tn(r,t,n+1)]:[]}function Tn(e,t=e??{},n=0){if(!e||n>M_)return null;if(typeof e.$ref=="string"){const o=D_(e.$ref,t);return o!==void 0?Tn(o,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 o={},s=[];for(const i of e.allOf){Object.assign(o,i.properties??{});for(const a of i.required??[])s.includes(a)||s.push(a)}return Qu({...e,properties:o,required:s},t,n)}const r=Yu(e.oneOf)??Yu(e.anyOf);if(r)return Tn(r,t,n+1);switch(L_(e)){case"object":return Qu(e,t,n);case"array":return B_(e,t,n);case"string":return U_(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function mp(e){if(!e)return;const t=Tn(e);return`Example: ${JSON.stringify(t)}`}Aa.id,ja.id,Ia.id,xa.id,Pa.id,Ta.id;const gp=A_();R_(gp);const yp=x_(gp.freeze());function F_(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function q_(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.properties)==null?void 0:n.data;return Object.keys((r==null?void 0:r.properties)??{})}function V_(e,t){var n,r,o;const s=(o=(r=(n=e.input)==null?void 0:n.properties)==null?void 0:r.data)==null?void 0:o.properties,i=s==null?void 0:s[t];return i!==void 0?i:void 0}function K_(e,t){return t===void 0||e===void 0?e:yp.decode(e,t)}function Ro(e,t){const n=t.output;return!n||Object.keys(n).length===0?e:yp.encode(e,n)}async function G_(e,t,n,r,o,s){const i=q_(n).map(c=>K_(s[c],V_(n,c)));if(F_(n,"session")&&t){const c=await t({session:o.session}),u=await e[r](c,...i);return Ro(u,n)}if(n.hasCtx){const c=t?await t(o):void 0,u=await e[r](c,...i);return Ro(u,n)}const a=await e[r](...i);return Ro(a,n)}let $p=class{constructor(){this._map=new Map}set(e,t){this._map.set(e,t)}get(e){return this._map.get(e)}has(e){return this._map.has(e)}};function z_(e=[]){return async function(t,n,r){const o=r.schemas[t];if(!o)throw new Error(`apigen/invoke: no schema found for operation "${t}"`);const s=()=>G_(r.fns,r.createClient,o,t,n.envelope,n.domainArgs);return e.reduceRight((i,a)=>()=>a(n,i),s)()}}const J_={"decimal.js":"Decimal"};function W_(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(J_).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${W_(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function H_(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"),s={level:t};if(o==="pretty")return s.transport={target:"pino-pretty",options:{colorize:!n,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...n?{destination:e.destination,mkdir:!0}:{destination:2}}},ke(s);const i=n?ke.destination({dest:e.destination,mkdir:!0,sync:!0}):ke.destination(2);return ke(s,i)}function vp(e){return e?e.type==="array"?`${vp(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Y_(e){var t;const n=(t=((e==null?void 0:e.input)??{}).properties)==null?void 0:t.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:vp(c),required:o.has(a)})),i=s.map(a=>`${a.name}${a.required?"":"?"}: ${a.type}`).join(", ");return{params:s,text:i}}const Q_=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class wp 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 Z_(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&Q_.includes(e.code)&&typeof e.toJSON=="function"}function Zu(e,t,n=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}const Jr=new jr({allErrors:!0});Ir(Jr);for(const e of[_a,ka,Ts,Cs,"discriminator"])Jr.addKeyword({keyword:e,valid:!0});Jr.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function X_(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function ek(e,t){const n=mp(t),r=[`Validation failed: ${X_(e)}`];return n&&r.push(n),r.join(" — ")}function tk(e){return async function(t,n){const r=t.operation.id,o=e[r];if(o===void 0)return n();const s={data:t.domainArgs,...t.envelope},i=Jr.compile(o.input);if(!i(s)){const a=i.errors??[];throw new wp("invalid_argument",ek(a,o.input),a)}return n()}}async function nk(e){const t=[];try{for await(const n of e)t.push(n);return{ok:!0,chunks:t}}catch(n){const r=Z_(n)?n:new wp("internal",n instanceof Error?n.message:String(n));return t.length===0?{ok:!1,carrier:Zu("before-first-chunk",r)}:{ok:!1,carrier:Zu("after-first-chunk",r,t.length)}}}function rk(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class ht extends Error{constructor(t,n){super(n),this.name="UnionCodecError",this.code=t}}function Mo(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 bp(e,t){const n=e[ka];if(typeof n=="string"){const r=t.registry.get(n);if(r)return r}return t.registry.resolve(e)}function ok(e,t,n){const r=bp(t,n);return r?r.encode(e,t,n):e}function sk(e,t,n){const r=bp(t,n);return r?r.decode(e,t,n):e}function ik(e){const{id:t,schema:n}=e;return{id:t,kind:"union",schema:n,matches(r){if(r[_a]==="union")return!0;const o=r.oneOf;return!Array.isArray(o)||o.length===0?!1:Mo(r)!==void 0},encode(r,o,s){const i=Mo(o);if(!i)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 ht("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${s.path}" is missing the discriminator property "${a}".`);const l=String(u),f=c[l];if(!f)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" at "${s.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const p=s.resolve(f);return ok(r,p,{...s,path:`${s.path}[${l}]`})},decode(r,o,s){if(r===null||typeof r!="object"||Array.isArray(r)){let d;throw r===null?d="null":Array.isArray(r)?d="array":d=typeof r,new ht("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${d}.`)}const i=r,a=Mo(o);if(!a)throw new ht("E_UNION_NO_DISCRIMINATOR",`[${t}] 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 ht("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${s.path}" is missing the discriminator property "${c}".`);const f=String(l),p=u[f];if(!p)throw new ht("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${f}" on the wire at "${s.path}" is not in the mapping (known: ${Object.keys(u).join(", ")}).`);const h=s.resolve(p);return sk(r,h,{...s,path:`${s.path}[${f}]`})}}}const ak="x-apigen-instances";class or extends Error{constructor(t,n){super(n),this.name="NominalCodecError",this.code=t}}function Xu(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function ck(e){const t=e.required;return Array.isArray(t)?t.filter(n=>typeof n=="string"):[]}function el(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function uk(e,t,n){if(t){const r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function lk(e){const{id:t,schema:n,ctor:r}=e;return{id:t,kind:"nominal",schema:n,matches(o){return o[_a]==="nominal"?!0:o[ka]===t},encode(o,s,i){if(o===null||typeof o!="object")return o;if(i.seen.has(o)){if(i.mode==="strict")throw new or("E_NOMINAL_CYCLE",`[${t}] 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=Xu(s),c=typeof s[Cs]=="string"?s[Cs]:"toJSON",u=o[c];if(typeof u=="function"){const d=u.call(o);if(d!==null&&typeof d=="object"&&!Array.isArray(d)){const m={};for(const[y,$]of Object.entries(d))m[y]=el($,a[y],{...i,path:`${i.path}/${y}`});return m}return d}const l={},f=Object.keys(a),p=o,h=f.length>0?f:Object.keys(p);for(const d of h){const m=p[d];m!==void 0&&(l[d]=el(m,a[d],{...i,path:`${i.path}/${d}`}))}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 or("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${l}.`)}const a=o;for(const l of ck(s))if(!(l in a))throw new or("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${l}" missing on the wire at "${i.path}".`);if(s[ak]===!1)throw new or("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=Xu(s),u={};for(const[l,f]of Object.entries(a))u[l]=uk(f,c[l],{...i,path:`${i.path}/${l}`});if(r){const l=typeof s[Ts]=="string"?s[Ts]:"fromJSON",f=r[l];if(typeof f=="function")return f.call(r,u);const p=r;return new p(u)}return u}}}const fk=[Aa,ja,Ia,xa,Pa,Ta],dk={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},tl=lk({id:"ts.NominalSentinel",schema:dk}),pk={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},nl=ik({id:"ts.UnionSentinel",schema:pk});function hk(){const e=[...fk.map(t=>[t.id,t]),[tl.id,tl],[nl.id,nl]];return Object.freeze(new Map(e))}Object.freeze({host:"ts",logicalTypeVersion:j_,codecs:hk()});function rl(e,t,n){var r;const o=typeof((r=t==null?void 0:t.input)==null?void 0:r.description)=="string"?t.input.description:void 0,s=mp(t==null?void 0:t.input),i=[n,o,s].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" — "):e}function Ep(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:!1}:{outputSchema:{type:"object",properties:{result:t},required:["result"]},wrapped:!0}}function mk(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const ol=new Set(["string","number","boolean","integer"]);function gk(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"?ol.has(n):Array.isArray(n)?n.every(r=>ol.has(r)||r==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(r=>["string","number","boolean"].includes(typeof r)):!1}function yk(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(gk)}const $k={"decimal.js":"Decimal"};function vk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries($k).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${vk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function sl(e){return e.words.join("-")}function il(e){return e.words.map(Ok).join("")}function al(e){return e.words.join("_")}function wk(e,t={}){var n,r;const o=[e.namespace,...e.path],s=e.safe||yk(e.input)?"GET":"POST",i=((r=(n=t.http)==null?void 0:n.verb)==null?void 0:r[e.id])??s,a="/"+o.map(h=>sl(h)).join("/"),c=o.map(h=>al(h)).join("_"),u=o.map(h=>al(h)).slice(0,-1).join("."),l=il(o[o.length-2]??o[0]),f=il(o[o.length-1]),p=o.map(h=>sl(h));return{http:{verb:i,route:a},mcp:{name:c},grpc:{package:u,service:l,method:f},cli:{path:p}}}function bk(e,t){return`x-${e}-${t}`}function Ek(e,t){return`--${e}-${t}`}function Sk(e,t){const n=r=>r.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Ok(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Ca(e){return e.anyOf??e.oneOf}function Nk(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=Ca(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 _k(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=Ca(e);if(t){const n=t.filter(r=>r.type!=="null");return n.length>0&&n.every(r=>r.type==="boolean")}return!1}function kk(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=Ca(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 Ak(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function jk(e){var t,n;const r=(n=(t=e.input)==null?void 0:t.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 cl(e){return typeof e.handler=="function"}function Ik(e){var t;const n=((t=e.input)==null?void 0:t.properties)??{},r=e["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=bk(i,s);o.push({field:s,pluginId:i,httpHeader:a,mcpMetaKey:a,cliFlag:Ek(i,s),envVar:Sk(i,s)})}return o}function xk(e,t){const n=new Map,{props:r}=jk(e);for(const[o,s]of Object.entries(r)){let i="string";_k(s)?i="boolean":(Nk(s)||kk(s))&&(i="json"),n.set(Ak(o),{camelKey:o,kind:"domain",valueKind:i})}for(const o of t){const s=o.cliFlag.replace(/^--/,"");n.set(s,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return n}function ul(e){const{op:t,schema:n,transport:r,projection:o}=e,s=wk(t,o),i=n?Ik(n):[],a=n?xk(n,i):new Map,c=n?Y_(n).params:void 0,u={op:t,transport:r,http:s.http,mcp:s.mcp,cli:s.cli,grpc:s.grpc,params:c,envelope:i,cliFlags:a,streaming:t.streaming,isMount:cl(t)};if(cl(t)){const l=t.handler;u.mountHandler=async f=>l(f)}return u}function Pk(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function Tk(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Ck(e){return async function(t,n){const r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function Do(e,t){var n;const r=[];for(const o of t){const s=(n=o.capabilities)==null?void 0:n.layer;s&&r.push(Ck(s))}return r.push(tk(e)),z_(r)}function Rk(){const e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}const Mk={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function ll(e,t,n,r){const o={...n,operation:{id:e.op.id},ctx:new $p};if(e.isMount){const s=e.mountHandler;if(!s)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const i={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:Rk(),transport:e.transport,signal:n.signal??new AbortController().signal},a={...r,fns:{[e.op.id]:()=>s(i)},schemas:{[e.op.id]:Mk}};return t(e.op.id,o,a)}return t(e.op.id,o,r)}const Dk={"decimal.js":"Decimal"};function Lk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Dk).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Lk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function Uk(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)}const Bk={"decimal.js":"Decimal"};function Fk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Bk).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Fk(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function qk(e){return e.replace(/\.[^.]+$/,"").replace(/[._]+/g,"-")}function Ls(e){return{raw:e,words:Uk(e)}}function Vk(e){return Ls(qk(Bo.basename(e)))}function Kk(e,t,n){if(n){const o=n.find(s=>{var i;return s.kind==="action"&&s.namespace.raw===e.id&&((i=s.path[s.path.length-1])==null?void 0:i.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=Ls(t);return{id:`${e.id}/${t}`,host:"ts",namespace:Ls(e.id),path:e.dropFileSegment?[r]:[Vk(e.importPath),r],kind:"action",async:!1,streaming:!1,safe:!1,input:{},output:{},envelope:{},typeText:null}}const Gk=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];function zk(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&Gk.includes(e.code)&&typeof e.toJSON=="function"}async function Jk(e){const t=await nk(e);if(t.ok){const o=t.chunks.map(s=>({type:"text",text:JSON.stringify(s)}));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}}class Wk{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.toolMeta.set(t,n)}registerRoute(t,n){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(){return[...this.plans.keys()].map(t=>{const n=this.toolMeta.get(t);return{name:t,description:(n==null?void 0:n.description)??t,inputSchema:(n==null?void 0:n.inputSchema)??{type:"object",properties:{}},...n!=null&&n.outputSchema?{outputSchema:n.outputSchema}:{}}})}readCall(t,n){const r={};for(const s of n.envelope){const i=t.meta[s.mcpMetaKey];i!==void 0&&(r[s.field]=i)}const o=n.isMount?t.args:t.args.data??{};return{envelope:r,domainArgs:o}}async writeResult(t,n,r){if(rk(n)){t.output=await Jk(n);return}const o=this.schemasByOpId.get(r.op.id),{wrapped:s}=Ep(o==null?void 0:o.output),i=mk(s,n);t.output={content:[{type:"text",text:JSON.stringify(n)}],...i?{structuredContent:i}:{}}}writeError(t,n,r){throw zk(n)&&n.code,n}}function Hk(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 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{...e,type:"object",properties:n,...r&&r.length>0?{required:r}:{}}}return{type:"object",properties:{}}}function Yk(e,t,n,r,o){var s;const i=[],a={host:n,operations:r};for(const c of e){const u=(s=c.capabilities)==null?void 0:s.mount;if(!u)continue;const l=u.operations(a,t[c.id],o);for(const f of l)f.transports&&!f.transports.includes("mcp")||i.push(f)}return i}function Qk(e,t){var n,r;const o=e.options.projection??{},s=e.options.toolDescriptions??{},i=Pk(e.options),a=Tk(e.options),c={},u={};for(const d of e.packages){if(!d.fns)throw new Error(`Package "${d.id}" is missing fns`);const m=d.fns,y=Object.entries(d.schemas).map(([O,j])=>({fnName:O,fnSchema:j,op:Kk({id:d.id,importPath:d.importPath},O,e.operations)})),$={},v={};for(const{fnName:O,fnSchema:j,op:C}of y)$[C.id]=j,v[C.id]=m[O],c[C.id]=j,u[C.id]=m[O];const E=Do($,i),b={fns:v,createClient:d.createClient,schemas:$};for(const{fnName:O,fnSchema:j,op:C}of y){const z=ul({op:C,schema:j,transport:"mcp",projection:o});t.bindSchema(C.id,j);const{outputSchema:U}=Ep(j.output),q=rl(z.mcp.name,j,s[z.mcp.name]??s[O]);t.bindToolMeta(z.mcp.name,{description:q,inputSchema:j.input,outputSchema:U}),t.registerRoute(z,Q=>ll(z,E,Q,b))}}const l=((n=e.packages[0])==null?void 0:n.id)??"ts",f=Do(c,i),p={invoke:(d,m,y)=>f(d,{operation:{id:d},ctx:new $p,domainArgs:m.domainArgs,envelope:m.envelope,signal:m.signal},y),invokeOptions:{fns:u,schemas:c,createClient:(r=e.packages[0])==null?void 0:r.createClient}},h=Yk(i,a,l,e.operations??[],p);if(h.length>0){const d=Do({},i),m={fns:{},schemas:{}};for(const y of h){const $=ul({op:y,transport:"mcp",projection:o}),v=Hk(y.input),E=rl($.mcp.name,{input:v},s[$.mcp.name]);t.bindToolMeta($.mcp.name,{description:E,inputSchema:v}),t.registerRoute($,b=>ll($,d,b,m))}}}function Lo(e,t){const n=new lm.Server({name:"apigen-mcp",version:"1.0.0"},{capabilities:{tools:{}}});return n.setRequestHandler(Ya.ListToolsRequestSchema,async()=>({tools:e.listTools()})),n.setRequestHandler(Ya.CallToolRequestSchema,async r=>{const{name:o,arguments:s={}}=r.params,i=e.getPlan(o),a=e.getDispatch(o);if(!i||!a)throw new Error(`Unknown tool: ${o}`);const c=s,u=c._meta??{},l={args:c,meta:u},f=Date.now();try{const p=await e.readCall(l,i),h=await a(p);return await e.writeResult(l,h,i),t.info({tool:o,ms:Date.now()-f},`→ ${o}`),l.output}catch(p){throw t.error({tool:o,ms:Date.now()-f,err:p},`✗ ${o}`),e.writeError(l,p,i),p}}),n}function fl(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")}}}async function Zk(e){const t=e.options.transport??"stdio",n=e.options.port??3e3,r=e.options.host??"127.0.0.1",o=e.logger??H_();o.info(`mcp server starting (${t})`);const s=new Wk;Qk(e,s);const i=s.listTools().map(c=>c.name);o.info({tools:i},`${i.length} tools available`);for(const c of i){const u=s.getPlan(c),l=(u==null?void 0:u.params)??[],f=l.map(p=>`${p.name}${p.required?"":"?"}: ${p.type}`).join(", ");o.info({tool:c,args:{data:l}},`tool: ${c} args { data: {${f?` ${f} `:""}} }`)}if(t==="stdio"){const c=Lo(s,o),u=new fm.StdioServerTransport;return await c.connect(u),o.info("stdio transport ready"),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),l()})})}if(t==="sse"){const c=new Map,u=Ha.createServer(fl(o,async(l,f)=>{const p=l.url??"";if(l.method==="GET"&&p==="/sse"){const h=Lo(s,o),d=new dm.SSEServerTransport("/messages",f);c.set(d.sessionId,d),d.onclose=()=>c.delete(d.sessionId),await h.connect(d)}else if(l.method==="POST"&&p.startsWith("/messages")){const h=new URLSearchParams(p.split("?")[1]??"").get("sessionId"),d=h?c.get(h):void 0;if(!d){f.writeHead(404),f.end("Session not found");return}await d.handlePostMessage(l,f)}else f.writeHead(404),f.end("Not found")}));return u.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(l=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),u.close(()=>l())})})}const a=Ha.createServer(fl(o,async(c,u)=>{const l=Lo(s,o),f=new pm.StreamableHTTPServerTransport({sessionIdGenerator:void 0});await l.connect(f),await f.handleRequest(c,u)}));return a.listen(n,r,()=>{o.info({host:r,port:n},`listening on http://${r}:${n}`)}),new Promise(c=>{e.signal&&e.signal.addEventListener("abort",()=>{o.info("mcp server shutting down"),a.close(()=>c())})})}const Xk={id:"mcp",run(e){return Zk(e)}},Sp=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED"]),Op=new Set(["MITIGATED"]),Np=new Set(["SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]),Ra=new Set(["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Ue(e){return Ra.has(e)}function kr(e){return Sp.has(e)||Op.has(e)}function Ar(e){return Np.has(e)}class _p extends Error{constructor(t,n,r=[]){const o=r.length>0?` - did you mean repo ${r.map(s=>`'${s}'`).join(" or ")}?`:"";super(`backlog item not found: ${t}::${n}${o}`),this.foundInRepos=r,this.name="BacklogItemNotFoundError"}}class kp extends Error{constructor(t){super(`transition to terminal status "${t}" requires at least one citation (either already attached via addCitation or passed inline to transitionStatus/resolveItem) — per the global CLAUDE.md rule "No citation, no claim."`),this.name="CitationRequiredError"}}class Ap extends Error{constructor(t){super(`transition to terminal-dismissed status "${t}" requires a reason string`),this.name="ReasonRequiredError"}}class jp extends Error{constructor(t,n){super(`item is claimed by "${t}" since ${n} (not stale) — cannot start work`),this.heldBy=t,this.heldSince=n,this.name="ClaimHeldError"}}class eA extends Error{constructor(t){super(`dependency cycle detected: ${t.join(" -> ")}`),this.cycle=t,this.name="DependencyCycleError"}}class Me extends Error{constructor(t,n){super(n),this.argument=t,this.name="InvalidArgumentError"}}class Ma extends Error{constructor(t,n,r){super(`backlog: ambiguous lookup — ${r.length} live items share the same (repo, humanId) key "${t}"::"${n}" (nodeIds: ${r.join(", ")}). Refusing to silently pick one — this is a data-integrity defect (see BUG-BACKLOG-HUMANID-COLLISION-001); repair the collision (e.g. rename one of these nodeIds to a distinct humanId) before retrying this operation.`),this.nodeIds=r,this.name="AmbiguousHumanIdError"}}function tA(e,t){const n=t??T.join(We.homedir(),`.${e.orgNamespace}`);return T.join(n,e.project,e.namespace,"config.yaml")}function nA(e,t,n){const r=tA(e,n);let o={};if(L.existsSync(r))try{const a=Qa.parse(L.readFileSync(r,"utf8"));a!==null&&typeof a=="object"&&!Array.isArray(a)&&(o=a)}catch{o={}}const s=o.migration&&typeof o.migration=="object"&&!Array.isArray(o.migration)?o.migration:{},i={...o,migration:{...s,phase:t}};return L.mkdirSync(T.dirname(r),{recursive:!0}),L.writeFileSync(r,Qa.stringify(i),"utf8"),r}const be="backlog-item",dl="backlog-plan",pl="backlog-assignee",rA="adhd-backlog:";function oA(e){return Mn.createHash("sha256").update(e.trim().toLowerCase()).digest("hex")}function Da(e){return e.replace(/[^\p{L}\p{N}_\s]/gu," ").trim().replace(/\s+/g," ")}function Wr(e){return e.split("-")[0]??e}function Hr(e){return e.replace(/-\d+$/,"")}function La(e,t,n,r){return`${n}
|
|
176
176
|
|
|
177
177
|
${r}
|
|
178
178
|
|
|
179
|
-
<!-- ${eA}${e}::${t} -->`}function La(e,t){return`${e}::${t}`}function Ua(e){switch(e){case"CRITICAL":return 10;case"HIGH":return 8;case"MEDIUM":return 5;case"LOW":return 2;default:return 1}}function kp(e,t,n=[]){return[...new Set([be,e,t,...n])]}function De(e){return e.tags.includes(be)&&!e.isSuperseded}function ie(e){const t=e.metadata??{},n=t.humanId??"",r=t.kind??Hr(n),o=t.family??Wr(n),s=new Set([be,r,o]);return{nodeId:e.id,humanId:n,kind:r,family:o,title:t.title??e.summary??"",body:t.body??"",status:t.status??"UNKNOWN",priority:t.priority,repo:t.repo??e.namespace,projectPath:t.projectPath,plan:t.plan,importedFrom:t.importedFrom,assignee:t.assignee,claimedBy:t.claimedBy,claimedAt:t.claimedAt,citations:t.citations??[],notes:t.notes??[],tags:e.tags.filter(i=>!s.has(i)),createdAt:t.createdAt??e.tCreated,updatedAt:t.updatedAt??t.createdAt??e.tCreated}}const nA=5,rA=20,oA=500;function sA(e){const t=e==null?void 0:e.code;return t==="SQLITE_BUSY"||t==="SQLITE_BUSY_TIMEOUT"||t==="SQLITE_BUSY_SNAPSHOT"}function iA(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Math.max(0,Math.round(e)))}function Ap(e,t={}){const n=t.maxAttempts??nA;for(let r=0;;r++)try{return e()}catch(o){if(!sA(o)||r>=n-1)throw o;const s=Math.min(oA,rA*2**r);iA(s*(.5+Math.random()*.5))}}function aA(e,t,n){if(typeof n!="string"||n.trim().length===0)throw new Me("family",`backlog: cannot allocate a humanId for repo=${JSON.stringify(t)} — "family" is required and must be a non-empty string, received ${JSON.stringify(n)}. See BUG-BACKLOG-HUMANID-COLLISION-001.`);const r=e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{family:n}});let o=0;for(const s of r){const i=s.metadata,a=/-(\d+)$/.exec((i==null?void 0:i.humanId)??"");a&&(o=Math.max(o,Number(a[1])))}return`${n}-${String(o+1).padStart(3,"0")}`}function cA(e,t,n){const o=e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{humanId:n}}).filter(s=>{var i;return De(s)&&((i=s.metadata)==null?void 0:i.humanId)===n});if(o.length>1)throw new Ra(t,n,o.map(s=>s.id));return o[0]??null}function jp(e,t,n,r,o){return Ap(()=>e.db.transaction(()=>{if(r){const i=cA(e,t,r);return o(r,i)}const s=aA(e,t,n);return o(s,null)}).immediate())}const Ip="backlog-audit-event";function xp(e,t,n,r,o,s){const i=new Date().toISOString(),a={itemNodeId:t,kind:o,at:i,detail:s},c=`audit-event::${n}::${r}::${o}::${i}::${Math.random().toString(36).slice(2)}`,u=e.graph.writeNode(c,{kind:"generic",name:`audit-event::${n}::${r}::${i}`,tags:[Ip],namespace:n,metadata:a});e.graph.writeEdge(u,t,"DERIVED_FROM")}function uA(e,t){return e.graph.queryNodes({kind:"generic",tags:[Ip],metadata:{itemNodeId:t}}).map(r=>r.metadata).filter(r=>r!==void 0&&r.itemNodeId===t).map(r=>({at:r.at,kind:r.kind,detail:r.detail})).sort((r,o)=>r.at.localeCompare(o.at))}const pl={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3};function hl(e){const t=[be];e.kind&&t.push(e.kind),e.tags&&t.push(...e.tags);const n={};e.family&&(n.family=e.family),e.priority&&(n.priority=e.priority),e.plan&&(n.plan=e.plan),e.importedFrom&&(n.importedFrom=e.importedFrom),e.assignee&&(n.assignee=e.assignee),e.claimedBy&&(n.claimedBy=e.claimedBy),e.status&&e.status!=="open"&&e.status!=="closed"&&(n.status=e.status);const r={kind:"generic",tags:t,tagsMatchAll:!0};return e.repo!==void 0&&(r.namespace=e.repo),e.projectPath!==void 0&&(r.projectPath=e.projectPath),Object.keys(n).length>0&&(r.metadata=n),r}function lA(e,t){return t.status==="open"?e.filter(n=>!Ue(n.status)):t.status==="closed"?e.filter(n=>Ue(n.status)):e}function ml(e,t){return t.rootLevel?e.filter(n=>{const r=n.metadata;return!(r!=null&&r.projectPath)&&!(r!=null&&r.plan)}):e}function gl(e,t){return t.excludeArchived?e.filter(n=>{var r;return!((r=n.metadata)!=null&&r.archivedAt)}):e}function Pp(e,t={}){if(t.grep){const o=hl({...t}),s=Ma(t.grep);if(!s)return[];const i=e.graph.searchNodes(s,{limit:t.limit??1e3,filter:o});let a=gl(ml(i.filter(De),t),t);return t.offset&&(a=a.slice(t.offset)),a}const n=hl(t);t.limit!==void 0&&(n.limit=t.limit),t.offset!==void 0&&(n.offset=t.offset);const r=e.graph.queryNodes(n);return gl(ml(r.filter(De),t),t)}function ct(e,t={}){const r=Pp(e,t).map(ie);return lA(r,t)}function Qe(e,t,n){const r=La(t,n),s=e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{humanId:n}}).filter(De);if(s.length>1)throw new Ra(t,n,s.map(i=>i.id));return s.find(i=>i.name===r)??s[0]??null}function Ls(e){var t;return((t=e.metadata)==null?void 0:t.repo)??e.namespace??""}function fA(e,t){return e.graph.queryNodes({kind:"generic",tags:[be],metadata:{humanId:t}}).filter(De)}function Tp(e){const t=e.graph.queryNodes({kind:"generic",tags:[be]}),n=new Set;for(const r of t){if(!De(r))continue;const o=Ls(r);o&&n.add(o)}return n}function Se(e,t,n){const r=fA(e,n).filter(s=>Ls(s)!==t),o=[...new Set(r.map(Ls).filter(s=>s.length>0))];return new Sp(t,n,o)}function ln(e,t){const n={};for(const r of e){const o=t(r);o&&(n[o]=(n[o]??0)+1)}return n}function dA(e,t={}){const n=ct(e,{repo:t.repo,projectPath:t.projectPath}),r=n.filter(s=>!Ue(s.status)),o=n.filter(s=>Ue(s.status));return{total:n.length,open:r.length,closed:o.length,byStatus:ln(n,s=>s.status),byKind:ln(n,s=>s.kind),byFamily:ln(n,s=>s.family),byPriority:ln(n,s=>s.priority),byRepo:t.repo===void 0?ln(n,s=>s.repo):{}}}function pA(e,t={},n=20){const o=ct(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}).filter(s=>s.priority!==void 0);return o.sort((s,i)=>{const a=pl[s.priority??""]??4,c=pl[i.priority??""]??4;return a-c||s.humanId.localeCompare(i.humanId)}),o.slice(0,n)}function Cp(e,t){const n=e.graph.getEdges({src:t,rel:"DEPENDS_ON"}),r=[];for(const o of n){const s=e.graph.getNode(o.dst);s&&r.push(s)}return r}function hA(e,t,n){const r=Qe(e,t,n);return r?Cp(e,r.id).filter(o=>!o.tInvalid).map(ie).filter(o=>!Ue(o.status)):[]}function mA(e,t={}){return ct(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}).filter(r=>{if(r.claimedBy)return!1;const o=Qe(e,r.repo,r.humanId);return o?Cp(e,o.id).filter(i=>!i.tInvalid).every(i=>Ue(ie(i).status)):!1})}function Rp(e,t={}){const n=ct(e,{repo:t.repo,projectPath:t.projectPath}),r=n.map(s=>({humanId:s.humanId,title:s.title,status:s.status})),o=[];for(const s of n){const i=Qe(e,s.repo,s.humanId);if(i)for(const a of["DEPENDS_ON","RELATES_TO","PART_OF"])for(const c of e.graph.getEdges({src:i.id,rel:a})){const u=e.graph.getNode(c.dst);if(!u||u.tInvalid)continue;const l=u.metadata;l!=null&&l.humanId&&o.push({from:s.humanId,to:l.humanId,rel:a})}}return{nodes:r,edges:o}}function gA(e,t={}){var c;const n=Rp(e,t),r=n.edges.filter(u=>u.rel==="DEPENDS_ON"),o=new Map;for(const u of n.nodes)o.set(u.humanId,new Set);for(const u of r)(c=o.get(u.from))==null||c.add(u.to);const s=new Set(n.nodes.map(u=>u.humanId)),i=[];let a=!0;for(;s.size>0&&a;){a=!1;for(const u of[...s].sort())[...o.get(u)??new Set].every(p=>!s.has(p))&&(i.push(u),s.delete(u),a=!0)}return s.size>0?{ok:!1,cycle:yA([...s],o)}:{ok:!0,order:i}}function yA(e,t){const n=new Set(e),r=new Set,o=[];function s(i){if(r.has(i)){const a=o.indexOf(i);return[...o.slice(a),i]}if(!n.has(i))return null;r.add(i),o.push(i);for(const a of t.get(i)??[]){const c=s(a);if(c)return c}return o.pop(),r.delete(i),null}for(const i of e){const a=s(i);if(a)return a}return e}function $A(e,t,n={}){const r=ct(e,{repo:n.repo,projectPath:n.projectPath}),o=t*6e4,s=Date.now();return r.filter(i=>!i.claimedBy||!i.claimedAt?!1:s-Date.parse(i.claimedAt)>=o)}function vA(e,t,n){var u,l,f,p;const r=Qe(e,t,n);if(!r)throw Se(e,t,n);const o=ie(r),s=[{at:o.createdAt,kind:"created",detail:{title:o.title,repo:o.repo}}];for(const h of o.citations)s.push({at:o.updatedAt,kind:"citation",detail:{...h}});for(const h of o.notes)s.push({at:h.at,kind:"note",detail:{by:h.by,text:h.text}});s.push(...uA(e,r.id)),s.sort((h,d)=>h.at.localeCompare(d.at));const i=e.graph.getSupersessionChain(r.id);let a;if(i.length>1){const h=i.findIndex(y=>y.id===r.id),d=h>0?((l=(u=i[h-1])==null?void 0:u.metadata)==null?void 0:l.humanId)??void 0:void 0,g=h>=0&&h<i.length-1?((p=(f=i[h+1])==null?void 0:f.metadata)==null?void 0:p.humanId)??void 0:void 0;a={},d&&(a.supersedes=d),g&&(a.supersededBy=g)}const c={humanId:o.humanId,history:s};return a&&(c.supersessionChain=a),c}class wA extends Error{constructor(t){super(`backlog item not found or invalidated: node ${t}`),this.nodeId=t,this.name="NotFoundError"}}function Oe(e,t,n){return Ap(()=>e.db.transaction(()=>{const r=e.graph.getNode(t);if(!r||r.tInvalid)throw new wA(t);const o=r.metadata??{},s=n(o);return e.graph.touch(t,{metadata:s}),s}).immediate())}const bA=new Set(["a","an","and","are","as","at","be","been","but","by","can","do","does","for","from","had","has","have","if","in","into","is","it","its","no","not","of","on","or","our","so","such","than","that","the","their","then","there","these","this","to","was","were","will","with","would","you","your"]),EA=.5;function Mp(e){return Ma(e).toLowerCase().split(" ").filter(t=>t.length>0&&!bA.has(t))}function SA(e,t){if(e.length===0)return!0;const n=new Set(Mp(t));return e.filter(o=>n.has(o)).length/e.length>=EA}function OA(e,t,n){var i;const r=new Map,o=Ma(n.title);if(o){const a=Mp(n.title);for(const c of e.graph.searchNodes(o,{limit:10,filter:{tags:[be],namespace:t}})){if(!De(c))continue;const u=((i=c.metadata)==null?void 0:i.title)??c.summary??"";SA(a,u)&&r.set(c.id,c)}}const s=n.dedupeScan;if(s!=null&&s.symbol)for(const a of e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{dedupeSymbol:s.symbol}}))De(a)&&r.set(a.id,a);if(s!=null&&s.path)for(const a of e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{dedupePath:s.path}}))De(a)&&r.set(a.id,a);if(s!=null&&s.errorText)for(const a of e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{dedupeErrorText:s.errorText}}))De(a)&&r.set(a.id,a);return[...r.values()].map(ie)}function Ba(e,t){if(!t.idOverride&&(typeof t.family!="string"||t.family.trim().length===0))throw new Me("family",`backlog: createItem requires a non-empty "family" (e.g. "BUG-APIGEN") unless "idOverride" is given — received family=${JSON.stringify(t.family)}. See BUG-BACKLOG-HUMANID-COLLISION-001.`);if(typeof t.title!="string"||t.title.trim().length===0)throw new Me("title",`backlog: createItem requires a non-empty "title" — received title=${JSON.stringify(t.title)}.`);if(typeof t.body!="string"||t.body.trim().length===0)throw new Me("body",`backlog: createItem requires a non-empty "body" — received body=${JSON.stringify(t.body)}.`);if(typeof t.repo!="string"||t.repo.trim().length===0)throw new Me("repo",`backlog: createItem requires a non-empty "repo" — received repo=${JSON.stringify(t.repo)}.`);if(t.idOverride){const s=Qe(e,t.repo,t.idOverride);if(s){const i=ie(s);return{item:i,created:!1,duplicateCandidates:[i]}}}const n=t.force?[]:OA(e,t.repo,t);if(n.length>0&&!t.force)return{item:n[0],created:!1,duplicateCandidates:n};const r=Tp(e),o=r.size>0&&!r.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...r].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0;return jp(e,t.repo,t.family,t.idOverride,(s,i)=>{var h,d,g;if(i){const y=ie(i);return{item:y,created:!1,duplicateCandidates:[y]}}const a=Hr(s),c=Wr(s),u=new Date().toISOString(),l={humanId:s,kind:a,family:c,title:t.title,body:t.body,status:"OPEN",repo:t.repo,citations:[],notes:[],createdAt:u,updatedAt:u};t.priority!==void 0&&(l.priority=t.priority),t.projectPath!==void 0&&(l.projectPath=t.projectPath),t.plan!==void 0&&(l.plan=t.plan),t.importedFrom!==void 0&&(l.importedFrom=t.importedFrom),((h=t.dedupeScan)==null?void 0:h.symbol)!==void 0&&(l.dedupeSymbol=t.dedupeScan.symbol),((d=t.dedupeScan)==null?void 0:d.path)!==void 0&&(l.dedupePath=t.dedupeScan.path),((g=t.dedupeScan)==null?void 0:g.errorText)!==void 0&&(l.dedupeErrorText=t.dedupeScan.errorText);const f=e.graph.writeNode(Da(t.repo,s,t.title,t.body),{kind:"generic",name:La(t.repo,s),summary:t.title,tags:kp(a,c,t.tags),namespace:t.repo,importance:Ua(t.priority),confidence:"confirmed",...t.projectPath!==void 0?{projectPath:t.projectPath}:{},metadata:l}),p=e.graph.getNode(f);if(!p)throw new Error(`backlog: writeNode returned an id that does not resolve: ${f}`);return{item:ie(p),created:!0,duplicateCandidates:[],...o!==void 0?{repoWarning:o}:{}}})}function Dp(e,t,n){const r=Qe(e,t,n);return r?ie(r):null}function Lp(e,t,n){const r=Qe(e,t,n);if(!r)throw Se(e,t,n);return r}function Up(e,t,n,r){const o=Lp(e,t,n);let s="",i="";if(Oe(e,o.id,c=>{const u={...c,updatedAt:new Date().toISOString()};return r.title!==void 0&&(u.title=r.title),r.body!==void 0&&(u.body=r.body),r.projectPath!==void 0&&(u.projectPath=r.projectPath),r.importedFrom!==void 0&&(u.importedFrom=r.importedFrom),s=u.title,i=u.body,u}),r.title!==void 0||r.tags!==void 0||r.projectPath!==void 0){const c={};if(r.title!==void 0&&(c.summary=r.title),r.tags!==void 0){const u=Hr(n),l=Wr(n);c.tags=kp(u,l,r.tags)}r.projectPath!==void 0&&(c.projectPath=r.projectPath),e.graph.touch(o.id,c)}if(r.title!==void 0||r.body!==void 0){const c=Da(t,n,s,i);e.db.prepare("UPDATE node SET content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL").run(c,tA(c),o.id)}const a=e.graph.getNode(o.id);if(!a)throw Se(e,t,n);return ie(a)}function NA(e,t,n,r){if(typeof r!="string"||r.trim().length===0)throw new Me("reason",`backlog: softDeleteItem requires a non-empty "reason" — received reason=${JSON.stringify(r)}.`);const o=Lp(e,t,n);e.graph.invalidate(o.id,r)}function Fa(e,t,n){const r=e.graph.getNode(t),o=r==null?void 0:r.metadata;o!=null&&o.repo&&(o!=null&&o.humanId)&&xp(e,t,o.repo,o.humanId,"claim",n)}const _A=30;class kA extends Error{constructor(t,n){super(`cannot release claim held by "${t}" as "${n}" without force`),this.heldBy=t,this.name="ClaimContentionError"}}function Bp(e,t,n,r={}){const o=(r.staleAfterMin??_A)*6e4;let s;return Oe(e,t,i=>{const a=Date.now(),c=new Date(a).toISOString();return!i.claimedBy||i.claimedBy===n?(s={status:i.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:c},{...i,claimedBy:n,claimedAt:c,updatedAt:c}):(i.claimedAt?a-Date.parse(i.claimedAt):Number.POSITIVE_INFINITY)<=o&&!r.force?(s={status:"held",claimedBy:n,claimedAt:c,heldBy:i.claimedBy,...i.claimedAt!==void 0?{heldSince:i.claimedAt}:{}},i):(s={status:"reclaimed-stale",claimedBy:n,claimedAt:c,previousClaimant:i.claimedBy},{...i,claimedBy:n,claimedAt:c,updatedAt:c})}),s.status!=="held"&&Fa(e,t,{status:s.status,by:n}),s}function AA(e,t,n){let r;return Oe(e,t,o=>{const s=new Date().toISOString();return r={status:o.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:s},{...o,claimedBy:n,claimedAt:s,updatedAt:s}}),Fa(e,t,{status:r.status,by:n}),r}function jA(e,t,n,r={}){let o;return Oe(e,t,s=>{if(!s.claimedBy)return o={status:"release-noop"},s;if(s.claimedBy!==n&&!r.force)throw new kA(s.claimedBy,n);o={status:"released",wasClaimedBy:s.claimedBy};const a=new Date().toISOString(),c={...s,updatedAt:a};return delete c.claimedBy,delete c.claimedAt,c}),o.status!=="release-noop"&&Fa(e,t,{status:o.status,by:n,wasClaimedBy:o.wasClaimedBy}),o}function Yr(e,t,n){const r=Qe(e,t,n);if(!r)throw Se(e,t,n);return r}function Fp(e){if(typeof e.file!="string"||e.file.trim().length===0)throw new Me("citation.file",`backlog: a citation requires a non-empty "file" — received file=${JSON.stringify(e.file)}.`)}function Cn(e,t,n,r,o){if(o.citations)for(const c of o.citations)Fp(c);const s=Yr(e,t,n);let i;Oe(e,s.id,c=>{i=c.status;const u=o.citations&&o.citations.length>0?[...c.citations,...o.citations]:c.citations;if(kr(r)&&u.length===0)throw new Op(r);if(Ar(r)&&(!o.reason||o.reason.trim().length===0))throw new Np(r);const l=new Date().toISOString(),f=[...c.notes];o.note&&f.push({by:o.by,at:l,text:o.note}),o.reason&&f.push({by:o.by,at:l,text:`[transition to ${r}] ${o.reason}`});const p={...c,status:r,citations:u,notes:f,updatedAt:l};return Ca.has(r)&&(delete p.claimedBy,delete p.claimedAt),p}),xp(e,s.id,t,n,"transition",{from:i,to:r,by:o.by,...o.reason?{reason:o.reason}:{}});const a=e.graph.getNode(s.id);if(!a)throw Se(e,t,n);return ie(a)}function IA(e,t,n,r,o){return Cn(e,t,n,r,o)}function xA(e,t,n,r){const o=Yr(e,t,n),s=Bp(e,o.id,r);if(s.status==="held")throw new _p(s.heldBy??"unknown",s.heldSince??"unknown");return Cn(e,t,n,"IN_PROGRESS",{by:r})}function PA(e,t,n,r){Fp(r);const o=Yr(e,t,n);Oe(e,o.id,i=>({...i,citations:[...i.citations,r],updatedAt:new Date().toISOString()}));const s=e.graph.getNode(o.id);if(!s)throw Se(e,t,n);return ie(s)}function TA(e,t,n,r,o){const s=Yr(e,t,n);Oe(e,s.id,a=>{const c=new Date().toISOString();return{...a,notes:[...a.notes,{by:r,at:c,text:o}],updatedAt:c}});const i=e.graph.getNode(s.id);if(!i)throw Se(e,t,n);return ie(i)}function CA(e,t,n={}){const r=new Set((n.exclude??[]).map(i=>i.toUpperCase())),o=ct(e,{repo:t.repo,projectPath:t.projectPath,status:"closed"}),s=[];for(const i of o){if(r.has(i.humanId.toUpperCase())||!Ue(i.status))continue;const a=new Date().toISOString();Oe(e,i.nodeId,u=>({...u,archivedAt:a,updatedAt:a}));const c=e.graph.getNode(i.nodeId);c&&s.push(ie(c))}return s}function Ee(e,t,n){const r=Qe(e,t,n);if(!r)throw Se(e,t,n);return r}function RA(e,t,n,r){const o=Ee(e,t,n),s=Ee(e,t,r);e.graph.writeEdge(o.id,s.id,"DEPENDS_ON")}function MA(e,t,n,r){const o=Ee(e,t,n),s=Ee(e,t,r);e.db.prepare("DELETE FROM edge WHERE src = ? AND dst = ? AND rel = 'DEPENDS_ON'").run(o.id,s.id)}function DA(e,t,n,r){const o=Ee(e,t,n),s=Ee(e,t,r);e.graph.writeEdge(o.id,s.id,"RELATES_TO")}function LA(e,t,n,r,o){if(typeof o!="string"||o.trim().length===0)throw new Me("reason",`backlog: supersedeItem requires a non-empty "reason" — received reason=${JSON.stringify(o)}.`);const s=Ee(e,t,n),i=new Date().toISOString();let a="";const c=jp(e,t,r.family,r.idOverride,l=>{a=l;const f=Hr(a),p=Wr(a),h={humanId:a,kind:f,family:p,title:r.title,body:r.body,status:"OPEN",repo:t,citations:[],notes:[],createdAt:i,updatedAt:i};return r.priority!==void 0&&(h.priority=r.priority),r.projectPath!==void 0&&(h.projectPath=r.projectPath),r.plan!==void 0&&(h.plan=r.plan),e.graph.supersede(s.id,Da(t,a,r.title,r.body),{kind:"generic",name:La(t,a),summary:r.title,tags:["backlog-item",f,p,...r.tags??[]],namespace:t,importance:Ua(r.priority),confidence:"confirmed",...r.projectPath!==void 0?{projectPath:r.projectPath}:{},metadata:h})});Oe(e,s.id,l=>{const f=[...l.notes,{by:"system",at:i,text:`[superseded by ${a}] ${o}`}],p={...l,status:"SUPERSEDED",notes:f,updatedAt:i};return delete p.claimedBy,delete p.claimedAt,p}),e.graph.invalidate(s.id,o);const u=e.graph.getNode(c);if(!u)throw new Error(`backlog: supersede() returned an id that does not resolve: ${c}`);return ie(u)}function UA(e,t,n,r){const o=Ee(e,t,n),s=[];for(const i of r){const a=Ba(e,{...i,repo:t});e.graph.writeEdge(a.item.nodeId,o.id,"PART_OF"),s.push(a.item)}return s}function BA(e,t,n,r,o){if(typeof o!="string"||o.trim().length===0)throw new Me("reason",`backlog: mergeItems requires a non-empty "reason" — received reason=${JSON.stringify(o)}.`);const s=Ee(e,t,n),i=Ee(e,t,r);Oe(e,i.id,c=>{const u=new Date().toISOString(),l={...c,status:"DUPLICATE",notes:[...c.notes,{by:"system",at:u,text:`[merged into ${n}] ${o}`}],updatedAt:u};return delete l.claimedBy,delete l.claimedAt,l}),e.graph.writeEdge(i.id,s.id,"SAME_AS"),e.graph.invalidate(i.id,o);const a=e.graph.getNode(s.id);if(!a)throw Se(e,t,n);return ie(a)}function qp(e,t,n,r){const o=Ee(e,t,n);Oe(e,o.id,i=>({...i,priority:r,updatedAt:new Date().toISOString()})),e.graph.touch(o.id,{importance:Ua(r)});const s=e.graph.getNode(o.id);if(!s)throw Se(e,t,n);return ie(s)}function FA(e,t,n){const r=`${t}::plan:${n}`,s=e.graph.queryNodes({kind:"generic",tags:[fl],namespace:t,metadata:{planSlug:n}}).find(i=>i.name===r&&!i.isSuperseded);return s?s.id:e.graph.writeNode(`plan:${n}`,{kind:"generic",name:r,summary:n,tags:[fl],namespace:t,metadata:{planSlug:n}})}function Us(e,t,n,r){const o=Ee(e,t,n),s=FA(e,t,r);Oe(e,o.id,i=>({...i,plan:r,updatedAt:new Date().toISOString()})),e.graph.writeEdge(o.id,s,"MEMBER_OF")}function qA(e,t){const r=e.graph.queryNodes({kind:"entity",tags:[dl],metadata:{identity:t}}).find(o=>o.name===t&&!o.isSuperseded);return r?r.id:e.graph.writeNode(`assignee:${t}`,{kind:"entity",name:t,summary:t,tags:[dl],metadata:{identity:t}})}function VA(e,t,n,r,o){const s=Ee(e,t,n),i=qA(e,r);Oe(e,s.id,c=>{const u=new Date().toISOString();return{...c,assignee:r,notes:[...c.notes,{by:o,at:u,text:`assigned to ${r}`}],updatedAt:u}}),e.graph.writeEdge(s.id,i,"ASSIGNED_TO");const a=e.graph.getNode(s.id);if(!a)throw Se(e,t,n);return ie(a)}const yl=/^(#{2,3})\s+([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)/,KA=["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","CLOSED"],GA=["MITIGATED"],zA=["INVALID","SUPERSEDED","DUPLICATE","WONTFIX"],JA=new Set([...KA,...GA,...zA]),HA=new Set(["OPEN","IN_PROGRESS","PARTIAL","OUTSTANDING","DEFERRED","BLOCKED","MIXED","UNKNOWN","FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function Vp(e){const t=e.toUpperCase();return t==="IN-PROGRESS"?"IN_PROGRESS":t==="CLOSED"?"RESOLVED":HA.has(t)?t:"UNKNOWN"}function Kp(e){var s;const t=(e??"").toLowerCase();if(!t.trim())return null;const n=i=>t.includes(i);if(n("outstanding"))return{label:"OUTSTANDING",open:!0};if(n("partially"))return{label:"PARTIAL",open:!0};if(n("in progress"))return{label:"IN-PROGRESS",open:!0};const r=n("shipped")&&"SHIPPED"||n("superseded")&&"SUPERSEDED"||n("invalid")&&"INVALID"||n("mitigated")&&"MITIGATED"||n("removed")&&!n("open")&&"REMOVED"||n("fixed")&&"FIXED"||n("resolved")&&"RESOLVED"||n("done")&&"DONE"||null,o=n("open")&&"OPEN"||(n("deferred")||n("defer"))&&"DEFERRED"||null;return r&&o?{label:"MIXED",open:!0}:r?{label:r,open:!1}:o?{label:o,open:!0}:n("downgraded")?{label:"OPEN",open:!0}:{label:((s=t.trim().split(/\s+/)[0])==null?void 0:s.toUpperCase().replace(/[^A-Z]/g,""))||"UNKNOWN",open:!0}}function Gp(e,t){const n=t.match(/^\s*-?\s*\*\*Status:\*?\*?\s*([^\n]+)/im),r=n?Kp(n[1]):null;if(r)return r;const o=e.toUpperCase();for(const s of["RESOLVED","FIXED","MITIGATED","DONE","CLOSED"])if(o.includes(s))return{label:s,open:!1};return{label:"UNKNOWN",open:!0}}function zp(e,t){const r=`${e}
|
|
180
|
-
${t}`.match(/\*{0,2}priority:?\*{0,2}\s*[:-]?\s*(CRITICAL|HIGH|MEDIUM|LOW)/i);return r?r[1].toUpperCase():/—\s*CRITICAL\b/i.test(e)||/\bCRITICAL\b/.test(e)?"CRITICAL":""}const
|
|
179
|
+
<!-- ${rA}${e}::${t} -->`}function Ua(e,t){return`${e}::${t}`}function Ba(e){switch(e){case"CRITICAL":return 10;case"HIGH":return 8;case"MEDIUM":return 5;case"LOW":return 2;default:return 1}}function Ip(e,t,n=[]){return[...new Set([be,e,t,...n])]}function De(e){return e.tags.includes(be)&&!e.isSuperseded}function ie(e){const t=e.metadata??{},n=t.humanId??"",r=t.kind??Wr(n),o=t.family??Hr(n),s=new Set([be,r,o]);return{nodeId:e.id,humanId:n,kind:r,family:o,title:t.title??e.summary??"",body:t.body??"",status:t.status??"UNKNOWN",priority:t.priority,repo:t.repo??e.namespace,projectPath:t.projectPath,plan:t.plan,importedFrom:t.importedFrom,assignee:t.assignee,claimedBy:t.claimedBy,claimedAt:t.claimedAt,citations:t.citations??[],notes:t.notes??[],tags:e.tags.filter(i=>!s.has(i)),createdAt:t.createdAt??e.tCreated,updatedAt:t.updatedAt??t.createdAt??e.tCreated}}const sA=5,iA=20,aA=500;function cA(e){return Uo.isBusyError(e)||Uo.isConcurrentConflict(e)}function uA(e){return new Promise(t=>setTimeout(t,Math.max(0,Math.round(e))))}async function xp(e,t={}){const n=t.maxAttempts??sA;for(let r=0;;r++)try{return await e()}catch(o){if(!cA(o)||r>=n-1)throw o;const s=Math.min(aA,iA*2**r);await uA(s*(.5+Math.random()*.5))}}async function lA(e,t,n){if(typeof n!="string"||n.trim().length===0)throw new Me("family",`backlog: cannot allocate a humanId for repo=${JSON.stringify(t)} — "family" is required and must be a non-empty string, received ${JSON.stringify(n)}. See BUG-BACKLOG-HUMANID-COLLISION-001.`);const r=await e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{family:n}});let o=0;for(const s of r){const i=s.metadata,a=/-(\d+)$/.exec((i==null?void 0:i.humanId)??"");a&&(o=Math.max(o,Number(a[1])))}return`${n}-${String(o+1).padStart(3,"0")}`}async function fA(e,t,n){const o=(await e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{humanId:n}})).filter(s=>{var i;return De(s)&&((i=s.metadata)==null?void 0:i.humanId)===n});if(o.length>1)throw new Ma(t,n,o.map(s=>s.id));return o[0]??null}async function Pp(e,t,n,r,o){return xp(()=>e.adapter.transaction(async()=>{if(r){const i=await fA(e,t,r);return o(r,i)}const s=await lA(e,t,n);return o(s,null)},{mode:"immediate"}))}const Tp="backlog-audit-event";async function Cp(e,t,n,r,o,s){const i=new Date().toISOString(),a={itemNodeId:t,kind:o,at:i,detail:s},c=`audit-event::${n}::${r}::${o}::${i}::${Math.random().toString(36).slice(2)}`,u=await e.graph.writeNode(c,{kind:"generic",name:`audit-event::${n}::${r}::${i}`,tags:[Tp],namespace:n,metadata:a});await e.graph.writeEdge(u,t,"DERIVED_FROM")}async function dA(e,t){return(await e.graph.queryNodes({kind:"generic",tags:[Tp],metadata:{itemNodeId:t}})).map(r=>r.metadata).filter(r=>r!==void 0&&r.itemNodeId===t).map(r=>({at:r.at,kind:r.kind,detail:r.detail})).sort((r,o)=>r.at.localeCompare(o.at))}const hl={CRITICAL:0,HIGH:1,MEDIUM:2,LOW:3};function ml(e){const t=[be];e.kind&&t.push(e.kind),e.tags&&t.push(...e.tags);const n={};e.family&&(n.family=e.family),e.priority&&(n.priority=e.priority),e.plan&&(n.plan=e.plan),e.importedFrom&&(n.importedFrom=e.importedFrom),e.assignee&&(n.assignee=e.assignee),e.claimedBy&&(n.claimedBy=e.claimedBy),e.status&&e.status!=="open"&&e.status!=="closed"&&(n.status=e.status);const r={kind:"generic",tags:t,tagsMatchAll:!0};return e.repo!==void 0&&(r.namespace=e.repo),e.projectPath!==void 0&&(r.projectPath=e.projectPath),Object.keys(n).length>0&&(r.metadata=n),r}function pA(e,t){return t.status==="open"?e.filter(n=>!Ue(n.status)):t.status==="closed"?e.filter(n=>Ue(n.status)):e}function gl(e,t){return t.rootLevel?e.filter(n=>{const r=n.metadata;return!(r!=null&&r.projectPath)&&!(r!=null&&r.plan)}):e}function yl(e,t){return t.excludeArchived?e.filter(n=>{var r;return!((r=n.metadata)!=null&&r.archivedAt)}):e}async function Rp(e,t={}){if(t.grep){const o=ml({...t}),s=Da(t.grep);if(!s)return[];const i=await e.graph.searchNodes(s,{limit:t.limit??1e3,filter:o});let a=yl(gl(i.filter(De),t),t);return t.offset&&(a=a.slice(t.offset)),a}const n=ml(t);t.limit!==void 0&&(n.limit=t.limit),t.offset!==void 0&&(n.offset=t.offset);const r=await e.graph.queryNodes(n);return yl(gl(r.filter(De),t),t)}async function ct(e,t={}){const r=(await Rp(e,t)).map(ie);return pA(r,t)}async function Qe(e,t,n){const r=Ua(t,n),s=(await e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{humanId:n}})).filter(De);if(s.length>1)throw new Ma(t,n,s.map(i=>i.id));return s.find(i=>i.name===r)??s[0]??null}function Us(e){var t;return((t=e.metadata)==null?void 0:t.repo)??e.namespace??""}async function hA(e,t){return(await e.graph.queryNodes({kind:"generic",tags:[be],metadata:{humanId:t}})).filter(De)}async function Mp(e){const t=await e.graph.queryNodes({kind:"generic",tags:[be]}),n=new Set;for(const r of t){if(!De(r))continue;const o=Us(r);o&&n.add(o)}return n}async function Se(e,t,n){const r=(await hA(e,n)).filter(s=>Us(s)!==t),o=[...new Set(r.map(Us).filter(s=>s.length>0))];return new _p(t,n,o)}function ln(e,t){const n={};for(const r of e){const o=t(r);o&&(n[o]=(n[o]??0)+1)}return n}async function mA(e,t={}){const n=await ct(e,{repo:t.repo,projectPath:t.projectPath}),r=n.filter(s=>!Ue(s.status)),o=n.filter(s=>Ue(s.status));return{total:n.length,open:r.length,closed:o.length,byStatus:ln(n,s=>s.status),byKind:ln(n,s=>s.kind),byFamily:ln(n,s=>s.family),byPriority:ln(n,s=>s.priority),byRepo:t.repo===void 0?ln(n,s=>s.repo):{}}}async function gA(e,t={},n=20){const o=(await ct(e,{repo:t.repo,projectPath:t.projectPath,status:"open"})).filter(s=>s.priority!==void 0);return o.sort((s,i)=>{const a=hl[s.priority??""]??4,c=hl[i.priority??""]??4;return a-c||s.humanId.localeCompare(i.humanId)}),o.slice(0,n)}async function Dp(e,t){const n=await e.graph.getEdges({src:t,rel:"DEPENDS_ON"}),r=[];for(const o of n){const s=await e.graph.getNode(o.dst);s&&r.push(s)}return r}async function yA(e,t,n){const r=await Qe(e,t,n);return r?(await Dp(e,r.id)).filter(o=>!o.tInvalid).map(ie).filter(o=>!Ue(o.status)):[]}async function $A(e,t={}){const n=await ct(e,{repo:t.repo,projectPath:t.projectPath,status:"open"}),r=[];for(const o of n){if(o.claimedBy)continue;const s=await Qe(e,o.repo,o.humanId);if(!s)continue;(await Dp(e,s.id)).filter(a=>!a.tInvalid).every(a=>Ue(ie(a).status))&&r.push(o)}return r}async function Lp(e,t={}){const n=await ct(e,{repo:t.repo,projectPath:t.projectPath}),r=n.map(s=>({humanId:s.humanId,title:s.title,status:s.status})),o=[];for(const s of n){const i=await Qe(e,s.repo,s.humanId);if(i)for(const a of["DEPENDS_ON","RELATES_TO","PART_OF"])for(const c of await e.graph.getEdges({src:i.id,rel:a})){const u=await e.graph.getNode(c.dst);if(!u||u.tInvalid)continue;const l=u.metadata;l!=null&&l.humanId&&o.push({from:s.humanId,to:l.humanId,rel:a})}}return{nodes:r,edges:o}}async function vA(e,t={}){var c;const n=await Lp(e,t),r=n.edges.filter(u=>u.rel==="DEPENDS_ON"),o=new Map;for(const u of n.nodes)o.set(u.humanId,new Set);for(const u of r)(c=o.get(u.from))==null||c.add(u.to);const s=new Set(n.nodes.map(u=>u.humanId)),i=[];let a=!0;for(;s.size>0&&a;){a=!1;for(const u of[...s].sort())[...o.get(u)??new Set].every(p=>!s.has(p))&&(i.push(u),s.delete(u),a=!0)}return s.size>0?{ok:!1,cycle:wA([...s],o)}:{ok:!0,order:i}}function wA(e,t){const n=new Set(e),r=new Set,o=[];function s(i){if(r.has(i)){const a=o.indexOf(i);return[...o.slice(a),i]}if(!n.has(i))return null;r.add(i),o.push(i);for(const a of t.get(i)??[]){const c=s(a);if(c)return c}return o.pop(),r.delete(i),null}for(const i of e){const a=s(i);if(a)return a}return e}async function bA(e,t,n={}){const r=await ct(e,{repo:n.repo,projectPath:n.projectPath}),o=t*6e4,s=Date.now();return r.filter(i=>!i.claimedBy||!i.claimedAt?!1:s-Date.parse(i.claimedAt)>=o)}async function EA(e,t,n){var u,l,f,p;const r=await Qe(e,t,n);if(!r)throw await Se(e,t,n);const o=ie(r),s=[{at:o.createdAt,kind:"created",detail:{title:o.title,repo:o.repo}}];for(const h of o.citations)s.push({at:o.updatedAt,kind:"citation",detail:{...h}});for(const h of o.notes)s.push({at:h.at,kind:"note",detail:{by:h.by,text:h.text}});s.push(...await dA(e,r.id)),s.sort((h,d)=>h.at.localeCompare(d.at));const i=await e.graph.getSupersessionChain(r.id);let a;if(i.length>1){const h=i.findIndex(y=>y.id===r.id),d=h>0?((l=(u=i[h-1])==null?void 0:u.metadata)==null?void 0:l.humanId)??void 0:void 0,m=h>=0&&h<i.length-1?((p=(f=i[h+1])==null?void 0:f.metadata)==null?void 0:p.humanId)??void 0:void 0;a={},d&&(a.supersedes=d),m&&(a.supersededBy=m)}const c={humanId:o.humanId,history:s};return a&&(c.supersessionChain=a),c}class SA extends Error{constructor(t){super(`backlog item not found or invalidated: node ${t}`),this.nodeId=t,this.name="NotFoundError"}}async function Oe(e,t,n){return xp(()=>e.adapter.transaction(async()=>{const r=await e.graph.getNode(t);if(!r||r.tInvalid)throw new SA(t);const o=r.metadata??{},s=n(o);return await e.graph.touch(t,{metadata:s}),s},{mode:"immediate"}))}const OA=new Set(["a","an","and","are","as","at","be","been","but","by","can","do","does","for","from","had","has","have","if","in","into","is","it","its","no","not","of","on","or","our","so","such","than","that","the","their","then","there","these","this","to","was","were","will","with","would","you","your"]);function Up(e){return Da(e).toLowerCase().split(" ").filter(t=>t.length>0&&!OA.has(t))}function NA(e,t){if(e.length===0)return!0;const n=new Set(Up(t));return e.every(r=>n.has(r))}async function _A(e,t,n){var i;const r=new Map,o=Da(n.title);if(o){const a=Up(n.title);for(const c of await e.graph.searchNodes(o,{limit:10,filter:{tags:[be],namespace:t}})){if(!De(c))continue;const u=((i=c.metadata)==null?void 0:i.title)??c.summary??"";NA(a,u)&&r.set(c.id,c)}}const s=n.dedupeScan;if(s!=null&&s.symbol)for(const a of await e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{dedupeSymbol:s.symbol}}))De(a)&&r.set(a.id,a);if(s!=null&&s.path)for(const a of await e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{dedupePath:s.path}}))De(a)&&r.set(a.id,a);if(s!=null&&s.errorText)for(const a of await e.graph.queryNodes({kind:"generic",tags:[be],namespace:t,metadata:{dedupeErrorText:s.errorText}}))De(a)&&r.set(a.id,a);return[...r.values()].map(ie)}async function Fa(e,t){if(!t.idOverride&&(typeof t.family!="string"||t.family.trim().length===0))throw new Me("family",`backlog: createItem requires a non-empty "family" (e.g. "BUG-APIGEN") unless "idOverride" is given — received family=${JSON.stringify(t.family)}. See BUG-BACKLOG-HUMANID-COLLISION-001.`);if(typeof t.title!="string"||t.title.trim().length===0)throw new Me("title",`backlog: createItem requires a non-empty "title" — received title=${JSON.stringify(t.title)}.`);if(typeof t.body!="string"||t.body.trim().length===0)throw new Me("body",`backlog: createItem requires a non-empty "body" — received body=${JSON.stringify(t.body)}.`);if(typeof t.repo!="string"||t.repo.trim().length===0)throw new Me("repo",`backlog: createItem requires a non-empty "repo" — received repo=${JSON.stringify(t.repo)}.`);if(t.idOverride){const s=await Qe(e,t.repo,t.idOverride);if(s){const i=ie(s);return{item:i,created:!1,duplicateCandidates:[i]}}}const n=t.force?[]:await _A(e,t.repo,t);if(n.length>0&&!t.force)return{item:n[0],created:!1,duplicateCandidates:n};const r=await Mp(e),o=r.size>0&&!r.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...r].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0;return Pp(e,t.repo,t.family,t.idOverride,async(s,i)=>{var h,d,m;if(i){const y=ie(i);return{item:y,created:!1,duplicateCandidates:[y]}}const a=Wr(s),c=Hr(s),u=new Date().toISOString(),l={humanId:s,kind:a,family:c,title:t.title,body:t.body,status:"OPEN",repo:t.repo,citations:[],notes:[],createdAt:u,updatedAt:u};t.priority!==void 0&&(l.priority=t.priority),t.projectPath!==void 0&&(l.projectPath=t.projectPath),t.plan!==void 0&&(l.plan=t.plan),t.importedFrom!==void 0&&(l.importedFrom=t.importedFrom),((h=t.dedupeScan)==null?void 0:h.symbol)!==void 0&&(l.dedupeSymbol=t.dedupeScan.symbol),((d=t.dedupeScan)==null?void 0:d.path)!==void 0&&(l.dedupePath=t.dedupeScan.path),((m=t.dedupeScan)==null?void 0:m.errorText)!==void 0&&(l.dedupeErrorText=t.dedupeScan.errorText);const f=await e.graph.writeNode(La(t.repo,s,t.title,t.body),{kind:"generic",name:Ua(t.repo,s),summary:t.title,tags:Ip(a,c,t.tags),namespace:t.repo,importance:Ba(t.priority),confidence:"confirmed",...t.projectPath!==void 0?{projectPath:t.projectPath}:{},metadata:l}),p=await e.graph.getNode(f);if(!p)throw new Error(`backlog: writeNode returned an id that does not resolve: ${f}`);return{item:ie(p),created:!0,duplicateCandidates:[],...o!==void 0?{repoWarning:o}:{}}})}async function Bp(e,t,n){const r=await Qe(e,t,n);return r?ie(r):null}async function Fp(e,t,n){const r=await Qe(e,t,n);if(!r)throw await Se(e,t,n);return r}async function qp(e,t,n,r){const o=await Fp(e,t,n);let s="",i="";if(await Oe(e,o.id,c=>{const u={...c,updatedAt:new Date().toISOString()};return r.title!==void 0&&(u.title=r.title),r.body!==void 0&&(u.body=r.body),r.projectPath!==void 0&&(u.projectPath=r.projectPath),r.importedFrom!==void 0&&(u.importedFrom=r.importedFrom),s=u.title,i=u.body,u}),r.title!==void 0||r.tags!==void 0||r.projectPath!==void 0){const c={};if(r.title!==void 0&&(c.summary=r.title),r.tags!==void 0){const u=Wr(n),l=Hr(n);c.tags=Ip(u,l,r.tags)}r.projectPath!==void 0&&(c.projectPath=r.projectPath),await e.graph.touch(o.id,c)}if(r.title!==void 0||r.body!==void 0){const c=La(t,n,s,i);await e.adapter.executeRun("UPDATE node SET content = ?, content_hash = ? WHERE rowid = ? AND t_invalid IS NULL",[c,oA(c),o.id])}const a=await e.graph.getNode(o.id);if(!a)throw await Se(e,t,n);return ie(a)}async function kA(e,t,n,r){if(typeof r!="string"||r.trim().length===0)throw new Me("reason",`backlog: softDeleteItem requires a non-empty "reason" — received reason=${JSON.stringify(r)}.`);const o=await Fp(e,t,n);await e.graph.invalidate(o.id,r)}async function qa(e,t,n){const r=await e.graph.getNode(t),o=r==null?void 0:r.metadata;o!=null&&o.repo&&(o!=null&&o.humanId)&&await Cp(e,t,o.repo,o.humanId,"claim",n)}const AA=30;class jA extends Error{constructor(t,n){super(`cannot release claim held by "${t}" as "${n}" without force`),this.heldBy=t,this.name="ClaimContentionError"}}async function Vp(e,t,n,r={}){const o=(r.staleAfterMin??AA)*6e4;let s;return await Oe(e,t,i=>{const a=Date.now(),c=new Date(a).toISOString();return!i.claimedBy||i.claimedBy===n?(s={status:i.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:c},{...i,claimedBy:n,claimedAt:c,updatedAt:c}):(i.claimedAt?a-Date.parse(i.claimedAt):Number.POSITIVE_INFINITY)<=o&&!r.force?(s={status:"held",claimedBy:n,claimedAt:c,heldBy:i.claimedBy,...i.claimedAt!==void 0?{heldSince:i.claimedAt}:{}},i):(s={status:"reclaimed-stale",claimedBy:n,claimedAt:c,previousClaimant:i.claimedBy},{...i,claimedBy:n,claimedAt:c,updatedAt:c})}),s.status!=="held"&&await qa(e,t,{status:s.status,by:n}),s}async function IA(e,t,n){let r;return await Oe(e,t,o=>{const s=new Date().toISOString();return r={status:o.claimedBy?"renewed":"claimed",claimedBy:n,claimedAt:s},{...o,claimedBy:n,claimedAt:s,updatedAt:s}}),await qa(e,t,{status:r.status,by:n}),r}async function xA(e,t,n,r={}){let o;return await Oe(e,t,s=>{if(!s.claimedBy)return o={status:"release-noop"},s;if(s.claimedBy!==n&&!r.force)throw new jA(s.claimedBy,n);o={status:"released",wasClaimedBy:s.claimedBy};const a=new Date().toISOString(),c={...s,updatedAt:a};return delete c.claimedBy,delete c.claimedAt,c}),o.status!=="release-noop"&&await qa(e,t,{status:o.status,by:n,wasClaimedBy:o.wasClaimedBy}),o}async function Yr(e,t,n){const r=await Qe(e,t,n);if(!r)throw await Se(e,t,n);return r}function Kp(e){if(typeof e.file!="string"||e.file.trim().length===0)throw new Me("citation.file",`backlog: a citation requires a non-empty "file" — received file=${JSON.stringify(e.file)}.`)}async function Cn(e,t,n,r,o){if(o.citations)for(const c of o.citations)Kp(c);const s=await Yr(e,t,n);let i;await Oe(e,s.id,c=>{i=c.status;const u=o.citations&&o.citations.length>0?[...c.citations,...o.citations]:c.citations;if(kr(r)&&u.length===0)throw new kp(r);if(Ar(r)&&(!o.reason||o.reason.trim().length===0))throw new Ap(r);const l=new Date().toISOString(),f=[...c.notes];o.note&&f.push({by:o.by,at:l,text:o.note}),o.reason&&f.push({by:o.by,at:l,text:`[transition to ${r}] ${o.reason}`});const p={...c,status:r,citations:u,notes:f,updatedAt:l};return Ra.has(r)&&(delete p.claimedBy,delete p.claimedAt),p}),await Cp(e,s.id,t,n,"transition",{from:i,to:r,by:o.by,...o.reason?{reason:o.reason}:{}});const a=await e.graph.getNode(s.id);if(!a)throw await Se(e,t,n);return ie(a)}async function PA(e,t,n,r,o){return Cn(e,t,n,r,o)}async function TA(e,t,n,r){const o=await Yr(e,t,n),s=await Vp(e,o.id,r);if(s.status==="held")throw new jp(s.heldBy??"unknown",s.heldSince??"unknown");return Cn(e,t,n,"IN_PROGRESS",{by:r})}async function CA(e,t,n,r){Kp(r);const o=await Yr(e,t,n);await Oe(e,o.id,i=>({...i,citations:[...i.citations,r],updatedAt:new Date().toISOString()}));const s=await e.graph.getNode(o.id);if(!s)throw await Se(e,t,n);return ie(s)}async function RA(e,t,n,r,o){const s=await Yr(e,t,n);await Oe(e,s.id,a=>{const c=new Date().toISOString();return{...a,notes:[...a.notes,{by:r,at:c,text:o}],updatedAt:c}});const i=await e.graph.getNode(s.id);if(!i)throw await Se(e,t,n);return ie(i)}async function MA(e,t,n={}){const r=new Set((n.exclude??[]).map(i=>i.toUpperCase())),o=await ct(e,{repo:t.repo,projectPath:t.projectPath,status:"closed"}),s=[];for(const i of o){if(r.has(i.humanId.toUpperCase())||!Ue(i.status))continue;const a=new Date().toISOString();await Oe(e,i.nodeId,u=>({...u,archivedAt:a,updatedAt:a}));const c=await e.graph.getNode(i.nodeId);c&&s.push(ie(c))}return s}async function Ee(e,t,n){const r=await Qe(e,t,n);if(!r)throw await Se(e,t,n);return r}async function DA(e,t,n,r){const o=await Ee(e,t,n),s=await Ee(e,t,r);await e.graph.writeEdge(o.id,s.id,"DEPENDS_ON")}async function LA(e,t,n,r){const o=await Ee(e,t,n),s=await Ee(e,t,r);await e.adapter.executeRun("DELETE FROM edge WHERE src = ? AND dst = ? AND rel = 'DEPENDS_ON'",[o.id,s.id])}async function UA(e,t,n,r){const o=await Ee(e,t,n),s=await Ee(e,t,r);await e.graph.writeEdge(o.id,s.id,"RELATES_TO")}async function BA(e,t,n,r,o){if(typeof o!="string"||o.trim().length===0)throw new Me("reason",`backlog: supersedeItem requires a non-empty "reason" — received reason=${JSON.stringify(o)}.`);const s=await Ee(e,t,n),i=new Date().toISOString(),a=await Pp(e,t,r.family,r.idOverride,c=>c);{const c=Wr(a),u=Hr(a),l={humanId:a,kind:c,family:u,title:r.title,body:r.body,status:"OPEN",repo:t,citations:[],notes:[],createdAt:i,updatedAt:i};r.priority!==void 0&&(l.priority=r.priority),r.projectPath!==void 0&&(l.projectPath=r.projectPath),r.plan!==void 0&&(l.plan=r.plan);const f=await e.graph.supersede(s.id,La(t,a,r.title,r.body),{kind:"generic",name:Ua(t,a),summary:r.title,tags:["backlog-item",c,u,...r.tags??[]],namespace:t,importance:Ba(r.priority),confidence:"confirmed",...r.projectPath!==void 0?{projectPath:r.projectPath}:{},metadata:l});await Oe(e,s.id,h=>{const d=[...h.notes,{by:"system",at:i,text:`[superseded by ${a}] ${o}`}],m={...h,status:"SUPERSEDED",notes:d,updatedAt:i};return delete m.claimedBy,delete m.claimedAt,m}),await e.graph.invalidate(s.id,o);const p=await e.graph.getNode(f);if(!p)throw new Error(`backlog: supersede() returned an id that does not resolve: ${f}`);return ie(p)}}async function FA(e,t,n,r){const o=await Ee(e,t,n),s=[];for(const i of r){const a=await Fa(e,{...i,repo:t});await e.graph.writeEdge(a.item.nodeId,o.id,"PART_OF"),s.push(a.item)}return s}async function qA(e,t,n,r,o){if(typeof o!="string"||o.trim().length===0)throw new Me("reason",`backlog: mergeItems requires a non-empty "reason" — received reason=${JSON.stringify(o)}.`);const s=await Ee(e,t,n),i=await Ee(e,t,r);await Oe(e,i.id,c=>{const u=new Date().toISOString(),l={...c,status:"DUPLICATE",notes:[...c.notes,{by:"system",at:u,text:`[merged into ${n}] ${o}`}],updatedAt:u};return delete l.claimedBy,delete l.claimedAt,l}),await e.graph.writeEdge(i.id,s.id,"SAME_AS"),await e.graph.invalidate(i.id,o);const a=await e.graph.getNode(s.id);if(!a)throw await Se(e,t,n);return ie(a)}async function Gp(e,t,n,r){const o=await Ee(e,t,n);await Oe(e,o.id,i=>({...i,priority:r,updatedAt:new Date().toISOString()})),await e.graph.touch(o.id,{importance:Ba(r)});const s=await e.graph.getNode(o.id);if(!s)throw await Se(e,t,n);return ie(s)}async function VA(e,t,n){const r=`${t}::plan:${n}`,s=(await e.graph.queryNodes({kind:"generic",tags:[dl],namespace:t,metadata:{planSlug:n}})).find(i=>i.name===r&&!i.isSuperseded);return s?s.id:e.graph.writeNode(`plan:${n}`,{kind:"generic",name:r,summary:n,tags:[dl],namespace:t,metadata:{planSlug:n}})}async function Bs(e,t,n,r){const o=await Ee(e,t,n),s=await VA(e,t,r);await Oe(e,o.id,i=>({...i,plan:r,updatedAt:new Date().toISOString()})),await e.graph.writeEdge(o.id,s,"MEMBER_OF")}async function KA(e,t){const r=(await e.graph.queryNodes({kind:"entity",tags:[pl],metadata:{identity:t}})).find(o=>o.name===t&&!o.isSuperseded);return r?r.id:e.graph.writeNode(`assignee:${t}`,{kind:"entity",name:t,summary:t,tags:[pl],metadata:{identity:t}})}async function GA(e,t,n,r,o){const s=await Ee(e,t,n),i=await KA(e,r);await Oe(e,s.id,c=>{const u=new Date().toISOString();return{...c,assignee:r,notes:[...c.notes,{by:o,at:u,text:`assigned to ${r}`}],updatedAt:u}}),await e.graph.writeEdge(s.id,i,"ASSIGNED_TO");const a=await e.graph.getNode(s.id);if(!a)throw await Se(e,t,n);return ie(a)}const $l=/^(#{2,3})\s+([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)+)/,zA=["FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","CLOSED"],JA=["MITIGATED"],WA=["INVALID","SUPERSEDED","DUPLICATE","WONTFIX"],HA=new Set([...zA,...JA,...WA]),YA=new Set(["OPEN","IN_PROGRESS","PARTIAL","OUTSTANDING","DEFERRED","BLOCKED","MIXED","UNKNOWN","FIXED","RESOLVED","DONE","SHIPPED","VERIFIED","REMOVED","MITIGATED","SUPERSEDED","INVALID","DUPLICATE","WONTFIX"]);function zp(e){const t=e.toUpperCase();return t==="IN-PROGRESS"?"IN_PROGRESS":t==="CLOSED"?"RESOLVED":YA.has(t)?t:"UNKNOWN"}function Jp(e){var s;const t=(e??"").toLowerCase();if(!t.trim())return null;const n=i=>t.includes(i);if(n("outstanding"))return{label:"OUTSTANDING",open:!0};if(n("partially"))return{label:"PARTIAL",open:!0};if(n("in progress"))return{label:"IN-PROGRESS",open:!0};const r=n("shipped")&&"SHIPPED"||n("superseded")&&"SUPERSEDED"||n("invalid")&&"INVALID"||n("mitigated")&&"MITIGATED"||n("removed")&&!n("open")&&"REMOVED"||n("fixed")&&"FIXED"||n("resolved")&&"RESOLVED"||n("done")&&"DONE"||null,o=n("open")&&"OPEN"||(n("deferred")||n("defer"))&&"DEFERRED"||null;return r&&o?{label:"MIXED",open:!0}:r?{label:r,open:!1}:o?{label:o,open:!0}:n("downgraded")?{label:"OPEN",open:!0}:{label:((s=t.trim().split(/\s+/)[0])==null?void 0:s.toUpperCase().replace(/[^A-Z]/g,""))||"UNKNOWN",open:!0}}function Wp(e,t){const n=t.match(/^\s*-?\s*\*\*Status:\*?\*?\s*([^\n]+)/im),r=n?Jp(n[1]):null;if(r)return r;const o=e.toUpperCase();for(const s of["RESOLVED","FIXED","MITIGATED","DONE","CLOSED"])if(o.includes(s))return{label:s,open:!1};return{label:"UNKNOWN",open:!0}}function Hp(e,t){const r=`${e}
|
|
180
|
+
${t}`.match(/\*{0,2}priority:?\*{0,2}\s*[:-]?\s*(CRITICAL|HIGH|MEDIUM|LOW)/i);return r?r[1].toUpperCase():/—\s*CRITICAL\b/i.test(e)||/\bCRITICAL\b/.test(e)?"CRITICAL":""}const QA=/^[A-Z][A-Z0-9_-]*$/;function ZA(e){const t=e.trim().split(/\s+/)[0]??"";return QA.test(t)&&/[0-9_]/.test(t)}function Yp(e){const t=e.split(`
|
|
181
181
|
`),n=[],r=[];let o=null;const s=()=>{if(!o)return;const i=o.bodyLines.join(`
|
|
182
|
-
`),a=
|
|
183
|
-
`).trimEnd()}function
|
|
182
|
+
`),a=Wp(o.headerLine,i),c=Hp(o.headerLine,i),{bodyLines:u,...l}=o,f=!HA.has(a.label);n.push({...l,status:a.label,open:f,terminal:!f,priority:c,body:i.trim()}),o=null};return t.forEach((i,a)=>{const c=i.match($l),u=/^#{2,3}\s/.test(i);if(c&&/\d/.test(c[2])){s();const l=c[2],f=i.replace($l,"").replace(/^\s*[—–-]\s*/,"").trim(),p=l.split("-");o={id:l,kind:p[0]??l,family:l.replace(/-\d+[a-z]?$/i,""),title:f,level:c[1].length,line:a+1,headerLine:i,bodyLines:[]}}else if(u){const l=i.replace(/^#{2,3}\s+/,"");ZA(l)&&r.push({line:a+1,headerLine:i}),s(),o=null}else o&&o.bodyLines.push(i)}),s(),{items:n,malformedHeaders:r}}function XA(e){return Yp(e).items}function Qp(e){return Yp(e)}function ej(e){return`**Citations:** [${e.map(n=>{const r=n.lines?`${n.file}:${n.lines}`:n.file;return n.context?`${r} (${n.context})`:r}).join(", ")}]`}function tj(e){return e==="IN_PROGRESS"?"IN PROGRESS":e}function Zp(e){const t=[];t.push(`### ${e.humanId} — ${e.title}`),t.push(""),t.push(`**Status:** ${tj(e.status)}`),e.priority&&t.push(`**Priority:** ${e.priority}`),e.assignee&&t.push(`**Assignee:** ${e.assignee}`),e.plan&&t.push(`**Plan:** ${e.plan}`),t.push(""),e.body&&t.push(e.body,""),e.citations.length>0&&t.push(ej(e.citations));for(const n of e.notes)t.push(`- Note (${n.by}, ${n.at}): ${n.text}`);return t.join(`
|
|
183
|
+
`).trimEnd()}function Xp(e){return e.length===0?"":`${e.map(Zp).join(`
|
|
184
184
|
|
|
185
185
|
`)}
|
|
186
|
-
`}function
|
|
187
|
-
`).map(
|
|
188
|
-
`)}function
|
|
186
|
+
`}function nj(e){return e.split(`
|
|
187
|
+
`).map(rj).join(`
|
|
188
|
+
`)}function rj(e){return/^###\s/.test(e)?`##${e}`:/^##\s/.test(e)?`##${e}`:e}function eh(e,t){let n=`### Archived — resolved/terminal backlog items relocated in batch (${t})
|
|
189
189
|
|
|
190
190
|
`;return n+="> Moved via `@adhd/backlog`'s `archiveResolved` (canonical terminal statuses: FIXED/RESOLVED/DONE/\n",n+=`> SHIPPED/VERIFIED/REMOVED/MITIGATED/SUPERSEDED/INVALID/DUPLICATE/WONTFIX). The graph node itself is
|
|
191
191
|
`,n+=`> NEVER deleted — this is a rendered snapshot; full history remains queryable via auditTrail.
|
|
192
192
|
|
|
193
|
-
`,n+=e.map(r=>
|
|
193
|
+
`,n+=e.map(r=>nj(Zp(r))).join(`
|
|
194
194
|
|
|
195
195
|
`),n+=`
|
|
196
|
-
`,n}function Zp(e){return e.map(t=>{const n={humanId:t.id,title:t.title,body:t.body,status:Vp(t.status)};return t.priority&&(t.priority==="CRITICAL"||t.priority==="HIGH"||t.priority==="MEDIUM"||t.priority==="LOW")&&(n.priority=t.priority),n})}function qa(e,t,n){const r=Dp(e.store,t,n);if(!r)throw Se(e.store,t,n);return r}async function Xp(e,t){return Ba(e.store,t)}async function eh(e,t,n){const r=Dp(e.store,t,n);if(r)return r;const o=Se(e.store,t,n);if(o.foundInRepos.length>0)throw o;return null}async function th(e,t,n,r){return Up(e.store,t,n,r)}async function nh(e,t){return ct(e.store,t??{})}async function rh(e,t,n,r){NA(e.store,t,n,r)}async function oh(e,t){return dA(e.store,t??{})}async function sh(e,t,n){return pA(e.store,t??{},n??20)}async function ih(e,t){return mA(e.store,t??{})}async function ah(e,t,n){return hA(e.store,t,n)}async function ch(e,t){return Rp(e.store,t??{})}async function uh(e,t){return gA(e.store,t??{})}async function lh(e,t,n){return $A(e.store,t,n??{})}async function fh(e,t,n,r,o){const s=qa(e,t,n);return Bp(e.store,s.nodeId,r,o??{})}async function dh(e,t,n,r){const o=qa(e,t,n);return AA(e.store,o.nodeId,r)}async function ph(e,t,n,r,o){const s=qa(e,t,n);return jA(e.store,s.nodeId,r,o??{})}async function hh(e,t,n,r,o){return VA(e.store,t,n,r,o)}async function mh(e,t,n,r){return xA(e.store,t,n,r)}async function gh(e,t,n,r,o){return Cn(e.store,t,n,r,o)}async function yh(e,t,n,r){return PA(e.store,t,n,r)}async function $h(e,t,n,r,o){return TA(e.store,t,n,r,o)}async function vh(e,t,n,r,o){return IA(e.store,t,n,r,o)}async function wh(e,t,n){const r=CA(e.store,t,n??{}),o=r.length>0?Qp(r,new Date().toISOString().slice(0,10)):"";return{archivedCount:r.length,changelogMarkdown:o}}async function bh(e,t,n,r){RA(e.store,t,n,r)}async function Eh(e,t,n,r){MA(e.store,t,n,r)}async function Sh(e,t,n,r){DA(e.store,t,n,r)}async function Oh(e,t,n,r,o){return LA(e.store,t,n,r,o)}async function Nh(e,t,n,r){return UA(e.store,t,n,r)}async function _h(e,t,n,r,o){return BA(e.store,t,n,r,o)}async function kh(e,t,n,r){return qp(e.store,t,n,r)}async function Ah(e,t,n,r){Us(e.store,t,n,r)}async function jh(e,t){const n=L.readFileSync(t.path,"utf8"),{items:r,malformedHeaders:o}=Hp(n),s=Zp(r),i=t.sourcePath??t.path,a=Tp(e.store),c=a.size>0&&!a.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...a].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0,u={parsed:s.length,created:0,skippedDuplicates:0,updated:0,errors:[],malformedHeaders:o,...c!==void 0?{repoWarning:c}:{}};if(t.dryRun)return u;for(const l of s)try{const f=Ba(e.store,{family:l.humanId.replace(/-\d+$/,""),idOverride:l.humanId,title:l.title,body:l.body,repo:t.repo,...t.projectPath!==void 0?{projectPath:t.projectPath}:{},...t.plan!==void 0?{plan:t.plan}:{},importedFrom:i,...l.priority!==void 0?{priority:l.priority}:{},force:!0});if(f.created&&t.plan!==void 0&&Us(e.store,t.repo,l.humanId,t.plan),f.created&&l.status!=="OPEN"&&Cn(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...kr(l.status)?{citations:[{file:t.path}]}:{},...Ar(l.status)?{reason:`imported from markdown at status ${l.status}`}:{}}),f.created){u.created+=1;continue}u.skippedDuplicates+=1;const p=f.duplicateCandidates[0]??f.item;let h=!1;if(p.importedFrom===void 0||p.importedFrom===i){const g={};p.title!==l.title&&(g.title=l.title),p.body!==l.body&&(g.body=l.body),p.importedFrom===void 0&&(g.importedFrom=i),t.projectPath!==void 0&&p.projectPath!==t.projectPath&&(g.projectPath=t.projectPath),Object.keys(g).length>0&&(Up(e.store,t.repo,l.humanId,g),h=!0),l.priority!==void 0&&p.priority!==l.priority&&(qp(e.store,t.repo,l.humanId,l.priority),h=!0),p.status!==l.status&&(Cn(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...kr(l.status)?{citations:[{file:t.path}]}:{},...Ar(l.status)?{reason:`re-imported from markdown at status ${l.status}`}:{}}),h=!0)}t.plan!==void 0&&p.plan!==t.plan&&(Us(e.store,t.repo,l.humanId,t.plan),h=!0),h&&(u.updated+=1)}catch(f){u.errors.push({humanId:l.humanId,message:f instanceof Error?f.message:String(f)})}return u}async function Ih(e,t){let r=Pp(e.store,{...t,excludeArchived:!0}).map(ie);return(t==null?void 0:t.status)==="open"?r=r.filter(o=>!Ue(o.status)):(t==null?void 0:t.status)==="closed"&&(r=r.filter(o=>Ue(o.status))),Yp(r)}async function xh(e,t){return ct(e.store,t??{})}async function Ph(e,t,n){return vA(e.store,t,n)}const nj={"not-started":"not-started: BACKLOG.md is authoritative everywhere; the tool has not been adopted for this repo yet.","phase-1":"phase-1: seed import complete (or in progress) — BACKLOG.md remains authoritative; the graph is a read-only shadow copy.","phase-2":"phase-2: BACKLOG.md is still authoritative; the tool is shadow-running in parity-check mode (render vs. hand-edited markdown, non-blocking).","phase-3":"phase-3: the graph is authoritative. File/claim/transition/resolve via the backlog CLI/MCP — every BACKLOG.md is a generated projection, never hand-edited.","phase-4":"phase-4: phase-3 write path is live; the backlog-usage skill is published and distributed for agent discovery.","phase-5":"phase-5: the legacy tools/util/backlog.mjs parser has been deprecated/removed.",complete:"complete: migration fully done, including cross-repo rollout (Phase 6) where applicable."};async function Th(e){const t=e.env.config.migration.phase;return Ch(t)}function Ch(e){const t=nj[e]??`unknown phase value: ${e}`;return{phase:e,description:t,toolIsAuthoritative:e==="phase-3"||e==="phase-4"||e==="phase-5"||e==="complete"}}async function Rh(e,t){const n=Xk(e.env,t,e.adhdRoot);return{...Ch(t),configPath:n}}function rj(){const e=T.dirname(Rn.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),t=T.join(e,"package.json");return L.existsSync(t)?t:T.join(e,"..","package.json")}async function Mh(e){const t=rj(),n=JSON.parse(L.readFileSync(t,"utf8"));return{name:n.name,version:n.version}}const oj=Object.freeze(Object.defineProperty({__proto__:null,addCitation:yh,addDependency:bh,appendNote:$h,archiveResolved:wh,assignItem:hh,attachToPlan:Ah,auditTrail:Ph,blockers:ah,claimItem:fh,createItem:Xp,dependencyGraph:ch,exportJson:xh,getItem:eh,importFromMarkdown:jh,linkRelated:Sh,listItems:nh,mergeItems:_h,migrationStatus:Th,readyItems:ih,releaseClaim:ph,removeDependency:Eh,renderToMarkdown:Ih,renewClaim:dh,resolveItem:vh,setMigrationPhase:Rh,setPriority:kh,softDeleteItem:rh,splitItem:Nh,spotlight:sh,staleClaims:lh,startWork:mh,stats:oh,supersedeItem:Oh,topoOrder:uh,transitionStatus:gh,updateItem:th,version:Mh},Symbol.toStringTag,{value:"Module"}));function Bs(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function Dh(){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}function Lh(){const e=T.dirname(Rn.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href));return L.existsSync(T.join(e,"client.d.ts"))?e:T.join(e,"..","dist")}function $l(e){if(!e||typeof e!="object")return e;const t={},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 t||(t[c]=u)}for(const[i,a]of Object.entries(s))i==="definitions"||i==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;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 t)?{}:r(t[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(e,new Set)}const sj=bl.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href),ij=sj("@adhd/apigen-core-client/package.json").version;function aj(){return process.env.APIGEN_IR_CACHE_FILE??T.join(process.cwd(),"tmp","apigen","ir-cache","backlog-client.ir.json")}function cj(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function uj(){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:LO({cache:aj(),extractorVersion:ij})}}}}let vl;function lj(){return vl??(vl=IO(cj()?[uj()]:[],e=>{var t;return vO({sourceFile:e.source,namespace:e.namespace,tsconfig:typeof((t=e.extractorOptions)==null?void 0:t.tsconfig)=="string"?e.extractorOptions.tsconfig:void 0,dropFileSegment:!0})})),vl}async function fj(){const e=T.join(Lh(),"client.d.ts");if(!L.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 lj()({source:e,host:"ts",namespace:"backlog",extractorOptions:{}})}async function Va(e){const t=typeof e=="function"?e:()=>e,n=await fj(),r={schemas:Object.fromEntries(n.filter(s=>s.kind==="action").map(s=>{var i;return[((i=s.path[s.path.length-1])==null?void 0:i.raw)??"",{input:$l(s.input),output:$l(s.output),hasCtx:s.hasCtx,safe:s.safe}]}))};return{pkg:{id:"backlog",schemas:zS(r,[]),importPath:T.join(Lh(),"client.js"),fns:oj,createClient:async()=>t()},operations:n}}async function Uh(e){const t=da({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd});t.ensureDirs();const n=ii(t.files.db,t.config.db.busyTimeoutMs),r={store:n,env:t},{pkg:o,operations:s}=await Va(r),i=Dh(),a=[];(e.transport==="http"||e.transport==="both")&&a.push(Bs(l_)({packages:[o],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[O_,ns]},signal:e.signal,operations:s,logger:i})),(e.transport==="mcp"||e.transport==="both")&&a.push(Bs(Yk)({packages:[o],outputDir:"",options:{transport:"stdio",usePlugins:[ns]},signal:e.signal,operations:s,logger:i}));try{await Promise.all(a)}finally{ai(n)}}const Wt=["claude","codex","opencode"],dj={claude:".claude",codex:".codex",opencode:".opencode"};function Bh(e,t){return t?T.join(e,".codex"):process.env.CODEX_HOME??T.join(e,".codex")}function pj(e,t,n,r){if(t==="project")return T.join(n,dj[e],"skills");const o=r??He.homedir();return e==="claude"?T.join(o,".claude","skills"):e==="codex"?T.join(Bh(o,r),"skills"):T.join(o,".config","opencode","skills")}function hj(){const e=T.dirname(Rn.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),t=T.join(e,"skill","SKILL.md");return L.existsSync(t)?t:T.join(e,"..","skill","SKILL.md")}function mj(e){let t="all",n="user";for(let o=0;o<e.length;o++){const s=e[o];if(s==="--host")t=e[++o]??"all";else if(s==="--scope")n=e[++o]??"user";else throw new Error(`backlog install-skill: unknown argument "${s}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project")throw new Error(`backlog install-skill: --scope must be "user" or "project", got "${n}"`);const r=t==="all"?[...Wt]:[t];for(const o of r)if(!Wt.includes(o))throw new Error(`backlog install-skill: --host must be one of ${Wt.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function Fh(e,t=process.cwd(),n){const{hosts:r,scope:o}=mj(e);return qh(r,o,t,n)}function qh(e,t,n,r){const o=hj();if(!L.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const s=L.readFileSync(o,"utf8"),i=T.dirname(Rn.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),a=T.join(i,"package.json"),c=L.existsSync(a)?a:T.join(i,"..","package.json"),u=JSON.parse(L.readFileSync(c,"utf8")),l=[];for(const f of e){const p=T.join(pj(f,t,n,r),"backlog");L.mkdirSync(p,{recursive:!0});const h=T.join(p,"SKILL.md");L.writeFileSync(h,s,"utf8"),L.writeFileSync(T.join(p,"extension.json"),JSON.stringify({name:u.name,version:u.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
|
|
197
|
-
`,"utf8"),l.push({host:f,scope:t,path:h})}return l}async function
|
|
198
|
-
`,"utf8")}function
|
|
196
|
+
`,n}function th(e){return e.map(t=>{const n={humanId:t.id,title:t.title,body:t.body,status:zp(t.status)};return t.priority&&(t.priority==="CRITICAL"||t.priority==="HIGH"||t.priority==="MEDIUM"||t.priority==="LOW")&&(n.priority=t.priority),n})}async function Va(e,t,n){const r=await Bp(e.store,t,n);if(!r)throw await Se(e.store,t,n);return r}async function nh(e,t){return Fa(e.store,t)}async function rh(e,t,n){const r=await Bp(e.store,t,n);if(r)return r;const o=await Se(e.store,t,n);if(o.foundInRepos.length>0)throw o;return null}async function oh(e,t,n,r){return qp(e.store,t,n,r)}async function sh(e,t){return ct(e.store,t??{})}async function ih(e,t,n,r){await kA(e.store,t,n,r)}async function ah(e,t){return mA(e.store,t??{})}async function ch(e,t,n){return gA(e.store,t??{},n??20)}async function uh(e,t){return $A(e.store,t??{})}async function lh(e,t,n){return yA(e.store,t,n)}async function fh(e,t){return Lp(e.store,t??{})}async function dh(e,t){return vA(e.store,t??{})}async function ph(e,t,n){return bA(e.store,t,n??{})}async function hh(e,t,n,r,o){const s=await Va(e,t,n);return Vp(e.store,s.nodeId,r,o??{})}async function mh(e,t,n,r){const o=await Va(e,t,n);return IA(e.store,o.nodeId,r)}async function gh(e,t,n,r,o){const s=await Va(e,t,n);return xA(e.store,s.nodeId,r,o??{})}async function yh(e,t,n,r,o){return GA(e.store,t,n,r,o)}async function $h(e,t,n,r){return TA(e.store,t,n,r)}async function vh(e,t,n,r,o){return Cn(e.store,t,n,r,o)}async function wh(e,t,n,r){return CA(e.store,t,n,r)}async function bh(e,t,n,r,o){return RA(e.store,t,n,r,o)}async function Eh(e,t,n,r,o){return PA(e.store,t,n,r,o)}async function Sh(e,t,n){const r=await MA(e.store,t,n??{}),o=r.length>0?eh(r,new Date().toISOString().slice(0,10)):"";return{archivedCount:r.length,changelogMarkdown:o}}async function Oh(e,t,n,r){await DA(e.store,t,n,r)}async function Nh(e,t,n,r){await LA(e.store,t,n,r)}async function _h(e,t,n,r){await UA(e.store,t,n,r)}async function kh(e,t,n,r,o){return BA(e.store,t,n,r,o)}async function Ah(e,t,n,r){return FA(e.store,t,n,r)}async function jh(e,t,n,r,o){return qA(e.store,t,n,r,o)}async function Ih(e,t,n,r){return Gp(e.store,t,n,r)}async function xh(e,t,n,r){await Bs(e.store,t,n,r)}async function Ph(e,t){const n=L.readFileSync(t.path,"utf8"),{items:r,malformedHeaders:o}=Qp(n),s=th(r),i=t.sourcePath??t.path,a=await Mp(e.store),c=a.size>0&&!a.has(t.repo)?`repo '${t.repo}' is new to this store — existing repo value(s) here: ${[...a].sort().join(", ")}. If this is meant to be the same project, use the existing repo value instead.`:void 0,u={parsed:s.length,created:0,skippedDuplicates:0,updated:0,errors:[],malformedHeaders:o,...c!==void 0?{repoWarning:c}:{}};if(t.dryRun)return u;for(const l of s)try{const f=await Fa(e.store,{family:l.humanId.replace(/-\d+$/,""),idOverride:l.humanId,title:l.title,body:l.body,repo:t.repo,...t.projectPath!==void 0?{projectPath:t.projectPath}:{},...t.plan!==void 0?{plan:t.plan}:{},importedFrom:i,...l.priority!==void 0?{priority:l.priority}:{},force:!0});if(f.created&&t.plan!==void 0&&await Bs(e.store,t.repo,l.humanId,t.plan),f.created&&l.status!=="OPEN"&&await Cn(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...kr(l.status)?{citations:[{file:t.path}]}:{},...Ar(l.status)?{reason:`imported from markdown at status ${l.status}`}:{}}),f.created){u.created+=1;continue}u.skippedDuplicates+=1;const p=f.duplicateCandidates[0]??f.item;let h=!1;if(p.importedFrom===void 0||p.importedFrom===i){const m={};p.title!==l.title&&(m.title=l.title),p.body!==l.body&&(m.body=l.body),p.importedFrom===void 0&&(m.importedFrom=i),t.projectPath!==void 0&&p.projectPath!==t.projectPath&&(m.projectPath=t.projectPath),Object.keys(m).length>0&&(await qp(e.store,t.repo,l.humanId,m),h=!0),l.priority!==void 0&&p.priority!==l.priority&&(await Gp(e.store,t.repo,l.humanId,l.priority),h=!0),p.status!==l.status&&(await Cn(e.store,t.repo,l.humanId,l.status,{by:"system:importFromMarkdown",...kr(l.status)?{citations:[{file:t.path}]}:{},...Ar(l.status)?{reason:`re-imported from markdown at status ${l.status}`}:{}}),h=!0)}t.plan!==void 0&&p.plan!==t.plan&&(await Bs(e.store,t.repo,l.humanId,t.plan),h=!0),h&&(u.updated+=1)}catch(f){u.errors.push({humanId:l.humanId,message:f instanceof Error?f.message:String(f)})}return u}async function Th(e,t){let r=(await Rp(e.store,{...t,excludeArchived:!0})).map(ie);return(t==null?void 0:t.status)==="open"?r=r.filter(o=>!Ue(o.status)):(t==null?void 0:t.status)==="closed"&&(r=r.filter(o=>Ue(o.status))),Xp(r)}async function Ch(e,t){return ct(e.store,t??{})}async function Rh(e,t,n){return EA(e.store,t,n)}const oj={"not-started":"not-started: BACKLOG.md is authoritative everywhere; the tool has not been adopted for this repo yet.","phase-1":"phase-1: seed import complete (or in progress) — BACKLOG.md remains authoritative; the graph is a read-only shadow copy.","phase-2":"phase-2: BACKLOG.md is still authoritative; the tool is shadow-running in parity-check mode (render vs. hand-edited markdown, non-blocking).","phase-3":"phase-3: the graph is authoritative. File/claim/transition/resolve via the backlog CLI/MCP — every BACKLOG.md is a generated projection, never hand-edited.","phase-4":"phase-4: phase-3 write path is live; the backlog-usage skill is published and distributed for agent discovery.","phase-5":"phase-5: the legacy tools/util/backlog.mjs parser has been deprecated/removed.",complete:"complete: migration fully done, including cross-repo rollout (Phase 6) where applicable."};async function Mh(e){const t=e.env.config.migration.phase;return Dh(t)}function Dh(e){const t=oj[e]??`unknown phase value: ${e}`;return{phase:e,description:t,toolIsAuthoritative:e==="phase-3"||e==="phase-4"||e==="phase-5"||e==="complete"}}async function Lh(e,t){const n=nA(e.env,t,e.adhdRoot);return{...Dh(t),configPath:n}}function sj(){const e=T.dirname(Rn.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),t=T.join(e,"package.json");return L.existsSync(t)?t:T.join(e,"..","package.json")}async function Uh(e){const t=sj(),n=JSON.parse(L.readFileSync(t,"utf8"));return{name:n.name,version:n.version}}const ij=Object.freeze(Object.defineProperty({__proto__:null,addCitation:wh,addDependency:Oh,appendNote:bh,archiveResolved:Sh,assignItem:yh,attachToPlan:xh,auditTrail:Rh,blockers:lh,claimItem:hh,createItem:nh,dependencyGraph:fh,exportJson:Ch,getItem:rh,importFromMarkdown:Ph,linkRelated:_h,listItems:sh,mergeItems:jh,migrationStatus:Mh,readyItems:uh,releaseClaim:gh,removeDependency:Nh,renderToMarkdown:Th,renewClaim:mh,resolveItem:Eh,setMigrationPhase:Lh,setPriority:Ih,softDeleteItem:ih,splitItem:Ah,spotlight:ch,staleClaims:ph,startWork:$h,stats:ah,supersedeItem:kh,topoOrder:dh,transitionStatus:vh,updateItem:oh,version:Uh},Symbol.toStringTag,{value:"Module"}));function Fs(e){if(!e.run)throw new Error(`@adhd/backlog: apigen plugin "${e.id}" declares no run() — cannot mount live`);return e.run}function Bh(){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}function Fh(){const e=T.dirname(Rn.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href));return L.existsSync(T.join(e,"client.d.ts"))?e:T.join(e,"..","dist")}function vl(e){if(!e||typeof e!="object")return e;const t={},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 t||(t[c]=u)}for(const[i,a]of Object.entries(s))i==="definitions"||i==="$defs"||n(a)};if(n(e),n(t),Object.keys(t).length===0)return e;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 t)?{}:r(t[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(e,new Set)}const aj=El.createRequire(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href),cj=aj("@adhd/apigen-core-client/package.json").version;function uj(){return process.env.APIGEN_IR_CACHE_FILE??T.join(process.cwd(),"tmp","apigen","ir-cache","backlog-client.ir.json")}function lj(){return process.env.APIGEN_IR_CACHE_ENABLED!=="0"}function fj(){return{id:"ir-cache",description:"Extract-stage IR cache, configured for the backlog hot path (BUG-019).",language:"ts",capabilities:{extractLayer:{layer:FO({cache:uj(),extractorVersion:cj})}}}}let wl;function dj(){return wl??(wl=TO(lj()?[fj()]:[],e=>{var t;return EO({sourceFile:e.source,namespace:e.namespace,tsconfig:typeof((t=e.extractorOptions)==null?void 0:t.tsconfig)=="string"?e.extractorOptions.tsconfig:void 0,dropFileSegment:!0})})),wl}async function pj(){const e=T.join(Fh(),"client.d.ts");if(!L.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 dj()({source:e,host:"ts",namespace:"backlog",extractorOptions:{}})}async function Ka(e){const t=typeof e=="function"?e:()=>e,n=await pj(),r={schemas:Object.fromEntries(n.filter(s=>s.kind==="action").map(s=>{var i;return[((i=s.path[s.path.length-1])==null?void 0:i.raw)??"",{input:vl(s.input),output:vl(s.output),hasCtx:s.hasCtx,safe:s.safe}]}))};return{pkg:{id:"backlog",schemas:HS(r,[]),importPath:T.join(Fh(),"client.js"),fns:ij,createClient:async()=>t()},operations:n}}async function qh(e){const t=da({scope:e.scope,adhdRoot:e.adhdRoot,cwd:e.cwd});t.ensureDirs();const n=await ai(pa(t),t.config.db.busyTimeoutMs),r={store:n,env:t},{pkg:o,operations:s}=await Ka(r),i=Bh(),a=[];(e.transport==="http"||e.transport==="both")&&a.push(Fs(p_)({packages:[o],outputDir:"",options:{port:e.port??3300,host:e.host??"127.0.0.1",usePlugins:[k_,rs]},signal:e.signal,operations:s,logger:i})),(e.transport==="mcp"||e.transport==="both")&&a.push(Fs(Xk)({packages:[o],outputDir:"",options:{transport:"stdio",usePlugins:[rs]},signal:e.signal,operations:s,logger:i}));try{await Promise.all(a)}finally{await zl(n)}}const Ht=["claude","codex","opencode"],hj={claude:".claude",codex:".codex",opencode:".opencode"};function Vh(e,t){return t?T.join(e,".codex"):process.env.CODEX_HOME??T.join(e,".codex")}function mj(e,t,n,r){if(t==="project")return T.join(n,hj[e],"skills");const o=r??We.homedir();return e==="claude"?T.join(o,".claude","skills"):e==="codex"?T.join(Vh(o,r),"skills"):T.join(o,".config","opencode","skills")}function gj(){const e=T.dirname(Rn.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),t=T.join(e,"skill","SKILL.md");return L.existsSync(t)?t:T.join(e,"..","skill","SKILL.md")}function yj(e){let t="all",n="user";for(let o=0;o<e.length;o++){const s=e[o];if(s==="--host")t=e[++o]??"all";else if(s==="--scope")n=e[++o]??"user";else throw new Error(`backlog install-skill: unknown argument "${s}" (expected --host/--scope)`)}if(n!=="user"&&n!=="project")throw new Error(`backlog install-skill: --scope must be "user" or "project", got "${n}"`);const r=t==="all"?[...Ht]:[t];for(const o of r)if(!Ht.includes(o))throw new Error(`backlog install-skill: --host must be one of ${Ht.join("|")}|all, got "${t}"`);return{hosts:r,scope:n}}function Kh(e,t=process.cwd(),n){const{hosts:r,scope:o}=yj(e);return Gh(r,o,t,n)}function Gh(e,t,n,r){const o=gj();if(!L.existsSync(o))throw new Error(`backlog install-skill: packaged skill file not found at ${o} — was @adhd/backlog built/installed correctly?`);const s=L.readFileSync(o,"utf8"),i=T.dirname(Rn.fileURLToPath(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)),a=T.join(i,"package.json"),c=L.existsSync(a)?a:T.join(i,"..","package.json"),u=JSON.parse(L.readFileSync(c,"utf8")),l=[];for(const f of e){const p=T.join(mj(f,t,n,r),"backlog");L.mkdirSync(p,{recursive:!0});const h=T.join(p,"SKILL.md");L.writeFileSync(h,s,"utf8"),L.writeFileSync(T.join(p,"extension.json"),JSON.stringify({name:u.name,version:u.version,type:"skill",entrypoint:"SKILL.md"},null,2)+`
|
|
197
|
+
`,"utf8"),l.push({host:f,scope:t,path:h})}return l}async function zh(e){const t=Kh(e);console.log(JSON.stringify({installed:t}))}const Ga=["-y","@adhd/backlog@latest","serve","--transport","mcp"];function $j(e){if(!L.existsSync(e))return{};const t=L.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 Jh(e,t,n,r){const o=$j(e),s=o[t],i=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:{};i[n]=r,o[t]=i,L.mkdirSync(T.dirname(e),{recursive:!0}),L.writeFileSync(e,JSON.stringify(o,null,2)+`
|
|
198
|
+
`,"utf8")}function vj(e,t,n){if(e==="project")return T.join(t,".mcp.json");const r=We.homedir();return T.join(r,".claude.json")}function wj(e,t,n){if(e==="project")return T.join(t,"opencode.json");const r=We.homedir();return T.join(r,".config","opencode","opencode.json")}function bj(e,t,n){if(e==="project")return T.join(t,".codex","config.toml");const r=We.homedir();return T.join(Vh(r,n),"config.toml")}function Ej(e,t,n){var u,l;const r=`[${t}]`,o=e.length>0?e.split(`
|
|
199
199
|
`):[],s=o.findIndex(f=>f.trim()===r),i=[r,...n];if(s===-1){if(o.length===0||o.every(f=>f.trim()===""))return i.join(`
|
|
200
200
|
`)+`
|
|
201
201
|
`;for(;o.length>0&&((u=o[o.length-1])==null?void 0:u.trim())==="";)o.pop();return[...o,"",...i].join(`
|
|
202
202
|
`)+`
|
|
203
203
|
`}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(`
|
|
204
204
|
`)+`
|
|
205
|
-
`}function
|
|
205
|
+
`}function Sj(e){return`[${e.map(t=>JSON.stringify(t)).join(", ")}]`}function Oj(e,t,n){const r=vj(e,t);return Jh(r,"mcpServers","backlog",{type:"stdio",command:"npx",args:[...Ga]}),{host:"claude",scope:e,configPath:r,status:"written"}}function Nj(e,t,n){const r=wj(e,t);return Jh(r,"mcp","backlog",{type:"local",command:["npx",...Ga]}),{host:"opencode",scope:e,configPath:r,status:"written"}}function _j(e,t,n){const r=bj(e,t,n),o=L.existsSync(r)?L.readFileSync(r,"utf8"):"",s=Ej(o,"mcp_servers.backlog",['command = "npx"',`args = ${Sj(Ga)}`]);return L.mkdirSync(T.dirname(r),{recursive:!0}),L.writeFileSync(r,s,"utf8"),{host:"codex",scope:e,configPath:r,status:"written"}}function kj(e,t,n,r){return e==="claude"?Oj(t,n):e==="opencode"?Nj(t,n):_j(t,n,r)}function Aj(e,t){let n="all",r="user",o=!1,s=!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")s=!0;else throw new Error(`backlog ${t}: unknown argument "${c}" (expected --host/--scope/--skill-only/--mcp-only)`)}if(o&&s)throw new Error(`backlog ${t}: --skill-only and --mcp-only are mutually exclusive`);if(r!=="user"&&r!=="project")throw new Error(`backlog ${t}: --scope must be "user" or "project", got "${r}"`);const i=n==="all"?[...Ht]:[n];for(const a of i)if(!Ht.includes(a))throw new Error(`backlog ${t}: --host must be one of ${Ht.join("|")}|all, got "${n}"`);return{hosts:i,scope:r,skillOnly:o,mcpOnly:s}}const jj=`backlog install [--host claude|opencode|codex|all] [--scope user|project] [--skill-only | --mcp-only]
|
|
206
206
|
|
|
207
207
|
Installs the backlog skill AND registers the backlog MCP server into an agent
|
|
208
208
|
host's config, in one step.
|
|
@@ -219,4 +219,4 @@ Examples:
|
|
|
219
219
|
|
|
220
220
|
Back-compat: \`backlog install-skill\` remains available and behaves exactly
|
|
221
221
|
like \`backlog install --skill-only\` (original --host/--scope grammar only).
|
|
222
|
-
`;function
|
|
222
|
+
`;function Ij(e,t=process.cwd(),n){const{hosts:r,scope:o,skillOnly:s,mcpOnly:i}=Aj(e,"install"),a=i?[]:Gh(r,o,t,n),c=s?[]:r.map(u=>kj(u,o,t,n));return{skill:a,mcp:c}}async function xj(e){if(e[0]==="--help"||e[0]==="-h"){console.log(jj);return}const t=Ij(e);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))}function Pj(e){let t="mcp",n,r;for(let s=0;s<e.length;s++){const i=e[s];if(i==="--transport")t=e[++s];else if(i==="--port")n=Number(e[++s]);else if(i==="--host")r=e[++s];else throw new Error(`backlog serve: unknown argument "${i}" (expected --transport/--port/--host)`)}if(t!=="mcp"&&t!=="http"&&t!=="both")throw new Error(`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 Wh(e,t={}){const n=Pj(e),r=new AbortController;process.on("SIGTERM",()=>r.abort()),process.on("SIGINT",()=>r.abort()),await qh({...n,...t,signal:r.signal})}function Hh(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 Kl(t).cli.path.slice(0,-1)}const bl=[rs];function Tj(e,t,n){const r={host:n,operations:t},o=new Set;for(const s of e){const i=s.capabilities.mount;if(!i)continue;const a=i.operations(r,void 0,void 0);for(const c of a){const[u]=Kl(c).cli.path;u!==void 0&&o.add(u)}}return o}function Yh(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((s,i)=>e[i]===s)?[...e]:[...t,...e]}async function Qh(e,t={}){const n=e??process.argv.slice(2);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("")),n[0]==="install-skill"){await zh(n.slice(1));return}if(n[0]==="install"){await xj(n.slice(1));return}if(n[0]==="serve"){await Wh(n.slice(1),t);return}let o;const s=async()=>{if(!o){const i=da({scope:t.scope,adhdRoot:t.adhdRoot,cwd:t.cwd});i.ensureDirs();const a=await ai(pa(i),i.config.db.busyTimeoutMs);o={store:a,ctx:{store:a,env:i}}}return o.ctx};try{const{pkg:i,operations:a}=await Ka(s),c=n,u=Hh(a),l=Tj(bl,a,i.id);await Fs(Vg)({packages:[i],operations:a,outputDir:"",options:{argv:Yh(c,u,l),usePlugins:[...bl]},signal:t.signal??new AbortController().signal,logger:Bh()})}finally{await zl(o==null?void 0:o.store)}}if(process.argv[1]&&(typeof document>"u"?require("url").pathToFileURL(__filename).href:re&&re.tagName.toUpperCase()==="SCRIPT"&&re.src||new URL("index.js",document.baseURI).href)===Rn.pathToFileURL(L.realpathSync(process.argv[1])).href){try{im.initTelemetry({service:"backlog",role:"cli",logSink:"file"})}catch(e){console.error(`[sox-telemetry] WARNING: initTelemetry failed (${e instanceof Error?e.message:String(e)}); telemetry records will be silently dropped this process`)}Qh().catch(e=>{console.error(e instanceof Error?e.stack??e.message:String(e)),process.exitCode=1})}exports.AmbiguousHumanIdError=Ma;exports.BacklogItemNotFoundError=_p;exports.CitationRequiredError=kp;exports.ClaimHeldError=jp;exports.DependencyCycleError=eA;exports.InvalidArgumentError=Me;exports.ReasonRequiredError=Ap;exports.TERMINAL_DISMISSED_STATUSES=Np;exports.TERMINAL_DONE_STATUSES=Sp;exports.TERMINAL_STATUSES=Ra;exports.TERMINAL_WORKAROUND_STATUSES=Op;exports.addCitation=wh;exports.addDependency=Oh;exports.appendNote=bh;exports.archiveResolved=Sh;exports.assignItem=yh;exports.attachToPlan=xh;exports.auditTrail=Rh;exports.backlogEnvironmentSpec=zd;exports.blockers=lh;exports.buildBacklogApigenPackage=Ka;exports.buildBacklogEnv=da;exports.buildChangelogSection=eh;exports.claimItem=hh;exports.classifyStatus=Jp;exports.closeGraphBacklogStore=Gl;exports.createItem=nh;exports.dependencyGraph=fh;exports.detectPriority=Hp;exports.detectStatus=Wp;exports.exportJson=Ch;exports.getItem=rh;exports.importFromMarkdown=Ph;exports.installSkill=Kh;exports.isTerminalStatus=Ue;exports.linkRelated=_h;exports.listItems=sh;exports.mergeItems=jh;exports.migrationStatus=Mh;exports.normalizeLegacyStatus=zp;exports.openGraphBacklogStore=ai;exports.parseBacklogMarkdown=XA;exports.parseBacklogMarkdownWithDiagnostics=Qp;exports.prefixCommand=Yh;exports.readyItems=uh;exports.releaseClaim=gh;exports.removeDependency=Nh;exports.renderItemsToMarkdown=Xp;exports.renderToMarkdown=Th;exports.renewClaim=mh;exports.requiresCitation=kr;exports.requiresReason=Ar;exports.resolveBacklogDbPath=pa;exports.resolveBacklogScope=Jd;exports.resolveCommandPrefix=Hh;exports.resolveItem=Eh;exports.runBacklogCli=Qh;exports.runInstallSkillCommand=zh;exports.runServeCommand=Wh;exports.setMigrationPhase=Lh;exports.setPriority=Ih;exports.softDeleteItem=ih;exports.splitItem=Ah;exports.spotlight=ch;exports.staleClaims=ph;exports.startBacklogServer=qh;exports.startWork=$h;exports.stats=ah;exports.suggestClaimantIdentity=FS;exports.supersedeItem=kh;exports.toImportItems=th;exports.topoOrder=dh;exports.transitionStatus=vh;exports.updateItem=oh;exports.version=Uh;
|