@makaio/framework 1.0.0-dev-1790772200584 → 1.0.0-dev-1791396836202
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/.makaio-build.json +2 -2
- package/dist/artifact-BbNQHNDL.mjs +1 -0
- package/dist/bus/index.d.mts +39 -9
- package/dist/bus/index.mjs +1 -1
- package/dist/{bus--m38BS3i.mjs → bus-CtT6XeB_.mjs} +4 -4
- package/dist/contracts/artifact/index.d.mts +3 -3
- package/dist/contracts/artifact/index.mjs +1 -1
- package/dist/contracts/capabilities/index.d.mts +1 -1
- package/dist/contracts/client/index.d.mts +1 -1
- package/dist/contracts/extension/index.d.mts +2 -2
- package/dist/contracts/index.d.mts +32 -32
- package/dist/contracts/index.mjs +1 -1
- package/dist/contracts/materialization/index.d.mts +2 -2
- package/dist/contracts/materialization/index.mjs +1 -1
- package/dist/contracts/session/index.d.mts +2 -2
- package/dist/contracts/worker/index.d.mts +1 -1
- package/dist/contracts/worker/index.mjs +1 -1
- package/dist/contracts/workflow/index.d.mts +2 -2
- package/dist/contracts/workflow/index.mjs +1 -1
- package/dist/fast-connection-FG3yAA7o.mjs +1 -0
- package/dist/{framework-packages-blqho6Nk.mjs → framework-packages-CdpSqDeo.mjs} +1 -1
- package/dist/inbound-hooks/fast-connection.d.mts +1 -1
- package/dist/inbound-hooks/fast-connection.mjs +1 -1
- package/dist/inbound-hooks/index.mjs +1 -1
- package/dist/{index-CBzHX2vt.d.mts → index-BXaNt9GP.d.mts} +1 -1
- package/dist/{index-21Tx9_N1.d.mts → index-CgcMrxhm.d.mts} +24 -24
- package/dist/{index-Dj60LBqi2.d.mts → index-ChwEMUbc2.d.mts} +3 -3
- package/dist/{index-DeSmhDs9.d.mts → index-CjM6Fi-N.d.mts} +1 -1
- package/dist/{index-v1-To1jx.d.mts → index-D5eIy_qx.d.mts} +4 -4
- package/dist/{index-CMmUS-p2.d.mts → index-DBkmFhrn.d.mts} +160 -38
- package/dist/{index-DulipRwg.d.mts → index-DnsMV2xK.d.mts} +10 -10
- package/dist/{index-vARKBSt9.d.mts → index-Rd9Teoza.d.mts} +16 -16
- package/dist/{index-Bxm5RUGG2.d.mts → index-chwNKVMu2.d.mts} +33 -33
- package/dist/{index-BPoX2Q9Z.d.mts → index-y6zuCdvH.d.mts} +58 -58
- package/dist/kernel/extension/index.d.mts +2 -2
- package/dist/kernel/index.d.mts +2 -2
- package/dist/kernel/observability/index.d.mts +1 -1
- package/dist/{materialization-BzSgnv2R.mjs → materialization-C1qlFBV2.mjs} +1 -1
- package/dist/{namespace-u4eoUCLp.d.mts → namespace-DZooy1DW.d.mts} +18 -18
- package/dist/node/transports/index.mjs +2 -2
- package/dist/package.json +1 -1
- package/dist/packages-BOM7wECe.mjs +1 -0
- package/dist/{packages-Fy4a6vQy.d.mts → packages-g6BtlUF9.d.mts} +9 -6
- package/dist/{schemas-BKE3qw_w.d.mts → schemas-DnrIc9g7.d.mts} +49 -10
- package/dist/{schemas-BQhtYuCM.d.mts → schemas-Y3EJu698.d.mts} +8 -8
- package/dist/{schemas-BvDsO8Is.mjs → schemas-uNzmiLso.mjs} +1 -1
- package/dist/services/filesystem/namespace.d.mts +6 -6
- package/dist/services/filesystem/schemas.d.mts +3 -3
- package/dist/services/index.d.mts +9 -9
- package/dist/services/index.mjs +1 -1
- package/dist/services/materialization/index.d.mts +1 -1
- package/dist/services/materialization/index.mjs +1 -1
- package/dist/services/session/index.d.mts +1 -1
- package/dist/services/session/session-events/namespace.d.mts +1 -1
- package/dist/services/settings/namespace.d.mts +8 -8
- package/dist/services/subagent-template/index.d.mts +1 -1
- package/dist/services/subagent-template/schemas.d.mts +1 -1
- package/dist/services/tools/index.mjs +1 -1
- package/dist/services/workflow-transitions/index.mjs +1 -1
- package/dist/{tools-Cbuj-ClQ.mjs → tools-EK2HiPee.mjs} +1 -1
- package/dist/{transition-DNNBGMtx.d.mts → transition-yohyGRmc.d.mts} +1 -1
- package/dist/{types-DsZBnL7z.d.mts → types-CRKyrt5_.d.mts} +12 -12
- package/dist/{view-builder-HU_v1Jg7.d.mts → view-builder-BjVjGZAI.d.mts} +2 -2
- package/dist/{worker-toBnRJ0A.mjs → worker-DulBFC0P.mjs} +1 -1
- package/dist/{workflow-BDDB6EJi.mjs → workflow-Dvv_8Xu6.mjs} +1 -1
- package/dist/workflow-engine/index.d.mts +39 -39
- package/dist/{workflow-transitions-CvT6P03B.mjs → workflow-transitions-ztq90FUj.mjs} +1 -1
- package/package.json +1 -1
- package/dist/artifact-XE82Q2bH.mjs +0 -1
- package/dist/fast-connection-CIZ6nL7o.mjs +0 -1
- package/dist/packages-CZ2x-Ver.mjs +0 -1
package/dist/.makaio-build.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 1,
|
|
3
|
-
"fingerprint": "
|
|
4
|
-
"builtAt": "2026-
|
|
3
|
+
"fingerprint": "10349ae190209ea62ec6197e7cbae26a328e83a4f41f144571eaadf0c51dfc30",
|
|
4
|
+
"builtAt": "2026-10-07T18:15:05.739Z",
|
|
5
5
|
"declarations": true,
|
|
6
6
|
"declarationBackend": "tsc"
|
|
7
7
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{o as e}from"./chunk-DTipWd-i.mjs";import{n as t,o as n,s as r}from"./json-value-DM-EjTC1.mjs";import{S as i,T as a,_ as o,a as s,c,d as l,i as u,l as d,n as ee,p as te,r as ne,t as re,u as ie,w as f,x as ae,y as oe}from"./schemas-uNzmiLso.mjs";import{C as se,M as ce,a as le,d as p,h as ue,k as de,r as fe,s as m,t as h,x as pe}from"./kind-registration-CdjmVxY_.mjs";import{t as me}from"./zod-json-schema-ZUmGtQhT.mjs";import{t as he}from"./ajv-Cvnmw2yn.mjs";import{t as ge}from"./2020-CRfgqanb.mjs";import{t as _e}from"./dist-onY7e-pd.mjs";import{z as g}from"zod";import{createBusNamespace as ve}from"@makaio/framework/core";const ye=g.strictObject({evidence:f}),_=g.strictObject({kind:g.literal(`text`),text:g.string()}),[be,xe,Se]=f.options,Ce=g.union([be.pick({source:!0,location:!0}).extend({content:_}),xe.pick({source:!0,location:!0}).extend({content:_}),Se.pick({source:!0,location:!0}).extend({content:_})]);function v(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function y(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function we(e,t){if(t===`#`)return{node:e,pointer:``};if(!t.startsWith(`#/`))return;let n;try{n=decodeURIComponent(t.slice(1))}catch{return}let r=e;for(let e of n.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(Array.isArray(r)){if(!/^(0|[1-9]\d*)$/.test(t)||Number(t)>=r.length)return;r=r[Number(t)]}else{let e=v(r);if(!e||!Object.hasOwn(e,t))return;r=e[t]}}let i=typeof r==`boolean`?r:v(r);return i===void 0?void 0:{node:i,pointer:n}}function b(e,t){if(t===``)return!1;let n=e;for(let e of t.slice(1).split(`/`)){let t=e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`);if(n=Array.isArray(n)?n[Number(t)]:v(n)?.[t],typeof v(n)?.$id==`string`)return!0}return!1}function Te(e,t,n){if(e[`x-makaio-value-type`]!==`evidence/v1`)return;let r=f.safeParse(t);if(!r.success)throw Error(`Invalid schema-declared evidence at ${n}`);return{evidence:r.data,dataPath:n}}function Ee(e,t,n,r){if(typeof t.$ref!=`string`)return!1;if(r)return!0;let i=we(e,t.$ref);return i===void 0?!0:typeof i.node!=`boolean`&&x(e,i.node,n,b(e,i.pointer))}function x(e,t,n=new WeakSet,r=!1){let i=v(t);if(!i||n.has(i))return!1;n.add(i);let a=r||i!==e&&typeof i.$id==`string`;if(i[`x-makaio-value-type`]===`evidence/v1`||typeof i.$dynamicRef==`string`||Ee(e,i,n,a)||[`additionalItems`,`additionalProperties`,`contains`,`else`,`if`,`items`,`then`,`unevaluatedItems`,`unevaluatedProperties`].some(t=>x(e,i[t],n,a))||[`allOf`,`anyOf`,`oneOf`,`prefixItems`].some(t=>Array.isArray(i[t])&&i[t].some(t=>x(e,t,n,a)))||Array.isArray(i.items)&&i.items.some(t=>x(e,t,n,a)))return!0;for(let t of[`dependentSchemas`,`dependencies`,`patternProperties`,`properties`]){let r=v(i[t]);if(r&&Object.values(r).some(t=>x(e,t,n,a)))return!0}return!1}var De=class{dataSchema;matchesSchema;occurrences=new Map;visited=new WeakMap;constructor(e,t){this.dataSchema=e,this.matchesSchema=t}extract(e){return this.visit(this.dataSchema,e,`/data`),[...this.occurrences.values()]}visit(e,t,n,r=``){let i=this.visited.get(e)??new Set;if(i.has(n))return;if(i.add(n),this.visited.set(e,i),typeof e.$dynamicRef==`string`)throw Error(`Evidence discovery does not support active $dynamicRef at ${n}`);if(typeof e.$ref==`string`){if(b(this.dataSchema,r))throw Error(`Evidence discovery does not support local $ref inside nested $id resource at ${n}`);let i=we(this.dataSchema,e.$ref);if(i===void 0)throw Error(`Cannot resolve local schema reference ${e.$ref} at ${n}`);if(typeof i.node!=`boolean`&&this.visit(i.node,t,n,i.pointer),this.dataSchema.$schema!==`https://json-schema.org/draft/2020-12/schema`)return}let a=Te(e,t,n);if(a){this.occurrences.set(n,a);return}this.visitCombiners(e,t,n,r),this.visitConditional(e,t,n,r),this.visitDependencies(e,t,n,r),this.assertSupportedApplicators(e,n,r),Array.isArray(t)?this.visitArray(e,t,n,r):typeof t==`object`&&t&&this.visitObject(e,t,n,r)}visitCombiners(e,t,n,r){for(let i of[`allOf`,`anyOf`,`oneOf`]){let a=e[i];if(Array.isArray(a))for(let[e,o]of a.entries()){let a=v(o),s=`${r}/${i}/${e}`;a&&(i===`allOf`||this.matchesSchema(this.dataSchema,s,t))&&this.visit(a,t,n,s)}}}visitConditional(e,t,n,r){let i=typeof e.if==`boolean`?e.if:v(e.if);if(i===void 0)return;let a=`${r}/if`,o=this.matchesSchema(this.dataSchema,a,t);o&&typeof i!=`boolean`&&this.visit(i,t,n,a);let s=o?`then`:`else`,c=v(e[s]);c&&this.visit(c,t,n,`${r}/${s}`)}visitDependencies(e,t,n,r){if(!(typeof t!=`object`||!t||Array.isArray(t)))for(let i of[`dependentSchemas`,`dependencies`]){let a=v(e[i]);if(a)for(let[e,o]of Object.entries(a)){let a=v(o);Object.hasOwn(t,e)&&a&&this.visit(a,t,n,`${r}/${i}/${y(e)}`)}}}assertSupportedApplicators(e,t,n){for(let r of[`unevaluatedProperties`,`unevaluatedItems`])if(x(this.dataSchema,e[r],void 0,b(this.dataSchema,n)))throw Error(`Evidence under unsupported ${r} applicator at ${t}`)}visitArray(e,t,n,r){let i=Array.isArray(e.prefixItems),a=i?e.prefixItems:Array.isArray(e.items)?e.items:[];a.forEach((e,a)=>{let o=v(e),s=i?`prefixItems`:`items`;o&&a<t.length&&this.visit(o,t[a],`${n}/${a}`,`${r}/${s}/${a}`)});let o=Array.isArray(e.items)?v(e.additionalItems):v(e.items);if(o){let i=Array.isArray(e.items)?`additionalItems`:`items`;t.slice(a.length).forEach((e,t)=>this.visit(o,e,`${n}/${a.length+t}`,`${r}/${i}`))}this.visitContains(e,t,n,r)}visitContains(e,t,n,r){let i=v(e.contains);if(!i)return;let a=`${r}/contains`;t.forEach((e,t)=>{this.matchesSchema(this.dataSchema,a,e)&&this.visit(i,e,`${n}/${t}`,a)})}visitObject(e,t,n,r){let i=v(e.properties),a=v(e.patternProperties);for(let[o,s]of Object.entries(t)){let t=y(o),c=i!==void 0&&Object.hasOwn(i,o),l=v(i?.[o]);l&&this.visit(l,s,`${n}/${t}`,`${r}/properties/${t}`);let u=this.visitPatterns(a,o,s,`${n}/${t}`,r),d=v(e.additionalProperties);!c&&!u&&d&&this.visit(d,s,`${n}/${t}`,`${r}/additionalProperties`)}}visitPatterns(e,t,n,r,i){let a=!1;for(let[o,s]of Object.entries(e??{})){if(!new RegExp(o,`u`).test(t))continue;a=!0;let e=v(s);e&&this.visit(e,n,r,`${i}/patternProperties/${y(o)}`)}return a}};function Oe(e,t,n){return new De(e,n.matchesSchema).extract(t)}function ke(e){let{dataSchema:t,hooks:n,...r}=e,i={$schema:`https://json-schema.org/draft/2020-12/schema`,...me(t)};de(i);let a=le.parse({...r,dataSchema:i});if(a.kind!==e.kind)throw Error(`Artifact kind identifiers must not contain surrounding whitespace`);let o=g.fromJSONSchema(a.dataSchema),s=g.unknown().superRefine((e,t)=>{let n=o.safeParse(e);if(!n.success)for(let e of n.error.issues)t.addIssue({code:`custom`,path:e.path,message:e.message})}).pipe(t).superRefine((e,t)=>{Object.hasOwn(e,`slug`)&&t.addIssue({code:`custom`,path:[pe],message:se});try{ce(e,a.titlePath)}catch(e){t.addIssue({code:`custom`,path:a.titlePath.split(`.`),message:e instanceof Error?e.message:`Artifact title must be a nonblank string`})}});return{...structuredClone(a),kind:e.kind,schemaVersion:e.schemaVersion,dataSchema:s,...n?{hooks:n}:{},toRegistration:()=>structuredClone(a)}}var Ae=e(he(),1),je=e(ge(),1),Me=e(_e(),1);function Ne(e){let t={allErrors:!0,strict:!1,strictSchema:!0},n=e.dataSchema.$schema===`https://json-schema.org/draft/2020-12/schema`?new je.default(t):new Ae.default(t);return(0,Me.default)(n),n.addKeyword({keyword:i,schemaType:`string`,valid:!0}),n.compile(e.dataSchema)}function Pe(e){return e.replace(/~1/gu,`/`).replace(/~0/gu,`~`)}function Fe(e){let t=e.instancePath.split(`/`).slice(1).map(Pe),n=e.keyword===`required`?e.params.missingProperty:e.params.additionalProperty;return typeof n==`string`&&(e.keyword===`required`||e.keyword===`additionalProperties`)&&t.push(n),t.join(`.`)}function Ie(e){if(e.keyword!==`type`)return;let t=e.params.type;if(typeof t==`string`)return t;if(Array.isArray(t)&&t.every(e=>typeof e==`string`))return t.join(` | `)}const Le=n.array();function Re(e){if(e.keyword!==`enum`)return;let t=Le.safeParse(e.params.allowedValues);return t.success?t.data:void 0}function ze(e){return(e??[]).map(e=>{let t=Ie(e),n=Re(e);return{path:Fe(e),reason:e.message??`violates ${e.keyword}`,...t===void 0?{}:{expectedType:t},...n===void 0?{}:{allowedValues:n}}})}function Be(e){return typeof e==`object`&&!!e&&Object.hasOwn(e,`slug`)}const Ve={path:pe,reason:se};function He(e){let t=Ne(e);return e=>t(e)&&!Be(e)}function Ue(e){let t=Ne(e);return e=>{let n=t(e)?[]:ze(t.errors);return Be(e)&&n.push(Ve),n.length===0?{valid:!0}:{valid:!1,issues:n}}}function We(e){return{hooks:[...e.hooks]}}const Ge=[`inline`,`summary`,`link`,`omit`],Ke=[`outbound`,`inbound`],S=g.string().min(1),C=g.enum(Ke),qe=g.object({kinds:g.array(g.string().min(1)).optional(),hint:S.optional(),depth:g.number().int().min(1).max(20).optional(),nested:g.lazy(()=>w).optional(),direction:C.optional()}),w=g.record(g.string().min(1),qe);function T(e){return JSON.stringify([e.kind,e.id,e.revision])}const Je=g.enum([`not-selected`,`not-found`,`depth-exceeded`,`unsupported-ref-class`,`cycle-detected`]),Ye=g.object({target:d,sourceRef:a,relationType:g.string().min(1),sourceLocalId:c.shape.sourceLocalId,direction:C.optional(),hint:S,status:g.enum([`resolved`,`unresolved`]),reason:Je.optional()}).superRefine((e,t)=>{e.status===`unresolved`&&e.reason===void 0&&t.addIssue({code:g.ZodIssueCode.custom,path:[`reason`],message:`reason is required for unresolved artifact context refs`}),e.status===`resolved`&&e.reason!==void 0&&t.addIssue({code:g.ZodIssueCode.custom,path:[`reason`],message:`reason must be omitted for resolved artifact context refs`}),e.status===`resolved`&&e.target.refClass!==`artifact`&&t.addIssue({code:g.ZodIssueCode.custom,path:[`target`],message:`resolved artifact context refs must target an artifact revision`})}),E=g.object({rootRef:a,refs:g.array(Ye),resolved:g.array(l)}).superRefine((e,t)=>{let n=new Set(e.resolved.map(T));n.has(T(e.rootRef))||t.addIssue({code:g.ZodIssueCode.custom,path:[`resolved`],message:`resolved artifact context wire payloads must include the root artifact revision`}),e.refs.forEach((e,r)=>{n.has(T(e.sourceRef))||t.addIssue({code:g.ZodIssueCode.custom,path:[`refs`,r,`sourceRef`],message:`artifact context ref sources must have a matching revision in resolved`}),!(e.status!==`resolved`||e.target.refClass!==`artifact`)&&(n.has(T(e.target))||t.addIssue({code:g.ZodIssueCode.custom,path:[`refs`,r,`target`],message:`resolved artifact context refs must have a matching revision in resolved`}))})});function Xe(e){let t=E.parse(e),n=new Map(t.resolved.map(e=>[T(e),e])),r=new Map;for(let e of t.refs){let t=T(e.sourceRef),n=r.get(t);n||(n=[],r.set(t,n)),n.push(e)}let i=n.get(T(t.rootRef));if(!i)throw Error(`Resolved artifact context is missing root artifact '${T(t.rootRef)}'`);let a=Ze(t.rootRef,i,`inline`,r,n);return{root:a,flatten(){let e=[];return et(a,e),e}}}function Ze(e,t,n,r,i){return{status:`resolved`,ref:e,artifact:t,hint:n,children:$e(e,r,i,new Set([T(e)]))}}function Qe(e,t,n,r,i,a,o,s,c){let l=T(e),u=new Set(c);return u.add(l),{status:`resolved`,ref:e,artifact:t,relation:n,sourceLocalId:r,direction:i,hint:a,children:$e(e,o,s,u)}}function $e(e,t,n,r){return(t.get(T(e))??[]).map(e=>{if(e.status===`unresolved`)return{status:`unresolved`,target:e.target,relation:e.relationType,sourceLocalId:e.sourceLocalId,direction:e.direction,hint:e.hint,reason:e.reason};if(e.target.refClass!==`artifact`)throw Error(`Resolved artifact context refs must target an artifact revision`);let i=T(e.target),a=n.get(i);if(!a)throw Error(`Resolved artifact context is missing target artifact '${i}'`);return r.has(i)?{status:`unresolved`,target:e.target,relation:e.relationType,sourceLocalId:e.sourceLocalId,direction:e.direction,hint:e.hint,reason:`cycle-detected`}:Qe(e.target,a,e.relationType,e.sourceLocalId,e.direction,e.hint,t,n,r)})}function et(e,t){if(e.status!==`unresolved`){t.push(e.artifact);for(let n of e.children)et(n,t)}}const D=[`$set`,`$unset`,`$push`,`$pull`],O=`[A-Za-z_$][A-Za-z0-9_$]*`,k=`[A-Za-z_$][A-Za-z0-9_$-]*`,tt=`(?:0|[1-9][0-9]*)`,nt=`(?:${`\\$\\[${O}\\]`}|${tt}|${k})`,rt=RegExp(`^${k}(?:\\.${nt})*$`),it=RegExp(`^${O}(?:\\.${k})*$`),at=RegExp(`^${tt}$`),ot=RegExp(`^\\$\\[(${O})\\]$`),A=g.string().regex(rt,`Expected a data-relative path of object properties, array positions, or $[filter] placeholders`);function st(e){let t=ot.exec(e);return t?.[1]===void 0?at.test(e)?{kind:`index`,index:Number(e)}:{kind:`property`,name:e}:{kind:`filter`,placeholder:t[1]}}function ct(e){return e.split(`.`).map(st)}function lt(e){return ct(e).flatMap(e=>e.kind===`filter`?[e.placeholder]:[])}const ut=r(g.record(g.string().regex(it,`Expected a filter key of the form name or name.field.path`),n),{prototypeKey:`an array filter cannot compare a __proto__ key, which JSON transport drops`,nonPlainObject:`an array filter must be a plain object of comparison keys`,symbolKey:`an array filter cannot carry symbol-keyed comparisons`,nonEnumerableKey:`an array filter cannot carry non-enumerable comparison keys`,extraArrayKey:`an array filter must be a plain object, not an array`});function dt(e){let t=new Set(Object.keys(e).map(e=>e.split(`.`)[0]));if(t.size!==1)return;let[n]=t;return n!==void 0&&n.length>0?n:void 0}function j(e,t){return r(g.record(A,t),{prototypeKey:`${e} cannot address __proto__, which JSON transport drops`,nonPlainObject:`${e} must be a plain object of path instructions`,symbolKey:`${e} cannot carry symbol-keyed instructions`,nonEnumerableKey:`${e} cannot carry non-enumerable instructions`,extraArrayKey:`${e} must be a plain object, not an array`})}const ft=g.literal(!0),pt=g.strictObject({$set:j(`$set`,n).optional(),$unset:j(`$unset`,ft).optional(),$push:j(`$push`,n).optional(),$pull:j(`$pull`,n).optional(),arrayFilters:g.array(ut).optional()});function M(e){return D.flatMap(t=>Object.entries(e[t]??{}).map(([e,n])=>({operator:t,path:e,value:n})))}function mt(e,t){let n=M(e),r=new Map;(e.arrayFilters??[]).forEach((e,n)=>{let i=dt(e);if(i===void 0){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`An array filter must bind exactly one placeholder name across all of its keys`});return}if(r.has(i)){t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter placeholder ${i} is already bound by another filter`});return}r.set(i,n)});let i=new Set;for(let{operator:e,path:a}of n)for(let n of lt(a))i.add(n),r.has(n)||t.addIssue({code:`custom`,path:[e,a],message:`Path uses placeholder $[${n}] without a matching entry in arrayFilters`});for(let[e,n]of r)i.has(e)||t.addIssue({code:`custom`,path:[`arrayFilters`,n],message:`Array filter binds placeholder ${e}, which no path uses`})}const ht=pt.superRefine(mt).superRefine((e,t)=>{M(e).length===0&&t.addIssue({code:`custom`,message:`Declare at least one of ${D.join(`, `)}`})}),gt=pt.superRefine(mt),_t=g.strictObject({kind:a.shape.kind,id:a.shape.id}),vt=g.strictObject({ref:_t,baseRevision:a.shape.revision,patch:gt,dryRun:g.boolean().optional(),schemaVersion:p.optional().describe(`Target schema version for the patched revision; defaults to the base revision's. Use it to migrate an artifact left at an older version by a kind bump.`),statusPath:te.optional(),representations:ie.strict().nullable().optional().describe(`Rendering hints (markdown, summary, plaintext) for the new revision. Omit to keep the previous revision's hints. An object replaces all of them, it does not merge: send every hint you want to keep. null clears them.`)}).superRefine((e,t)=>{e.schemaVersion===void 0&&M(e.patch).length===0&&t.addIssue({code:`custom`,path:[`patch`],message:`Declare at least one of ${D.join(`, `)}, or name a schemaVersion to migrate a payload that already fits`})}),yt=[`ARTIFACT_NOT_FOUND`,`BASE_REVISION_CONFLICT`,`KIND_NOT_REGISTERED`,`SCHEMA_VERSION_MISMATCH`,`PATH_NOT_DECLARED`,`PATH_NOT_RESOLVABLE`,`TARGET_NOT_A_COLLECTION`,`UNSUPPORTED_TARGET`,`NO_MATCH`,`SCHEMA_VALIDATION_FAILED`,`PAYLOAD_INVARIANT_FAILED`,`NO_CHANGE`,`STORE_REJECTED`,`HOST_FAILED`],bt=g.strictObject({path:g.string(),reason:g.string().min(1),expectedType:g.string().min(1).optional(),allowedValues:g.array(n).optional()}),xt=g.strictObject({code:g.enum(yt),message:g.string().min(1),operator:g.enum(D).optional(),path:A.optional(),currentRevision:a.shape.revision.optional(),issues:g.array(bt).optional(),repair:g.string().min(1)}).superRefine((e,t)=>{e.code===`BASE_REVISION_CONFLICT`&&e.currentRevision===void 0&&t.addIssue({code:g.ZodIssueCode.custom,message:`A BASE_REVISION_CONFLICT must name the revision the artifact carries.`,path:[`currentRevision`]})}),St=g.strictObject({operator:g.enum(D),path:A,matched:g.number().int().positive()}),Ct=g.strictObject({from:p,to:p}).refine(e=>e.to>e.from,{path:[`to`],message:`A migration moves the artifact forward to a newer schema version`}),wt=g.strictObject({ok:g.literal(!0),base:a,operations:g.array(St),migration:Ct.optional()});function Tt(e,t){e.operations.length===0&&e.migration===void 0&&t.addIssue({code:`custom`,path:[`operations`],message:`A success without a migration must report at least one applied instruction`})}const Et=wt.extend({dryRun:g.literal(!0)}).superRefine(Tt),Dt=wt.extend({dryRun:g.literal(!1),artifact:a}).superRefine(Tt),Ot=g.discriminatedUnion(`dryRun`,[Et,Dt]),kt=g.strictObject({ok:g.literal(!1),error:xt}),At=g.union([Ot,kt]),jt=g.object({ref:oe}),Mt=g.union([g.strictObject({ok:g.literal(!0),ref:oe,areaPath:fe,part:t}),g.strictObject({ok:g.literal(!1),error:ue})]),N=a.pick({kind:!0,id:!0}),P=g.number().int().positive(),F=P,I={knowledge:`valid`,commitment:`proposed`,interaction:`open`},L=g.discriminatedUnion(`category`,[g.strictObject({category:g.literal(`knowledge`),state:g.enum(h.knowledge),version:F}),g.strictObject({category:g.literal(`commitment`),state:g.enum(h.commitment),version:F}),g.strictObject({category:g.literal(`interaction`),state:g.enum(h.interaction),version:F})]).superRefine((e,t)=>{e.version===1&&e.state!==I[e.category]&&t.addIssue({code:`custom`,path:[`state`],message:`Lifecycle version 1 is reserved for the category initial state`})}),R=g.union([L,g.strictObject({category:g.literal(`record`)})]),z=g.string().trim().min(1),Nt=g.strictObject({kind:z,ref:z}),B=g.discriminatedUnion(`kind`,[g.strictObject({kind:g.literal(`revision-assessment`),assessedRevision:a.shape.revision,source:Nt.optional()}),g.strictObject({kind:g.literal(`handover`),source:Nt})]),Pt={artifact:N,expectedVersion:F,state:m,situation:B,reason:z.optional()},V=g.strictObject(Pt),Ft=g.strictObject({...Pt,actor:re}),It={valid:[`retired`],retired:[`valid`],proposed:[`decided`],decided:[`fulfilled`,`revoked`],fulfilled:[],revoked:[],open:[`resolved`,`closed-without-resolution`],resolved:[],"closed-without-resolution":[]};function H(e,t){return It[e].includes(t)}const Lt={artifact:N,lifecycle:L,actor:re,timestamp:g.number().int().nonnegative(),observedRevision:a.shape.revision},Rt=g.strictObject({...Lt,operation:g.literal(`initialized`)}).superRefine((e,t)=>{(e.lifecycle.version!==1||e.lifecycle.state!==I[e.lifecycle.category])&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`Initialization requires the category initial state and version 1`})});function zt(e,t){return t===`retired`||e===`retired`&&t===`valid`}const Bt=`Retiring or reinstating knowledge requires a reason`,U=g.strictObject({...Lt,operation:g.literal(`transitioned`),previousState:m,situation:B,reason:V.shape.reason}).superRefine((e,t)=>{(!H(e.previousState,e.lifecycle.state)||e.lifecycle.version<=1)&&t.addIssue({code:`custom`,path:[`lifecycle`],message:`History requires a category-compatible transition after initialization`}),zt(e.previousState,e.lifecycle.state)&&!e.reason&&t.addIssue({code:`custom`,path:[`reason`],message:Bt}),e.situation.kind===`revision-assessment`&&e.situation.assessedRevision!==e.observedRevision&&t.addIssue({code:`custom`,path:[`situation`],message:`An assessment cannot authorize a different observed content revision`})}),Vt=g.discriminatedUnion(`operation`,[Rt,U]),W=g.discriminatedUnion(`reason`,[g.strictObject({reason:g.literal(`lifecycle-version-conflict`),expectedVersion:F,current:L,requestedState:m}),g.strictObject({reason:g.literal(`content-basis-conflict`),assessedRevision:a.shape.revision,currentRevision:a.shape.revision}),g.strictObject({reason:g.literal(`invalid-transition`),current:R,requestedState:m}),g.strictObject({reason:g.literal(`precondition-failed`),current:L,requestedState:m})]),G=`artifact-lifecycle-rejected`;var K=class extends Error{code=G;data;constructor(e,t){super(e),this.name=`ArtifactLifecycleError`,this.data=W.parse(t)}};function Ht(e){return e===`record`?{category:`record`}:L.parse({category:e,state:I[e],version:1})}function Ut(e){let t=R.parse(e.current),n=a.shape.revision.parse(e.currentRevision),r=Ft.parse(e.command);if(t.category===`record`)throw new K(`Record artifacts do not have a lifecycle`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(r.expectedVersion!==t.version)throw new K(`Artifact lifecycle changed since the supplied baseline`,{reason:`lifecycle-version-conflict`,expectedVersion:r.expectedVersion,current:t,requestedState:r.state});if(r.situation.kind===`revision-assessment`&&r.situation.assessedRevision!==n)throw new K(`Assessed content revision is no longer current`,{reason:`content-basis-conflict`,assessedRevision:r.situation.assessedRevision,currentRevision:n});if(!H(t.state,r.state))throw new K(`Artifact lifecycle transition is not allowed`,{reason:`invalid-transition`,current:t,requestedState:r.state});if(zt(t.state,r.state)&&!r.reason)throw new K(Bt,{reason:`precondition-failed`,current:t,requestedState:r.state});return L.parse({...t,state:r.state,version:t.version+1})}const Wt=g.strictObject({artifact:N}),Gt=g.strictObject({lifecycle:R}),Kt=g.strictObject({artifact:N,afterVersion:P.optional(),limit:g.number().int().min(1).max(100).default(50)}),qt=g.strictObject({entries:g.array(Vt).max(100),nextCursor:P.optional()}).superRefine(({entries:e,nextCursor:t},n)=>{let r=e[0],i;for(let[t,a]of e.entries()){let e=a.artifact.kind===r?.artifact.kind&&a.artifact.id===r?.artifact.id,o=i===void 0||a.lifecycle.version===i.lifecycle.version+1,s=i===void 0||a.operation===`transitioned`&&a.lifecycle.category===i.lifecycle.category&&a.previousState===i.lifecycle.state;if(!e||!o||!s){n.addIssue({code:`custom`,path:[`entries`,t],message:`History pages contain one artifact in contiguous ascending, state-linked order`});break}i=a}t!==void 0&&t!==i?.lifecycle.version&&n.addIssue({code:`custom`,path:[`nextCursor`],message:`nextCursor must equal the last returned lifecycle version`})}),q=g.strictObject({entry:U}),Jt=q,Yt=g.strictObject({code:g.literal(G),message:g.string().min(1),data:W});function Xt(e){return{code:e.code,message:e.message,data:e.data}}function Zt(e,t){switch(t.reason){case`content-basis-conflict`:return en(e,t);case`lifecycle-version-conflict`:return[...Qt(e,t),...$t(e,t)];case`invalid-transition`:case`precondition-failed`:return[...Qt(e,t),...tn(e,t)]}}function Qt(e,t){return t.requestedState===e.state?[]:[{path:[`requestedState`],message:`Rejection requestedState must match the rejected transition`}]}function $t(e,t){let n=[];return t.expectedVersion!==e.expectedVersion&&n.push({path:[`expectedVersion`],message:`Version conflict baseline must match the rejected transition`}),t.current.version===e.expectedVersion&&n.push({path:[`current`,`version`],message:`Version conflict requires a current version different from the supplied baseline`}),n}function en(e,t){let n=[];return(e.situation.kind!==`revision-assessment`||t.assessedRevision!==e.situation.assessedRevision)&&n.push({path:[`assessedRevision`],message:`Content conflict must identify the rejected revision assessment`}),t.currentRevision===t.assessedRevision&&n.push({path:[`currentRevision`],message:`Content conflict requires a current revision different from the assessed revision`}),n}function tn(e,t){if(t.current.category===`record`)return[];let n=[];t.current.version!==e.expectedVersion&&n.push({path:[`current`,`version`],message:`A rejection after the version check must report the supplied baseline version`});let r=H(t.current.state,t.requestedState);return t.reason===`invalid-transition`&&r&&n.push({path:[`reason`],message:`invalid-transition requires a transition the lifecycle matrix disallows`}),t.reason===`precondition-failed`&&!r&&n.push({path:[`reason`],message:`precondition-failed requires a transition the lifecycle matrix allows`}),n}const nn=g.strictObject({transition:V,error:Yt}).superRefine(({transition:e,error:t},n)=>{for(let r of Zt(e,t.data))n.addIssue({code:`custom`,path:[`error`,`data`,...r.path],message:r.message})}),rn={"lifecycle.get":{request:Wt,response:Gt},"lifecycle.history":{request:Kt,response:qt},"lifecycle.transition":{request:V,response:q},"lifecycle.committed":Jt,"lifecycle.rejected":nn},an=l.omit({id:!0,slug:!0,revision:!0,timestamp:!0}),on={...rn,"kind.register":{request:le,response:g.object({registered:g.boolean()})},"kind.list":{request:g.object({kind:g.string().min(1).optional()}),response:g.object({kinds:g.array(le)})},"relation-type.register":{request:ae,response:g.object({registered:g.boolean()})},"relation-type.list":{request:g.object({type:g.string().min(1).optional()}),response:g.object({relationTypes:g.array(ae)})},create:{request:an.extend({id:a.shape.id.optional(),slug:l.shape.slug.optional()}),response:g.object({artifact:l})},revise:{request:g.object({previous:a,statusPath:te.optional(),revision:an}),response:g.object({artifact:l})},patch:{request:vt,response:At},resolve:{request:g.object({ref:a}),response:g.object({artifact:l.nullable()})},resolvePart:{request:jt,response:Mt},query:{request:s,response:g.object({artifacts:g.array(l)})},compare:{request:ee,response:ne},"evidence.resolve":{request:ye,response:Ce},resolveContext:{request:g.object({ref:a,selectors:w.optional(),maxDepth:g.number().int().min(1).max(20).default(5)}),response:g.object({context:E})},created:g.object({artifact:l}),revised:g.object({previous:a,artifact:l}),"relation.added":g.object({artifact:a,relation:c}),"observation.added":g.object({artifact:a,observation:u}),"status.changed":g.object({artifact:a,path:g.string().min(1),previous:g.unknown().optional(),current:g.unknown().optional()}),"kind.changed":g.object({kind:g.string().min(1),schemaVersion:p})},sn=ve(`artifact`,on),cn=sn.subjects,ln=g.discriminatedUnion(`refClass`,[a.omit({revision:!0}),o]);function J(e){if(e.refClass===`artifact`)return{refClass:`artifact`,kind:e.kind,id:e.id};if(e.refClass===`entity`)return{refClass:`entity`,entityType:e.entityType,id:e.id}}function Y(e){return e.refClass===`artifact`?JSON.stringify([`artifact`,e.kind,e.id]):JSON.stringify([`entity`,e.entityType,e.id])}function un(e){return e.refClass===`artifact`?`artifact:${e.kind}/${e.id}`:`entity:${e.entityType}/${e.id}`}const dn=[`relation-target`,`data`];function fn(e,t){if(!e||e.length===0)return{ok:!0,rules:[]};let n=[];for(let[r,i]of e.entries()){for(let[e,a]of i.by.entries())(!dn.includes(a.kind)||!t.includes(a.kind))&&n.push({ruleIndex:r,selectorIndex:e,capability:a.kind,message:`rule #${r}, selector #${e}: '${a.kind}' selectors are not supported`});i.lifecycleStates!==void 0&&!t.includes(`lifecycle-states`)&&n.push({ruleIndex:r,capability:`lifecycle-states`,message:`rule #${r}: lifecycleStates is declared but 'lifecycle-states' is not a supported capability`})}return n.length>0?{ok:!1,issues:n}:{ok:!0,rules:e}}function pn(e,t){let n=e;for(let e of t.split(`.`)){if(typeof n!=`object`||!n||Array.isArray(n)||!Object.hasOwn(n,e))return;n=Reflect.get(n,e)}return{value:n}}function mn(e,t,n,r){let{path:i}=e,a=pn(t,i);if(a===void 0||a.value===null||a.value===void 0)return{ruleIndex:n,selectorIndex:r,reason:`missing-value`,dataPath:i,message:`rule #${n}, selector #${r}, data path '${i}': no value found`};let{value:o}=a;return typeof o!=`string`&&typeof o!=`number`&&typeof o!=`boolean`?{ruleIndex:n,selectorIndex:r,reason:`unsupported-value-type`,dataPath:i,message:`rule #${n}, selector #${r}, data path '${i}': value must be a scalar (string, number, or boolean)`}:{path:i,value:o}}function hn(e,t,n,r,i){if(e.kind===`data`)return mn(e,n,r,i);let{relationType:a}=e,o=t.filter(e=>e.type===a&&e.sourceLocalId===void 0),s=new Set,c,l;for(let e of o){let t=J(e.target);if(t===void 0){l=e.target.refClass;break}s.add(Y(t)),c=t}return l===void 0?c===void 0?{ruleIndex:r,selectorIndex:i,reason:`missing-target`,relationType:a,message:`rule #${r}, selector #${i}, relation '${a}': no relations of this type found`}:s.size>1?{ruleIndex:r,selectorIndex:i,reason:`ambiguous-target`,relationType:a,message:`rule #${r}, selector #${i}, relation '${a}': ${s.size} distinct targets; expected exactly one`}:{type:a,target:c}:{ruleIndex:r,selectorIndex:i,reason:`unsupported-target`,relationType:a,message:`rule #${r}, selector #${i}, relation '${a}': found a relation with refClass '${l}'; only artifact and entity targets are supported`}}function gn(e){return`target`in e?[`relation-target`,e.type,Y(e.target)]:[`data`,e.path,e.value]}function _n(e,t,n){let r=[],i=[];for(let[a,o]of e.entries()){let e=o.by.map((e,r)=>hn(e,t,n,a,r)),s=e.filter(e=>`reason`in e);if(s.length>0){i.push(...s);continue}let c=e.filter(e=>!(`reason`in e)),l=JSON.stringify(c.map(e=>gn(e)));r.push({rule:o,ruleIndex:a,parts:c,serialized:l})}return{keys:r,issues:i}}function vn(e){return e.parts.map(e=>`target`in e?`${e.type} → ${un(e.target)}`:`${e.path} → ${JSON.stringify(e.value)}`).join(`; `)}function yn(e,t,n){let r=[];for(let[i,a]of(e??[]).entries()){if(!bn(a,n))continue;let e=xn(a,t);e<a.minItems&&r.push({index:i,requirement:a,reason:`below-min-items`,count:e}),a.maxItems!==void 0&&e>a.maxItems&&r.push({index:i,requirement:a,reason:`above-max-items`,count:e})}return r}function bn(e,t){return e.when===void 0?!0:pn(t,e.when.path)?.value===e.when.equals}function xn(e,t){let n=new Set;for(let r of t){if(r.sourceLocalId!==void 0||r.type!==e.relationType)continue;let t=J(r.target);t?.refClass===`artifact`&&(e.targetKinds?.length&&!e.targetKinds.includes(t.kind)||n.add(Y(t)))}return n.size}var X=class extends Error{type;field;constructor(e,t,n,r){super(`Relation type '${e}' is already registered with different ${t} (existing: '${n}', new: '${r}')`),this.name=`RelationTypeConflictError`,this.type=e,this.field=t}};function Sn(e){return{...e.sourceKinds===void 0?{}:{sourceKinds:e.sourceKinds},...e.targetKinds===void 0?{}:{targetKinds:e.targetKinds},...e.targetRefClasses===void 0?{}:{targetRefClasses:e.targetRefClasses}}}function Z(e){return e.endpoints??[Sn(e)]}function Q(e,t){return e===void 0?!0:t!==void 0&&e.includes(t)}function Cn(e,t){return Q(e.sourceKinds,t.sourceKind)&&Q(e.targetKinds,t.targetKind)&&Q(e.targetRefClasses,t.targetRefClass)}function wn(e,t){let n=e.implication===void 0||e.implication===e.type;if(!(e.symmetry!==`symmetric`||!n||t.targetRefClass!==`artifact`||t.targetKind===void 0))return{sourceKind:t.targetKind,targetRefClass:`artifact`,targetKind:t.sourceKind}}function Tn(e,t){let n=wn(e,t);return Z(e).some(e=>Cn(e,t)||n!==void 0&&Cn(e,n))}function $(e){return e===void 0?void 0:[...new Set(e)].sort()}function En(e){return Sn({sourceKinds:$(e.sourceKinds),targetKinds:$(e.targetKinds),targetRefClasses:$(e.targetRefClasses)})}function Dn(e){return JSON.stringify([e.sourceKinds??null,e.targetKinds??null,e.targetRefClasses??null])}function On(e){return Object.keys(e).length===0}function kn(e){let t=new Map;for(let n of e){let e=En(n);if(On(e))return;t.set(Dn(e),e)}return[...t.entries()].sort(([e],[t])=>e<t?-1:+(e>t)).map(([,e])=>e)}function An(e,t){let n=kn(t);return{type:e.type,symmetry:e.symmetry,...e.implication===void 0?{}:{implication:e.implication},...n===void 0?{}:{endpoints:n}}}function jn(e){return An(e,Z(e))}function Mn(e,t){if(e.implication!==void 0&&t.implication!==void 0&&e.implication!==t.implication)throw new X(e.type,`implication`,e.implication,t.implication);return e.implication??t.implication}function Nn(e,t){if(e.type!==t.type)throw Error(`Cannot merge relation type '${t.type}' into relation type '${e.type}'`);if(e.symmetry!==t.symmetry)throw new X(e.type,`symmetry`,e.symmetry,t.symmetry);let n=Mn(e,t);return An({type:e.type,symmetry:e.symmetry,implication:n},[...Z(e),...Z(t)])}export{St as $,N as A,Ht as B,rn as C,Ue as Ct,R as D,ye as Dt,G as E,Oe as Et,Ft as F,D as G,jt as H,V as I,Et as J,ut as K,U as L,W as M,B as N,K as O,Ce as Ot,L as P,Ct as Q,P as R,nn as S,We as St,Xt as T,ke as Tt,Mt as U,H as V,yt as W,kt as X,xt as Y,bt as Z,Yt as _,Ge as _t,yn as a,_t as at,Kt as b,S as bt,vn as c,lt as ct,un as d,Xe as dt,A as et,Y as f,Ye as ft,Jt as g,Ke as gt,cn as h,T as ht,Tn as i,Ot as it,Rt as j,Vt as k,ln as l,st as lt,on as m,E as mt,Nn as n,vt as nt,fn as o,dt as ot,sn as p,Je as pt,ht as q,jn as r,At as rt,_n as s,M as st,X as t,Dt as tt,J as u,ct as ut,Wt as v,C as vt,q as w,He as wt,qt as x,w as xt,Gt as y,qe as yt,Ut as z};
|
package/dist/bus/index.d.mts
CHANGED
|
@@ -2364,17 +2364,17 @@ interface MakaioBusContext {
|
|
|
2364
2364
|
priority: number;
|
|
2365
2365
|
}>>;
|
|
2366
2366
|
/**
|
|
2367
|
-
* Set of transport names that
|
|
2368
|
-
* (
|
|
2369
|
-
*
|
|
2370
|
-
*
|
|
2371
|
-
*
|
|
2372
|
-
* if a remote has event-only handlers for a subject, peers should still receive a
|
|
2373
|
-
* `subscribe` (with an empty priority array) rather than an `unsubscribe`.
|
|
2367
|
+
* Set of transport names that subscribed to each subject with event-only handlers
|
|
2368
|
+
* (subscribe messages whose priority array was empty). Tracked separately from `remoteRequestHandlers`
|
|
2369
|
+
* because event-only subscriptions produce no priority entries yet must still influence advertised-state
|
|
2370
|
+
* decisions: if a remote has event-only handlers for a subject, peers should still receive a `subscribe`
|
|
2371
|
+
* (with an empty priority array) rather than an `unsubscribe`.
|
|
2374
2372
|
*/
|
|
2375
2373
|
remoteEventHandlers: Map<string, Set<string>>;
|
|
2376
2374
|
/** Owner-derived delivery semantics keyed by subject pattern and source transport. */
|
|
2377
2375
|
remoteSubscriptionDeliveryClasses: Map<string, Map<string, SubscriptionDeliveryClass>>;
|
|
2376
|
+
/** Failure-safe sink for internal bus diagnostics; resolved once from `CreateBusOptions.debugLog`. */
|
|
2377
|
+
debugLog: (message: string) => void;
|
|
2378
2378
|
}
|
|
2379
2379
|
/**
|
|
2380
2380
|
* Result of registering a transport on the bus.
|
|
@@ -3323,6 +3323,24 @@ declare function matchesSubscription(subject: string, pattern: string): boolean;
|
|
|
3323
3323
|
*/
|
|
3324
3324
|
declare function matchesAnySubscription(subject: string, patterns: Iterable<string>): boolean;
|
|
3325
3325
|
//#endregion
|
|
3326
|
+
//#region core/bus-core/src/utils/debug-log.d.ts
|
|
3327
|
+
/**
|
|
3328
|
+
* Sink for internal bus diagnostics (one formatted line per call).
|
|
3329
|
+
*/
|
|
3330
|
+
type BusDebugLog = (message: string) => void;
|
|
3331
|
+
/**
|
|
3332
|
+
* Wrap a diagnostic sink so it can never change caller state.
|
|
3333
|
+
*
|
|
3334
|
+
* A diagnostic sink is observational only: a synchronous throw or a rejected
|
|
3335
|
+
* thenable returned by the callback (assignable to the `void`-returning type) is
|
|
3336
|
+
* swallowed instead of failing propagation, sync, or dispatch. The failure is
|
|
3337
|
+
* dropped deliberately: there is no safe channel to report it on (stdout may be a
|
|
3338
|
+
* protocol channel, and reporting through the same sink would recurse).
|
|
3339
|
+
* @param sink - Sink to wrap
|
|
3340
|
+
* @returns Sink that never throws and never leaves an unhandled rejection
|
|
3341
|
+
*/
|
|
3342
|
+
declare function toSafeDebugLog(sink: BusDebugLog): BusDebugLog;
|
|
3343
|
+
//#endregion
|
|
3326
3344
|
//#region core/bus-core/src/errors/bus-error.d.ts
|
|
3327
3345
|
/**
|
|
3328
3346
|
* Base error class for all bus-related errors.
|
|
@@ -3496,9 +3514,10 @@ declare class ValidationError extends BusError {
|
|
|
3496
3514
|
* Used internally by createBusInstance to manage event and request handlers.
|
|
3497
3515
|
* Can be used to create isolated bus instances (e.g., for testing) by providing
|
|
3498
3516
|
* separate handler maps per instance.
|
|
3517
|
+
* @param debugLog - Optional diagnostic sink; defaults to `console.debug`. Wrapped so it never throws.
|
|
3499
3518
|
* @returns A new MakaioBusContext instance with empty handler registries
|
|
3500
3519
|
*/
|
|
3501
|
-
declare const createBusContext: () => MakaioBusContext;
|
|
3520
|
+
declare const createBusContext: (debugLog?: (message: string) => void) => MakaioBusContext;
|
|
3502
3521
|
/**
|
|
3503
3522
|
* Options for creating a bus instance.
|
|
3504
3523
|
*/
|
|
@@ -3509,6 +3528,17 @@ interface CreateBusOptions<Namespace extends string | undefined = undefined> {
|
|
|
3509
3528
|
namespace?: Namespace;
|
|
3510
3529
|
/** Transports to register immediately after creation. */
|
|
3511
3530
|
transports?: BusTransport[];
|
|
3531
|
+
/**
|
|
3532
|
+
* Sink for internal bus diagnostics (subscription propagation and
|
|
3533
|
+
* subscribe-sync-complete failures, readiness-budget expiry). One formatted line
|
|
3534
|
+
* per call. Defaults to `console.debug`, so browser visibility is unchanged; a
|
|
3535
|
+
* Node CLI can pass a stderr writer. A throwing or rejecting sink never changes bus
|
|
3536
|
+
* state. With an explicit `context`, this replaces that context's sink.
|
|
3537
|
+
*
|
|
3538
|
+
* Named `debugLog` to match the transports' `debugLog` option (same
|
|
3539
|
+
* `(message: string) => void` shape).
|
|
3540
|
+
*/
|
|
3541
|
+
debugLog?: (message: string) => void;
|
|
3512
3542
|
}
|
|
3513
3543
|
/**
|
|
3514
3544
|
* Creates a new bus instance with optional context, namespace isolation, and transports.
|
|
@@ -4355,4 +4385,4 @@ interface ProjectedTelemetryTransportOptions {
|
|
|
4355
4385
|
*/
|
|
4356
4386
|
declare function createProjectedTelemetryTransport(options: ProjectedTelemetryTransportOptions): BusTransport;
|
|
4357
4387
|
//#endregion
|
|
4358
|
-
export { type BroadcastContext, type BroadcastResult, BusAbortError, type BusBroadcastMessage, type BusBroadcastResponseMessage, BusError, type BusEventMessage, type BusHeartbeatMessage, BusLifecycle, type BusMessage, type BusMessageObserver, type BusNamespace, type BusReceiveHandler, type BusRequestMessage, type BusResponseMessage, type BusSubscribeMessage, type BusSubscribeSyncCompleteMessage, type BusSubscriptionAckMessage, type BusTransport, type BusTransportError, type BusTransportKeys, type BusTransportRegistry, type BusUnsubscribeMessage, type BusUrlConfig, type BusValidationMode, CONNECTION_LOST_ERROR_CODE, ChannelAuthError, ChannelClosedError, type ChannelEndpoint, type ChannelEndpointOptions, ChannelOnlyError, type ConnectOptions, type ConnectedPayload, ConnectionLostError, CorrelationTracker, DEFAULT_READINESS_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, type DefinedSubjectExtension, type DisconnectedPayload, type EmitOptions, type EventSubjectExtension, type ExtendedSubjectDefinition, type ExtensionNamespace, type ExtensionNamespaceConfig, type ExtensionNamespaceExtensions, type ExtensionNamespaceFromConfig, type IDirectChannel, type IFilteredBus, type IMakaioBus, type InterceptorContext, LOCAL_ORIGIN, LocalSubjectError, MakaioBus, type MakaioBusContext, NO_HANDLER_ERROR_CODE, type NamespaceRegistrationOptions, NoHandlerError, type ObservedBusMessage, type OnOptions, OnceAbortError, type OptionalResult, type PendingReadyEntry, type ProjectableBusMessage, type ProjectedTelemetryTransportOptions, REMOTE_ORIGIN, RequestError, type RequestOptions, type RequestSubjectExtension, type SchemaViolationCallback, type SchemaViolationReport, type ScopedBus, type ScopedBusFor, type SubjectExtension, type SubjectTelemetryAttributes, type SubjectTelemetryProjectionInput, type SubjectTelemetryProjector, type SubjectTelemetryProjectorInput, type SubjectTelemetryProjectorRegistry, type SubscriptionDeliveryClass, type SubscriptionEntry, SystemChannelSchemas, TimeoutError, type TransportRegistration, ValidationError, __resetWarnedSubjects, buildSubscribeMessage, buildUnsubscribeMessage, channelSubject, collectorOnlySubject, createBusContext, createBusInstance, createChannelEndpoint, createExtensionNamespace, createFilteredBus, createProjectedTelemetryTransport, createSubjectTelemetryProjectorRegistry, defaultTransports, defineSubjectExtension, deserializeTransportError, extendSubjectImpl as extendSubject, findInErrorChain, getFullSubjectForSubjectDefinition, getPath, getSubjectFromBusMessage, handleCorrelationResponse, hostLocalRequest, isNoHandlerErrorForSubject, isRequestCancellation, isRequestSchema, localSubject, matchesAnySubscription, matchesFilter, matchesSubscription, mergeFilters, openChannel, parseBusUrl, projectSubjectTelemetryFacts, serializeTransportError, shouldReceiveMessage, trackMessageCorrelation, transportErrorData, waitForSubscriptionPropagation };
|
|
4388
|
+
export { type BroadcastContext, type BroadcastResult, BusAbortError, type BusBroadcastMessage, type BusBroadcastResponseMessage, type BusDebugLog, BusError, type BusEventMessage, type BusHeartbeatMessage, BusLifecycle, type BusMessage, type BusMessageObserver, type BusNamespace, type BusReceiveHandler, type BusRequestMessage, type BusResponseMessage, type BusSubscribeMessage, type BusSubscribeSyncCompleteMessage, type BusSubscriptionAckMessage, type BusTransport, type BusTransportError, type BusTransportKeys, type BusTransportRegistry, type BusUnsubscribeMessage, type BusUrlConfig, type BusValidationMode, CONNECTION_LOST_ERROR_CODE, ChannelAuthError, ChannelClosedError, type ChannelEndpoint, type ChannelEndpointOptions, ChannelOnlyError, type ConnectOptions, type ConnectedPayload, ConnectionLostError, CorrelationTracker, DEFAULT_READINESS_TIMEOUT_MS, DEFAULT_REQUEST_TIMEOUT_MS, type DefinedSubjectExtension, type DisconnectedPayload, type EmitOptions, type EventSubjectExtension, type ExtendedSubjectDefinition, type ExtensionNamespace, type ExtensionNamespaceConfig, type ExtensionNamespaceExtensions, type ExtensionNamespaceFromConfig, type IDirectChannel, type IFilteredBus, type IMakaioBus, type InterceptorContext, LOCAL_ORIGIN, LocalSubjectError, MakaioBus, type MakaioBusContext, NO_HANDLER_ERROR_CODE, type NamespaceRegistrationOptions, NoHandlerError, type ObservedBusMessage, type OnOptions, OnceAbortError, type OptionalResult, type PendingReadyEntry, type ProjectableBusMessage, type ProjectedTelemetryTransportOptions, REMOTE_ORIGIN, RequestError, type RequestOptions, type RequestSubjectExtension, type SchemaViolationCallback, type SchemaViolationReport, type ScopedBus, type ScopedBusFor, type SubjectExtension, type SubjectTelemetryAttributes, type SubjectTelemetryProjectionInput, type SubjectTelemetryProjector, type SubjectTelemetryProjectorInput, type SubjectTelemetryProjectorRegistry, type SubscriptionDeliveryClass, type SubscriptionEntry, SystemChannelSchemas, TimeoutError, type TransportRegistration, ValidationError, __resetWarnedSubjects, buildSubscribeMessage, buildUnsubscribeMessage, channelSubject, collectorOnlySubject, createBusContext, createBusInstance, createChannelEndpoint, createExtensionNamespace, createFilteredBus, createProjectedTelemetryTransport, createSubjectTelemetryProjectorRegistry, defaultTransports, defineSubjectExtension, deserializeTransportError, extendSubjectImpl as extendSubject, findInErrorChain, getFullSubjectForSubjectDefinition, getPath, getSubjectFromBusMessage, handleCorrelationResponse, hostLocalRequest, isNoHandlerErrorForSubject, isRequestCancellation, isRequestSchema, localSubject, matchesAnySubscription, matchesFilter, matchesSubscription, mergeFilters, openChannel, parseBusUrl, projectSubjectTelemetryFacts, serializeTransportError, shouldReceiveMessage, toSafeDebugLog, trackMessageCorrelation, transportErrorData, waitForSubscriptionPropagation };
|
package/dist/bus/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as ee,M as te,N as f,O as ne,P as re,Q as p,R as m,S as h,T as ie,U as ae,V as g,W as oe,X as se,Y as ce,Z as le,_ as ue,a as de,at as fe,b as pe,d as _,et as me,f as he,g as v,h as y,i as ge,it as b,j as x,k as S,l as C,m as w,nt as T,o as E,p as D,q as O,r as k,rt as A,s as j,t as M,tt as N,u as P,v as F,w as I,x as L,y as _e,z as ve}from"../bus--m38BS3i.mjs";import{z as R}from"zod";const z={"channel.open":{request:R.object({endpoint:R.string(),token:R.string(),clientPubKey:R.string(),transports:R.array(R.string())}),response:R.object({channelId:R.string(),endpointPubKey:R.string()})}};function B(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array(t.length);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return btoa(n.join(``))}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function H(){return globalThis.crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`])}async function U(e){return B(await globalThis.crypto.subtle.exportKey(`raw`,e))}async function W(e){let t=V(e);return globalThis.crypto.subtle.importKey(`raw`,t,{name:`ECDH`,namedCurve:`P-256`},!1,[])}async function G(e,t){return globalThis.crypto.subtle.deriveKey({name:`ECDH`,public:t},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function K(e,t,n){let r=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.encrypt(a,e,i);return{iv:B(r),data:B(o)}}async function q(e,t,n){let r=V(t.iv),i=V(t.data),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.decrypt(a,e,i);return new TextDecoder().decode(o)}function J(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!1,payload:{},local:!1,channel:!1}}}function Y(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!0,payload:{},local:!1,channel:!1}}}var X=class{channelId;sharedKey;context;transportNames;cleanups=[];pendingRequests=new Set;closed=!1;constructor(e,t,n,r){this.channelId=e,this.sharedKey=t,this.context=n,this.transportNames=r;let i=J(e,`$close`);this.cleanups.push(this.registerEventHandler(i,t,e=>{this.handlePeerClose()}))}on(e,t,n){this.assertOpen();let r=this.requireKey(),i=e.$meta.isRequest?this.registerRequestHandler(e,r,t,n):this.registerEventHandler(e,r,t,n);return this.cleanups.push(i),()=>{i();let e=this.cleanups.indexOf(i);e!==-1&&this.cleanups.splice(e,1)}}once(e,t){this.assertOpen();let n=this.requireKey(),r=null,i=(e=>{let n=r;if(r=null,n){let e=this.cleanups.indexOf(n);e!==-1&&this.cleanups.splice(e,1)}return n?.(),t(e)});return r=e.$meta.isRequest?this.registerRequestHandler(e,n,i):this.registerEventHandler(e,n,i),this.cleanups.push(r),()=>{if(r){let e=r;r=null;let t=this.cleanups.indexOf(e);t!==-1&&this.cleanups.splice(t,1),e()}}}async emit(e,t){this.assertOpen();let n=this.requireKey(),r=J(this.channelId,e.subject),i=await K(n,JSON.stringify(t),`${this.channelId}:${e.subject}:evt`);await w(this.context,r,i,{...this.transportNames?{transports:[...this.transportNames]}:{}})}async request(e,t,n){this.assertOpen();let r=this.requireKey(),i=new AbortController;this.pendingRequests.add(i);try{let a=Y(this.channelId,e.subject),o=await K(r,JSON.stringify(t),`${this.channelId}:${e.subject}:req`),s=await q(r,await _(this.context,a,o,{signal:i.signal,...n?.timeout===void 0?{}:{timeout:n.timeout},...this.transportNames?{transports:[...this.transportNames]}:{}}),`${this.channelId}:${e.subject}:res`);return JSON.parse(s)}finally{this.pendingRequests.delete(i)}}async requestOptional(e,t,n){try{return{handled:!0,data:await this.request(e,t,n)}}catch(e){if(e instanceof l)return{handled:!1};throw e}}close(){if(this.closed)return;this.closed=!0;let e=this.sharedKey;if(e){let t=J(this.channelId,`$close`);K(e,JSON.stringify({}),`${this.channelId}:$close:evt`).then(e=>w(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new g(this.channelId)}requireKey(){return this.sharedKey}registerEventHandler(e,t,n,r){let i=J(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:evt`;return v(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r);return n({...e,payload:i})},r)}registerRequestHandler(e,t,n,r){let i=Y(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:req`,o=`${this.channelId}:${e.subject}:res`;return v(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r),s,c=e=>{s={value:e}},l=e=>{s={value:{...s?.value??{},...e}}},u=async()=>{let n=s;if(await e.next(),n!==void 0){s=n;return}let r=e.result;if(r!==void 0){let e=await q(t,r,o);s={value:JSON.parse(e)}}};if(await n({...e,payload:i,get result(){return s?.value},setResult:c,extendResult:l,next:u}),s!==void 0){let n=await K(t,JSON.stringify(s.value),o);e.setResult(n)}},r)}handlePeerClose(){this.closed||(this.closed=!0,this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null)}abortPendingRequests(){let e=new g(this.channelId);for(let t of this.pendingRequests)t.abort(e);this.pendingRequests.clear()}runCleanups(){for(let e of this.cleanups)try{e()}catch{}this.cleanups.length=0}};function Z(e){return e.namespaceRegistry.registerNamespace(p(`system`,z)).subjects.channel.open}function ye(e,t,n,r){let i=v(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new c(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),l=globalThis.crypto.randomUUID(),u=new Set(e.transportRegistry.names()),d=new X(l,s,e,(i.payload.transports??[]).filter(e=>u.has(e)));try{n(d),i.setResult({channelId:l,endpointPubKey:await U(a)})}catch(e){throw d.close(),e}});return{name:t,token:r.token,close:i}}async function be(e,t,n){let r=Z(e),{publicKey:i,privateKey:a}=await H(),o=await U(i),s=n.transports!==void 0,c=s?[...n.transports]:[...e.transportRegistry.names()],l=s?{transports:c}:void 0,u=await _(e,r,{endpoint:t,token:n.token,clientPubKey:o,transports:c},l),d=await G(a,await W(u.endpointPubKey));return new X(u.channelId,d,e,c)}var xe=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(s(n.reason));return}let a=t===0?void 0:setTimeout(()=>{let n=this.pending.get(e);n!==void 0&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(new f(e,t)))},t);if(this.pending.set(e,{resolve:r,reject:i,timeoutId:a,removeAbortListener:void 0}),n){let t=()=>{this.reject(e,s(n.reason))};n.addEventListener(`abort`,t,{once:!0});let r=()=>{n.removeEventListener(`abort`,t)},i=this.pending.get(e);i&&(i.removeAbortListener=r)}n?.aborted&&this.reject(e,s(n.reason))})}resolve(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.resolve(t))}reject(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(t))}cancel(e,t){this.reject(e,t??s(void 0))}rejectAll(e){for(let[t,n]of this.pending.entries())clearTimeout(n.timeoutId),n.removeAbortListener?.(),n.reject(e);this.pending.clear()}cleanup(){this.rejectAll(Error(`Transport disconnected`))}};const Se=p(`bus:lifecycle`,de).subjects;function Ce(e,t){let n={},r={},i={};for(let[t,a]of e)n[t]=a.priorities,r[t]=a.deliveryClass??`relayable`,a.filter!==void 0&&(i[t]=a.filter);return{type:`subscribe`,...t===void 0?{}:{ackId:t},subjects:n,deliveryClasses:r,...Object.keys(i).length>0&&{filters:i}}}function we(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Q(e,t){let n=e.trim();if(n.length===0||n.startsWith(`extension:`))throw Error(`Invalid extensionName: expected a non-empty extension name without the "extension:" prefix.`);let r=n;return{...p(`extension:${r}`,t.schemas),domain:r,extensions:t.extensions??{}}}function $(e,t){return`${e}.${t}`}function Te(){let e=new Map;return{register(t){let n=$(t.namespace,t.subject);return e.set(n,t),()=>{e.get(n)===t&&e.delete(n)}},get(t,n){return e.get($(t,n))}}}const Ee=x.fact.$meta.namespace,De=x.fact.subject;function Oe(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function ke(e,t,n,r,i,a){let o=y({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:Ee,subject:De,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function Ae(e,t,n,r,i){return async function(a,o){if(!Oe(a))return!0;if(await ke(e,a,t,n,r,i),a.type===`request`)throw Error(`Projected telemetry transport cannot satisfy request responses; exclude it from request routing.`);return a.type===`broadcast`?[]:!0}}function je(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:Ae(t,n,r,i,a),onReceive(e){return t.onReceive(async()=>{})},connect(){return t.connect()},disconnect(){return t.disconnect()},subscribe(){return Promise.resolve()},unsubscribe(){return Promise.resolve()},get ready(){return t.ready},get onNewReadySession(){return t.onNewReadySession},set onNewReadySession(e){t.onNewReadySession=e},get onConnected(){return t.onConnected},set onConnected(e){t.onConnected=e},get onDisconnected(){return t.onDisconnected},set onDisconnected(e){t.onDisconnected=e},isReady(){return t.isReady?.()??!0},cancelRequest(e,n){t.cancelRequest?.(e,n)},onBroadcastResults(e,n,r){t.onBroadcastResults?.(e,n,r)}};return t.reconnect&&(o.reconnect=()=>t.reconnect()),o}export{ae as BusAbortError,d as BusError,Se as BusLifecycle,m as CONNECTION_LOST_ERROR_CODE,c as ChannelAuthError,g as ChannelClosedError,n as ChannelOnlyError,ve as ConnectionLostError,xe as CorrelationTracker,he as DEFAULT_READINESS_TIMEOUT_MS,D as DEFAULT_REQUEST_TIMEOUT_MS,pe as LOCAL_ORIGIN,ee as LocalSubjectError,M as MakaioBus,o as NO_HANDLER_ERROR_CODE,l as NoHandlerError,P as OnceAbortError,L as REMOTE_ORIGIN,re as RequestError,z as SystemChannelSchemas,f as TimeoutError,te as ValidationError,F as __resetWarnedSubjects,Ce as buildSubscribeMessage,we as buildUnsubscribeMessage,b as channelSubject,me as collectorOnlySubject,k as createBusContext,ge as createBusInstance,ye as createChannelEndpoint,Q as createExtensionNamespace,C as createFilteredBus,je as createProjectedTelemetryTransport,Te as createSubjectTelemetryProjectorRegistry,N as defaultTransports,E as defineSubjectExtension,a as deserializeTransportError,j as extendSubject,i as findInErrorChain,e as getFullSubjectForSubjectDefinition,O as getPath,ne as getSubjectFromBusMessage,h as handleCorrelationResponse,T as hostLocalRequest,S as isNoHandlerErrorForSubject,oe as isRequestCancellation,fe as isRequestSchema,A as localSubject,se as matchesAnySubscription,u as matchesFilter,le as matchesSubscription,ce as mergeFilters,be as openChannel,_e as parseBusUrl,y as projectSubjectTelemetryFacts,r as serializeTransportError,I as shouldReceiveMessage,ie as trackMessageCorrelation,t as transportErrorData,ue as waitForSubscriptionPropagation};
|
|
1
|
+
import{$ as e,A as t,B as n,C as r,D as i,E as a,F as o,G as s,H as c,I as l,J as u,K as d,L as f,M as p,N as ee,O as te,P as m,Q as ne,R as re,S as h,T as ie,U as g,V as ae,W as oe,X as se,Y as ce,Z as le,_ as ue,a as de,at as fe,b as pe,d as _,et as me,f as he,g as v,h as y,i as ge,it as b,j as x,k as S,l as C,m as w,nt as T,o as E,ot as D,p as O,q as k,r as A,rt as j,s as M,t as N,tt as P,u as F,v as I,w as L,x as _e,y as ve,z as ye}from"../bus-CtT6XeB_.mjs";import{z as R}from"zod";const z={"channel.open":{request:R.object({endpoint:R.string(),token:R.string(),clientPubKey:R.string(),transports:R.array(R.string())}),response:R.object({channelId:R.string(),endpointPubKey:R.string()})}};function B(e){let t=e instanceof Uint8Array?e:new Uint8Array(e),n=Array(t.length);for(let e=0;e<t.length;e++)n[e]=String.fromCharCode(t[e]);return btoa(n.join(``))}function V(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n.buffer}async function H(){return globalThis.crypto.subtle.generateKey({name:`ECDH`,namedCurve:`P-256`},!1,[`deriveKey`])}async function U(e){return B(await globalThis.crypto.subtle.exportKey(`raw`,e))}async function W(e){let t=V(e);return globalThis.crypto.subtle.importKey(`raw`,t,{name:`ECDH`,namedCurve:`P-256`},!1,[])}async function G(e,t){return globalThis.crypto.subtle.deriveKey({name:`ECDH`,public:t},e,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`])}async function K(e,t,n){let r=globalThis.crypto.getRandomValues(new Uint8Array(12)),i=new TextEncoder().encode(t),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.encrypt(a,e,i);return{iv:B(r),data:B(o)}}async function q(e,t,n){let r=V(t.iv),i=V(t.data),a={name:`AES-GCM`,iv:r};n!==void 0&&(a.additionalData=new TextEncoder().encode(n));let o=await globalThis.crypto.subtle.decrypt(a,e,i);return new TextDecoder().decode(o)}function J(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!1,payload:{},local:!1,channel:!1}}}function Y(e,t){return{subject:t,$meta:{namespace:`channel:${e}`,isRequest:!0,payload:{},local:!1,channel:!1}}}var X=class{channelId;sharedKey;context;transportNames;cleanups=[];pendingRequests=new Set;closed=!1;constructor(e,t,n,r){this.channelId=e,this.sharedKey=t,this.context=n,this.transportNames=r;let i=J(e,`$close`);this.cleanups.push(this.registerEventHandler(i,t,e=>{this.handlePeerClose()}))}on(e,t,n){this.assertOpen();let r=this.requireKey(),i=e.$meta.isRequest?this.registerRequestHandler(e,r,t,n):this.registerEventHandler(e,r,t,n);return this.cleanups.push(i),()=>{i();let e=this.cleanups.indexOf(i);e!==-1&&this.cleanups.splice(e,1)}}once(e,t){this.assertOpen();let n=this.requireKey(),r=null,i=(e=>{let n=r;if(r=null,n){let e=this.cleanups.indexOf(n);e!==-1&&this.cleanups.splice(e,1)}return n?.(),t(e)});return r=e.$meta.isRequest?this.registerRequestHandler(e,n,i):this.registerEventHandler(e,n,i),this.cleanups.push(r),()=>{if(r){let e=r;r=null;let t=this.cleanups.indexOf(e);t!==-1&&this.cleanups.splice(t,1),e()}}}async emit(e,t){this.assertOpen();let n=this.requireKey(),r=J(this.channelId,e.subject),i=await K(n,JSON.stringify(t),`${this.channelId}:${e.subject}:evt`);await w(this.context,r,i,{...this.transportNames?{transports:[...this.transportNames]}:{}})}async request(e,t,n){this.assertOpen();let r=this.requireKey(),i=new AbortController;this.pendingRequests.add(i);try{let a=Y(this.channelId,e.subject),o=await K(r,JSON.stringify(t),`${this.channelId}:${e.subject}:req`),s=await q(r,await _(this.context,a,o,{signal:i.signal,...n?.timeout===void 0?{}:{timeout:n.timeout},...this.transportNames?{transports:[...this.transportNames]}:{}}),`${this.channelId}:${e.subject}:res`);return JSON.parse(s)}finally{this.pendingRequests.delete(i)}}async requestOptional(e,t,n){try{return{handled:!0,data:await this.request(e,t,n)}}catch(e){if(e instanceof f)return{handled:!1};throw e}}close(){if(this.closed)return;this.closed=!0;let e=this.sharedKey;if(e){let t=J(this.channelId,`$close`);K(e,JSON.stringify({}),`${this.channelId}:$close:evt`).then(e=>w(this.context,t,e,{...this.transportNames?{transports:[...this.transportNames]}:{}})).catch(()=>{})}this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null}assertOpen(){if(this.closed)throw new c(this.channelId)}requireKey(){return this.sharedKey}registerEventHandler(e,t,n,r){let i=J(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:evt`;return v(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r);return n({...e,payload:i})},r)}registerRequestHandler(e,t,n,r){let i=Y(this.channelId,e.subject),a=`${this.channelId}:${e.subject}:req`,o=`${this.channelId}:${e.subject}:res`;return v(this.context,i,async e=>{let r=await q(t,e.payload,a),i=JSON.parse(r),s,c=e=>{s={value:e}},l=e=>{s={value:{...s?.value??{},...e}}},u=async()=>{let n=s;if(await e.next(),n!==void 0){s=n;return}let r=e.result;if(r!==void 0){let e=await q(t,r,o);s={value:JSON.parse(e)}}};if(await n({...e,payload:i,get result(){return s?.value},setResult:c,extendResult:l,next:u}),s!==void 0){let n=await K(t,JSON.stringify(s.value),o);e.setResult(n)}},r)}handlePeerClose(){this.closed||(this.closed=!0,this.abortPendingRequests(),this.runCleanups(),this.sharedKey=null)}abortPendingRequests(){let e=new c(this.channelId);for(let t of this.pendingRequests)t.abort(e);this.pendingRequests.clear()}runCleanups(){for(let e of this.cleanups)try{e()}catch{}this.cleanups.length=0}};function Z(t){return t.namespaceRegistry.registerNamespace(e(`system`,z)).subjects.channel.open}function be(e,t,n,r){let i=v(e,Z(e),async i=>{if(i.payload.endpoint!==t){await i.next();return}if(i.payload.token!==r.token)throw new g(t);let{publicKey:a,privateKey:o}=await H(),s=await G(o,await W(i.payload.clientPubKey)),c=globalThis.crypto.randomUUID(),l=new Set(e.transportRegistry.names()),u=new X(c,s,e,(i.payload.transports??[]).filter(e=>l.has(e)));try{n(u),i.setResult({channelId:c,endpointPubKey:await U(a)})}catch(e){throw u.close(),e}});return{name:t,token:r.token,close:i}}async function xe(e,t,n){let r=Z(e),{publicKey:i,privateKey:a}=await H(),o=await U(i),s=n.transports!==void 0,c=s?[...n.transports]:[...e.transportRegistry.names()],l=s?{transports:c}:void 0,u=await _(e,r,{endpoint:t,token:n.token,clientPubKey:o,transports:c},l),d=await G(a,await W(u.endpointPubKey));return new X(u.channelId,d,e,c)}var Se=class{pending;constructor(){this.pending=new Map}track(e,t,n){return new Promise((r,i)=>{if(n?.aborted){i(d(n.reason));return}let a=t===0?void 0:setTimeout(()=>{let n=this.pending.get(e);n!==void 0&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(new m(e,t)))},t);if(this.pending.set(e,{resolve:r,reject:i,timeoutId:a,removeAbortListener:void 0}),n){let t=()=>{this.reject(e,d(n.reason))};n.addEventListener(`abort`,t,{once:!0});let r=()=>{n.removeEventListener(`abort`,t)},i=this.pending.get(e);i&&(i.removeAbortListener=r)}n?.aborted&&this.reject(e,d(n.reason))})}resolve(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.resolve(t))}reject(e,t){let n=this.pending.get(e);n&&(clearTimeout(n.timeoutId),n.removeAbortListener?.(),this.pending.delete(e),n.reject(t))}cancel(e,t){this.reject(e,t??d(void 0))}rejectAll(e){for(let[t,n]of this.pending.entries())clearTimeout(n.timeoutId),n.removeAbortListener?.(),n.reject(e);this.pending.clear()}cleanup(){this.rejectAll(Error(`Transport disconnected`))}};const Ce=e(`bus:lifecycle`,de).subjects;function we(e,t){let n={},r={},i={};for(let[t,a]of e)n[t]=a.priorities,r[t]=a.deliveryClass??`relayable`,a.filter!==void 0&&(i[t]=a.filter);return{type:`subscribe`,...t===void 0?{}:{ackId:t},subjects:n,deliveryClasses:r,...Object.keys(i).length>0&&{filters:i}}}function Q(e,t){return{type:`unsubscribe`,...t===void 0?{}:{ackId:t},subjects:e}}function Te(t,n){let r=t.trim();if(r.length===0||r.startsWith(`extension:`))throw Error(`Invalid extensionName: expected a non-empty extension name without the "extension:" prefix.`);let i=r;return{...e(`extension:${i}`,n.schemas),domain:i,extensions:n.extensions??{}}}function $(e,t){return`${e}.${t}`}function Ee(){let e=new Map;return{register(t){let n=$(t.namespace,t.subject);return e.set(n,t),()=>{e.get(n)===t&&e.delete(n)}},get(t,n){return e.get($(t,n))}}}const De=p.fact.$meta.namespace,Oe=p.fact.subject;function ke(e){return e.type===`event`||e.type===`request`||e.type===`broadcast`}async function Ae(e,t,n,r,i,a){let o=y({message:t,direction:`outbound`,observedAt:a(),machineId:i,namespaceRegistry:n,projectorRegistry:r});for(let n of o)await e.send({type:`event`,namespace:De,subject:Oe,payload:n,messageId:`${t.messageId}:telemetry:${n.factId}`,correlationId:t.correlationId})}function je(e,t,n,r,i){return async function(a,o){if(!ke(a))return!0;if(await Ae(e,a,t,n,r,i),a.type===`request`)throw Error(`Projected telemetry transport cannot satisfy request responses; exclude it from request routing.`);return a.type===`broadcast`?[]:!0}}function Me(e){let{inner:t,namespaceRegistry:n,projectorRegistry:r,machineId:i,now:a=Date.now}=e,o={name:e.name,send:je(t,n,r,i,a),onReceive(e){return t.onReceive(async()=>{})},connect(){return t.connect()},disconnect(){return t.disconnect()},subscribe(){return Promise.resolve()},unsubscribe(){return Promise.resolve()},get ready(){return t.ready},get onNewReadySession(){return t.onNewReadySession},set onNewReadySession(e){t.onNewReadySession=e},get onConnected(){return t.onConnected},set onConnected(e){t.onConnected=e},get onDisconnected(){return t.onDisconnected},set onDisconnected(e){t.onDisconnected=e},isReady(){return t.isReady?.()??!0},cancelRequest(e,n){t.cancelRequest?.(e,n)},onBroadcastResults(e,n,r){t.onBroadcastResults?.(e,n,r)}};return t.reconnect&&(o.reconnect=()=>t.reconnect()),o}export{oe as BusAbortError,k as BusError,Ce as BusLifecycle,ye as CONNECTION_LOST_ERROR_CODE,g as ChannelAuthError,c as ChannelClosedError,ae as ChannelOnlyError,n as ConnectionLostError,Se as CorrelationTracker,he as DEFAULT_READINESS_TIMEOUT_MS,O as DEFAULT_REQUEST_TIMEOUT_MS,_e as LOCAL_ORIGIN,re as LocalSubjectError,N as MakaioBus,l as NO_HANDLER_ERROR_CODE,f as NoHandlerError,F as OnceAbortError,h as REMOTE_ORIGIN,o as RequestError,z as SystemChannelSchemas,m as TimeoutError,ee as ValidationError,I as __resetWarnedSubjects,we as buildSubscribeMessage,Q as buildUnsubscribeMessage,fe as channelSubject,P as collectorOnlySubject,A as createBusContext,ge as createBusInstance,be as createChannelEndpoint,Te as createExtensionNamespace,C as createFilteredBus,Me as createProjectedTelemetryTransport,Ee as createSubjectTelemetryProjectorRegistry,T as defaultTransports,E as defineSubjectExtension,i as deserializeTransportError,M as extendSubject,te as findInErrorChain,me as getFullSubjectForSubjectDefinition,u as getPath,S as getSubjectFromBusMessage,r as handleCorrelationResponse,j as hostLocalRequest,t as isNoHandlerErrorForSubject,s as isRequestCancellation,D as isRequestSchema,b as localSubject,le as matchesAnySubscription,ce as matchesFilter,ne as matchesSubscription,se as mergeFilters,xe as openChannel,pe as parseBusUrl,y as projectSubjectTelemetryFacts,L as serializeTransportError,ie as shouldReceiveMessage,ve as toSafeDebugLog,a as trackMessageCorrelation,x as transportErrorData,ue as waitForSubscriptionPropagation};
|