@adhd/apigen-engine-runtime 0.2.3 โ†’ 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,58 @@
1
+ ## 0.3.0 (2026-09-26)
2
+
3
+ ### ๐Ÿš€ Features
4
+
5
+ - **vite-plugins:** absorb perf/test-resolve-fix โ€” test-time @adhd/* source resolution ([3e344506](https://github.com/PseudoSky/adhd/commit/3e344506))
6
+
7
+ ### ๐Ÿฉน Fixes
8
+
9
+ - โš ๏ธ **apigen:** regenerate the ADR-0004 golden snapshot, add the MAJOR release note, clear the format gate ([1fea3c2f](https://github.com/PseudoSky/adhd/commit/1fea3c2f))
10
+ - **apigen:** rebase onto main โ€” flip [BUG-APIGEN-059] to ADR-0004 semantics ([a8009900](https://github.com/PseudoSky/adhd/commit/a8009900))
11
+ - **apigen:** ADR-0004 โ€” MCP tool output is the flat content payload ([7896594d](https://github.com/PseudoSky/adhd/commit/7896594d))
12
+ - **nx:** reconcile main's e2e lane with the flat ESLint config + fix missing-deps ([cf72a2ab](https://github.com/PseudoSky/adhd/commit/cf72a2ab))
13
+ - **vite:** restore import.meta.url in CJS output under vite 8 ([7916e639](https://github.com/PseudoSky/adhd/commit/7916e639))
14
+ - **nx:** finish the ESLint v9 flat-config migration and unblock the gate ([53f4ff3e](https://github.com/PseudoSky/adhd/commit/53f4ff3e))
15
+
16
+ ### โš ๏ธ Breaking Changes
17
+
18
+ - **apigen:** regenerate the ADR-0004 golden snapshot, add the MAJOR release note, clear the format gate ([1fea3c2f](https://github.com/PseudoSky/adhd/commit/1fea3c2f))
19
+ McpOutputAdapter.wrapped (exported from
20
+ @adhd/apigen-engine-runtime and @adhd/apigen-plugin-mcp) kept its name but
21
+ inverted its meaning (true now means "the return is already a top-level object,
22
+ emit the value as flat structuredContent", not "wrapped under result"), and an
23
+ MCP tool return that is not a top-level object no longer emits an outputSchema
24
+ or structuredContent. This is semver-MAJOR for those two packages; republish
25
+ them first per ADR-0004 D6.
26
+
27
+ ### โค๏ธ Thank You
28
+
29
+ - pseudosky
30
+
31
+ ## 0.2.4 (2026-09-24)
32
+
33
+
34
+ ### ๐Ÿš€ Features
35
+
36
+ - **apigen:** let a CLI host derive its process exit code from the result
37
+
38
+ - **backlog:** INTERFACE_v2 consolidation โ€” six-verb surface, web UI (search/stats/batch/edit), stats API (citationCount, closedAt, summary scope + window)
39
+
40
+
41
+ ### ๐Ÿฉน Fixes
42
+
43
+ - **apigen:** accept camelCase flag spellings as aliases in the flag table
44
+
45
+ - **apigen-cli:** batch nested-input CLI/HTTP wiring, sandbox isolation leaks, morph-walk index-signature regression
46
+
47
+ - **apigen:** audit fixes โ€” S-18/S-19/C-20/C-21/S-20, java mvn race, union-encoder envelope, lazy heavy-dep loading
48
+
49
+
50
+ ### โค๏ธ Thank You
51
+
52
+ - parity-harness-self-test
53
+ - pseudosky
54
+ - Sky
55
+
1
56
  ## 0.2.3 (2026-08-07)
2
57
 
3
58
 
package/README.md CHANGED
@@ -56,3 +56,16 @@ the envelope fields a function requires (e.g. a `session` added by middleware) a
56
56
  npx nx build apigen-engine-runtime
57
57
  npx nx test apigen-engine-runtime
58
58
  ```
59
+
60
+ `nx test` runs only the cheap in-process `*.spec.ts` lane (and is what
61
+ `nx affected -t test` / the git hooks run). The resource-consuming self-tests
62
+ (real `git` subprocesses, a real `node:http` server) live in sibling
63
+ `*.e2e.ts` files and run on demand only:
64
+
65
+ ```bash
66
+ npx nx run apigen-engine-runtime:e2e
67
+ ```
68
+
69
+ Both `.e2e.ts` suites are currently `describe.skip`'d (CPU-THRASH-SKIP,
70
+ owner-requested); `*.spec.ts` stubs at the original paths hold their mocked
71
+ `it.todo` inventory.
package/index.d.ts CHANGED
@@ -31,6 +31,6 @@ export type { BatchOptions, BatchItemResult } from './lib/batch';
31
31
  export { buildOpPlan } from './lib/op-plan';
32
32
  export type { OpPlan, BuildOpPlanInput, OpPlanEnvelopeField, OpPlanCliFlag, } from './lib/op-plan';
33
33
  export type { TransportAdapter } from './lib/transport-adapter';
34
- export { createPackageInvoker, readUsePlugins, readUseOptions, adaptCoreLayer, } from './lib/package-invoker';
34
+ export { createPackageInvoker, readUsePlugins, readExitCodeHook, readUseOptions, adaptCoreLayer, } from './lib/package-invoker';
35
35
  export type { UsePlugin, UseOptions } from './lib/package-invoker';
36
36
  export { dispatchForPlan } from './lib/dispatch-for-plan';
package/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});require("ts-morph");require("node:fs");require("node:path");require("ts-json-schema-generator");const N=require("pino"),Be=require("ajv"),qe=require("ajv-formats"),I="$apigen";class J extends Error{constructor(t){super(t),this.code="E_DUP_CODEC",this.name="CodecRegistryError"}}function Fe(e){const t=new Map;return{register(r,n){if(t.has(r.id)&&!(n!=null&&n.override))throw new J(`E_DUP_CODEC: a codec is already registered for id "${r.id}"`);t.set(r.id,r)},resolve(r){for(const n of t.values())if(n.matches(r))return n},get(r){return t.get(r)},ids(){return[...t.keys()]},freeze(){const r=new Map(t),n={register(){throw new J("E_DUP_CODEC: registry is frozen and cannot accept new codecs")},resolve(o){for(const i of r.values())if(i.matches(o))return i},get(o){return r.get(o)},ids(){return[...r.keys()]},freeze(){return n}};return n}}}const R="x-apigen-logical",B="x-apigen-codec",x="x-apigen-ctor",T="x-apigen-tojson",He="0.1.0";function Y(e,t){return{registry:e,resolve:r=>{throw new Error(`[apigen-logical] $ref "${r}" 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 v(e,t,r){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return v(e,a,r)}const i=t.oneOf;if(Array.isArray(i)){const a=pe(e,i,t);return v(e,a,r)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return _(e,t,r);const a=t.items;if(!a)return e.map(c=>w(c));const f=r.path;return Array.isArray(a)?e.map((c,u)=>{const l=a[u];return l===void 0?w(c):v(c,l,{...r,path:`${f}/${u}`})}):e.map((c,u)=>v(c,a,{...r,path:`${f}/${u}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return _(e,t,r);const a=t.properties;if(!a)return w(e);const f=r.path,c={};for(const[u,l]of Object.entries(a)){const d=e[u];d!==void 0&&(c[u]=v(d,l,{...r,path:`${f}/${u}`}))}return c}return s==null?_(e,t,r):w(e)}function $(e,t,r){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r);const o=t.$ref;if(typeof o=="string"){const a=r.resolve(o);return $(e,a,r)}const i=t.oneOf;if(Array.isArray(i)){const a=pe(e,i,t);return $(e,a,r)}const s=t.type;if(s==="array"){if(!Array.isArray(e))return e;const a=t.items;if(!a)return e;const f=r.path;return Array.isArray(a)?e.map((c,u)=>{const l=a[u];return l===void 0?c:$(c,l,{...r,path:`${f}/${u}`})}):e.map((c,u)=>$(c,a,{...r,path:`${f}/${u}`}))}if(s==="object"){if(e===null||typeof e!="object"||Array.isArray(e))return e;const a=t.properties;if(!a)return e;const f=r.path,c={};for(const[u,l]of Object.entries(a)){const d=e[u];d!==void 0&&(c[u]=$(d,l,{...r,path:`${f}/${u}`}))}return c}return s==null?Ke(e,r):e}function pe(e,t,r,n){const o=r.discriminator;if(o!=null&&o.propertyName){const i=e!==null&&typeof e=="object"?e[o.propertyName]:void 0;if(typeof i=="string"&&o.mapping){const s=o.mapping[i];if(s){const a=t.find(f=>f.$ref===s);if(a)return a}}}return t[0]??{}}function _(e,t,r){for(const n of r.registry.ids()){const o=r.registry.get(n);if(o)try{const i=o.encode(e,o.schema,r);return{[I]:n,v:i}}catch{}}return w(e)}function Ke(e,t){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&I in e){const r=e,n=r[I],o=t.registry.get(n);if(o)return o.decode(r.v,o.schema,t)}return e}function w(e){if(e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(Array.isArray(e))return e.map(w);if(typeof e=="object"){const t={};for(const[r,n]of Object.entries(e))n!==void 0&&(t[r]=w(n));return t}return null}function We(e){return{encode(t,r,n){const o=Y(e,n);return v(t,r,o)},decode(t,r,n){const o=Y(e,n);return $(t,r,o)}}}const q={id:"date-time",kind:"scalar",schema:{type:"string",format:"date-time"},matches(e){return e.type==="string"&&e.format==="date-time"},encode(e,t,r){return e.toISOString()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[date-time] expected a string on the wire at "${r.path}", got ${typeof e}`);return new Date(String(e))}if(r.mode==="strict"&&Number.isNaN(new Date(e).getTime()))throw new TypeError(`[date-time] invalid date-time string at "${r.path}": ${JSON.stringify(e)}`);return new Date(e)}},F={id:"int64",kind:"scalar",schema:{type:"string",format:"int64"},matches(e){return e.type==="string"&&e.format==="int64"},encode(e,t,r){return String(e)},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[int64] expected a string on the wire at "${r.path}", got ${typeof e}`);try{return BigInt(Math.trunc(Number(e)))}catch{return BigInt(0)}}if(r.mode==="strict")return BigInt(e);if(/^-?\d+$/.test(e))try{return BigInt(e)}catch{return BigInt(0)}return BigInt(0)}},H={id:"decimal",kind:"scalar",schema:{type:"string",format:"decimal"},matches(e){return e.type==="string"&&e.format==="decimal"},encode(e,t,r){return e},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[decimal] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e)}if(r.mode==="strict"&&!/^-?\d+(\.\d+)?$/.test(e))throw new TypeError(`[decimal] wire value "${e}" at "${r.path}" is not a valid decimal string`);return e}},K={id:"byte",kind:"scalar",schema:{type:"string",format:"byte"},matches(e){return e.type==="string"&&e.format==="byte"},encode(e,t,r){return Buffer.from(e).toString("base64")},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[byte] expected a base64 string on the wire at "${r.path}", got ${typeof e}`);return new Uint8Array(0)}if(r.mode==="strict"&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw new TypeError(`[byte] wire value at "${r.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,"base64"))}},ze=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,W={id:"uuid",kind:"scalar",schema:{type:"string",format:"uuid"},matches(e){return e.type==="string"&&e.format==="uuid"},encode(e,t,r){return e.toLowerCase()},decode(e,t,r){if(typeof e!="string"){if(r.mode==="strict")throw new TypeError(`[uuid] expected a string on the wire at "${r.path}", got ${typeof e}`);return String(e).toLowerCase()}if(r.mode==="strict"&&!ze.test(e))throw new TypeError(`[uuid] wire value "${e}" at "${r.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},M="NaN",P="Infinity",U="-Infinity",Ve=new Set([M,P,U]),z={id:"number-special",kind:"scalar",schema:{type:"number"},matches(e){return e.type==="number"&&e.format===void 0},encode(e,t,r){return Number.isNaN(e)?M:e===1/0?P:e===-1/0?U:e},decode(e,t,r){if(typeof e=="number")return e;if(typeof e=="string"){if(e===M)return NaN;if(e===P)return 1/0;if(e===U)return-1/0;const n=Number(e);if(!Number.isNaN(n))return n}if(r.mode==="strict")throw new TypeError(`[number-special] unrecognized wire value at "${r.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...Ve].join(", ")}.`);return NaN}},Je=[q,F,H,K,W,z];function Ye(e,t={}){for(const r of Je)e.register(r,{override:t.override??!1})}const Ge=12;function Ze(e,t){const r=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!r)return;const[,n,o]=r,i=n==="$defs"?t.$defs:t.definitions;return i==null?void 0:i[decodeURIComponent(o)]}function G(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function Xe(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 Qe(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 Z(e,t,r){const n=e.properties??{},o=e.required??[],i={};for(const s of o){const a=n[s];i[s]=a!==void 0?O(a,t,r+1):`<${s}>`}return i}function et(e,t,r){const n=Array.isArray(e.items)?e.items[0]:e.items;return n?[O(n,t,r+1)]:[]}function O(e,t=e??{},r=0){if(!e||r>Ge)return null;if(typeof e.$ref=="string"){const o=Ze(e.$ref,t);return o!==void 0?O(o,t,r+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={},i=[];for(const s of e.allOf){Object.assign(o,s.properties??{});for(const a of s.required??[])i.includes(a)||i.push(a)}return Z({...e,properties:o,required:i},t,r)}const n=G(e.oneOf)??G(e.anyOf);if(n)return O(n,t,r+1);switch(Xe(e)){case"object":return Z(e,t,r);case"array":return et(e,t,r);case"string":return Qe(e);case"integer":case"number":return 0;case"boolean":return!1;case"null":return null;default:return null}}function de(e){if(!e)return;const t=O(e);return`Example: ${JSON.stringify(t)}`}q.id,F.id,H.id,K.id,W.id,z.id;const ye=Fe();Ye(ye);const me=We(ye.freeze());function he(e,t){var n;const r=((n=e.input)==null?void 0:n.properties)??{};return t in r}function ge(e){var r,n;const t=(n=(r=e.input)==null?void 0:r.properties)==null?void 0:n.data;return Object.keys((t==null?void 0:t.properties)??{})}function tt(e,t){var o,i,s;const r=(s=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data)==null?void 0:s.properties,n=r==null?void 0:r[t];return n!==void 0?n:void 0}function rt(e,t){return t===void 0||e===void 0?e:me.decode(e,t)}function C(e,t){const r=t.output;return!r||Object.keys(r).length===0?e:me.encode(e,r)}async function we(e,t,r,n,o,i){const a=ge(r).map(c=>rt(i[c],tt(r,c)));if(he(r,"session")&&t){const c=await t({session:o.session}),u=await e[n](c,...a);return C(u,r)}if(r.hasCtx){const c=t?await t(o):void 0,u=await e[n](c,...a);return C(u,r)}const f=await e[n](...a);return C(f,r)}class be{constructor(){this._map=new Map}set(t,r){this._map.set(t,r)}get(t){return this._map.get(t)}has(t){return this._map.has(t)}}function ve(e=[]){return async function(r,n,o){const i=o.schemas[r];if(!i)throw new Error(`apigen/invoke: no schema found for operation "${r}"`);const s=()=>we(o.fns,o.createClient,i,r,n.envelope,n.domainArgs);return e.reduceRight((f,c)=>()=>c(n,f),s)()}}function nt(e){return e}class $e{constructor(){this.handlers=new Map}on(t,r){const n=this.handlers.get(t)??[];return this.handlers.set(t,[...n,r]),()=>this.off(t,r)}off(t,r){const n=this.handlers.get(t);if(!n)return;const o=n.filter(i=>i!==r);o.length===0?this.handlers.delete(t):this.handlers.set(t,o)}clear(){this.handlers.clear()}async emit(t){for(const[r,n]of this.handlers)if(ot(r,t))for(const o of n)await o(t)}}function ot(e,t){const[r,n,o]=e.split(":");return!(r!=="*"&&r!==t.module||n&&n!=="*"&&n!==t.method||o&&o!=="*"&&o!==t.lifecycle)}function Oe(e,t){for(const r of e)if(r.eventMapping)for(const[n,o]of Object.entries(r.eventMapping))t.on(n,o)}async function Ae(e,t,r){let n={...t};for(const o of e)if(o.createContext){await r.emit({module:o.id,method:"createContext",lifecycle:"start",ctx:n});try{const i=await o.createContext(n);n={...n,...i},await r.emit({module:o.id,method:"createContext",lifecycle:"complete",ctx:n})}catch(i){throw await r.emit({module:o.id,method:"createContext",lifecycle:"error",ctx:n,error:i}),i}}return n}function X(e,t){const r=new Set,n=[e];for(;n.length>0;){const o=n.pop();if(!o||r.has(o))continue;r.add(o);const i=o.$ref;if(typeof i=="string"){if(t){const l=t[i];if(!l){const d=Object.keys(t).join(", ")||"(none)";throw new Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${d}`)}n.push(l)}continue}const s=o.oneOf;if(Array.isArray(s))for(const l of s)typeof l=="object"&&l!==null&&n.push(l);const a=o.properties;if(a)for(const l of Object.values(a))n.push(l);const f=o.items;if(Array.isArray(f))for(const l of f)typeof l=="object"&&l!==null&&n.push(l);else typeof f=="object"&&f!==null&&n.push(f);const c=o.additionalProperties;typeof c=="object"&&c!==null&&n.push(c);const u=o.propertyNames;typeof u=="object"&&u!==null&&n.push(u)}}const Q=new Set(["string","number","boolean","integer"]);function it(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:r}=t;return typeof r=="string"?Q.has(r):Array.isArray(r)?r.every(n=>Q.has(n)||n==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(n=>["string","number","boolean"].includes(typeof n)):!1}function st(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(it)}function at(e){const t={},r=n=>{for(const o of["definitions","$defs"]){const i=n[o];if(i)for(const[s,a]of Object.entries(i)){const f=s.startsWith("#/")?s:`#/${o}/${s}`;t[f]=a}}};for(const n of Object.values(e.schemas))r(n.input),r(n.output);if(Object.keys(t).length!==0)for(const[n,o]of Object.entries(e.schemas))try{X(o.input,t),X(o.output,t)}catch(i){throw new Error(`[apigen-core-client] Schema validation failed for function "${n}": ${i.message}`)}}function ct(e,t){const r=['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&&r.push(`Field(s) ${e.map(n=>`"${n}"`).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.`),r.join(" ")}function ut(e,t,r){at(e);const n={};for(const[o,i]of Object.entries(e.schemas)){const s=(r==null?void 0:r[o])??{},a=i.input.properties??{},f=i.input.required??[],c={},u=[],l={};for(const h of t)if(h.envelope&&s[h.id]!==!1)for(const[b,Re]of Object.entries(h.envelope))c[b]=Re,l[b]=h.id,u.includes(b)||u.push(b);const d={type:"object",properties:a,additionalProperties:!1,...f.length>0?{required:f}:{}},m=i.safe===!0||st(i.input),p=i.input.definitions,y=i.input.$defs;n[o]={input:{type:"object",properties:{...c,data:d},required:[...u,...f.length>0?["data"]:[]],additionalProperties:!1,description:ct(Object.keys(c),Object.keys(a).length>0),...p?{definitions:p}:{},...y?{$defs:y}:{}},output:i.output,...i.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":m,...Object.keys(l).length>0?{"x-apigen-envelope":l}:{}}}return n}const ft={"decimal.js":"Decimal"};function lt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(ft).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${lt(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));class D extends Error{constructor(t){super(t),this.name="ConfigurationError"}}function Ne(e){for(const t of e)for(const r of Object.keys(t.eventMapping??{})){const[n]=r.split(":");if(n!=="*"&&n===t.id)throw new D(`Middleware "${t.id}" subscribes to its own events via "${r}". This would cause infinite recursion.`)}}function pt(e){const{domainSchemas:t,middlewares:r,overrides:n={},strict:o=!1}=e;Ne(r);for(const c of Object.keys(n))if(!(c in t.schemas)){const u=`Override key "${c}" not found in domain schemas.`;if(o)throw new D(u);console.warn("[apigen-runtime]",u)}const i=new Set(r.map(c=>c.id));for(const[c,u]of Object.entries(n))for(const l of Object.keys(u??{}))if(!i.has(l)){const d=`Override key "${c}.${l}" does not match any declared middleware id.`;if(o)throw new D(d);console.warn("[apigen-runtime]",d)}const s=ut(t,r,n),a=new $e;return Oe(r,a),{schemas:s,createClient:async c=>Ae(r,c,a),dispose:()=>a.clear()}}function dt(e={}){const t=e.level??"info",r=typeof e.destination=="string"&&e.destination.length>0,n=!r&&!!process.stderr.isTTY,o=e.format??(n?"pretty":"json"),i={level:t};if(o==="pretty")return i.transport={target:"pino-pretty",options:{colorize:!r,translateTime:"SYS:HH:MM:ss.l",ignore:"pid,hostname",...r?{destination:e.destination,mkdir:!0}:{destination:2}}},N(i);const s=r?N.destination({dest:e.destination,mkdir:!0,sync:!0}):N.destination(2);return N(i,s)}function je(e){return e?e.type==="array"?`${je(e.items)}[]`:e.enum?"enum":e.$ref?String(e.$ref).split("/").pop()||"object":e.anyOf||e.oneOf?"union":e.type??"object":"unknown"}function Ee(e){var a;const r=(a=((e==null?void 0:e.input)??{}).properties)==null?void 0:a.data,n=(r==null?void 0:r.properties)??{},o=new Set((r==null?void 0:r.required)??[]),i=Object.entries(n).map(([f,c])=>({name:f,type:je(c),required:o.has(f)})),s=i.map(f=>`${f.name}${f.required?"":"?"}: ${f.type}`).join(", ");return{params:i,text:s}}function yt(e){let t;return Array.isArray(e)?t=e:e?t=[e]:t=[],t.find(r=>r==="number"||r==="integer"||r==="boolean")}function mt(e,t){var i,s;const n=((s=(i=((t==null?void 0:t.input)??{}).properties)==null?void 0:i.data)==null?void 0:s.properties)??{},o={...e};for(const[a,f]of Object.entries(n)){const c=o[a];if(typeof c!="string")continue;const u=yt(f==null?void 0:f.type);if(u==="number"||u==="integer"){const l=Number(c);!Number.isNaN(l)&&c.trim()!==""&&(o[a]=l)}else u==="boolean"&&(c==="true"?o[a]=!0:c==="false"&&(o[a]=!1))}return o}const ee=new Set(["default","module.exports","__esModule"]);function ht(e){const t={},r=(n,o)=>{for(const[i,s]of Object.entries(n))if(typeof s=="function"){!ee.has(i)&&!(i in t)&&(t[i]=s);const a=s.name;a&&!(a in t)&&(t[a]=s)}else s&&typeof s=="object"&&o<2&&ee.has(i)&&r(s,o+1)};return r(e,0),t}const gt=["invalid_argument","unauthenticated","permission_denied","not_found","internal"];class E extends Error{constructor(t,r,n){super(r),this.name="ApiError",this.code=t,this.details=n,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 _e(e){return typeof e=="object"&&e!==null&&e.name==="ApiError"&&gt.includes(e.code)&&typeof e.toJSON=="function"}function te(e,t,r=0){return e==="before-first-chunk"?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:r}}const A=new Be({allErrors:!0});qe(A);for(const e of[R,B,x,T,"discriminator"])A.addKeyword({keyword:e,valid:!0});A.addFormat("decimal",/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function wt(e){return e.map(t=>`${t.instancePath||"(root)"} ${t.message??"failed schema check"}`).join("; ")}function Ce(e,t){const r=de(t),n=[`Validation failed: ${wt(e)}`];return r&&n.push(r),n.join(" โ€” ")}const bt=async(e,t)=>{const r=e.ctx.get(ke);if(r===void 0)return t();const n=e.operation.id,o=r[n];if(o===void 0)return t();const i={data:e.domainArgs,...e.envelope},s=A.compile(o.input);if(!s(i)){const f=s.errors??[];throw new E("invalid_argument",Ce(f,o.input),f)}return t()},ke=Symbol("ValidateSchemasToken");function Se(e){return async function(r,n){const o=r.operation.id,i=e[o];if(i===void 0)return n();const s={data:r.domainArgs,...r.envelope},a=A.compile(i.input);if(!a(s)){const c=a.errors??[];throw new E("invalid_argument",Ce(c,i.input),c)}return n()}}function vt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}class $t{constructor(t={}){var n,o;this._store=new Map,this._sweeper=null,this._defaultTtlMs=t.defaultTtlMs;let r=null;t.sweepIntervalMs===0?r=null:t.sweepIntervalMs!==void 0?r=t.sweepIntervalMs:this._defaultTtlMs!==void 0?r=Math.max(1e3,Math.floor(this._defaultTtlMs/4)):r=null,r!==null&&r>0&&(this._sweeper=setInterval(()=>this._sweep(),r),(o=(n=this._sweeper).unref)==null||o.call(n))}create(t,r=[],n){const o=new t(...r),i=vt(),s=n??this._defaultTtlMs,a=s!==void 0?Date.now()+s:null;return this._store.set(i,{instance:o,expiresAt:a}),{instanceId:i}}get(t){const r=this._store.get(t);if(!r)throw new Error(`[instance-registry] Unknown instanceId: "${t}"`);if(r.expiresAt!==null&&Date.now()>r.expiresAt)throw this._evict(t,r),new Error(`[instance-registry] Instance "${t}" has expired`);return r.instance}async dispatch(t,r,n=[]){const o=this.get(t),i=o[r];if(typeof i!="function")throw new Error(`[instance-registry] Method "${r}" not found on instance "${t}"`);return i.call(o,...n)}async dispose(t){const r=this._store.get(t);r&&(this._store.delete(t),await k(r.instance))}async disposeAll(){this._sweeper!==null&&(clearInterval(this._sweeper),this._sweeper=null);const t=[...this._store.entries()];this._store.clear(),await Promise.all(t.map(([,r])=>k(r.instance)))}get size(){return this._store.size}_sweep(){const t=Date.now();for(const[r,n]of this._store)n.expiresAt!==null&&t>n.expiresAt&&this._evict(r,n)}_evict(t,r){this._store.delete(t),k(r.instance)}}async function k(e){if(e!==null&&typeof e=="object"&&"dispose"in e){const t=e.dispose;typeof t=="function"&&await t.call(e)}}function Ot(e){const{produce:t,signal:r}=e,n=r??new AbortController().signal;return{[Symbol.asyncIterator](){const o=t(n);return{async next(){return n.aborted?(await o.return(void 0),{done:!0,value:void 0}):o.next()},async return(i){return await o.return(i),{done:!0,value:void 0}},async throw(i){return await o.throw(i),{done:!0,value:void 0}}}}}}async function At(e){const t=[];for await(const r of e)t.push(r);return t}async function Ie(e){const t=[];try{for await(const r of e)t.push(r);return{ok:!0,chunks:t}}catch(r){const n=_e(r)?r:new E("internal",r instanceof Error?r.message:String(r));return t.length===0?{ok:!1,carrier:te("before-first-chunk",n)}:{ok:!1,carrier:te("after-first-chunk",n,t.length)}}}function xe(e){return e!==null&&typeof e=="object"&&Symbol.asyncIterator in e}class g extends Error{constructor(t,r){super(r),this.name="UnionCodecError",this.code=t}}function S(e){const t=e.discriminator;if(t===null||typeof t!="object"||Array.isArray(t))return;const r=t;if(typeof r.propertyName!="string")return;const n=r.mapping;if(!(n===null||typeof n!="object"||Array.isArray(n)))return{propertyName:r.propertyName,mapping:n}}function Te(e,t){const r=e[B];if(typeof r=="string"){const n=t.registry.get(r);if(n)return n}return t.registry.resolve(e)}function Nt(e,t,r){const n=Te(t,r);return n?n.encode(e,t,r):e}function jt(e,t,r){const n=Te(t,r);return n?n.decode(e,t,r):e}function Me(e){const{id:t,schema:r}=e;return{id:t,kind:"union",schema:r,matches(n){if(n[R]==="union")return!0;const o=n.oneOf;return!Array.isArray(o)||o.length===0?!1:S(n)!==void 0},encode(n,o,i){const s=S(o);if(!s)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:a,mapping:f}=s,c=n[a];if(c==null)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] value at "${i.path}" is missing the discriminator property "${a}".`);const u=String(c),l=f[u];if(!l)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${u}" at "${i.path}" is not in the mapping (known: ${Object.keys(f).join(", ")}).`);const d=i.resolve(l);return Nt(n,d,{...i,path:`${i.path}[${u}]`})},decode(n,o,i){if(n===null||typeof n!="object"||Array.isArray(n)){let p;throw n===null?p="null":Array.isArray(n)?p="array":p=typeof n,new g("E_UNION_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${i.path}", got ${p}.`)}const s=n,a=S(o);if(!a)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] schema node at "${i.path}" has no discriminator.propertyName; cannot dispatch union branch.`);const{propertyName:f,mapping:c}=a,u=s[f];if(u==null)throw new g("E_UNION_NO_DISCRIMINATOR",`[${t}] wire object at "${i.path}" is missing the discriminator property "${f}".`);const l=String(u),d=c[l];if(!d)throw new g("E_UNION_UNKNOWN_TAG",`[${t}] discriminator tag "${l}" on the wire at "${i.path}" is not in the mapping (known: ${Object.keys(c).join(", ")}).`);const m=i.resolve(d);return jt(n,m,{...i,path:`${i.path}[${l}]`})}}}const Et="x-apigen-instances";class j extends Error{constructor(t,r){super(r),this.name="NominalCodecError",this.code=t}}function re(e){const t=e.properties;return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function _t(e){const t=e.required;return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}function ne(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.encode(e,t,r)}return e}function Ct(e,t,r){if(t){const n=r.registry.resolve(t);if(n)return n.decode(e,t,r)}return e}function kt(e){const{id:t,schema:r,ctor:n}=e;return{id:t,kind:"nominal",schema:r,matches(o){return o[R]==="nominal"?!0:o[B]===t},encode(o,i,s){if(o===null||typeof o!="object")return o;if(s.seen.has(o)){if(s.mode==="strict")throw new j("E_NOMINAL_CYCLE",`[${t}] cycle detected at "${s.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN ยง8.3); break the cycle or use 'lossy' mode.`);return null}s.seen.add(o);try{const a=re(i),f=typeof i[T]=="string"?i[T]:"toJSON",c=o[f];if(typeof c=="function"){const p=c.call(o);if(p!==null&&typeof p=="object"&&!Array.isArray(p)){const y={};for(const[h,b]of Object.entries(p))y[h]=ne(b,a[h],{...s,path:`${s.path}/${h}`});return y}return p}const u={},l=Object.keys(a),d=o,m=l.length>0?l:Object.keys(d);for(const p of m){const y=d[p];y!==void 0&&(u[p]=ne(y,a[p],{...s,path:`${s.path}/${p}`}))}return u}finally{s.seen.delete(o)}},decode(o,i,s){if(o===null||typeof o!="object"||Array.isArray(o)){let u;throw o===null?u="null":Array.isArray(o)?u="array":u=typeof o,new j("E_NOMINAL_INVALID_WIRE",`[${t}] expected a JSON object on the wire at "${s.path}", got ${u}.`)}const a=o;for(const u of _t(i))if(!(u in a))throw new j("E_NOMINAL_INVALID_WIRE",`[${t}] required field "${u}" missing on the wire at "${s.path}".`);if(i[Et]===!1)throw new j("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 f=re(i),c={};for(const[u,l]of Object.entries(a))c[u]=Ct(l,f[u],{...s,path:`${s.path}/${u}`});if(n){const u=typeof i[x]=="string"?i[x]:"fromJSON",l=n[u];if(typeof l=="function")return l.call(n,c);const d=n;return new d(c)}return c}}}const Pe=[q,F,H,K,W,z],St={type:"object","x-apigen-logical":"nominal","x-apigen-codec":"ts.NominalSentinel"},oe=kt({id:"ts.NominalSentinel",schema:St}),It={oneOf:[],discriminator:{propertyName:"kind",mapping:{}},"x-apigen-logical":"union","x-apigen-codec":"ts.UnionSentinel"},ie=Me({id:"ts.UnionSentinel",schema:It});function xt(){const e=[...Pe.map(t=>[t.id,t]),[oe.id,oe],[ie.id,ie]];return Object.freeze(new Map(e))}const Tt=Object.freeze({host:"ts",logicalTypeVersion:He,codecs:xt()});function Mt(e,t,r){var s;const n=typeof((s=t==null?void 0:t.input)==null?void 0:s.description)=="string"?t.input.description:void 0,o=de(t==null?void 0:t.input),i=[r,n,o].filter(a=>typeof a=="string"&&a.length>0);return i.length>0?i.join(" โ€” "):e}function Pt(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 Ut(e,t){return e?{result:t}:t&&typeof t=="object"&&!Array.isArray(t)?t:void 0}const Ue=4,De=32;function L(e){return _e(e)?e:e instanceof Error?new E("internal",e.message):e}function Dt(e,t){if(e==="serial"||e==="chained")return 1;const r=t??Ue;return!Number.isFinite(r)||r<1?1:Math.min(Math.floor(r),De)}function Lt(){}function Rt(e,t){var i;if(!e&&!t)return{signal:void 0,dispose:Lt};const r=new AbortController,n=()=>{r.abort(e==null?void 0:e.reason)};e&&(e.aborted?r.abort(e.reason):e.addEventListener("abort",n,{once:!0}));let o;return t!==void 0&&!r.signal.aborted&&(o=setTimeout(()=>{r.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,"TimeoutError"))},t),(i=o.unref)==null||i.call(o)),{signal:r.signal,dispose(){e&&e.removeEventListener("abort",n),o&&clearTimeout(o)}}}async function se(e,t,r,n,o,i){const s=Rt(n.signal,i);try{const a=s.signal?{...n,signal:s.signal}:n,f=await e(t,a,o);if(xe(f)){const c=await Ie(f);if(c.ok)return{index:r,status:"fulfilled",chunks:c.chunks};const u=c.carrier;return{index:r,status:"rejected",reason:L(u.error),...u.phase==="after-first-chunk"?{chunksDelivered:u.chunksDelivered}:{}}}return{index:r,status:"fulfilled",value:f}}catch(a){return{index:r,status:"rejected",reason:L(a)}}finally{s.dispose()}}async function Bt(e,t,r,n,o={}){const i=o.mode??"parallel",s=o.onItemError??"continue",a=Dt(i,o.concurrency),f=new Array(r.length),c=p=>({index:p,status:"rejected",reason:L(new Error("apigen/invokeBatch: not attempted โ€” an earlier item failed and "+(i==="chained"?'mode is "chained"':'onItemError is "abort"')))});if(i==="serial"||i==="chained"){let p=!1;for(let y=0;y<r.length;y++){if(p){f[y]=c(y);continue}const h=await se(e,t,y,r[y],n,o.itemTimeoutMs);f[y]=h,h.status==="rejected"&&(i==="chained"||s==="abort")&&(p=!0)}return f}let u=0,l=!1;const d=Math.max(1,Math.min(a,r.length)),m=Array.from({length:d},async()=>{for(;;){const p=u++;if(p>=r.length)return;if(l){f[p]=c(p);continue}const y=await se(e,t,p,r[p],n,o.itemTimeoutMs);f[p]=y,y.status==="rejected"&&s==="abort"&&(l=!0)}});return await Promise.all(m),f}const ae=new Set(["string","number","boolean","integer"]);function qt(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:r}=t;return typeof r=="string"?ae.has(r):Array.isArray(r)?r.every(n=>ae.has(n)||n==="null"):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(n=>["string","number","boolean"].includes(typeof n)):!1}function Ft(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(qt)}const Ht={"decimal.js":"Decimal"};function Kt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}Object.entries(Ht).map(([e,t])=>({pattern:new RegExp(`import\\(["'][^"']*${Kt(e)}[^"']*["']\\)\\.\\w+`,"g"),key:t}));function ce(e){return e.words.join("-")}function ue(e){return e.words.map(Yt).join("")}function fe(e){return e.words.join("_")}function Wt(e,t={}){var r,n;const o=[e.namespace,...e.path],i=e.safe||Ft(e.input)?"GET":"POST",s=((n=(r=t.http)==null?void 0:r.verb)==null?void 0:n[e.id])??i,a="/"+o.map(m=>ce(m)).join("/"),f=o.map(m=>fe(m)).join("_"),c=o.map(m=>fe(m)).slice(0,-1).join("."),u=ue(o[o.length-2]??o[0]),l=ue(o[o.length-1]),d=o.map(m=>ce(m));return{http:{verb:s,route:a},mcp:{name:f},grpc:{package:c,service:u,method:l},cli:{path:d}}}function zt(e,t){return`x-${e}-${t}`}function Vt(e,t){return`--${e}-${t}`}function Jt(e,t){const r=n=>n.toUpperCase().replace(/-/g,"_");return e==="adhd"?`APIGEN_${r(t)}`:`APIGEN_${r(e)}_${r(t)}`}function Yt(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function V(e){return e.anyOf??e.oneOf}function Gt(e){if(!e)return!1;if(e.type==="array"||e.type==="object")return!0;const t=V(e);if(t){const r=t.filter(n=>n.type!=="null");return r.length>0&&r.every(n=>n.type==="array"||n.type==="object")}return!1}function Zt(e){if(!e)return!1;if(e.type==="boolean")return!0;const t=V(e);if(t){const r=t.filter(n=>n.type!=="null");return r.length>0&&r.every(n=>n.type==="boolean")}return!1}function Xt(e){if(!e)return!1;if(e.type==="number"||e.type==="integer")return!0;const t=V(e);if(t){const r=t.filter(n=>n.type!=="null");return r.length>0&&r.every(n=>n.type==="number"||n.type==="integer")}return!1}function Qt(e){return e.replace(/[A-Z]/g,t=>"-"+t.toLowerCase())}function er(e){var o,i;const t=(i=(o=e.input)==null?void 0:o.properties)==null?void 0:i.data,r=(t==null?void 0:t.properties)??{},n=(t==null?void 0:t.required)??[];return{props:r,required:n}}function le(e){return typeof e.handler=="function"}function tr(e){var o;const t=((o=e.input)==null?void 0:o.properties)??{},r=e["x-apigen-envelope"],n=[];for(const i of Object.keys(t)){if(i==="data")continue;const s=(r==null?void 0:r[i])??"adhd",a=zt(s,i);n.push({field:i,pluginId:s,httpHeader:a,mcpMetaKey:a,cliFlag:Vt(s,i),envVar:Jt(s,i)})}return n}function rr(e,t){const r=new Map,{props:n}=er(e);for(const[o,i]of Object.entries(n)){let s="string";Zt(i)?s="boolean":(Gt(i)||Xt(i))&&(s="json"),r.set(Qt(o),{camelKey:o,kind:"domain",valueKind:s})}for(const o of t){const i=o.cliFlag.replace(/^--/,"");r.set(i,{camelKey:o.field,kind:"envelope",valueKind:"string",envVar:o.envVar})}return r}function nr(e){const{op:t,schema:r,transport:n,projection:o}=e,i=Wt(t,o),s=r?tr(r):[],a=r?rr(r,s):new Map,f=r?Ee(r).params:void 0,c={op:t,transport:n,http:i.http,mcp:i.mcp,cli:i.cli,grpc:i.grpc,params:f,envelope:s,cliFlags:a,streaming:t.streaming,isMount:le(t)};if(le(t)){const u=t.handler;c.mountHandler=async l=>u(l)}return c}function or(e){const t=e.usePlugins;return Array.isArray(t)?t:[]}function ir(e){const t=e.useOptions;return t&&typeof t=="object"?t:{}}function Le(e){return async function(r,n){const o=Object.assign(r,{data:r.domainArgs});return await e.layer(o,n)}}function sr(e,t){var n;const r=[];for(const o of t){const i=(n=o.capabilities)==null?void 0:n.layer;i&&r.push(Le(i))}return r.push(Se(e)),ve(r)}function ar(){const e=new Map;return{get:t=>e.get(t),set:(t,r)=>{e.set(t,r)}}}const cr={input:{type:"object",properties:{data:{type:"object",properties:{}}}},output:{}};async function ur(e,t,r,n){const o={...r,operation:{id:e.op.id},ctx:new be};if(e.isMount){const i=e.mountHandler;if(!i)throw new Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);const s={operation:e.op,data:r.domainArgs,envelope:r.envelope,ctx:ar(),transport:e.transport,signal:r.signal??new AbortController().signal},a={...n,fns:{[e.op.id]:()=>i(s)},schemas:{[e.op.id]:cr}};return t(e.op.id,o,a)}return t(e.op.id,o,n)}exports.BATCH_DEFAULT_CONCURRENCY=Ue;exports.BATCH_MAX_CONCURRENCY=De;exports.EventBus=$e;exports.InstanceRegistry=$t;exports.LayerContext=be;exports.UnionCodecError=g;exports.ValidateSchemasToken=ke;exports.WELL_KNOWN_TS_CODECS=Pe;exports.adaptCoreLayer=Le;exports.assertNoSelfSubscription=Ne;exports.buildContext=Ae;exports.buildFnTable=ht;exports.buildMcpOutputSchema=Pt;exports.buildOpPlan=nr;exports.buildToolDescription=Mt;exports.coerceQueryParams=mt;exports.collectWithPhase=Ie;exports.createApiPackage=pt;exports.createInvoker=ve;exports.createLogger=dt;exports.createPackageInvoker=sr;exports.createStream=Ot;exports.createUnionCodec=Me;exports.dataParamNames=ge;exports.defineMiddleware=nt;exports.describeParams=Ee;exports.dispatch=we;exports.dispatchForPlan=ur;exports.drainStream=At;exports.invokeBatch=Bt;exports.isApiStream=xe;exports.makeValidateLayer=Se;exports.needsEnvelopeField=he;exports.readUseOptions=ir;exports.readUsePlugins=or;exports.tsHostBinding=Tt;exports.validateLayer=bt;exports.wireObservers=Oe;exports.wrapMcpStructuredContent=Ut;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));require("node:fs");let c=require("node:module");require("node:path");let l=require("pino");l=s(l);let u=require("ajv");u=s(u);let d=require("ajv-formats");d=s(d);var f=`$apigen`,p=class extends Error{constructor(e){super(e),this.code=`E_DUP_CODEC`,this.name=`CodecRegistryError`}};function m(e){e?.wellKnown;let t=new Map;return{register(e,n){if(t.has(e.id)&&!n?.override)throw new p(`E_DUP_CODEC: a codec is already registered for id "${e.id}"`);t.set(e.id,e)},resolve(e){for(let n of t.values())if(n.matches(e))return n},get(e){return t.get(e)},ids(){return[...t.keys()]},freeze(){let e=new Map(t),n={register(){throw new p(`E_DUP_CODEC: registry is frozen and cannot accept new codecs`)},resolve(t){for(let n of e.values())if(n.matches(t))return n},get(t){return e.get(t)},ids(){return[...e.keys()]},freeze(){return n}};return n}}}var ee=`x-apigen-logical`,h=`x-apigen-codec`,g=`x-apigen-ctor`,te=`x-apigen-tojson`,ne=`0.1.0`;function re(e,t){return{registry:e,resolve:e=>{throw Error(`[apigen-logical] $ref "${e}" 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 _(e,t,n){let r=n.registry.resolve(t);if(r)return r.encode(e,t,n);let i=t.$ref;if(typeof i==`string`)return _(e,n.resolve(i),n);let a=t.oneOf;if(Array.isArray(a))return _(e,ie(e,a,t,n),n);let o=t.type;if(o===`array`){if(!Array.isArray(e))return x(e,t,n);let r=t.items;if(!r)return e.map(e=>C(e));let i=n.path;return Array.isArray(r)?e.map((e,t)=>{let a=r[t];return a===void 0?C(e):_(e,a,{...n,path:`${i}/${t}`})}):e.map((e,t)=>_(e,r,{...n,path:`${i}/${t}`}))}if(o===`object`){if(typeof e!=`object`||!e||Array.isArray(e))return x(e,t,n);let r=t.properties;if(!r)return C(e);let i=n.path,a={};for(let[t,o]of Object.entries(r)){let r=e[t];r!==void 0&&(a[t]=_(r,o,{...n,path:`${i}/${t}`}))}return a}return o==null?x(e,t,n):C(e)}function v(e,t,n){let r=n.registry.resolve(t);if(r)return r.decode(e,t,n);let i=t.$ref;if(typeof i==`string`)return v(e,n.resolve(i),n);let a=t.oneOf;if(Array.isArray(a))return v(e,ie(e,a,t,n),n);let o=t.type;if(o===`array`){if(!Array.isArray(e))return e;let r=t.items;if(!r)return e;let i=n.path;return Array.isArray(r)?e.map((e,t)=>{let a=r[t];return a===void 0?e:v(e,a,{...n,path:`${i}/${t}`})}):e.map((e,t)=>v(e,r,{...n,path:`${i}/${t}`}))}if(o===`object`){if(typeof e!=`object`||!e||Array.isArray(e))return e;let r=t.properties;if(!r)return e;let i=n.path,a={};for(let[t,o]of Object.entries(r)){let r=e[t];r!==void 0&&(a[t]=v(r,o,{...n,path:`${i}/${t}`}))}for(let[t,n]of Object.entries(e))!(t in r)&&n!==void 0&&(a[t]=n);return a}return o==null?S(e,n):e}function ie(e,t,n,r){let i=n.discriminator;if(i?.propertyName){let n=i.propertyName,a=typeof e==`object`&&e?e[n]:void 0;if(typeof a==`string`){if(i.mapping){let e=i.mapping[a];if(e){let n=t.find(t=>t.$ref===e);if(n)return n}}for(let e of t){let t=y(e,r).properties?.[n];if(!t)continue;let i=t.enum;if(t.const===a||Array.isArray(i)&&i.includes(a))return e}}}let a=oe(e,t,r);if(a)return a;let o,s=-1;for(let n of t){let t=b(e,y(n,r),r);t!==null&&t>s&&(s=t,o=n)}return o===void 0?t[0]??{}:o}function y(e,t){let n=e.$ref;return typeof n==`string`?t.resolve(n):e}function ae(e){if(`const`in e)return e.const;let t=e.enum;if(Array.isArray(t)&&t.length===1)return t[0]}function oe(e,t,n){if(typeof e!=`object`||!e||Array.isArray(e))return;let r=e,i=t.map(e=>y(e,n)),a=new Set;for(let e of i){let t=e.properties;if(t)for(let[e,n]of Object.entries(t))ae(n)!==void 0&&a.add(e)}for(let o of a){let a=i.map(e=>{let t=e.properties?.[o];return t?ae(t):void 0}),s=a.filter(e=>e!==void 0),c=new Set(s);if(s.length<2||c.size!==s.length)continue;let l=r[o];if(l===void 0)continue;let u=a.findIndex(e=>e===l);if(u!==-1&&b(e,i[u],n)!==null)return t[u]}}function se(e){if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=typeof e;return t===`number`?Number.isInteger(e)?`integer`:`number`:t}function b(e,t,n){let r=t.oneOf;if(Array.isArray(r)){let t=null;for(let i of r){let r=b(e,y(i,n),n);r!==null&&(t===null||r>t)&&(t=r)}return t}let i=t.type,a=se(e);if(typeof i==`string`){if(!(i===a||i===`number`&&a===`integer`))return null}else if(Array.isArray(i)&&!i.some(e=>e===a||e===`number`&&a===`integer`))return null;if(typeof e!=`object`||!e||Array.isArray(e))return+(typeof i==`string`);let o=e,s=t.required,c=0;if(Array.isArray(s)){for(let e of s)if(typeof e==`string`){if(o[e]===void 0)return null;c+=2}}let l=t.properties;if(l){for(let e of Object.keys(l))o[e]!==void 0&&(c+=1);for(let e of Object.keys(o))l[e]===void 0&&--c}return c}function x(e,t,n){for(let t of n.registry.ids()){let r=n.registry.get(t);if(r?.ownsValue?.(e))return{[f]:t,v:r.encode(e,r.schema,n)}}if(Array.isArray(e))return e.map(e=>x(e,{},n));if(ce(e)){let t={};for(let[r,i]of Object.entries(e))i!==void 0&&(t[r]=x(i,{},n));return t}return C(e)}function ce(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function S(e,t){if(typeof e==`object`&&e&&!Array.isArray(e)&&`$apigen`in e){let n=e,r=n[f],i=t.registry.get(r);if(i)return i.decode(n.v,i.schema,t)}if(Array.isArray(e))return e.map(e=>S(e,t));if(ce(e)){let n={};for(let[r,i]of Object.entries(e))n[r]=S(i,t);return n}return e}function C(e){if(e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))return e.map(C);if(typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))r!==void 0&&(t[n]=C(r));return t}return null}function w(e,t){let n=new Set,r=[e];for(;r.length>0;){let e=r.pop();if(!e||n.has(e))continue;n.add(e);let i=e.$ref;if(typeof i==`string`){if(t){let e=t[i];if(!e){let e=Object.keys(t).join(`, `)||`(none)`;throw Error(`[apigen-logical] $ref "${i}" cannot be resolved. Available $defs: ${e}`)}r.push(e)}continue}let a=e.oneOf;if(Array.isArray(a))for(let e of a)typeof e==`object`&&e&&r.push(e);let o=e.properties;if(o)for(let e of Object.values(o))r.push(e);let s=e.items;if(Array.isArray(s))for(let e of s)typeof e==`object`&&e&&r.push(e);else typeof s==`object`&&s&&r.push(s);let c=e.additionalProperties;typeof c==`object`&&c&&r.push(c);let l=e.propertyNames;typeof l==`object`&&l&&r.push(l)}}function le(e){return{encode(t,n,r){return _(t,n,re(e,r))},decode(t,n,r){return v(t,n,re(e,r))}}}var T={id:`date-time`,kind:`scalar`,schema:{type:`string`,format:`date-time`},matches(e){return e.type===`string`&&e.format===`date-time`},ownsValue(e){return e instanceof Date},encode(e,t,n){return e.toISOString()},decode(e,t,n){if(typeof e!=`string`){if(n.mode===`strict`)throw 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 TypeError(`[date-time] invalid date-time string at "${n.path}": ${JSON.stringify(e)}`);return new Date(e)}},E={id:`int64`,kind:`scalar`,schema:{type:`string`,format:`int64`},matches(e){return e.type===`string`&&e.format===`int64`},ownsValue(e){return typeof e==`bigint`},encode(e,t,n){return String(e)},decode(e,t,n){if(typeof e!=`string`){if(n.mode===`strict`)throw 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)}};function ue(e){return e}var D={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 TypeError(`[decimal] expected a string on the wire at "${n.path}", got ${typeof e}`);return ue(String(e))}if(n.mode===`strict`&&!/^-?\d+(\.\d+)?$/.test(e))throw TypeError(`[decimal] wire value "${e}" at "${n.path}" is not a valid decimal string`);return ue(e)}},O={id:`byte`,kind:`scalar`,schema:{type:`string`,format:`byte`},matches(e){return e.type===`string`&&e.format===`byte`},ownsValue(e){return e instanceof Uint8Array},encode(e,t,n){return Buffer.from(e).toString(`base64`)},decode(e,t,n){if(typeof e!=`string`){if(n.mode===`strict`)throw TypeError(`[byte] expected a base64 string on the wire at "${n.path}", got ${typeof e}`);return new Uint8Array}if(n.mode===`strict`&&!/^[A-Za-z0-9+/]*={0,2}$/.test(e))throw TypeError(`[byte] wire value at "${n.path}" is not standard base64 (format:byte): "${e}"`);return new Uint8Array(Buffer.from(e,`base64`))}},de=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,k={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 TypeError(`[uuid] expected a string on the wire at "${n.path}", got ${typeof e}`);return String(e).toLowerCase()}if(n.mode===`strict`&&!de.test(e))throw TypeError(`[uuid] wire value "${e}" at "${n.path}" is not a lowercase-hyphenated RFC 4122 UUID`);return e}},A=`NaN`,j=`Infinity`,M=`-Infinity`,fe=new Set([A,j,M]),N={id:`number-special`,kind:`scalar`,schema:{type:`number`},matches(e){return e.type===`number`&&e.format===void 0},ownsValue(e){return typeof e==`number`&&!Number.isFinite(e)},encode(e,t,n){return Number.isNaN(e)?A:e===1/0?j:e===-1/0?M:e},decode(e,t,n){if(typeof e==`number`)return e;if(typeof e==`string`){if(e===A)return NaN;if(e===j)return 1/0;if(e===M)return-1/0;let t=Number(e);if(!Number.isNaN(t))return t}if(n.mode===`strict`)throw TypeError(`[number-special] unrecognized wire value at "${n.path}": ${JSON.stringify(e)}. Expected a number or one of ${[...fe].join(`, `)}.`);return NaN}},pe=[T,E,D,O,k,N];function me(e,t={}){for(let n of pe)e.register(n,{override:t.override??!1})}var he=12;function ge(e,t){let n=/^#\/(definitions|\$defs)\/(.+)$/.exec(e);if(!n)return;let[,r,i]=n;return(r===`$defs`?t.$defs:t.definitions)?.[decodeURIComponent(i)]}function P(e){return Array.isArray(e)&&e.length>0?e[0]:void 0}function _e(e){if(Array.isArray(e.type))return e.type.find(e=>e!==`null`)??e.type[0];if(typeof e.type==`string`)return e.type;if(e.properties)return`object`}function ve(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 F(e,t,n){let r=e.properties??{},i=e.required??[],a={};for(let e of i){let i=r[e];a[e]=i===void 0?`<${e}>`:I(i,t,n+1)}return a}function ye(e,t,n){let r=Array.isArray(e.items)?e.items[0]:e.items;return r?[I(r,t,n+1)]:[]}function I(e,t=e??{},n=0){if(!e||n>he)return null;if(typeof e.$ref==`string`){let r=ge(e.$ref,t);return r===void 0?null:I(r,t,n+1)}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){let r={},i=[];for(let t of e.allOf){Object.assign(r,t.properties??{});for(let e of t.required??[])i.includes(e)||i.push(e)}return F({...e,properties:r,required:i},t,n)}let r=P(e.oneOf)??P(e.anyOf);if(r)return I(r,t,n+1);switch(_e(e)){case`object`:return F(e,t,n);case`array`:return ye(e,t,n);case`string`:return ve(e);case`integer`:case`number`:return 0;case`boolean`:return!1;case`null`:return null;default:return null}}function L(e){if(!e)return;let t=I(e);return`Example: ${JSON.stringify(t)}`}T.id,E.id,D.id,O.id,k.id,N.id,Object.freeze({typescript:{"date-time":{encode:`$.toISOString()`,decode:`new Date($)`,mode:`native`},int64:{encode:`String($)`,decode:`BigInt($)`,mode:`native`},decimal:{encode:`$.toString()`,decode:`new Decimal($)`,imports:[],dep:{name:`decimal.js`,version:`^10`},mode:`branded`},byte:{encode:`Buffer.from($).toString('base64')`,decode:`new Uint8Array(Buffer.from($, 'base64'))`,mode:`native`},uuid:{encode:`$.toLowerCase()`,decode:`$`,mode:`native`},"number-special":{encode:`numToWire($)`,decode:`wireToNum($)`,mode:`native`}},python:{"date-time":{encode:`$.isoformat()`,decode:`datetime.fromisoformat($)`,imports:[`from datetime import datetime`],mode:`native`},int64:{encode:`str($)`,decode:`int($)`,mode:`native`},decimal:{encode:`str($)`,decode:`Decimal($)`,imports:[`from decimal import Decimal`],mode:`native`},byte:{encode:`b64encode($).decode()`,decode:`b64decode($)`,imports:[`from base64 import b64encode, b64decode`],mode:`native`},uuid:{encode:`str($)`,decode:`UUID($)`,imports:[`from uuid import UUID`],mode:`native`},"number-special":{encode:`num_to_wire($)`,decode:`wire_to_num($)`,mode:`native`}},rust:{"date-time":{encode:`__SCAFFOLD_RUST_DATETIME_ENCODE__`,decode:`__SCAFFOLD_RUST_DATETIME_DECODE__`,imports:[`use chrono::{DateTime, Utc};`],dep:{name:`chrono`,version:`^0.4`},mode:`lib`},int64:{encode:`__SCAFFOLD_RUST_INT64_ENCODE__`,decode:`__SCAFFOLD_RUST_INT64_DECODE__`,imports:[`use serde_with::DisplayFromStr;`],dep:{name:`serde_with`,version:`^3`},mode:`lib`},decimal:{encode:`__SCAFFOLD_RUST_DECIMAL_ENCODE__`,decode:`__SCAFFOLD_RUST_DECIMAL_DECODE__`,imports:[`use rust_decimal::Decimal;`],dep:{name:`rust_decimal`,version:`^1`},mode:`lib`},byte:{encode:`__SCAFFOLD_RUST_BYTE_ENCODE__`,decode:`__SCAFFOLD_RUST_BYTE_DECODE__`,imports:[`use serde_with::base64::Base64;`],dep:{name:`serde_with`,version:`^3`},mode:`lib`},uuid:{encode:`__SCAFFOLD_RUST_UUID_ENCODE__`,decode:`__SCAFFOLD_RUST_UUID_DECODE__`,imports:[`use uuid::Uuid;`],dep:{name:`uuid`,version:`^1`},mode:`lib`},"number-special":{encode:`__SCAFFOLD_RUST_NUMSPECIAL_ENCODE__`,decode:`__SCAFFOLD_RUST_NUMSPECIAL_DECODE__`,mode:`native`}},go:{"date-time":{encode:`__SCAFFOLD_GO_DATETIME_ENCODE__`,decode:`__SCAFFOLD_GO_DATETIME_DECODE__`,imports:[`"time"`],mode:`native`},int64:{encode:`__SCAFFOLD_GO_INT64_ENCODE__`,decode:`__SCAFFOLD_GO_INT64_DECODE__`,imports:[`"strconv"`],mode:`native`},decimal:{encode:`__SCAFFOLD_GO_DECIMAL_ENCODE__`,decode:`__SCAFFOLD_GO_DECIMAL_DECODE__`,imports:[`"github.com/shopspring/decimal"`],dep:{name:`github.com/shopspring/decimal`,version:`v1`},mode:`lib`},byte:{encode:`__SCAFFOLD_GO_BYTE_ENCODE__`,decode:`__SCAFFOLD_GO_BYTE_DECODE__`,imports:[`"encoding/base64"`],mode:`native`},uuid:{encode:`__SCAFFOLD_GO_UUID_ENCODE__`,decode:`__SCAFFOLD_GO_UUID_DECODE__`,imports:[`"github.com/google/uuid"`],dep:{name:`github.com/google/uuid`,version:`v1`},mode:`lib`},"number-special":{encode:`__SCAFFOLD_GO_NUMSPECIAL_ENCODE__`,decode:`__SCAFFOLD_GO_NUMSPECIAL_DECODE__`,mode:`native`}},java:{"date-time":{encode:`$.toString()`,decode:`Instant.parse($)`,imports:[`import java.time.Instant;`],dep:{name:`jackson-datatype-jsr310`,version:`2.x`},mode:`lib`},int64:{encode:`@JsonFormat(shape = JsonFormat.Shape.STRING)`,decode:`@JsonFormat(shape = JsonFormat.Shape.STRING)`,imports:[`import com.fasterxml.jackson.annotation.JsonFormat;`],mode:`native`},decimal:{encode:`@JsonSerialize(using = ToStringSerializer.class)`,decode:`new BigDecimal($)`,imports:[`import java.math.BigDecimal;`,`import com.fasterxml.jackson.databind.annotation.JsonSerialize;`,`import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;`],mode:`native`},byte:{encode:`$`,decode:`$`,mode:`native`},uuid:{encode:`$.toString()`,decode:`UUID.fromString($)`,imports:[`import java.util.UUID;`],mode:`native`},"number-special":{encode:`@JsonSerialize(using = NumberSpecialSerializer.class)`,decode:`@JsonDeserialize(using = NumberSpecialDeserializer.class)`,imports:[`import com.fasterxml.jackson.databind.annotation.JsonSerialize;`,`import com.fasterxml.jackson.databind.annotation.JsonDeserialize;`],mode:`native`}}});var R=m();me(R);var z=le(R.freeze());function B(e,t){return t in(e.input?.properties??{})}function V(e){let t=e.input?.properties?.data;return Object.keys(t?.properties??{})}function be(e,t){let n=e.input?.properties?.data?.properties?.[t];return n===void 0?void 0:n}function xe(e,t){return t===void 0||e===void 0?e:z.decode(e,t)}function H(e,t){let n=t.output;return!n||Object.keys(n).length===0?e:z.encode(e,n)}async function Se(e,t,n,r,i,a){let o=V(n).map(e=>xe(a[e],be(n,e)));if(B(n,`session`)&&t){let a=await t({session:i.session});return H(await e[r](a,...o),n)}if(n.hasCtx){let a=t?await t(i):void 0;return H(await e[r](a,...o),n)}return H(await e[r](...o),n)}var Ce=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 we(e=[]){return async function(t,n,r){let i=r.schemas[t];if(!i)throw Error(`apigen/invoke: no schema found for operation "${t}"`);return e.reduceRight((e,t)=>()=>t(n,e),()=>Se(r.fns,r.createClient,i,t,n.envelope,n.domainArgs))()}}function Te(e){return e}var Ee=class{constructor(){this.handlers=new Map}on(e,t){let n=this.handlers.get(e)??[];return this.handlers.set(e,[...n,t]),()=>this.off(e,t)}off(e,t){let n=this.handlers.get(e);if(!n)return;let r=n.filter(e=>e!==t);r.length===0?this.handlers.delete(e):this.handlers.set(e,r)}clear(){this.handlers.clear()}async emit(e){for(let[t,n]of this.handlers)if(De(t,e))for(let t of n)await t(e)}};function De(e,t){let[n,r,i]=e.split(`:`);return!(n!==`*`&&n!==t.module||r&&r!==`*`&&r!==t.method||i&&i!==`*`&&i!==t.lifecycle)}function Oe(e,t){for(let n of e)if(n.eventMapping)for(let[e,r]of Object.entries(n.eventMapping))t.on(e,r)}async function ke(e,t,n){let r={...t};for(let t of e)if(t.createContext){await n.emit({module:t.id,method:`createContext`,lifecycle:`start`,ctx:r});try{let e=await t.createContext(r);r={...r,...e},await n.emit({module:t.id,method:`createContext`,lifecycle:`complete`,ctx:r})}catch(e){throw await n.emit({module:t.id,method:`createContext`,lifecycle:`error`,ctx:r,error:e}),e}}return r}(0,c.createRequire)(require("node:url").pathToFileURL(__filename).href);var Ae=new Set([`string`,`number`,`boolean`,`integer`]);function je(e){if(typeof e!=`object`||!e)return!1;let t=e;if(t.$ref!==void 0||t.oneOf||t.anyOf||t.allOf)return!1;let{type:n}=t;return typeof n==`string`?Ae.has(n):Array.isArray(n)?n.every(e=>Ae.has(e)||e===`null`):Array.isArray(t.enum)&&t.enum.length>0?t.enum.every(e=>[`string`,`number`,`boolean`].includes(typeof e)):!1}function Me(e){if(!e||typeof e!=`object`)return!1;let t=e.properties;return t===void 0||typeof t!=`object`||!t?!1:Object.values(t).every(je)}function Ne(e){let t={},n=e=>{for(let n of[`definitions`,`$defs`]){let r=e[n];if(r)for(let[e,i]of Object.entries(r)){let r=e.startsWith(`#/`)?e:`#/${n}/${e}`;t[r]=i}}};for(let t of Object.values(e.schemas))n(t.input),n(t.output);if(Object.keys(t).length!==0)for(let[n,r]of Object.entries(e.schemas))try{w(r.input,t),w(r.output,t)}catch(e){throw Error(`[apigen-core-client] Schema validation failed for function "${n}": ${e.message}`)}}function Pe(e,t){let 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(e=>`"${e}"`).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 Fe(e,t,n){Ne(e);let r={};for(let[i,a]of Object.entries(e.schemas)){let e=n?.[i]??{},o=a.input.properties??{},s=a.input.required??[],c={},l=[],u={};for(let n of t)if(n.envelope&&e[n.id]!==!1)for(let[e,t]of Object.entries(n.envelope))c[e]=t,u[e]=n.id,l.includes(e)||l.push(e);let d={type:`object`,properties:o,additionalProperties:!1,...s.length>0?{required:s}:{}},f=a.safe===!0||Me(a.input),p=a.input.definitions,m=a.input.$defs;r[i]={input:{type:`object`,properties:{...c,data:d},required:[...l,...s.length>0?[`data`]:[]],additionalProperties:!1,description:Pe(Object.keys(c),Object.keys(o).length>0),...p?{definitions:p}:{},...m?{$defs:m}:{}},output:a.output,...a.hasCtx?{hasCtx:!0}:{},"x-apigen-safe":f,...Object.keys(u).length>0?{"x-apigen-envelope":u}:{}}}return r}var Ie={"decimal.js":`Decimal`};function Le(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}Object.entries(Ie).map(([e,t])=>({pattern:RegExp(`import\\(["'][^"']*${Le(e)}[^"']*["']\\)\\.\\w+`,`g`),key:t}));var U=class extends Error{constructor(e){super(e),this.name=`ConfigurationError`}};function Re(e){for(let t of e)for(let e of Object.keys(t.eventMapping??{})){let[n]=e.split(`:`);if(n!==`*`&&n===t.id)throw new U(`Middleware "${t.id}" subscribes to its own events via "${e}". This would cause infinite recursion.`)}}function ze(e){let{domainSchemas:t,middlewares:n,overrides:r={},strict:i=!1}=e;Re(n);for(let e of Object.keys(r))if(!(e in t.schemas)){let t=`Override key "${e}" not found in domain schemas.`;if(i)throw new U(t);console.warn(`[apigen-runtime]`,t)}let a=new Set(n.map(e=>e.id));for(let[e,t]of Object.entries(r))for(let n of Object.keys(t??{}))if(!a.has(n)){let t=`Override key "${e}.${n}" does not match any declared middleware id.`;if(i)throw new U(t);console.warn(`[apigen-runtime]`,t)}let o=Fe(t,n,r),s=new Ee;return Oe(n,s),{schemas:o,createClient:async e=>ke(n,e,s),dispose:()=>s.clear()}}function Be(e={}){let t=e.level??`info`,n=typeof e.destination==`string`&&e.destination.length>0,r=!n&&!!process.stderr.isTTY,i=e.format??(r?`pretty`:`json`),a={level:t};if(i===`pretty`)return a.transport={target:`pino-pretty`,options:{colorize:!n,translateTime:`SYS:HH:MM:ss.l`,ignore:`pid,hostname`,...n?{destination:e.destination,mkdir:!0}:{destination:2}}},(0,l.default)(a);let o=n?l.default.destination({dest:e.destination,mkdir:!0,sync:!0}):l.default.destination(2);return(0,l.default)(a,o)}function Ve(e){if(e?.type!==`object`||!e.properties)return;let t=Object.entries(e.properties);if(t.length===0)return;let n=new Set(e.required??[]);return`{ ${t.map(([e,t])=>`${e}${n.has(e)?``:`?`}: ${W(t)}`).join(`, `)} }`}function He(e){return typeof e==`string`?`'${e}'`:JSON.stringify(e)}function Ue(e){let t=e.enum??[];return t.length===0?`unknown`:t.map(He).join(`|`)}function We(e,t){return e.map(e=>W(e,t)).join(` | `)}function W(e,t=0){if(!e)return`unknown`;if(e.type===`array`)return`${W(e.items,0)}[]`;if(e.enum)return Ue(e);if(e.$ref)return String(e.$ref).split(`/`).pop()||`object`;let n=e.anyOf??e.oneOf;return n?n.length===0?`unknown`:t>=2?We(n,t-1):`union`:t>=1&&e.type===`object`?Ve(e)??`object`:e.type??`object`}function Ge(e){let t=(e?.input??{}).properties?.data,n=t?.properties??{},r=new Set(t?.required??[]),i=Object.entries(n).map(([e,t])=>({name:e,type:W(t,2),required:r.has(e)}));return{params:i,text:i.map(e=>`${e.name}${e.required?``:`?`}: ${e.type}`).join(`, `)}}function Ke(e){let t;return t=Array.isArray(e)?e:e?[e]:[],t.find(e=>e===`number`||e===`integer`||e===`boolean`)}function qe(e,t){let n=(t?.input??{}).properties?.data?.properties??{},r={...e};for(let[e,t]of Object.entries(n)){let n=r[e];if(typeof n!=`string`)continue;let i=Ke(t?.type);if(i===`number`||i===`integer`){let t=Number(n);!Number.isNaN(t)&&n.trim()!==``&&(r[e]=t)}else i===`boolean`&&(n===`true`?r[e]=!0:n===`false`&&(r[e]=!1))}return r}var Je=new Set([`default`,`module.exports`,`__esModule`]);function Ye(e){let t={},n=(e,r)=>{for(let[i,a]of Object.entries(e))if(typeof a==`function`){!Je.has(i)&&!(i in t)&&(t[i]=a);let e=a.name;e&&!(e in t)&&(t[e]=a)}else a&&typeof a==`object`&&r<2&&Je.has(i)&&n(a,r+1)};return n(e,0),t}var Xe=[`invalid_argument`,`unauthenticated`,`permission_denied`,`not_found`,`internal`],G=class extends Error{constructor(e,t,n){super(t),this.name=`ApiError`,this.code=e,this.details=n,Object.setPrototypeOf(this,new.target.prototype)}toJSON(){let e={code:this.code,message:this.message};return this.details!==void 0&&(e.details=this.details),e}};function Ze(e){return typeof e==`object`&&!!e&&e.name===`ApiError`&&Xe.includes(e.code)&&typeof e.toJSON==`function`}function Qe(e,t,n=0){return e===`before-first-chunk`?{phase:e,error:t}:{phase:e,error:t,chunksDelivered:n}}var K=new u.default({allErrors:!0});(0,d.default)(K);for(let e of[ee,h,g,te,`discriminator`])K.addKeyword({keyword:e,valid:!0});K.addFormat(`decimal`,/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/);function $e(e){return e.map(e=>`${e.instancePath||`(root)`} ${e.message??`failed schema check`}`).join(`; `)}function et(e,t){let n=L(t),r=[`Validation failed: ${$e(e)}`];return n&&r.push(n),r.join(` โ€” `)}var tt=async(e,t)=>{let n=e.ctx.get(nt);if(n===void 0)return t();let r=n[e.operation.id];if(r===void 0)return t();let i={data:e.domainArgs,...e.envelope},a=K.compile(r.input);if(!a(i)){let e=a.errors??[];throw new G(`invalid_argument`,et(e,r.input),e)}return t()},nt=Symbol(`ValidateSchemasToken`);function rt(e){return async function(t,n){let r=e[t.operation.id];if(r===void 0)return n();let i={data:t.domainArgs,...t.envelope},a=K.compile(r.input);if(!a(i)){let e=a.errors??[];throw new G(`invalid_argument`,et(e,r.input),e)}return n()}}function it(){return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)})}var at=class{constructor(e={}){this._store=new Map,this._sweeper=null,this._defaultTtlMs=e.defaultTtlMs;let t=null;t=e.sweepIntervalMs===0?null:e.sweepIntervalMs===void 0?this._defaultTtlMs===void 0?null:Math.max(1e3,Math.floor(this._defaultTtlMs/4)):e.sweepIntervalMs,t!==null&&t>0&&(this._sweeper=setInterval(()=>this._sweep(),t),this._sweeper.unref?.())}create(e,t=[],n){let r=new e(...t),i=it(),a=n??this._defaultTtlMs,o=a===void 0?null:Date.now()+a;return this._store.set(i,{instance:r,expiresAt:o}),{instanceId:i}}get(e){let t=this._store.get(e);if(!t)throw Error(`[instance-registry] Unknown instanceId: "${e}"`);if(t.expiresAt!==null&&Date.now()>t.expiresAt)throw this._evict(e,t),Error(`[instance-registry] Instance "${e}" has expired`);return t.instance}async dispatch(e,t,n=[]){let r=this.get(e),i=r[t];if(typeof i!=`function`)throw Error(`[instance-registry] Method "${t}" not found on instance "${e}"`);return i.call(r,...n)}async dispose(e){let t=this._store.get(e);t&&(this._store.delete(e),await q(t.instance))}async disposeAll(){this._sweeper!==null&&(clearInterval(this._sweeper),this._sweeper=null);let e=[...this._store.entries()];this._store.clear(),await Promise.all(e.map(([,e])=>q(e.instance)))}get size(){return this._store.size}_sweep(){let e=Date.now();for(let[t,n]of this._store)n.expiresAt!==null&&e>n.expiresAt&&this._evict(t,n)}_evict(e,t){this._store.delete(e),q(t.instance)}};async function q(e){if(typeof e==`object`&&e&&`dispose`in e){let t=e.dispose;typeof t==`function`&&await t.call(e)}}function ot(e){let{produce:t,signal:n}=e,r=n??new AbortController().signal;return{[Symbol.asyncIterator](){let e=t(r);return{async next(){return r.aborted?(await e.return(void 0),{done:!0,value:void 0}):e.next()},async return(t){return await e.return(t),{done:!0,value:void 0}},async throw(t){return await e.throw(t),{done:!0,value:void 0}}}}}}async function st(e){let t=[];for await(let n of e)t.push(n);return t}async function ct(e){let t=[];try{for await(let n of e)t.push(n);return{ok:!0,chunks:t}}catch(e){let n=Ze(e)?e:new G(`internal`,e instanceof Error?e.message:String(e));return t.length===0?{ok:!1,carrier:Qe(`before-first-chunk`,n)}:{ok:!1,carrier:Qe(`after-first-chunk`,n,t.length)}}}function lt(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e}var J=class extends Error{constructor(e,t){super(t),this.name=`UnionCodecError`,this.code=e}};function Y(e){let t=e.discriminator;if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t;if(typeof n.propertyName!=`string`)return;let r=n.mapping;if(typeof r==`object`&&r&&!Array.isArray(r))return{propertyName:n.propertyName,mapping:r}}function ut(e,t){let n=e[h];if(typeof n==`string`){let e=t.registry.get(n);if(e)return e}return t.registry.resolve(e)}function dt(e,t,n){let r=ut(t,n);return r?r.encode(e,t,n):e}function ft(e,t,n){let r=ut(t,n);return r?r.decode(e,t,n):e}function pt(e){let{id:t,schema:n}=e;return{id:t,kind:`union`,schema:n,matches(e){if(e[`x-apigen-logical`]===`union`)return!0;let t=e.oneOf;return!Array.isArray(t)||t.length===0?!1:Y(e)!==void 0},encode(e,n,r){let i=Y(n);if(!i)throw new J(`E_UNION_NO_DISCRIMINATOR`,`[${t}] schema node at "${r.path}" has no discriminator.propertyName; cannot dispatch union branch.`);let{propertyName:a,mapping:o}=i,s=e[a];if(s==null)throw new J(`E_UNION_NO_DISCRIMINATOR`,`[${t}] value at "${r.path}" is missing the discriminator property "${a}".`);let c=String(s),l=o[c];if(!l)throw new J(`E_UNION_UNKNOWN_TAG`,`[${t}] discriminator tag "${c}" at "${r.path}" is not in the mapping (known: ${Object.keys(o).join(`, `)}).`);return dt(e,r.resolve(l),{...r,path:`${r.path}[${c}]`})},decode(e,n,r){if(typeof e!=`object`||!e||Array.isArray(e)){let n;throw n=e===null?`null`:Array.isArray(e)?`array`:typeof e,new J(`E_UNION_INVALID_WIRE`,`[${t}] expected a JSON object on the wire at "${r.path}", got ${n}.`)}let i=e,a=Y(n);if(!a)throw new J(`E_UNION_NO_DISCRIMINATOR`,`[${t}] schema node at "${r.path}" has no discriminator.propertyName; cannot dispatch union branch.`);let{propertyName:o,mapping:s}=a,c=i[o];if(c==null)throw new J(`E_UNION_NO_DISCRIMINATOR`,`[${t}] wire object at "${r.path}" is missing the discriminator property "${o}".`);let l=String(c),u=s[l];if(!u)throw new J(`E_UNION_UNKNOWN_TAG`,`[${t}] discriminator tag "${l}" on the wire at "${r.path}" is not in the mapping (known: ${Object.keys(s).join(`, `)}).`);return ft(e,r.resolve(u),{...r,path:`${r.path}[${l}]`})}}}var X=class extends Error{constructor(e,t){super(t),this.name=`NominalCodecError`,this.code=e}};function mt(e){let t=e.properties;return t&&typeof t==`object`&&!Array.isArray(t)?t:{}}function ht(e){let t=e.required;return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function gt(e,t,n){if(t){let r=n.registry.resolve(t);if(r)return r.encode(e,t,n)}return e}function _t(e,t,n){if(t){let r=n.registry.resolve(t);if(r)return r.decode(e,t,n)}return e}function vt(e){let{id:t,schema:n,ctor:r}=e;return{id:t,kind:`nominal`,schema:n,matches(e){return e[`x-apigen-logical`]===`nominal`||e[h]===t},encode(e,n,r){if(typeof e!=`object`||!e)return e;if(r.seen.has(e)){if(r.mode===`strict`)throw new X(`E_NOMINAL_CYCLE`,`[${t}] cycle detected at "${r.path}": a nominal instance references itself. Strict mode rejects cycles (DESIGN ยง8.3); break the cycle or use 'lossy' mode.`);return null}r.seen.add(e);try{let t=mt(n),i=e[typeof n[`x-apigen-tojson`]==`string`?n[te]:`toJSON`];if(typeof i==`function`){let n=i.call(e);if(typeof n==`object`&&n&&!Array.isArray(n)){let e={};for(let[i,a]of Object.entries(n))e[i]=gt(a,t[i],{...r,path:`${r.path}/${i}`});return e}return n}let a={},o=Object.keys(t),s=e,c=o.length>0?o:Object.keys(s);for(let e of c){let n=s[e];n!==void 0&&(a[e]=gt(n,t[e],{...r,path:`${r.path}/${e}`}))}return a}finally{r.seen.delete(e)}},decode(e,n,i){if(typeof e!=`object`||!e||Array.isArray(e)){let n;throw n=e===null?`null`:Array.isArray(e)?`array`:typeof e,new X(`E_NOMINAL_INVALID_WIRE`,`[${t}] expected a JSON object on the wire at "${i.path}", got ${n}.`)}let a=e;for(let e of ht(n))if(!(e in a))throw new X(`E_NOMINAL_INVALID_WIRE`,`[${t}] required field "${e}" missing on the wire at "${i.path}".`);if(n[`x-apigen-instances`]===!1)throw new X(`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.`);let o=mt(n),s={};for(let[e,t]of Object.entries(a))s[e]=_t(t,o[e],{...i,path:`${i.path}/${e}`});if(r){let e=typeof n[`x-apigen-ctor`]==`string`?n[g]:`fromJSON`,t=r[e];return typeof t==`function`?t.call(r,s):new r(s)}return s}}}var yt=[T,E,D,O,k,N],bt=vt({id:`ts.NominalSentinel`,schema:{type:`object`,"x-apigen-logical":`nominal`,"x-apigen-codec":`ts.NominalSentinel`}}),xt=pt({id:`ts.UnionSentinel`,schema:{oneOf:[],discriminator:{propertyName:`kind`,mapping:{}},"x-apigen-logical":`union`,"x-apigen-codec":`ts.UnionSentinel`}});function St(){let e=[...yt.map(e=>[e.id,e]),[bt.id,bt],[xt.id,xt]];return Object.freeze(new Map(e))}var Ct=Object.freeze({host:`ts`,logicalTypeVersion:ne,codecs:St()});function wt(e,t,n){let r=[n,typeof t?.input?.description==`string`?t.input.description:void 0,L(t?.input)].filter(e=>typeof e==`string`&&e.length>0);return r.length>0?r.join(` โ€” `):e}function Tt(e){if(!e||typeof e!=`object`||Array.isArray(e)||Object.keys(e).length===0)return{outputSchema:void 0,wrapped:!1};let t=e;return t.type===`object`?{outputSchema:t,wrapped:!0}:{outputSchema:void 0,wrapped:!1}}function Et(e,t){if(e)return t&&typeof t==`object`&&!Array.isArray(t)?t:void 0}var Dt=4,Ot=32;function Z(e){return Ze(e)?e:e instanceof Error?new G(`internal`,e.message):e}function kt(e,t){if(e===`serial`||e===`chained`)return 1;let n=t??4;return!Number.isFinite(n)||n<1?1:Math.min(Math.floor(n),32)}function At(){}function jt(e,t){if(!e&&!t)return{signal:void 0,dispose:At};let n=new AbortController,r=()=>{n.abort(e?.reason)};e&&(e.aborted?n.abort(e.reason):e.addEventListener(`abort`,r,{once:!0}));let i;return t!==void 0&&!n.signal.aborted&&(i=setTimeout(()=>{n.abort(new DOMException(`apigen/invokeBatch: item timed out after ${t}ms`,`TimeoutError`))},t),i.unref?.()),{signal:n.signal,dispose(){e&&e.removeEventListener(`abort`,r),i&&clearTimeout(i)}}}async function Mt(e,t,n,r,i,a){let o=jt(r.signal,a);try{let a=await e(t,o.signal?{...r,signal:o.signal}:r,i);if(lt(a)){let e=await ct(a);if(!e.ok){let t=e.carrier;return{index:n,status:`rejected`,reason:Z(t.error),...t.phase===`after-first-chunk`?{chunksDelivered:t.chunksDelivered}:{}}}return{index:n,status:`fulfilled`,chunks:e.chunks}}return{index:n,status:`fulfilled`,value:a}}catch(e){return{index:n,status:`rejected`,reason:Z(e)}}finally{o.dispose()}}async function Nt(e,t,n,r,i={}){let a=i.mode??`parallel`,o=i.onItemError??`continue`,s=kt(a,i.concurrency),c=Array(n.length),l=e=>({index:e,status:`rejected`,reason:Z(Error(`apigen/invokeBatch: not attempted โ€” an earlier item failed and `+(a===`chained`?`mode is "chained"`:`onItemError is "abort"`)))});if(a===`serial`||a===`chained`){let s=!1;for(let u=0;u<n.length;u++){if(s){c[u]=l(u);continue}let d=await Mt(e,t,u,n[u],r,i.itemTimeoutMs);c[u]=d,d.status===`rejected`&&(a===`chained`||o===`abort`)&&(s=!0)}return c}let u=0,d=!1,f=Math.max(1,Math.min(s,n.length)),p=Array.from({length:f},async()=>{for(;;){let a=u++;if(a>=n.length)return;if(d){c[a]=l(a);continue}let s=await Mt(e,t,a,n[a],r,i.itemTimeoutMs);c[a]=s,s.status===`rejected`&&o===`abort`&&(d=!0)}});return await Promise.all(p),c}function Pt(e){return e.words.join(`-`)}function Ft(e){return e.words.map(Vt).join(``)}function It(e){return e.words.join(`_`)}function Lt(e,t={}){let n=[e.namespace,...e.path],r=e.safe||Me(e.input)?`GET`:`POST`,i=t.http?.verb?.[e.id]??r,a=`/`+n.map(e=>Pt(e)).join(`/`),o=n.map(e=>It(e)).join(`_`),s=n.map(e=>It(e)).slice(0,-1).join(`.`),c=Ft(n[n.length-2]??n[0]),l=Ft(n[n.length-1]),u=n.map(e=>Pt(e));return{http:{verb:i,route:a},mcp:{name:o},grpc:{package:s,service:c,method:l},cli:{path:u}}}function Rt(e,t){return`x-${e}-${t}`}function zt(e,t){return`--${e}-${t}`}function Bt(e,t){let n=e=>e.toUpperCase().replace(/-/g,`_`);return e===`adhd`?`APIGEN_${n(t)}`:`APIGEN_${n(e)}_${n(t)}`}function Vt(e){return e.length===0?e:e[0].toUpperCase()+e.slice(1)}function Q(e){return e.anyOf??e.oneOf}function Ht(e){if(!e)return!1;if(e.type===`array`||e.type===`object`)return!0;let t=Q(e);if(t){let e=t.filter(e=>e.type!==`null`);return e.length>0&&e.every(e=>e.type===`array`||e.type===`object`)}return!1}function Ut(e){if(!e)return!1;if(e.type===`boolean`)return!0;let t=Q(e);if(t){let e=t.filter(e=>e.type!==`null`);return e.length>0&&e.every(e=>e.type===`boolean`)}return!1}function Wt(e){if(!e)return!1;if(e.type===`number`||e.type===`integer`)return!0;let t=Q(e);if(t){let e=t.filter(e=>e.type!==`null`);return e.length>0&&e.every(e=>e.type===`number`||e.type===`integer`)}return!1}function Gt(e){return e.replace(/[A-Z]/g,e=>`-`+e.toLowerCase())}function Kt(e){let t=e.input?.properties?.data;return{props:t?.properties??{},required:t?.required??[]}}function $(e){return typeof e.handler==`function`}function qt(e){let t=e.input?.properties??{},n=e[`x-apigen-envelope`],r=[];for(let e of Object.keys(t)){if(e===`data`)continue;let t=n?.[e]??`adhd`,i=Rt(t,e);r.push({field:e,pluginId:t,httpHeader:i,mcpMetaKey:i,cliFlag:zt(t,e),envVar:Bt(t,e)})}return r}function Jt(e,t,n,r){t===n||e.has(t)||e.set(t,{...r,aliasOf:n})}function Yt(e,t){let n=new Map,{props:r}=Kt(e);for(let[e,t]of Object.entries(r)){let r=`string`;Ut(t)?r=`boolean`:(Ht(t)||Wt(t))&&(r=`json`);let i=Gt(e),a={camelKey:e,kind:`domain`,valueKind:r};n.set(i,a),Jt(n,e,i,a)}for(let e of t){let t=e.cliFlag.replace(/^--/,``),r={camelKey:e.field,kind:`envelope`,valueKind:`string`,envVar:e.envVar};n.set(t,r)}return n}function Xt(e){let{op:t,schema:n,transport:r,projection:i}=e,a=Lt(t,i),o=n?qt(n):[],s=n?Yt(n,o):new Map,c=n?Ge(n).params:void 0,l={op:t,transport:r,http:a.http,mcp:a.mcp,cli:a.cli,grpc:a.grpc,params:c,envelope:o,cliFlags:s,streaming:t.streaming,isMount:$(t)};if($(t)){let e=t.handler;l.mountHandler=async t=>e(t)}return l}function Zt(e){let t=e.usePlugins;return Array.isArray(t)?t:[]}function Qt(e){let t=e.exitCode;return typeof t==`function`?t:void 0}function $t(e){let t=e.useOptions;return t&&typeof t==`object`?t:{}}function en(e){return async function(t,n){let r=Object.assign(t,{data:t.domainArgs});return await e.layer(r,n)}}function tn(e,t){let n=[];for(let e of t){let t=e.capabilities?.layer;t&&n.push(en(t))}return n.push(rt(e)),we(n)}function nn(){let e=new Map;return{get:t=>e.get(t),set:(t,n)=>{e.set(t,n)}}}var rn={input:{type:`object`,properties:{data:{type:`object`,properties:{}}}},output:{}};async function an(e,t,n,r){let i={...n,operation:{id:e.op.id},ctx:new Ce};if(e.isMount){let a=e.mountHandler;if(!a)throw Error(`apigen-engine-runtime/dispatchForPlan: OpPlan for mount op "${e.op.id}" has isMount=true but no mountHandler`);let o={operation:e.op,data:n.domainArgs,envelope:n.envelope,ctx:nn(),transport:e.transport,signal:n.signal??new AbortController().signal},s={...r,fns:{[e.op.id]:()=>a(o)},schemas:{[e.op.id]:rn}};return t(e.op.id,i,s)}return t(e.op.id,i,r)}exports.BATCH_DEFAULT_CONCURRENCY=Dt,exports.BATCH_MAX_CONCURRENCY=Ot,exports.EventBus=Ee,exports.InstanceRegistry=at,exports.LayerContext=Ce,exports.UnionCodecError=J,exports.ValidateSchemasToken=nt,exports.WELL_KNOWN_TS_CODECS=yt,exports.adaptCoreLayer=en,exports.assertNoSelfSubscription=Re,exports.buildContext=ke,exports.buildFnTable=Ye,exports.buildMcpOutputSchema=Tt,exports.buildOpPlan=Xt,exports.buildToolDescription=wt,exports.coerceQueryParams=qe,exports.collectWithPhase=ct,exports.createApiPackage=ze,exports.createInvoker=we,exports.createLogger=Be,exports.createPackageInvoker=tn,exports.createStream=ot,exports.createUnionCodec=pt,exports.dataParamNames=V,exports.defineMiddleware=Te,exports.describeParams=Ge,exports.dispatch=Se,exports.dispatchForPlan=an,exports.drainStream=st,exports.invokeBatch=Nt,exports.isApiStream=lt,exports.makeValidateLayer=rt,exports.needsEnvelopeField=B,exports.readExitCodeHook=Qt,exports.readUseOptions=$t,exports.readUsePlugins=Zt,exports.tsHostBinding=Ct,exports.validateLayer=tt,exports.wireObservers=Oe,exports.wrapMcpStructuredContent=Et;