@directive-run/core 1.13.0 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-utils.cjs +1 -1
- package/dist/adapter-utils.d.cts +3 -3
- package/dist/adapter-utils.d.ts +3 -3
- package/dist/adapter-utils.js +1 -1
- package/dist/{chunk-I722BZA5.js → chunk-3ETCZLAY.js} +3 -3
- package/dist/chunk-3ETCZLAY.js.map +1 -0
- package/dist/chunk-4MTC4BSK.cjs +2 -0
- package/dist/chunk-4MTC4BSK.cjs.map +1 -0
- package/dist/{chunk-644QZVTT.js → chunk-F5JPF4YX.js} +3 -3
- package/dist/chunk-F5JPF4YX.js.map +1 -0
- package/dist/{chunk-X7G7UBXU.cjs → chunk-JGPPJV5P.cjs} +3 -3
- package/dist/chunk-JGPPJV5P.cjs.map +1 -0
- package/dist/{chunk-2FF6QGOA.js → chunk-O4GQEV4G.js} +2 -2
- package/dist/chunk-O4GQEV4G.js.map +1 -0
- package/dist/{chunk-ENZEHIL7.cjs → chunk-Q5UTBMX2.cjs} +3 -3
- package/dist/chunk-Q5UTBMX2.cjs.map +1 -0
- package/dist/{chunk-T4TRJEJN.cjs → chunk-RWFKUNF7.cjs} +2 -2
- package/dist/chunk-RWFKUNF7.cjs.map +1 -0
- package/dist/chunk-RWJV7QLM.js +3 -0
- package/dist/chunk-RWJV7QLM.js.map +1 -0
- package/dist/{chunk-NPX5EKPP.cjs → chunk-SUCLMJSZ.cjs} +3 -3
- package/dist/chunk-SUCLMJSZ.cjs.map +1 -0
- package/dist/chunk-YYFRZJO2.js +2 -0
- package/dist/chunk-YYFRZJO2.js.map +1 -0
- package/dist/{audit-ledger-dxvslGi3.d.ts → index-D_oNDe4l.d.cts} +78 -50
- package/dist/{audit-ledger-Dc6hAXam.d.cts → index-c5wGodzh.d.ts} +78 -50
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -6
- package/dist/index.d.ts +6 -6
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +1 -1
- package/dist/internals.d.cts +5 -5
- package/dist/internals.d.ts +5 -5
- package/dist/internals.js +1 -1
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.cjs.map +1 -1
- package/dist/plugins/index.d.cts +2 -2
- package/dist/plugins/index.d.ts +2 -2
- package/dist/plugins/index.js +1 -1
- package/dist/plugins/index.js.map +1 -1
- package/dist/{plugins-BIzXaYbg.d.cts → plugins-BpNMkJRw.d.cts} +47 -8
- package/dist/{plugins-BIzXaYbg.d.ts → plugins-BpNMkJRw.d.ts} +47 -8
- package/dist/{predicate-BxQVf0ug.d.ts → predicate-BinuVL33.d.ts} +1 -1
- package/dist/{predicate-Bnx3LN7P.d.cts → predicate-DN1MnDbi.d.cts} +1 -1
- package/dist/system-MMCZKPI2.js +2 -0
- package/dist/{system-A6VYKLVF.js.map → system-MMCZKPI2.js.map} +1 -1
- package/dist/system-RHSYFDOB.cjs +2 -0
- package/dist/{system-CDJMD5O5.cjs.map → system-RHSYFDOB.cjs.map} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/{utils-Mg55IerF.d.cts → utils-BZBBwS5A.d.cts} +10 -1
- package/dist/{utils-Mg55IerF.d.ts → utils-BZBBwS5A.d.ts} +10 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +24 -7
- package/dist/worker.d.ts +24 -7
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-2FF6QGOA.js.map +0 -1
- package/dist/chunk-644QZVTT.js.map +0 -1
- package/dist/chunk-ENZEHIL7.cjs.map +0 -1
- package/dist/chunk-I722BZA5.js.map +0 -1
- package/dist/chunk-IXRS4LM4.cjs +0 -2
- package/dist/chunk-IXRS4LM4.cjs.map +0 -1
- package/dist/chunk-NPX5EKPP.cjs.map +0 -1
- package/dist/chunk-PA6VC32N.js +0 -2
- package/dist/chunk-PA6VC32N.js.map +0 -1
- package/dist/chunk-R2GHSCTR.js +0 -3
- package/dist/chunk-R2GHSCTR.js.map +0 -1
- package/dist/chunk-T4TRJEJN.cjs.map +0 -1
- package/dist/chunk-X7G7UBXU.cjs.map +0 -1
- package/dist/system-A6VYKLVF.js +0 -2
- package/dist/system-CDJMD5O5.cjs +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';var chunk4MNQDXH7_cjs=require('./chunk-4MNQDXH7.cjs');var g=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),Q=new Set(["$all","$any","$not"]);var T=new Set(["number","string","boolean","bigint","date","unknown"]);function P(e){if(!e)return {kind:"unknown"};let n=/^Branded<(.+)>$/.exec(e);return n?{kind:"branded",inner:P(n[1])}:e.endsWith(" | null")||e.endsWith(" | undefined")?{...P(e.replace(/ \| (null|undefined)$/,"")),nullable:true}:T.has(e)?{kind:e}:/^(email|uuid|url|cuid|datetime|iso\b)/i.test(e)?{kind:"string"}:e.includes(" | ")?{kind:"union",members:e.split(" | ").map(P)}:e==="array"?{kind:"array",element:{kind:"unknown"}}:e==="object"?{kind:"object",shape:{}}:e==="record"?{kind:"record",value:{kind:"unknown"}}:e==="tuple"?{kind:"tuple",elements:[]}:e==="union"?{kind:"union",members:[]}:{kind:"unknown"}}function z(e){if(e==null)return {kind:"unknown"};if(typeof e=="function")return chunk4MNQDXH7_cjs.a&&console.warn("[Directive] getKind: received a function \u2014 did you forget () on a t.* builder? Example: write `t.number()`, not `t.number`."),{kind:"unknown"};if(typeof e!="object")return {kind:"unknown"};let n=e,r;try{r=n._kind;}catch{return {kind:"unknown"}}if(r)return r;let i;try{i=n._typeName;}catch{return {kind:"unknown"}}return P(i)}function H(e){let n=new Map;if(!e||typeof e!="object")return n;let r=e,t="facts"in r&&r.facts&&typeof r.facts=="object"?r.facts:r;for(let[a,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let o;try{o=z(s);}catch{continue}if(n.set(a,o),o.kind==="object")for(let[c,l]of Object.entries(o.shape))n.set(`${a}.${c}`,l);}return n.size===0&&chunk4MNQDXH7_cjs.a&&console.warn("[Directive] getSchemaFieldKinds: schema appears empty (no introspectable keys). Did you pass the module instead of its schema? Pass `myModule.schema`, not `myModule`."),n}var k=["$eq","$ne","$in","$nin","$exists"],D=["$gt","$gte","$lt","$lte","$between"],W=["$matches","$startsWith","$endsWith","$contains"];function w(e){switch(e.kind){case "number":case "bigint":case "date":return [...k,...D];case "string":return [...k,...D,...W];case "boolean":case "unknown":return k;case "array":return [...k,"$contains"];case "object":case "record":case "tuple":return k;case "literal":case "enum":return w(e.primitive==="number"?{kind:"number"}:e.primitive==="boolean"?{kind:"boolean"}:e.primitive==="null"?{kind:"unknown"}:{kind:"string"});case "branded":return w(e.inner);case "union":{if(e.members.length===0)return k;let n=e.members.map(t=>new Set(w(t))),r=n[0],i=[];for(let t of r)n.every(a=>a.has(t))&&i.push(t);return i}default:{return k}}}function X(){return Array.from(g)}var O=64;function u(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function x(e){if(typeof e!="object"||e===null||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function E(e){if(!u(e))return false;let n=0,r=false;for(let i of Object.keys(e)){if(i.startsWith("$"))r=true,g.has(i)||f(`predicate: unknown operator "${i}" \u2014 looks like a typo. Known operators: ${[...g].join(", ")}`);else if(r||n===0)return false;n++;}return r?n>0:false}function re(e){return e===null?false:Array.isArray(e)?e.every(n=>x(n)&&"fact"in n&&"op"in n):x(e)}function h(e,n,r="",i=new WeakSet,t=0){if(t>O){chunk4MNQDXH7_cjs.a&&console.warn(`[Directive] predicate depth limit (${O}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),n.bail?.("depth");return}if(Array.isArray(e)){e.forEach((s,o)=>{if(!u(s))return;let c=s;if(typeof c.fact=="string"&&typeof c.op=="string"){let l=r?`${r}[${o}]`:`[${o}]`;n.operator?.(r?`${r}.${c.fact}`:c.fact,c.op,c.value,`${l}.value`);}});return}if(!u(e))return;if(i.has(e)){chunk4MNQDXH7_cjs.a&&console.warn("[Directive] walkPredicate: cyclic predicate spec"),n.bail?.("cycle");return}i.add(e);let a=e;for(let s of ["$all","$any","$not"])if(s in a){if(n.combinator?.(s)===false)return;let c=s==="$not"?[a.$not]:a[s]??[];for(let l of c)h(l,n,r,i,t+1);return}for(let s of Object.keys(a)){let o=r?`${r}.${s}`:s;if(s.startsWith("$")){n.strayOperatorKey?.(s,o);continue}let c=a[s];if(E(c)){let l=c;for(let p of Object.keys(l))n.operator?.(o,p,l[p],`${o}.${p}`);continue}if(x(c)){if(n.nested?.(s)===false)continue;h(c,n,o,i,t+1);continue}n.literal?.(o,c);}}function ie(e){if(!x(e))return false;let n=false;return h(e,{operator(){n=true;},literal(){n=true;},combinator(){n=true;},strayOperatorKey(){n=true;},bail(){n=true;}}),!n}function I(e){return u(e)&&Object.hasOwn(e,"$template")&&typeof e.$template=="string"}function oe(e,n=""){function r(t,a,s,o){if(typeof t=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${a}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(t instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${a}" is not JSON-serializable (serializes to {} and loses all members).`);if(t instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${a}" is not JSON-serializable (serializes to {} and loses all entries).`);if(t instanceof RegExp)throw new Error(`[Directive] validatePredicate: RegExp operand at "${a}" is not JSON-serializable (a regex lost to JSON.parse becomes {}). Only a direct $matches operand may be a RegExp.`);if(!(t===null||typeof t!="object")&&!(o>O)&&!s.has(t)){if(s.add(t),Array.isArray(t)){t.forEach((c,l)=>{r(c,`${a}[${l}]`,s,o+1);});return}for(let c of Object.keys(t))r(t[c],a?`${a}.${c}`:c,s,o+1);}}function i(t,a,s){if(typeof t=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${s}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(t instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${s}" is not JSON-serializable (serializes to {} and loses all members).`);if(t instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${s}" is not JSON-serializable (serializes to {} and loses all entries).`);if(a==="$matches"&&!(t instanceof RegExp))throw new Error(`[Directive] validatePredicate: $matches operand at "${s}" must be a RegExp; got ${t===null?"null":typeof t}. A regex lost to JSON.parse becomes {} \u2014 reify with new RegExp(pattern, flags) before installing.`);if(Array.isArray(t))t.forEach((o,c)=>{r(o,`${s}[${c}]`,new WeakSet,1);});else if(x(t))for(let o of Object.keys(t))r(t[o],`${s}.${o}`,new WeakSet,1);}if(e instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand${n?` at "${n}"`:""} is not JSON-serializable (serializes to {} and loses all members).`);if(e instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand${n?` at "${n}"`:""} is not JSON-serializable (serializes to {} and loses all entries).`);h(e,{operator(t,a,s,o){i(s,a,n?`${n}.${o}`:o);},literal(t,a){i(a,"",n?`${n}.${t}`:t);}});}function M(e){return typeof e!="string"||e.length===0?false:!!(/\)(?:[+*]\??|\{\d+,?\d*\})\s*[+*?]\s*[+*]/.test(e)||/\(([^()]*?[+*]|[^()]*?\{\d+,?\d*\})[^()]*\)\s*[+*]/.test(e)||/\(\??:?([^()|]+)\|\1\)\s*[+*]/.test(e))}function se(e,n,r={}){let i=[],t=0,a=r.maxOperatorCount,s=r.maxArrayOperandLength;return h(e,{operator(o,c,l,p){if(t++,a!==void 0&&t>a){i.some($=>$.reason.includes("maxOperatorCount"))||i.push({path:o,op:c,reason:`Predicate exceeds maxOperatorCount=${a} \u2014 too many clauses (DoS guard).`});return}if(s!==void 0&&(c==="$in"||c==="$nin")&&Array.isArray(l)&&l.length>s){i.push({path:o,op:c,reason:`Operator ${c} operand exceeds maxArrayOperandLength=${s} (got ${l.length}) \u2014 too large for a query planner.`});return}if(c==="$matches"){let $;if(l instanceof RegExp?$=l.source:typeof l=="string"&&($=l),$!==void 0&&M($)){i.push({path:o,op:c,reason:`Operator $matches operand at "${o}" contains nested quantifiers (ReDoS risk: ${JSON.stringify($)}). Reject untrusted regex or rewrite without nested + / *.`});return}}let m=n.get(o);if(!m){i.push({path:o,op:c,reason:`Unknown fact "${o}" \u2014 not in schema. Known facts: ${n.size===0?"(empty schema)":Array.from(n.keys()).join(", ")}`});return}let y=w(m);y.includes(c)||i.push({path:o,op:c,kind:m,allowedOps:y,reason:`Operator "${c}" is not allowed on fact "${o}" of kind "${m.kind}". Allowed operators for this kind: ${y.join(", ")}.`});},literal(o,c){t++,n.has(o)||i.push({path:o,op:"$eq",reason:`Unknown fact "${o}" \u2014 not in schema.`});},strayOperatorKey(o,c){i.push({path:c,op:o,reason:`Stray operator key "${o}" at "${c}" \u2014 operators must live inside a fact's operator object, not at the predicate top level.`});}}),i.length===0?{ok:true,operatorCount:t}:{ok:false,errors:i,operatorCount:t}}function _(){return {ids:new WeakMap,next:{v:1},pairs:new Set}}function v(e,n){let r=e.ids.get(n);return r===void 0&&(r=e.next.v++,e.ids.set(n,r)),r}function d(e,n,r){if(Object.is(e,n))return true;if(e instanceof Date&&n instanceof Date)return e.getTime()===n.getTime();if(typeof e!="object"||typeof n!="object"||e===null||n===null)return false;let i=r??_(),t=`${v(i,e)}:${v(i,n)}`;if(i.pairs.has(t))return true;if(i.pairs.add(t),Array.isArray(e)||Array.isArray(n))return !Array.isArray(e)||!Array.isArray(n)||e.length!==n.length?false:e.every((o,c)=>d(o,n[c],i));if(e instanceof Set||n instanceof Set){if(!(e instanceof Set)||!(n instanceof Set)||e.size!==n.size)return false;let o=[...n];return [...e].every(c=>o.some(l=>d(c,l,i)))}if(e instanceof Map||n instanceof Map){if(!(e instanceof Map)||!(n instanceof Map)||e.size!==n.size)return false;let o=[...n.entries()],c=new Array(o.length).fill(false);for(let[l,p]of e){let m=false;for(let y=0;y<o.length;y++){if(c[y])continue;let[$,N]=o[y];if(d(l,$,i)&&d(p,N,i)){c[y]=true,m=true;break}}if(!m)return false}return true}let a=Object.keys(e),s=Object.keys(n);return a.length!==s.length?false:a.every(o=>Object.hasOwn(n,o)&&d(e[o],n[o],i))}function j(e){if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e=="bigint"||typeof e=="string")return e}function A(e,n,r){let i=j(n),t=j(r);if(i===void 0||t===void 0||typeof i!=typeof t)return false;switch(e){case "$gt":return i>t;case "$gte":return i>=t;case "$lt":return i<t;case "$lte":return i<=t;default:return false}}function R(e,n,r,i){switch(e){case "$eq":return d(n,r);case "$ne":return !d(n,r);case "$in":return Array.isArray(r)&&r.some(t=>d(n,t));case "$nin":return Array.isArray(r)&&!r.some(t=>d(n,t));case "$exists":return r===(n!==void 0);case "$changed":return !d(n,i);case "$gt":case "$gte":case "$lt":case "$lte":return A(e,n,r);case "$between":{if(!Array.isArray(r)||r.length!==2)return false;let t=j(r[0]),a=j(r[1]);return t!==void 0&&a!==void 0&&typeof t==typeof a&&t>a?(f("$between: reversed pair \u2014 [min, max] required"),false):A("$gte",n,r[0])&&A("$lte",n,r[1])}case "$matches":{if(!(r instanceof RegExp))throw new Error("[Directive] $matches: operand must be a RegExp (string operands are no longer accepted; pass /pattern/flags directly).");return typeof n!="string"?false:r.test(n)}case "$startsWith":return typeof n!="string"?false:n.startsWith(String(r));case "$endsWith":return typeof n!="string"?false:n.endsWith(String(r));case "$contains":return typeof n=="string"?n.includes(String(r)):Array.isArray(n)?n.some(t=>d(t,r)):n instanceof Set?n.has(r):false;default:return false}}function f(e){chunk4MNQDXH7_cjs.a&&console.warn(`[Directive] ${e}`);}function q(e,n,r,i){if(E(e)){let t=Object.keys(e);t.length>1&&f(`predicate: operator object has ${t.length} operators (${t.join(", ")}) \u2014 write the array form or $all instead. The runtime ANDs them as a best-effort fallback.`);for(let a of t)if(!R(a,n,e[a],r))return false;return true}return u(e)?S(e,u(n)?n:Object.create(null),u(r)?r:void 0,i+1):d(n,e)}function S(e,n,r,i=0){if(i>O)return f(`predicate depth limit (${O}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),false;if(Array.isArray(e))return e.every(t=>{if(!u(t))return false;let{fact:a,op:s,value:o}=t;return R(s,n?.[a],o,r?.[a])});if(!u(e))return !!e;if("$all"in e)return e.$all.every(t=>S(t,n,r,i+1));if("$any"in e)return e.$any.some(t=>S(t,n,r,i+1));if("$not"in e)return !S(e.$not,n,r,i+1);for(let t of Object.keys(e)){if(g.has(t))return f(`predicate: operator "${t}" mixed with fact keys \u2014 wrap operators in a per-fact object`),false;if(!q(e[t],n?.[t],r?.[t],i))return false}return true}function V(e,n,r,i=""){let t=[];if(Array.isArray(e)){for(let a of e){if(!u(a))continue;let{fact:s,op:o,value:c}=a,l=n?.[s];t.push({path:i+s,op:o,expected:c,actual:l,pass:R(o,l,c,r?.[s])});}return t}if(!u(e))return t;for(let a of ["$all","$any","$not"])if(a in e){let s=a==="$not"?[e.$not]:e[a],o=[];for(let p of s)o.push(...V(p,n,r,i));let c=o.filter(p=>p.pass).length,l;return a==="$all"?l=o.length===0||c===o.length:a==="$any"?l=o.length>0&&c>0:l=!o.every(p=>p.pass),t.push({path:i||a,op:a,expected:s.length,actual:c,pass:l,children:o}),t}for(let a of Object.keys(e)){if(g.has(a))continue;let s=e[a],o=n?.[a],c=i+a;if(E(s))for(let l of Object.keys(s))t.push({path:c,op:l,expected:s[l],actual:o,pass:R(l,o,s[l],r?.[a])});else u(s)?t.push(...V(s,u(o)?o:Object.create(null),u(r?.[a])?r?.[a]:void 0,`${c}.`)):t.push({path:c,op:"$eq",expected:s,actual:o,pass:d(o,s)});}return t}var F=new WeakMap;function ce(e){if(e===null||typeof e!="object")throw new Error(`[Directive] memoizePredicate: predicate must be a plain object or array; got ${typeof e}`);let n=F.get(e);if(n)return n;let r=(i,t)=>S(e,i,t);return F.set(e,r),r}function le(e,n=""){let r=new Set;return h(e,{operator(i){r.add(n+i);},literal(i){r.add(n+i);},strayOperatorKey(i){g.has(i)||f(`extractDeps: unknown operator "${i}" \u2014 skipping. Known operators: ${[...g].join(", ")}`);}}),r}var C=/^[A-Za-z_][A-Za-z0-9_]*$/;function J(e){return typeof e=="symbol"||e==null?"":String(e)}function B(e,n){return typeof e=="symbol"?(f("template: cannot interpolate a symbol value \u2014 using empty string"),""):e===void 0?(f(`template: ${n?`key "${n}" is `:""}undefined \u2014 using empty string`),""):e===null?(f(`template: ${n?`key "${n}" is `:""}null \u2014 using empty string`),""):String(e)}function L(e,n){let r=e.$template,i="",t=0;for(;t<r.length;){if(r[t]==="$"&&r[t+1]==="$"&&r[t+2]==="{"){i+="${",t+=3;continue}if(r[t]==="$"&&r[t+1]==="{"){let a=r.indexOf("}",t+2);if(a===-1){f(`template: unterminated "\${" in ${JSON.stringify(r)}`),i+=r.slice(t);break}let s=r.slice(t+2,a);if(!C.test(s))f(`template: invalid placeholder "\${${s}}" \u2014 not an identifier`);else {let o=n!=null&&Object.hasOwn(n,s),c=o?n[s]:void 0;o?i+=B(c,s):(f(`template: unknown key "${s}"`),i+=J(c));}t=a+1;continue}i+=r[t],t++;}return i}function ue(e){let n=new Set,r=e.$template,i=0;for(;i<r.length;){if(r[i]==="$"&&r[i+1]==="$"&&r[i+2]==="{"){i+=3;continue}if(r[i]==="$"&&r[i+1]==="{"){let t=r.indexOf("}",i+2);if(t===-1)break;let a=r.slice(i+2,t);C.test(a)&&n.add(a),i=t+1;continue}i++;}return n}function de(e,n){return e.map(r=>chunk4MNQDXH7_cjs.e(n?.[r])).join("|")}function fe(e,n,r){let i=e.$set,t=r??{};for(let a of Object.keys(i)){let s=i[a];if(I(s))n[a]=L(s,t);else if(u(s)&&Object.hasOwn(s,"$ref")&&typeof s.$ref=="string"){let o=s.$ref;Object.hasOwn(t,o)||f(`applyPatch: $ref "${o}" is missing from event payload \u2014 assigning undefined to fact "${a}"`),n[a]=t[o];}else n[a]=s;}}exports.a=g;exports.b=Q;exports.c=z;exports.d=H;exports.e=w;exports.f=X;exports.g=O;exports.h=re;exports.i=h;exports.j=ie;exports.k=I;exports.l=oe;exports.m=M;exports.n=se;exports.o=S;exports.p=V;exports.q=ce;exports.r=le;exports.s=L;exports.t=ue;exports.u=de;exports.v=fe;//# sourceMappingURL=chunk-T4TRJEJN.cjs.map
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
'use strict';var chunk4MNQDXH7_cjs=require('./chunk-4MNQDXH7.cjs');var g=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),Q=new Set(["$all","$any","$not"]);var T=new Set(["number","string","boolean","bigint","date","unknown"]);function P(e){if(!e)return {kind:"unknown"};let n=/^Branded<(.+)>$/.exec(e);return n?{kind:"branded",inner:P(n[1])}:e.endsWith(" | null")||e.endsWith(" | undefined")?{...P(e.replace(/ \| (null|undefined)$/,"")),nullable:true}:T.has(e)?{kind:e}:/^(email|uuid|url|cuid|datetime|iso\b)/i.test(e)?{kind:"string"}:e.includes(" | ")?{kind:"union",members:e.split(" | ").map(P)}:e==="array"?{kind:"array",element:{kind:"unknown"}}:e==="object"?{kind:"object",shape:{}}:e==="record"?{kind:"record",value:{kind:"unknown"}}:e==="tuple"?{kind:"tuple",elements:[]}:e==="union"?{kind:"union",members:[]}:{kind:"unknown"}}function z(e){if(e==null)return {kind:"unknown"};if(typeof e=="function")return chunk4MNQDXH7_cjs.a&&console.warn("[Directive] getKind: received a function \u2014 did you forget () on a t.* builder? Example: write `t.number()`, not `t.number`."),{kind:"unknown"};if(typeof e!="object")return {kind:"unknown"};let n=e,r;try{r=n._kind;}catch{return {kind:"unknown"}}if(r)return r;let i;try{i=n._typeName;}catch{return {kind:"unknown"}}return P(i)}function H(e){let n=new Map;if(!e||typeof e!="object")return n;let r=e,t="facts"in r&&r.facts&&typeof r.facts=="object"?r.facts:r;for(let[a,s]of Object.entries(t)){if(!s||typeof s!="object")continue;let o;try{o=z(s);}catch{continue}if(n.set(a,o),o.kind==="object")for(let[c,l]of Object.entries(o.shape))n.set(`${a}.${c}`,l);}return n.size===0&&chunk4MNQDXH7_cjs.a&&console.warn("[Directive] getSchemaFieldKinds: schema appears empty (no introspectable keys). Did you pass the module instead of its schema? Pass `myModule.schema`, not `myModule`."),n}var k=["$eq","$ne","$in","$nin","$exists"],D=["$gt","$gte","$lt","$lte","$between"],W=["$matches","$startsWith","$endsWith","$contains"];function w(e){switch(e.kind){case "number":case "bigint":case "date":return [...k,...D];case "string":return [...k,...D,...W];case "boolean":case "unknown":return k;case "array":return [...k,"$contains"];case "object":case "record":case "tuple":return k;case "literal":case "enum":return w(e.primitive==="number"?{kind:"number"}:e.primitive==="boolean"?{kind:"boolean"}:e.primitive==="null"?{kind:"unknown"}:{kind:"string"});case "branded":return w(e.inner);case "union":{if(e.members.length===0)return k;let n=e.members.map(t=>new Set(w(t))),r=n[0],i=[];for(let t of r)n.every(a=>a.has(t))&&i.push(t);return i}default:{return k}}}function X(){return Array.from(g)}var O=64;function u(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function x(e){if(typeof e!="object"||e===null||Array.isArray(e))return false;let n=Object.getPrototypeOf(e);return n===Object.prototype||n===null}function E(e){if(!u(e))return false;let n=0,r=false;for(let i of Object.keys(e)){if(i.startsWith("$"))r=true,g.has(i)||f(`predicate: unknown operator "${i}" \u2014 looks like a typo. Known operators: ${[...g].join(", ")}`);else if(r||n===0)return false;n++;}return r?n>0:false}function re(e){return e===null?false:Array.isArray(e)?e.every(n=>x(n)&&"fact"in n&&"op"in n):x(e)}function h(e,n,r="",i=new WeakSet,t=0){if(t>O){chunk4MNQDXH7_cjs.a&&console.warn(`[Directive] predicate depth limit (${O}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),n.bail?.("depth");return}if(Array.isArray(e)){e.forEach((s,o)=>{if(!u(s))return;let c=s;if(typeof c.fact=="string"&&typeof c.op=="string"){let l=r?`${r}[${o}]`:`[${o}]`;n.operator?.(r?`${r}.${c.fact}`:c.fact,c.op,c.value,`${l}.value`);}});return}if(!u(e))return;if(i.has(e)){chunk4MNQDXH7_cjs.a&&console.warn("[Directive] walkPredicate: cyclic predicate spec"),n.bail?.("cycle");return}i.add(e);let a=e;for(let s of ["$all","$any","$not"])if(s in a){if(n.combinator?.(s)===false)return;let c=s==="$not"?[a.$not]:a[s]??[];for(let l of c)h(l,n,r,i,t+1);return}for(let s of Object.keys(a)){let o=r?`${r}.${s}`:s;if(s.startsWith("$")){n.strayOperatorKey?.(s,o);continue}let c=a[s];if(E(c)){let l=c;for(let p of Object.keys(l))n.operator?.(o,p,l[p],`${o}.${p}`);continue}if(x(c)){if(n.nested?.(s)===false)continue;h(c,n,o,i,t+1);continue}n.literal?.(o,c);}}function ie(e){if(!x(e))return false;let n=false;return h(e,{operator(){n=true;},literal(){n=true;},combinator(){n=true;},strayOperatorKey(){n=true;},bail(){n=true;}}),!n}function I(e){return u(e)&&Object.hasOwn(e,"$template")&&typeof e.$template=="string"}function oe(e,n=""){function r(t,a,s,o){if(typeof t=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${a}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(t instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${a}" is not JSON-serializable (serializes to {} and loses all members).`);if(t instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${a}" is not JSON-serializable (serializes to {} and loses all entries).`);if(t instanceof RegExp)throw new Error(`[Directive] validatePredicate: RegExp operand at "${a}" is not JSON-serializable (a regex lost to JSON.parse becomes {}). Only a direct $matches operand may be a RegExp.`);if(!(t===null||typeof t!="object")&&!(o>O)&&!s.has(t)){if(s.add(t),Array.isArray(t)){t.forEach((c,l)=>{r(c,`${a}[${l}]`,s,o+1);});return}for(let c of Object.keys(t))r(t[c],a?`${a}.${c}`:c,s,o+1);}}function i(t,a,s){if(typeof t=="bigint")throw new Error(`[Directive] validatePredicate: bigint operand at "${s}" is not JSON-serializable (JSON.stringify throws on bigint).`);if(t instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand at "${s}" is not JSON-serializable (serializes to {} and loses all members).`);if(t instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand at "${s}" is not JSON-serializable (serializes to {} and loses all entries).`);if(a==="$matches"&&!(t instanceof RegExp))throw new Error(`[Directive] validatePredicate: $matches operand at "${s}" must be a RegExp; got ${t===null?"null":typeof t}. A regex lost to JSON.parse becomes {} \u2014 reify with new RegExp(pattern, flags) before installing.`);if(Array.isArray(t))t.forEach((o,c)=>{r(o,`${s}[${c}]`,new WeakSet,1);});else if(x(t))for(let o of Object.keys(t))r(t[o],`${s}.${o}`,new WeakSet,1);}if(e instanceof Set)throw new Error(`[Directive] validatePredicate: Set operand${n?` at "${n}"`:""} is not JSON-serializable (serializes to {} and loses all members).`);if(e instanceof Map)throw new Error(`[Directive] validatePredicate: Map operand${n?` at "${n}"`:""} is not JSON-serializable (serializes to {} and loses all entries).`);h(e,{operator(t,a,s,o){i(s,a,n?`${n}.${o}`:o);},literal(t,a){i(a,"",n?`${n}.${t}`:t);}});}function M(e){return typeof e!="string"||e.length===0?false:!!(/\)(?:[+*]\??|\{\d+,?\d*\})\s*[+*?]\s*[+*]/.test(e)||/\(([^()]*?[+*]|[^()]*?\{\d+,?\d*\})[^()]*\)\s*[+*]/.test(e)||/\(\??:?([^()|]+)\|\1\)\s*[+*]/.test(e))}function se(e,n,r={}){let i=[],t=0,a=r.maxOperatorCount,s=r.maxArrayOperandLength;return h(e,{operator(o,c,l,p){if(t++,a!==void 0&&t>a){i.some($=>$.reason.includes("maxOperatorCount"))||i.push({path:o,op:c,reason:`Predicate exceeds maxOperatorCount=${a} \u2014 too many clauses (DoS guard).`});return}if(s!==void 0&&(c==="$in"||c==="$nin")&&Array.isArray(l)&&l.length>s){i.push({path:o,op:c,reason:`Operator ${c} operand exceeds maxArrayOperandLength=${s} (got ${l.length}) \u2014 too large for a query planner.`});return}if(c==="$matches"){let $;if(l instanceof RegExp?$=l.source:typeof l=="string"&&($=l),$!==void 0&&M($)){i.push({path:o,op:c,reason:`Operator $matches operand at "${o}" contains nested quantifiers (ReDoS risk: ${JSON.stringify($)}). Reject untrusted regex or rewrite without nested + / *.`});return}}let m=n.get(o);if(!m){i.push({path:o,op:c,reason:`Unknown fact "${o}" \u2014 not in schema. Known facts: ${n.size===0?"(empty schema)":Array.from(n.keys()).join(", ")}`});return}let y=w(m);y.includes(c)||i.push({path:o,op:c,kind:m,allowedOps:y,reason:`Operator "${c}" is not allowed on fact "${o}" of kind "${m.kind}". Allowed operators for this kind: ${y.join(", ")}.`});},literal(o,c){t++,n.has(o)||i.push({path:o,op:"$eq",reason:`Unknown fact "${o}" \u2014 not in schema.`});},strayOperatorKey(o,c){i.push({path:c,op:o,reason:`Stray operator key "${o}" at "${c}" \u2014 operators must live inside a fact's operator object, not at the predicate top level.`});}}),i.length===0?{ok:true,operatorCount:t}:{ok:false,errors:i,operatorCount:t}}function _(){return {ids:new WeakMap,next:{v:1},pairs:new Set}}function v(e,n){let r=e.ids.get(n);return r===void 0&&(r=e.next.v++,e.ids.set(n,r)),r}function d(e,n,r){if(Object.is(e,n))return true;if(e instanceof Date&&n instanceof Date)return e.getTime()===n.getTime();if(typeof e!="object"||typeof n!="object"||e===null||n===null)return false;let i=r??_(),t=`${v(i,e)}:${v(i,n)}`;if(i.pairs.has(t))return true;if(i.pairs.add(t),Array.isArray(e)||Array.isArray(n))return !Array.isArray(e)||!Array.isArray(n)||e.length!==n.length?false:e.every((o,c)=>d(o,n[c],i));if(e instanceof Set||n instanceof Set){if(!(e instanceof Set)||!(n instanceof Set)||e.size!==n.size)return false;let o=[...n];return [...e].every(c=>o.some(l=>d(c,l,i)))}if(e instanceof Map||n instanceof Map){if(!(e instanceof Map)||!(n instanceof Map)||e.size!==n.size)return false;let o=[...n.entries()],c=new Array(o.length).fill(false);for(let[l,p]of e){let m=false;for(let y=0;y<o.length;y++){if(c[y])continue;let[$,N]=o[y];if(d(l,$,i)&&d(p,N,i)){c[y]=true,m=true;break}}if(!m)return false}return true}let a=Object.keys(e),s=Object.keys(n);return a.length!==s.length?false:a.every(o=>Object.hasOwn(n,o)&&d(e[o],n[o],i))}function j(e){if(e instanceof Date)return e.getTime();if(typeof e=="number"||typeof e=="bigint"||typeof e=="string")return e}function A(e,n,r){let i=j(n),t=j(r);if(i===void 0||t===void 0||typeof i!=typeof t)return false;switch(e){case "$gt":return i>t;case "$gte":return i>=t;case "$lt":return i<t;case "$lte":return i<=t;default:return false}}function R(e,n,r,i){switch(e){case "$eq":return d(n,r);case "$ne":return !d(n,r);case "$in":return Array.isArray(r)&&r.some(t=>d(n,t));case "$nin":return Array.isArray(r)&&!r.some(t=>d(n,t));case "$exists":return r===(n!==void 0);case "$changed":return !d(n,i);case "$gt":case "$gte":case "$lt":case "$lte":return A(e,n,r);case "$between":{if(!Array.isArray(r)||r.length!==2)return false;let t=j(r[0]),a=j(r[1]);return t!==void 0&&a!==void 0&&typeof t==typeof a&&t>a?(f("$between: reversed pair \u2014 [min, max] required"),false):A("$gte",n,r[0])&&A("$lte",n,r[1])}case "$matches":{if(!(r instanceof RegExp))throw new Error("[Directive] $matches: operand must be a RegExp (string operands are no longer accepted; pass /pattern/flags directly).");return typeof n!="string"?false:r.test(n)}case "$startsWith":return typeof n!="string"?false:n.startsWith(String(r));case "$endsWith":return typeof n!="string"?false:n.endsWith(String(r));case "$contains":return typeof n=="string"?n.includes(String(r)):Array.isArray(n)?n.some(t=>d(t,r)):n instanceof Set?n.has(r):false;default:return false}}function f(e){chunk4MNQDXH7_cjs.a&&console.warn(`[Directive] ${e}`);}function q(e,n,r,i){if(E(e)){let t=Object.keys(e);t.length>1&&f(`predicate: operator object has ${t.length} operators (${t.join(", ")}) \u2014 write the array form or $all instead. The runtime ANDs them as a best-effort fallback.`);for(let a of t)if(!R(a,n,e[a],r))return false;return true}return u(e)?S(e,u(n)?n:Object.create(null),u(r)?r:void 0,i+1):d(n,e)}function S(e,n,r,i=0){if(i>O)return f(`predicate depth limit (${O}) exceeded \u2014 flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`),false;if(Array.isArray(e))return e.every(t=>{if(!u(t))return false;let{fact:a,op:s,value:o}=t;return R(s,n?.[a],o,r?.[a])});if(!u(e))return !!e;if("$all"in e)return e.$all.every(t=>S(t,n,r,i+1));if("$any"in e)return e.$any.some(t=>S(t,n,r,i+1));if("$not"in e)return !S(e.$not,n,r,i+1);for(let t of Object.keys(e)){if(g.has(t))return f(`predicate: operator "${t}" mixed with fact keys \u2014 wrap operators in a per-fact object`),false;if(!q(e[t],n?.[t],r?.[t],i))return false}return true}function V(e,n,r,i=""){let t=[];if(Array.isArray(e)){for(let a of e){if(!u(a))continue;let{fact:s,op:o,value:c}=a,l=n?.[s];t.push({path:i+s,op:o,expected:c,actual:l,pass:R(o,l,c,r?.[s])});}return t}if(!u(e))return t;for(let a of ["$all","$any","$not"])if(a in e){let s=a==="$not"?[e.$not]:e[a],o=[];for(let p of s)o.push(...V(p,n,r,i));let c=o.filter(p=>p.pass).length,l;return a==="$all"?l=o.length===0||c===o.length:a==="$any"?l=o.length>0&&c>0:l=!o.every(p=>p.pass),t.push({path:i||a,op:a,expected:s.length,actual:c,pass:l,children:o}),t}for(let a of Object.keys(e)){if(g.has(a))continue;let s=e[a],o=n?.[a],c=i+a;if(E(s))for(let l of Object.keys(s))t.push({path:c,op:l,expected:s[l],actual:o,pass:R(l,o,s[l],r?.[a])});else u(s)?t.push(...V(s,u(o)?o:Object.create(null),u(r?.[a])?r?.[a]:void 0,`${c}.`)):t.push({path:c,op:"$eq",expected:s,actual:o,pass:d(o,s)});}return t}var F=new WeakMap;function ce(e){if(e===null||typeof e!="object")throw new Error(`[Directive] memoizePredicate: predicate must be a plain object or array; got ${typeof e}`);let n=F.get(e);if(n)return n;let r=(i,t)=>S(e,i,t);return F.set(e,r),r}function le(e,n=""){let r=new Set;return h(e,{operator(i){r.add(n+i);},literal(i){r.add(n+i);},strayOperatorKey(i){g.has(i)||f(`extractDeps: unknown operator "${i}" \u2014 skipping. Known operators: ${[...g].join(", ")}`);}}),r}var C=/^[A-Za-z_][A-Za-z0-9_]*$/;function J(e){return typeof e=="symbol"||e==null?"":String(e)}function B(e,n){return typeof e=="symbol"?(f("template: cannot interpolate a symbol value \u2014 using empty string"),""):e===void 0?(f(`template: ${n?`key "${n}" is `:""}undefined \u2014 using empty string`),""):e===null?(f(`template: ${n?`key "${n}" is `:""}null \u2014 using empty string`),""):String(e)}function L(e,n){let r=e.$template,i="",t=0;for(;t<r.length;){if(r[t]==="$"&&r[t+1]==="$"&&r[t+2]==="{"){i+="${",t+=3;continue}if(r[t]==="$"&&r[t+1]==="{"){let a=r.indexOf("}",t+2);if(a===-1){f(`template: unterminated "\${" in ${JSON.stringify(r)}`),i+=r.slice(t);break}let s=r.slice(t+2,a);if(!C.test(s))f(`template: invalid placeholder "\${${s}}" \u2014 not an identifier`);else {let o=n!=null&&Object.hasOwn(n,s),c=o?n[s]:void 0;o?i+=B(c,s):(f(`template: unknown key "${s}"`),i+=J(c));}t=a+1;continue}i+=r[t],t++;}return i}function ue(e){let n=new Set,r=e.$template,i=0;for(;i<r.length;){if(r[i]==="$"&&r[i+1]==="$"&&r[i+2]==="{"){i+=3;continue}if(r[i]==="$"&&r[i+1]==="{"){let t=r.indexOf("}",i+2);if(t===-1)break;let a=r.slice(i+2,t);C.test(a)&&n.add(a),i=t+1;continue}i++;}return n}function de(e,n){return e.map(r=>chunk4MNQDXH7_cjs.e(n?.[r])).join("|")}function fe(e,n,r){let i=e.$set,t=r??{};for(let a of Object.keys(i)){let s=i[a];if(I(s))n[a]=L(s,t);else if(u(s)&&Object.hasOwn(s,"$ref")&&typeof s.$ref=="string"){let o=s.$ref;Object.hasOwn(t,o)||f(`applyPatch: $ref "${o}" is missing from event payload \u2014 assigning undefined to fact "${a}"`),n[a]=t[o];}else n[a]=s;}}exports.a=g;exports.b=Q;exports.c=z;exports.d=H;exports.e=w;exports.f=X;exports.g=O;exports.h=re;exports.i=h;exports.j=ie;exports.k=I;exports.l=oe;exports.m=M;exports.n=se;exports.o=S;exports.p=V;exports.q=ce;exports.r=le;exports.s=L;exports.t=ue;exports.u=de;exports.v=fe;//# sourceMappingURL=chunk-RWFKUNF7.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-RWFKUNF7.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/types/predicate.ts","../src/core/schema-introspection.ts","../src/core/predicate.ts"],"names":["PREDICATE_OPERATORS","PREDICATE_COMBINATORS","PRIMITIVE_KINDS","parseTypeName","typeName","branded","getKind","schema","dev_true_default","s","kindNode","getSchemaFieldKinds","out","root","facts","key","builder","node","innerKey","innerNode","COMMON_OPS","ORDERABLE_OPS","STRING_OPS","getOperatorsForKind","sets","m","first","intersection","op","listAllPredicateOperators","MAX_PREDICATE_DEPTH","isPlainObject","v","isPlainObjectStrict","proto","isOperatorObject","count","hasDollarKey","k","devWarn","isPredicate","c","walkPredicate","spec","visitor","path","seen","depth","clause","i","clausePath","obj","kind","children","child","childPath","value","opObj","isEmptyOrConfigPredicate","isPredicateBody","isTemplate","validatePredicate","checkValueJsonSafe","at","el","checkOperand","_factPath","operand","operandPath","factPath","dangerousRegex","source","validatePredicateAgainstSchema","kindMap","opts","errors","operatorCount","maxOperatorCount","maxArrayOperandLength","_operandPath","e","regexSource","allowedOps","_value","deepEqualSeen","pairId","id","deepEqual","a","b","guard","bArr","w","bEntries","used","ka","va","found","kb","vb","ak","bk","toComparable","relational","actual","applyOperator","prevValue","lo","hi","message","evalField","prev","keys","evaluatePredicate","fact","p","evaluatePredicateExplained","pathPrefix","childSpecs","passCount","pass","memoizedCache","memoizePredicate","predicate","cached","fn","extractDeps","prefix","deps","IDENTIFIER","stringifyValueQuiet","stringifyValue","evaluateTemplate","scope","tpl","end","present","extractTemplateKeys","evaluateKeySelector","selector","field","stableStringify","applyPatch","payload","set","safePayload","refKey"],"mappings":"mEA8CO,IAAMA,CAAAA,CAA2C,IAAI,GAAA,CAAY,CACtE,MACA,KAAA,CACA,KAAA,CACA,OACA,SAAA,CACA,KAAA,CACA,OACA,KAAA,CACA,MAAA,CACA,WACA,UAAA,CACA,aAAA,CACA,YACA,WAAA,CACA,UACF,CAAC,CAAA,CAOYC,CAAAA,CAA6C,IAAI,IAAY,CACxE,MAAA,CACA,OACA,MACF,CAAC,EC0BD,IAAMC,CAAAA,CAAkB,IAAI,GAAA,CAAgB,CAC1C,SACA,QAAA,CACA,SAAA,CACA,SACA,MAAA,CACA,SACF,CAAC,CAAA,CAOD,SAASC,CAAAA,CAAcC,CAAAA,CAA8C,CACnE,GAAI,CAACA,CAAAA,CAAU,OAAO,CAAE,IAAA,CAAM,SAAU,EAGxC,IAAMC,CAAAA,CAAU,kBAAkB,IAAA,CAAKD,CAAQ,EAC/C,OAAIC,CAAAA,CACK,CAAE,IAAA,CAAM,SAAA,CAAW,MAAOF,CAAAA,CAAcE,CAAAA,CAAQ,CAAC,CAAC,CAAE,CAAA,CAIzDD,EAAS,QAAA,CAAS,SAAS,GAAKA,CAAAA,CAAS,QAAA,CAAS,cAAc,CAAA,CAG3D,CAAE,GAFKD,CAAAA,CAAcC,CAAAA,CAAS,OAAA,CAAQ,wBAAyB,EAAE,CAAC,EAEtD,QAAA,CAAU,IAAK,EAIhCF,CAAAA,CAAgB,GAAA,CAAIE,CAAsB,CAAA,CACrC,CAAE,IAAA,CAAMA,CAAuB,CAAA,CAKpC,wCAAA,CAAyC,KAAKA,CAAQ,CAAA,CACjD,CAAE,IAAA,CAAM,QAAS,EAItBA,CAAAA,C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CAAA,CAAIyC,EAEjB,CACF","file":"chunk-RWFKUNF7.cjs","sourcesContent":["/**\n * Data-configuration predicates and templates.\n *\n * A {@link FactPredicate} is a declarative, serializable boolean spec over a\n * module's fact namespace — the data form of a constraint `when`, an effect\n * `on`, or a boolean derivation. A {@link FactTemplate} is the value-producing\n * counterpart: a fact-interpolating string.\n *\n * Convention: `$` marks an operator/expression node inside a predicate or\n * template body (`$eq`, `$gte`, `$all`, `$template`, `$set`, `$ref`).\n * Definition arms (`compute`, `handler`, `patch`) stay sigil-free.\n *\n * Operators are `$`-prefixed so they can never collide with a fact key —\n * schema keys starting with `$` are rejected at registration.\n */\n\n// ============================================================================\n// Operators\n// ============================================================================\n\n/** Comparison operator names — the `$`-prefixed keys inside an operator object. */\nexport type PredicateOp =\n | \"$eq\"\n | \"$ne\"\n | \"$in\"\n | \"$nin\"\n | \"$exists\"\n | \"$gt\"\n | \"$gte\"\n | \"$lt\"\n | \"$lte\"\n | \"$between\"\n | \"$matches\"\n | \"$startsWith\"\n | \"$endsWith\"\n | \"$contains\"\n | \"$changed\";\n\n/** Combinator node keys. */\nexport type PredicateCombinatorKey = \"$all\" | \"$any\" | \"$not\";\n\n/**\n * Every reserved `$`-key recognized inside a predicate body.\n *\n * @internal\n */\nexport const PREDICATE_OPERATORS: ReadonlySet<string> = new Set<string>([\n \"$eq\",\n \"$ne\",\n \"$in\",\n \"$nin\",\n \"$exists\",\n \"$gt\",\n \"$gte\",\n \"$lt\",\n \"$lte\",\n \"$between\",\n \"$matches\",\n \"$startsWith\",\n \"$endsWith\",\n \"$contains\",\n \"$changed\",\n]);\n\n/**\n * Combinator keys, as a runtime set.\n *\n * @internal\n */\nexport const PREDICATE_COMBINATORS: ReadonlySet<string> = new Set<string>([\n \"$all\",\n \"$any\",\n \"$not\",\n]);\n\n// ============================================================================\n// Operator object\n// ============================================================================\n\n/**\n * `true` when `V` supports relational operators (`$gt` … `$between`).\n * `[V]` tuple-wrapping suppresses distribution over union-typed facts.\n */\ntype IsOrderable<V> = [V] extends [number | bigint | Date]\n ? true\n : [V] extends [string]\n ? true\n : false;\n\n/**\n * The operator object permitted for a fact of type `V`. Built as a\n * **per-operator union** (one operator per member) rather than an\n * intersection — a typo'd operator (`$eqq`) then matches no member and is a\n * compile error, and a relational operator on a non-orderable fact resolves\n * to `never`.\n *\n * One operator per object — for two operators on the same fact, write the\n * array form or `$all`. This is by design (the type is the source of truth).\n *\n * `$matches` requires `RegExp`. The runtime throws on string operands.\n *\n * @example\n * ```ts\n * const op1: OperatorObject<number> = { $gte: 30 };\n * const op2: OperatorObject<string> = { $matches: /^J/i };\n * const op3: OperatorObject<string> = { $in: [\"red\", \"yellow\"] };\n * const op4: OperatorObject<string> = { $startsWith: \"Ada\" };\n * const op5: OperatorObject<string> = { $endsWith: \".com\" };\n * ```\n */\nexport type OperatorObject<V> =\n | { $eq: V }\n | { $ne: V }\n | { $in: readonly V[] }\n | { $nin: readonly V[] }\n | { $exists: boolean }\n | { $changed: true }\n | (IsOrderable<V> extends true\n ?\n | { $gt: V }\n | { $gte: V }\n | { $lt: V }\n | { $lte: V }\n | { $between: readonly [V, V] }\n : never)\n | ([V] extends [string]\n ?\n | { $matches: RegExp }\n | { $contains: string }\n | { $startsWith: string }\n | { $endsWith: string }\n : never)\n | ([V] extends [readonly (infer E)[]] ? { $contains: E } : never);\n\n/**\n * The spec for a single fact key: a bare value (equality), an operator\n * object, or — for an object-typed fact — a nested predicate (partial match).\n */\ntype PredicateField<V> =\n | V\n | OperatorObject<V>\n | ([V] extends [readonly unknown[]]\n ? never\n : [V] extends [object]\n ? PredicateObject<V>\n : never);\n\n// ============================================================================\n// FactPredicate\n// ============================================================================\n\n/**\n * Object form — every key is a fact name, every value a\n * {@link PredicateField}. Multiple keys are AND-ed. A nested object value\n * recurses (partial match), which is how cross-module namespaced predicates\n * (`{ self: { phase: \"red\" }, auth: { token: { $exists: true } } }`) work.\n */\nexport type PredicateObject<F> = {\n [K in keyof F]?: PredicateField<F[K]>;\n};\n\n/** Array form — explicit clauses, AND-ed. The codegen/devtools-friendly form. */\nexport type PredicateClause<F> = {\n [K in keyof F]: {\n readonly fact: K;\n readonly op: PredicateOp;\n readonly value: unknown;\n };\n}[keyof F];\n\n/** Combinator node — exactly one of `$all` / `$any` / `$not`. */\nexport type PredicateCombinator<F> =\n | { $all: readonly FactPredicate<F>[]; $any?: never; $not?: never }\n | { $any: readonly FactPredicate<F>[]; $all?: never; $not?: never }\n | { $not: FactPredicate<F>; $all?: never; $any?: never };\n\n/**\n * A declarative boolean spec over a fact namespace `F`. The data form of a\n * constraint `when`, an effect `on`, or a boolean derivation. Accepts an\n * object form, an array-of-clauses form, or a combinator node.\n *\n * Keys are **fact names only** — derivations are not addressable from inside\n * a predicate. To gate on a derivation, either reference the underlying fact\n * the derivation reads, or fall back to the function form of `when` / `on`.\n *\n * @example\n * ```ts\n * // Object form (the common case)\n * const p1: FactPredicate<{ phase: string; elapsed: number }> = {\n * phase: \"red\",\n * elapsed: { $gte: 30 },\n * };\n *\n * // Combinator form\n * const p2: FactPredicate<{ phase: string }> = {\n * $any: [{ phase: \"red\" }, { phase: \"yellow\" }],\n * };\n * ```\n */\nexport type FactPredicate<F> =\n | PredicateObject<F>\n | readonly PredicateClause<F>[]\n | PredicateCombinator<F>;\n\n// ============================================================================\n// FactTemplate\n// ============================================================================\n\n/**\n * A fact-interpolating string expression. `${key}` placeholders are replaced\n * with the named fact's value; `$${` emits a literal `${`. The value-producing\n * counterpart to {@link FactPredicate} — usable as a string derivation, a\n * constraint `require` field value, or an event `patch` value.\n *\n * @example { $template: \"Phase ${phase} for ${elapsed}s\" }\n */\nexport interface FactTemplate {\n readonly $template: string;\n}\n\n// ============================================================================\n// Selectors (resolver key, event patch)\n// ============================================================================\n\n/**\n * *Note: despite the \"Selector\" name, this does not select from facts — it\n * projects fields of the requirement payload for stable-stringification.*\n *\n * A resolver dedup key written as data: an ordered list of requirement-payload\n * field names. `key: [\"type\", \"to\"]` dedupes requirements by those fields.\n *\n * @example\n * ```ts\n * resolvers: {\n * fetch: {\n * requirement: \"FETCH\",\n * key: [\"url\", \"method\"] satisfies KeySelector<{ url: string; method: string }>,\n * resolve: doFetch,\n * },\n * }\n * ```\n */\nexport type KeySelector<R> = readonly (keyof R & string)[];\n\n/**\n * *Note: Directive's `$ref` is **not** a JSON Pointer or JSON Schema `$ref`.\n * It is a payload field copy — equivalent to `event.payload[key]`. Renaming\n * to `$from` is tracked as a possible v1.6+ additive alias.*\n *\n * A typed single-field copy from an event payload. Lives in the patch-spec\n * namespace — used inside a {@link PatchSpec} `$set` value.\n *\n * @example\n * ```ts\n * patch: { $set: { userId: { $ref: \"id\" } satisfies PayloadRef<{ id: string }> } }\n * ```\n */\nexport interface PayloadRef<P> {\n readonly $ref: keyof P & string;\n}\n\n/**\n * A patch value: a literal, a typed payload copy, or (for string facts) a\n * template. Lives in the patch-spec namespace — used inside a {@link PatchSpec}\n * `$set` block.\n *\n * @example\n * ```ts\n * const v1: PatchValue<boolean, { active: boolean }> = true;\n * const v2: PatchValue<string, { name: string }> = { $ref: \"name\" };\n * const v3: PatchValue<string, { name: string }> = { $template: \"user ${name}\" };\n * ```\n */\nexport type PatchValue<V, P> =\n | V\n | PayloadRef<P>\n | ([V] extends [string] ? FactTemplate : never);\n\n/**\n * An event handler written as data: assigns facts from literals, payload\n * fields (`$ref`), or interpolated strings (`$template`).\n *\n * @example\n * ```ts\n * const spec: PatchSpec<{ status: string; label: string }, { name: string }> = {\n * $set: {\n * status: \"active\",\n * label: { $template: \"user ${name}\" },\n * },\n * };\n * ```\n */\nexport interface PatchSpec<F, P> {\n readonly $set: { [K in keyof F]?: PatchValue<F[K], P> };\n}\n\n// ============================================================================\n// Explain\n// ============================================================================\n\n/**\n * The per-clause result of an explained predicate evaluation. One entry per\n * leaf operator (`$eq`, `$gte`, …); combinator nodes (`$all`, `$any`, `$not`)\n * may also appear as headers when the runtime emits them — hence the union\n * over {@link PredicateCombinatorKey}.\n *\n * @example\n * ```ts\n * const result: ClauseResult = {\n * path: \"elapsed\",\n * op: \"$gte\",\n * expected: 30,\n * actual: 20,\n * pass: false,\n * };\n * ```\n */\nexport interface ClauseResult {\n /** Dotted path to the fact (`elapsed`, `auth.token`). */\n readonly path: string;\n /** The operator applied (`$gte`, `$eq`, …) — `$eq` for a bare value. */\n readonly op: PredicateOp | PredicateCombinatorKey;\n /**\n * The value the predicate expected. For combinator clauses (`$all`,\n * `$any`, `$not`) this is the child count.\n */\n readonly expected: unknown;\n /**\n * The actual fact value at evaluation time. For combinator clauses this\n * is the number of child clauses that passed.\n */\n readonly actual: unknown;\n /** Whether this clause passed. */\n readonly pass: boolean;\n /**\n * Children of a combinator clause (`$all`, `$any`, `$not`). Preserves the\n * tree shape of the original predicate so renderers (devtools,\n * `system.explain()`) can indent nested clauses.\n */\n readonly children?: ClauseResult[];\n}\n","/**\n * Schema Introspection\n *\n * A runtime discriminant for every `t.*()` builder result, so downstream\n * consumers (`predicateFromIntent`, `doctor`, future `predicateToZod`)\n * can ask \"what kind is this fact?\" without grepping the source.\n *\n * The discriminant lives at `_kind?: SchemaKindNode` on `ExtendedSchemaType`.\n * Base builders set it; chain mutators (`.nullable()`, `.brand()`, etc.)\n * preserve / decorate it. When `_kind` is absent (legacy or third-party\n * builder), the parser falls back to reading the freeform `_typeName`\n * string. When even that fails: `{ kind: \"unknown\" }` — graceful close.\n *\n * This module has zero hot-path cost; it is only invoked when an\n * introspecting caller asks for it.\n */\n\nimport isDevelopment from \"#is-development\";\nimport { PREDICATE_OPERATORS, type PredicateOp } from \"./types/predicate.js\";\n\n/**\n * Minimal structural shape for a schema-builder result that\n * introspection cares about. Avoids the contravariance trap on\n * `ExtendedSchemaType<T>` when `T = unknown` (which makes\n * `ChainableString` un-assignable to `ExtendedSchemaType<unknown>`\n * via the `_refinements` field). Any builder result is structurally\n * compatible with this shape.\n */\nexport interface IntrospectableSchema {\n readonly _kind?: SchemaKindNode;\n readonly _typeName?: string;\n}\n\n// ============================================================================\n// SchemaKindNode tree\n// ============================================================================\n\n/**\n * The closed set of kinds a Directive schema field can be.\n *\n * Drives operator availability via {@link getOperatorsForKind}: e.g.\n * `\"number\"` gets the orderable operators (`$gte`, `$lte`); `\"boolean\"`\n * does not.\n */\nexport type SchemaKind =\n | \"number\"\n | \"string\"\n | \"boolean\"\n | \"bigint\"\n | \"date\"\n | \"array\"\n | \"object\"\n | \"record\"\n | \"tuple\"\n | \"enum\"\n | \"literal\"\n | \"union\"\n | \"branded\"\n | \"unknown\";\n\n/**\n * A tree-shaped discriminator for a schema field. Composite kinds\n * (array, object, tuple, etc.) carry their element / shape information\n * so an LLM-prompt builder can show \"cartTotal is a number\" AND\n * \"items is an array of { sku: string, qty: number }\".\n *\n * `nullable` / `hasDefault` flags appear on the inner node (NOT a\n * wrapping kind) so operator-lookup on `t.number().nullable()` returns\n * the number's operators unchanged — `$gte` works on the non-null arm.\n */\nexport type SchemaKindNode = (\n | { kind: \"number\" | \"string\" | \"boolean\" | \"bigint\" | \"date\" | \"unknown\" }\n | {\n kind: \"literal\";\n value: string | number | boolean | null;\n primitive: \"string\" | \"number\" | \"boolean\" | \"null\";\n }\n | {\n kind: \"enum\";\n values: readonly (string | number)[];\n primitive: \"string\" | \"number\";\n }\n | { kind: \"array\"; element: SchemaKindNode }\n | { kind: \"tuple\"; elements: readonly SchemaKindNode[] }\n | { kind: \"object\"; shape: Record<string, SchemaKindNode> }\n | { kind: \"record\"; value: SchemaKindNode }\n | { kind: \"union\"; members: readonly SchemaKindNode[] }\n | { kind: \"branded\"; inner: SchemaKindNode }\n) & {\n /** True if the schema accepts `null` (from `.nullable()` / `.optional()`). */\n nullable?: boolean;\n /** True if the schema has a `.default()`. */\n hasDefault?: boolean;\n};\n\n// ============================================================================\n// Parse `_typeName` → SchemaKindNode (fallback for legacy / third-party)\n// ============================================================================\n\nconst PRIMITIVE_KINDS = new Set<SchemaKind>([\n \"number\",\n \"string\",\n \"boolean\",\n \"bigint\",\n \"date\",\n \"unknown\",\n]);\n\n/**\n * Best-effort parse of a freeform `_typeName` string into a structured\n * kind node. Used only when `_kind` is absent. Always falls back to\n * `{ kind: \"unknown\" }`; never throws.\n */\nfunction parseTypeName(typeName: string | undefined): SchemaKindNode {\n if (!typeName) return { kind: \"unknown\" };\n\n // \"Branded<inner>\" — recurse.\n const branded = /^Branded<(.+)>$/.exec(typeName);\n if (branded) {\n return { kind: \"branded\", inner: parseTypeName(branded[1]) };\n }\n\n // \"X | null\" / \"X | undefined\" — nullable wrapper.\n if (typeName.endsWith(\" | null\") || typeName.endsWith(\" | undefined\")) {\n const inner = parseTypeName(typeName.replace(/ \\| (null|undefined)$/, \"\"));\n\n return { ...inner, nullable: true };\n }\n\n // Bare primitive.\n if (PRIMITIVE_KINDS.has(typeName as SchemaKind)) {\n return { kind: typeName as SchemaKind } as SchemaKindNode;\n }\n\n // String-flavored named types (email, uuid, url, etc.) all map to \"string\"\n // for operator purposes.\n if (/^(email|uuid|url|cuid|datetime|iso\\b)/i.test(typeName)) {\n return { kind: \"string\" };\n }\n\n // Generic union \"X | Y | Z\" → union of parsed members (used by t.union()).\n if (typeName.includes(\" | \")) {\n const members = typeName.split(\" | \").map(parseTypeName);\n\n return { kind: \"union\", members };\n }\n\n // Bare names we recognize as composite without elements.\n if (typeName === \"array\")\n return { kind: \"array\", element: { kind: \"unknown\" } };\n if (typeName === \"object\") return { kind: \"object\", shape: {} };\n if (typeName === \"record\")\n return { kind: \"record\", value: { kind: \"unknown\" } };\n if (typeName === \"tuple\") return { kind: \"tuple\", elements: [] };\n if (typeName === \"union\") return { kind: \"union\", members: [] };\n\n return { kind: \"unknown\" };\n}\n\n// ============================================================================\n// Get the kind node for a single schema field\n// ============================================================================\n\n/**\n * Return the {@link SchemaKindNode} for a schema field. Prefers the\n * explicit `_kind` discriminant set by the builder; falls back to\n * parsing the freeform `_typeName` string for legacy / third-party\n * builders that don't set `_kind`.\n *\n * Hostile-getter safe: `_kind` / `_typeName` reads are wrapped — a builder\n * that throws on property access returns `{ kind: \"unknown\" }` instead of\n * propagating the throw to introspecting callers.\n *\n * In dev mode, a function input (`typeof schema === \"function\"`) emits a\n * warning — common foot-gun where the caller forgot to invoke a builder\n * factory (e.g. wrote `t.number` instead of `t.number()`).\n *\n * @example\n * ```ts\n * getKind(t.number()) // → { kind: \"number\" }\n * getKind(t.string().nullable()) // → { kind: \"string\", nullable: true }\n * getKind(t.array(t.number())) // → { kind: \"array\", element: { kind: \"number\" } }\n * ```\n */\nexport function getKind(schema: unknown): SchemaKindNode {\n if (schema === null || schema === undefined) return { kind: \"unknown\" };\n if (typeof schema === \"function\") {\n if (isDevelopment) {\n console.warn(\n \"[Directive] getKind: received a function — did you forget () on a t.* builder? Example: write `t.number()`, not `t.number`.\",\n );\n }\n\n return { kind: \"unknown\" };\n }\n if (typeof schema !== \"object\") return { kind: \"unknown\" };\n const s = schema as IntrospectableSchema;\n\n // Hostile-getter guard: a third-party builder that throws on `_kind` /\n // `_typeName` reads must not crash an introspecting caller.\n let kindNode: SchemaKindNode | undefined;\n try {\n kindNode = s._kind;\n } catch {\n return { kind: \"unknown\" };\n }\n if (kindNode) return kindNode;\n\n let typeName: string | undefined;\n try {\n typeName = s._typeName;\n } catch {\n return { kind: \"unknown\" };\n }\n\n return parseTypeName(typeName);\n}\n\n// ============================================================================\n// Walk a module schema → Map<dotted-path, SchemaKindNode>\n// ============================================================================\n\n/**\n * Walk the `facts` block of a module schema and emit a flat map from\n * dotted path → kind node. Nested `t.object()` shapes flatten using\n * `.` as the separator, matching the convention used by\n * `OperatorObject<V>`'s nested-path support.\n *\n * Passing a top-level schema directly (without the `facts:` wrapper)\n * also works — anything iterable as `Record<string, ExtendedSchemaType>`\n * is acceptable.\n *\n * Hostile-getter safe: a builder whose `_kind` / `_typeName` throws is\n * silently skipped (treated as `{ kind: \"unknown\" }` for that field)\n * rather than aborting the whole walk.\n *\n * In dev mode, a top-level schema that yields an empty map (no\n * introspectable keys) emits a warning — common foot-gun where the\n * caller passed `myModule` instead of `myModule.schema`.\n */\nexport function getSchemaFieldKinds(\n schema: unknown,\n): Map<string, SchemaKindNode> {\n const out = new Map<string, SchemaKindNode>();\n if (!schema || typeof schema !== \"object\") return out;\n const root = schema as Record<string, unknown>;\n const factsCandidate =\n \"facts\" in root && root.facts && typeof root.facts === \"object\"\n ? root.facts\n : root;\n const facts = factsCandidate as Record<string, unknown>;\n\n for (const [key, builder] of Object.entries(facts)) {\n if (!builder || typeof builder !== \"object\") continue;\n let node: SchemaKindNode;\n try {\n node = getKind(builder);\n } catch {\n // A pathological builder whose getter throws past getKind's own\n // guards — skip the field but keep walking the rest.\n continue;\n }\n out.set(key, node);\n\n // Flatten nested object shapes one level — matches OperatorObject<V>'s\n // dotted-path support.\n if (node.kind === \"object\") {\n for (const [innerKey, innerNode] of Object.entries(node.shape)) {\n out.set(`${key}.${innerKey}`, innerNode);\n }\n }\n }\n\n if (out.size === 0 && isDevelopment) {\n console.warn(\n \"[Directive] getSchemaFieldKinds: schema appears empty (no introspectable keys). Did you pass the module instead of its schema? Pass `myModule.schema`, not `myModule`.\",\n );\n }\n\n return out;\n}\n\n// ============================================================================\n// Operator allowlist per kind\n// ============================================================================\n\nconst COMMON_OPS: readonly PredicateOp[] = [\n \"$eq\",\n \"$ne\",\n \"$in\",\n \"$nin\",\n \"$exists\",\n];\n\nconst ORDERABLE_OPS: readonly PredicateOp[] = [\n \"$gt\",\n \"$gte\",\n \"$lt\",\n \"$lte\",\n \"$between\",\n];\n\nconst STRING_OPS: readonly PredicateOp[] = [\n \"$matches\",\n \"$startsWith\",\n \"$endsWith\",\n \"$contains\",\n];\n\n/**\n * Return the set of `PredicateOp` strings that are valid against a\n * given {@link SchemaKindNode}.\n *\n * Mirrors the type-level matrix encoded in `OperatorObject<V>` in\n * `types/predicate.ts` — drift between the two is enforced by the\n * compile-time conformance test\n * (`schema-introspection-conformance.test-d.ts`).\n *\n * - **Common to all kinds:** `$eq`, `$ne`, `$in`, `$nin`, `$exists`\n * - **Orderable (`number`/`string`/`bigint`/`date`):** + `$gt`, `$gte`,\n * `$lt`, `$lte`, `$between`\n * - **String-specific:** + `$matches`, `$startsWith`, `$endsWith`, `$contains`\n * - **Array:** + `$contains` (over the element type)\n * - **Union:** *intersection* across members (the operand must be valid\n * for every branch).\n * - **Branded:** delegates to the inner kind.\n * - **Literal / Enum:** operators of the primitive, with `$eq` / `$in`\n * operand restricted at the LLM-prompt layer (not enforced here).\n *\n * `nullable` does not change operator availability — `$gte` on a\n * nullable number is fine on the non-null arm; `$exists` handles null.\n */\nexport function getOperatorsForKind(\n node: SchemaKindNode,\n): readonly PredicateOp[] {\n switch (node.kind) {\n case \"number\":\n case \"bigint\":\n case \"date\":\n return [...COMMON_OPS, ...ORDERABLE_OPS];\n case \"string\":\n return [...COMMON_OPS, ...ORDERABLE_OPS, ...STRING_OPS];\n case \"boolean\":\n case \"unknown\":\n return COMMON_OPS;\n case \"array\":\n return [...COMMON_OPS, \"$contains\"];\n case \"object\":\n case \"record\":\n case \"tuple\":\n return COMMON_OPS;\n case \"literal\":\n case \"enum\":\n // Operators allowed by the underlying primitive.\n return getOperatorsForKind(\n node.primitive === \"number\"\n ? { kind: \"number\" }\n : node.primitive === \"boolean\"\n ? { kind: \"boolean\" }\n : node.primitive === \"null\"\n ? { kind: \"unknown\" }\n : { kind: \"string\" },\n );\n case \"branded\":\n return getOperatorsForKind(node.inner);\n case \"union\": {\n // Intersection of operators valid on every member.\n if (node.members.length === 0) return COMMON_OPS;\n const sets = node.members.map((m) => new Set(getOperatorsForKind(m)));\n const first = sets[0]!;\n const intersection: PredicateOp[] = [];\n for (const op of first) {\n if (sets.every((s) => s.has(op))) intersection.push(op);\n }\n\n return intersection;\n }\n default: {\n // Exhaustiveness check — TS will flag if a new kind is added without\n // a switch arm.\n const _exhaustive: never = node;\n void _exhaustive;\n\n return COMMON_OPS;\n }\n }\n}\n\n/**\n * Return all known predicate operators — convenience for prompt builders\n * that need to show the LLM the full set.\n */\nexport function listAllPredicateOperators(): readonly PredicateOp[] {\n return Array.from(PREDICATE_OPERATORS) as readonly PredicateOp[];\n}\n","/**\n * Runtime for data-configuration predicates and templates.\n *\n * Pure module — imports only its own types. Reads facts through whatever\n * object it is handed (the reactive `Facts` proxy in production, a plain\n * snapshot in tests), so it never depends on the engine, store, or tracking.\n */\n\nimport isDevelopment from \"#is-development\";\nimport { stableStringify } from \"../utils/utils.js\";\nimport {\n type ClauseResult,\n type FactTemplate,\n PREDICATE_OPERATORS,\n type PatchSpec,\n type PredicateOp,\n} from \"./types/predicate.js\";\n\n// ============================================================================\n// Recursion bound\n// ============================================================================\n\n/**\n * Maximum predicate-AST recursion depth. Legitimate cross-module predicates\n * nest fewer than ~15 levels; 64 is generous but bounded — past it the runtime\n * dev-warns and bails rather than risking a stack overflow on a cyclic or\n * pathologically deep spec. Shared by every structural predicate walker\n * ({@link walkPredicate}, {@link evaluatePredicate}) so the cap lives in one\n * place.\n */\nexport const MAX_PREDICATE_DEPTH = 64;\n\n// ============================================================================\n// Discriminators\n// ============================================================================\n\n/** A readable scope — the `Facts` proxy and a plain snapshot both satisfy it. */\ntype Scope = Record<string, unknown>;\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) {\n return false;\n }\n\n return !(v instanceof Date) && !(v instanceof RegExp);\n}\n\n/**\n * True when `v` is a plain `{}` literal (its prototype is `Object.prototype`\n * or `null`). Excludes class instances, Date, RegExp, Map, Set, Promise, etc.\n */\nfunction isPlainObjectStrict(v: unknown): v is Record<string, unknown> {\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) {\n return false;\n }\n const proto = Object.getPrototypeOf(v);\n\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * True when every own key of `v` is a recognized `$`-operator (and there is ≥1).\n * If any key starts with `$` but is not a known operator, dev-warn (typo) and\n * still treat the value as an operator object so the typo is not masked as a\n * literal — `applyOperator` will return false for the unknown op.\n */\nfunction isOperatorObject(v: unknown): v is Record<string, unknown> {\n if (!isPlainObject(v)) {\n return false;\n }\n\n let count = 0;\n let hasDollarKey = false;\n for (const k of Object.keys(v)) {\n if (k.startsWith(\"$\")) {\n hasDollarKey = true;\n if (!PREDICATE_OPERATORS.has(k)) {\n devWarn(\n `predicate: unknown operator \"${k}\" — looks like a typo. Known operators: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n } else if (hasDollarKey || count === 0) {\n // Mixed $/non-$ keys aren't an operator object; let the caller treat\n // it as a literal/recursive predicate. The non-$ key check happens\n // below by short-circuiting when a non-$ key appears.\n return false;\n }\n count++;\n }\n\n if (!hasDollarKey) {\n return false;\n }\n\n // All keys are `$`-prefixed: this is an operator object, even if some keys\n // are typos. An unknown op makes applyOperator() return false.\n return count > 0;\n}\n\n/**\n * True when `v` is a data-form spec (predicate object/array) rather than a\n * function. Excludes class instances (Date, RegExp, Map, Set, Promise, etc.)\n * — only plain `{}` literals and arrays of plain clause shapes qualify.\n *\n * @example\n * ```ts\n * isPredicate({ phase: \"red\" }); // true\n * isPredicate((f) => f.phase === \"red\"); // false\n * isPredicate([{ fact: \"phase\", op: \"$eq\", value: \"red\" }]); // true\n * ```\n */\nexport function isPredicate(v: unknown): boolean {\n if (v === null) {\n return false;\n }\n if (Array.isArray(v)) {\n return v.every(\n (c) =>\n isPlainObjectStrict(c) &&\n \"fact\" in (c as object) &&\n \"op\" in (c as object),\n );\n }\n\n return isPlainObjectStrict(v);\n}\n\n// ============================================================================\n// Structural traversal\n// ============================================================================\n\n/**\n * Visitor passed to {@link walkPredicate}. Every callback is optional; a\n * walker implements only the arms it cares about.\n */\nexport interface PredicateVisitor {\n /**\n * A leaf operator clause: a fact + a `$`-operator + its operand. Fires once\n * per operator in a multi-operator object.\n *\n * @param factPath - Dotted path to the fact (`elapsed`, `auth.token`).\n * @param op - The operator key (`$gte`, `$matches`, …).\n * @param operand - The operator's operand value.\n * @param operandPath - Dotted path to the operand for diagnostics\n * (`elapsed.$gte`, `value` / `[0].value` for the array-clause form).\n */\n operator?(\n factPath: string,\n op: string,\n operand: unknown,\n operandPath: string,\n ): void;\n /**\n * A bare-value (equality) clause — a fact mapped to a non-object literal,\n * an array, or a non-plain class instance (Date, RegExp, Set, …).\n *\n * @param factPath - Dotted path to the fact.\n * @param value - The equality operand.\n */\n literal?(factPath: string, value: unknown): void;\n /**\n * A combinator node (`$all` / `$any` / `$not`), called before descending.\n * Return `false` to skip its children.\n */\n combinator?(kind: \"$all\" | \"$any\" | \"$not\"): boolean | void;\n /**\n * A nested-object (cross-module pivot) key, called before descending.\n * Return `false` to skip its children.\n */\n nested?(key: string): boolean | void;\n /**\n * A `$`-prefixed key appearing where a fact key was expected — either an\n * unknown/typo operator, or an operator mixed with fact keys at predicate\n * top level.\n *\n * @param key - The stray `$`-key.\n * @param factPath - Dotted path to the stray key.\n */\n strayOperatorKey?(key: string, factPath: string): void;\n /**\n * Called when traversal bails out early — a cycle was re-encountered or\n * the depth cap was hit. The subtree below the bail point is NOT visited.\n */\n bail?(reason: \"cycle\" | \"depth\"): void;\n}\n\n/**\n * Single depth-guarded, cycle-guarded structural traversal of a predicate\n * AST. The pure structural walkers — dependency extraction, `$changed`\n * detection, empty/config detection, serialization validation — share this\n * so a new operator or combinator is threaded through one place.\n *\n * Handles the object form, the array-clause form, combinator nodes, nested\n * cross-module objects, operator objects, and bare-value literals. It does\n * **not** evaluate — see {@link evaluatePredicate} for that.\n *\n * @internal\n */\nexport function walkPredicate(\n spec: unknown,\n visitor: PredicateVisitor,\n path = \"\",\n seen: WeakSet<object> = new WeakSet(),\n depth = 0,\n): void {\n if (depth > MAX_PREDICATE_DEPTH) {\n if (isDevelopment) {\n console.warn(\n `[Directive] predicate depth limit (${MAX_PREDICATE_DEPTH}) exceeded — flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`,\n );\n }\n visitor.bail?.(\"depth\");\n\n return;\n }\n\n // Array-clause form — each `{ fact, op, value }` clause is a leaf operator.\n if (Array.isArray(spec)) {\n spec.forEach((clause, i) => {\n if (!isPlainObject(clause)) {\n return;\n }\n const c = clause as Record<string, unknown>;\n if (typeof c.fact === \"string\" && typeof c.op === \"string\") {\n const clausePath = path ? `${path}[${i}]` : `[${i}]`;\n visitor.operator?.(\n path ? `${path}.${c.fact}` : c.fact,\n c.op,\n c.value,\n `${clausePath}.value`,\n );\n }\n });\n\n return;\n }\n\n if (!isPlainObject(spec)) {\n return;\n }\n if (seen.has(spec)) {\n if (isDevelopment) {\n console.warn(\"[Directive] walkPredicate: cyclic predicate spec\");\n }\n visitor.bail?.(\"cycle\");\n\n return;\n }\n seen.add(spec);\n\n const obj = spec as Record<string, unknown>;\n\n // Combinator node — descend into children unless the visitor opts out.\n for (const kind of [\"$all\", \"$any\", \"$not\"] as const) {\n if (kind in obj) {\n const descend = visitor.combinator?.(kind);\n if (descend === false) {\n return;\n }\n const children =\n kind === \"$not\" ? [obj.$not] : ((obj[kind] as unknown[]) ?? []);\n for (const child of children) {\n walkPredicate(child, visitor, path, seen, depth + 1);\n }\n\n return;\n }\n }\n\n // Object form — one entry per key.\n for (const key of Object.keys(obj)) {\n const childPath = path ? `${path}.${key}` : key;\n\n if (key.startsWith(\"$\")) {\n // A `$`-key at fact position — typo operator or top-level operator\n // mixed with fact keys. Surface it; do not descend.\n visitor.strayOperatorKey?.(key, childPath);\n continue;\n }\n\n const value = obj[key];\n\n if (isOperatorObject(value)) {\n const opObj = value as Record<string, unknown>;\n for (const op of Object.keys(opObj)) {\n visitor.operator?.(childPath, op, opObj[op], `${childPath}.${op}`);\n }\n continue;\n }\n\n // Only a strict plain object (`{}` / `Object.create(null)`) recurses as\n // a nested cross-module predicate. A Set, Map, or class instance is a\n // bare-value leaf — surfacing it as `literal` lets a walker inspect its\n // runtime class (e.g. validatePredicate's JSON-serializability check).\n if (isPlainObjectStrict(value)) {\n const descend = visitor.nested?.(key);\n if (descend === false) {\n continue;\n }\n walkPredicate(value, visitor, childPath, seen, depth + 1);\n continue;\n }\n\n // Bare value — equality leaf (also array / Set / Map / class instances).\n visitor.literal?.(childPath, value);\n }\n}\n\n/**\n * True when `v` structurally passes {@link isPredicate} but contains no\n * operators, no combinators, and no fact-clause entries that resolve to a\n * primitive/operator leaf — i.e. an empty `{}` or a deeply-nested object\n * tree that never bottoms out in a leaf value. Used by the dynamic\n * `register()` / `assign()` paths to dev-warn when a config object is\n * passed where a predicate (or function) was expected.\n *\n * Returns `false` for arrays — array-form predicates with `fact`+`op`\n * clauses are handled by the structural `isPredicate` check upstream.\n *\n * @example\n * ```ts\n * isEmptyOrConfigPredicate({}); // true (empty — config-object misuse)\n * isEmptyOrConfigPredicate({ phase: \"red\" }); // false (real fact clause)\n * isEmptyOrConfigPredicate({ $eq: 5 }); // false (operator)\n * isEmptyOrConfigPredicate({ count: { $gt: 5 } }); // false (operator clause)\n * ```\n *\n * @internal\n */\nexport function isEmptyOrConfigPredicate(v: unknown): boolean {\n // Arrays and non-plain-object specs are never \"empty config objects\".\n if (!isPlainObjectStrict(v)) {\n return false;\n }\n\n // A spec is a config tree only when walkPredicate fires NONE of the\n // predicate-semantic callbacks — no operator, no combinator, no literal\n // leaf, no stray `$`-key. Nested plain objects are descended; an empty\n // `{}` or a tree of empty `{}` fires nothing and stays \"config\". A cycle\n // or depth-cap bail is treated as \"not a config object\" (can't determine\n // — fail safe so the dev-warn is not spuriously emitted).\n let isPredicateBody = false;\n walkPredicate(v, {\n operator() {\n isPredicateBody = true;\n },\n literal() {\n isPredicateBody = true;\n },\n combinator() {\n isPredicateBody = true;\n },\n strayOperatorKey() {\n isPredicateBody = true;\n },\n bail() {\n isPredicateBody = true;\n },\n });\n\n return !isPredicateBody;\n}\n\n/**\n * True when `v` is a {@link FactTemplate} (`{ $template: string }`).\n *\n * @example\n * ```ts\n * isTemplate({ $template: \"Hi ${name}\" }); // true\n * isTemplate({ $set: { name: \"x\" } }); // false\n * ```\n */\nexport function isTemplate(v: unknown): v is FactTemplate {\n return (\n isPlainObject(v) &&\n Object.hasOwn(v, \"$template\") &&\n typeof (v as { $template: unknown }).$template === \"string\"\n );\n}\n\n// ============================================================================\n// Load-time validation\n// ============================================================================\n\n/**\n * Throw when a predicate spec contains an operand that cannot survive a\n * JSON round-trip — i.e. that would silently mis-evaluate if the spec was\n * loaded from `JSON.parse`.\n *\n * Three failure classes are detected:\n *\n * - **Lost `RegExp` operand.** A `$matches` operand that is not a\n * `RegExp` instance. `JSON.parse` reconstructs a serialized regex as\n * `{}`, so a `$matches` clause with an empty-object operand is the\n * signature of a regex that did not survive serialization. Reify it\n * with `new RegExp(pattern, flags)` before installing the predicate.\n * - **`bigint` operand.** `JSON.stringify` throws on `bigint`, so a\n * `bigint` operand cannot have been produced by a JSON pipeline and\n * cannot be persisted by one either.\n * - **`Set` / `Map` operand.** Both serialize to `{}` and lose all\n * members; a predicate carrying one is not JSON-safe.\n *\n * This is an opt-in helper — the engine does not call it automatically.\n * Users who load predicates from JSON should call it after `JSON.parse`\n * to fail loud rather than silently mis-evaluate. See the\n * \"Serialization\" section of RFC-0004.\n *\n * @example\n * ```ts\n * validatePredicate({ phase: { $matches: {} } });\n * // throws — empty object where a RegExp is required\n *\n * validatePredicate({ phase: \"red\", elapsed: { $gte: 30 } });\n * // ok — JSON-clean operands\n * ```\n */\nexport function validatePredicate(spec: unknown, path = \"\"): void {\n /**\n * Recursively walk an operand's object/array structure, throwing on any\n * value that cannot survive a JSON round-trip — `bigint`, `Set`, `Map`, or\n * a nested `RegExp`. Depth- and cycle-guarded. A top-level operand is\n * inspected by the operator-specific {@link checkOperand} (which permits a\n * `RegExp` as the direct `$matches` operand); this helper handles values\n * nested *inside* a plain-object or array operand, where a `RegExp` is just\n * as JSON-unsafe as a `Set`.\n */\n function checkValueJsonSafe(\n value: unknown,\n at: string,\n seen: WeakSet<object>,\n depth: number,\n ): void {\n if (typeof value === \"bigint\") {\n throw new Error(\n `[Directive] validatePredicate: bigint operand at \"${at}\" is not JSON-serializable (JSON.stringify throws on bigint).`,\n );\n }\n if (value instanceof Set) {\n throw new Error(\n `[Directive] validatePredicate: Set operand at \"${at}\" is not JSON-serializable (serializes to {} and loses all members).`,\n );\n }\n if (value instanceof Map) {\n throw new Error(\n `[Directive] validatePredicate: Map operand at \"${at}\" is not JSON-serializable (serializes to {} and loses all entries).`,\n );\n }\n if (value instanceof RegExp) {\n throw new Error(\n `[Directive] validatePredicate: RegExp operand at \"${at}\" is not JSON-serializable (a regex lost to JSON.parse becomes {}). Only a direct $matches operand may be a RegExp.`,\n );\n }\n if (value === null || typeof value !== \"object\") {\n return;\n }\n if (depth > MAX_PREDICATE_DEPTH) {\n return;\n }\n if (seen.has(value)) {\n return;\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n value.forEach((el, i) => {\n checkValueJsonSafe(el, `${at}[${i}]`, seen, depth + 1);\n });\n\n return;\n }\n\n for (const k of Object.keys(value as Record<string, unknown>)) {\n checkValueJsonSafe(\n (value as Record<string, unknown>)[k],\n at ? `${at}.${k}` : k,\n seen,\n depth + 1,\n );\n }\n }\n\n /** Throw on a JSON-unrehydratable operand value. */\n function checkOperand(value: unknown, op: string, at: string): void {\n if (typeof value === \"bigint\") {\n throw new Error(\n `[Directive] validatePredicate: bigint operand at \"${at}\" is not JSON-serializable (JSON.stringify throws on bigint).`,\n );\n }\n if (value instanceof Set) {\n throw new Error(\n `[Directive] validatePredicate: Set operand at \"${at}\" is not JSON-serializable (serializes to {} and loses all members).`,\n );\n }\n if (value instanceof Map) {\n throw new Error(\n `[Directive] validatePredicate: Map operand at \"${at}\" is not JSON-serializable (serializes to {} and loses all entries).`,\n );\n }\n if (op === \"$matches\" && !(value instanceof RegExp)) {\n throw new Error(\n `[Directive] validatePredicate: $matches operand at \"${at}\" must be a RegExp; got ${value === null ? \"null\" : typeof value}. A regex lost to JSON.parse becomes {} — reify with new RegExp(pattern, flags) before installing.`,\n );\n }\n // A plain-object / array operand (e.g. `$eq: { ... }`, `$in: [ ... ]`)\n // can carry a `bigint`, `Set`, `Map`, or nested `RegExp` arbitrarily deep\n // — `checkOperand` only sees the operand's top type, so recurse into its\n // structure. The direct `$matches` RegExp is handled above and never\n // reaches this branch (a RegExp is not a plain object / array).\n if (Array.isArray(value)) {\n value.forEach((el, i) => {\n checkValueJsonSafe(el, `${at}[${i}]`, new WeakSet(), 1);\n });\n } else if (isPlainObjectStrict(value)) {\n for (const k of Object.keys(value)) {\n checkValueJsonSafe(value[k], `${at}.${k}`, new WeakSet(), 1);\n }\n }\n }\n\n // Top-level Set / Map node — a regex / set / map handed in directly as the\n // whole spec. walkPredicate would treat it as an empty object, so check\n // the entry node here.\n if (spec instanceof Set) {\n throw new Error(\n `[Directive] validatePredicate: Set operand${path ? ` at \"${path}\"` : \"\"} is not JSON-serializable (serializes to {} and loses all members).`,\n );\n }\n if (spec instanceof Map) {\n throw new Error(\n `[Directive] validatePredicate: Map operand${path ? ` at \"${path}\"` : \"\"} is not JSON-serializable (serializes to {} and loses all entries).`,\n );\n }\n\n // Single structural traversal — every operator clause and equality leaf is\n // checked for a JSON-unrehydratable operand. The walker threads the dotted\n // operand path so error messages point at the offending clause.\n walkPredicate(spec, {\n operator(_factPath, op, operand, operandPath) {\n checkOperand(operand, op, path ? `${path}.${operandPath}` : operandPath);\n },\n literal(factPath, value) {\n checkOperand(value, \"\", path ? `${path}.${factPath}` : factPath);\n },\n });\n}\n\n// ============================================================================\n// Schema-aware validation (semantic — operator on kind, operator-count cap)\n// ============================================================================\n\nimport {\n type SchemaKindNode,\n getOperatorsForKind,\n} from \"./schema-introspection.js\";\n\nexport interface SchemaValidationError {\n /** Dotted path to the failing clause (e.g. `cartTotal`, `auth.token.$gte`). */\n readonly path: string;\n /** The operator that failed (or the literal-equality marker `$eq`). */\n readonly op: string;\n /** The kind of the fact at this path, or `undefined` when the fact wasn't in the kind map. */\n readonly kind?: SchemaKindNode;\n /** The operators that ARE allowed for this fact's kind. */\n readonly allowedOps?: readonly string[];\n /** Human-readable failure reason (suitable for feeding back to an LLM). */\n readonly reason: string;\n}\n\nexport interface SchemaValidationOptions {\n /** Reject predicates with more than this many operator clauses (DoS guard). Default unbounded. */\n readonly maxOperatorCount?: number;\n /**\n * Reject `$in` / `$nin` operands that contain more than this many elements\n * (query-planner DoS guard). Default unbounded. A typical safe cap is 1000\n * — beyond that, a downstream query compiler may degrade quadratically.\n */\n readonly maxArrayOperandLength?: number;\n}\n\n/**\n * Heuristic: flag a regex source string that has obvious nested quantifiers\n * (e.g. `(.+)+`, `(.*)*`, `(\\w+)+`, `(a|a)+`) — the classic ReDoS shapes.\n * Not a full ReDoS prover; intentionally conservative so a string-rehydrated\n * `$matches` operand can be rejected before it ever reaches `RegExp.test`.\n *\n * Callers MUST NOT treat a `false` result as \"safe\" — a determined adversary\n * can craft patterns this heuristic misses. The right answer for untrusted\n * regex is \"don't accept untrusted regex\"; this helper exists to catch the\n * obvious foot-guns.\n *\n * @example\n * ```ts\n * dangerousRegex(\"(a+)+\"); // → true\n * dangerousRegex(\"(.*)*\"); // → true\n * dangerousRegex(\"(\\\\w+)+\"); // → true\n * dangerousRegex(\"^[a-z]+$\"); // → false\n * ```\n */\nexport function dangerousRegex(source: string): boolean {\n if (typeof source !== \"string\" || source.length === 0) {\n return false;\n }\n // Nested quantifiers — a group ending in `*` or `+` (or `{n,}`) immediately\n // followed by another `*` / `+` / `{n,}` quantifier. Allow `?` between\n // (lazy) since `(...)?+` is still pathological. Also catch `{n,m}` upper\n // bounds when they wrap a quantified group.\n //\n // Patterns flagged:\n // (.+)+ (.*)* (.+)* (.*)+\n // (\\w+)+ (\\d*)+ ([abc]+)+\n // (a|a)+ (a|b|c)* ((x))+ (?:x+)+\n //\n // The check looks for a closing `)` preceded by a quantifier-bearing token\n // (`+`, `*`, `}` from `{n,m}`, or `+?` / `*?` lazy) and followed by another\n // quantifier (`+`, `*`, or `{n,`).\n const nestedQuantifier = /\\)(?:[+*]\\??|\\{\\d+,?\\d*\\})\\s*[+*?]\\s*[+*]/;\n if (nestedQuantifier.test(source)) {\n return true;\n }\n // Group whose inner content already has a `+` / `*` / `{n,}` quantifier on\n // a character class or token, and the group is then itself quantified.\n // E.g. `(a+)+`, `(\\w+)+`, `(.*)*`, `([abc]+)*`.\n const groupedQuantified =\n /\\(([^()]*?[+*]|[^()]*?\\{\\d+,?\\d*\\})[^()]*\\)\\s*[+*]/;\n if (groupedQuantified.test(source)) {\n return true;\n }\n // Alternation of identical branches: `(a|a)+`, `(foo|foo)*`.\n const sameBranchAlt = /\\(\\??:?([^()|]+)\\|\\1\\)\\s*[+*]/;\n if (sameBranchAlt.test(source)) {\n return true;\n }\n\n return false;\n}\n\nexport type SchemaValidationResult =\n | { ok: true; operatorCount: number }\n | {\n ok: false;\n errors: readonly SchemaValidationError[];\n operatorCount: number;\n };\n\n/**\n * Cross-check an LLM-emitted (or otherwise externally-sourced) predicate\n * against a schema's runtime kind map. Catches errors that\n * {@link validatePredicate} cannot — operator-on-wrong-kind (`$gte` on a\n * boolean fact), unknown fact paths, and (optionally) operator-count\n * exhaustion DoS attempts.\n *\n * Pair with {@link validatePredicate} (structural / JSON safety) for full\n * coverage. Use {@link getSchemaFieldKinds} to derive `kindMap` from a\n * module schema.\n *\n * Designed for the LLM-emit retry loop: returns a list of errors with\n * structured `{path, op, kind, allowedOps, reason}` rather than throwing,\n * so the caller can feed the errors back to the model.\n *\n * @example\n * ```ts\n * const kindMap = getSchemaFieldKinds({ facts: { cartTotal: t.number(), active: t.boolean() } });\n * const result = validatePredicateAgainstSchema(\n * { cartTotal: { $gte: 50 }, active: { $gte: true } },\n * kindMap,\n * );\n * // → { ok: false, errors: [{ path: \"active\", op: \"$gte\", reason: \"...\" }], operatorCount: 2 }\n * ```\n */\nexport function validatePredicateAgainstSchema(\n spec: unknown,\n kindMap: Map<string, SchemaKindNode>,\n opts: SchemaValidationOptions = {},\n): SchemaValidationResult {\n const errors: SchemaValidationError[] = [];\n let operatorCount = 0;\n const maxOperatorCount = opts.maxOperatorCount;\n const maxArrayOperandLength = opts.maxArrayOperandLength;\n\n walkPredicate(spec, {\n operator(factPath, op, operand, _operandPath) {\n operatorCount++;\n if (maxOperatorCount !== undefined && operatorCount > maxOperatorCount) {\n // Don't pile up identical errors past the cap; one is enough.\n if (!errors.some((e) => e.reason.includes(\"maxOperatorCount\"))) {\n errors.push({\n path: factPath,\n op,\n reason: `Predicate exceeds maxOperatorCount=${maxOperatorCount} — too many clauses (DoS guard).`,\n });\n }\n\n return;\n }\n\n // M1: $in / $nin operand length cap — too-large array operands choke\n // downstream query planners and OR-tree compilers.\n if (\n maxArrayOperandLength !== undefined &&\n (op === \"$in\" || op === \"$nin\") &&\n Array.isArray(operand) &&\n operand.length > maxArrayOperandLength\n ) {\n errors.push({\n path: factPath,\n op,\n reason: `Operator ${op} operand exceeds maxArrayOperandLength=${maxArrayOperandLength} (got ${operand.length}) — too large for a query planner.`,\n });\n\n return;\n }\n\n // M2: $matches operand ReDoS heuristic — flag obvious nested\n // quantifiers in either a RegExp or a string-form pattern. String-form\n // patterns are rejected at evaluation time (see applyOperator), but\n // a static check here catches them before they ever load.\n //\n // WARNING: don't rehydrate LLM-emitted string-form regex without your\n // own complexity audit; `dangerousRegex()` is a foot-gun catcher, not\n // a ReDoS prover.\n if (op === \"$matches\") {\n let regexSource: string | undefined;\n if (operand instanceof RegExp) {\n regexSource = operand.source;\n } else if (typeof operand === \"string\") {\n regexSource = operand;\n }\n if (regexSource !== undefined && dangerousRegex(regexSource)) {\n errors.push({\n path: factPath,\n op,\n reason: `Operator $matches operand at \"${factPath}\" contains nested quantifiers (ReDoS risk: ${JSON.stringify(regexSource)}). Reject untrusted regex or rewrite without nested + / *.`,\n });\n\n return;\n }\n }\n\n const kind = kindMap.get(factPath);\n if (!kind) {\n errors.push({\n path: factPath,\n op,\n reason: `Unknown fact \"${factPath}\" — not in schema. Known facts: ${\n kindMap.size === 0\n ? \"(empty schema)\"\n : Array.from(kindMap.keys()).join(\", \")\n }`,\n });\n\n return;\n }\n\n const allowedOps = getOperatorsForKind(kind);\n if (!allowedOps.includes(op as never)) {\n errors.push({\n path: factPath,\n op,\n kind,\n allowedOps,\n reason: `Operator \"${op}\" is not allowed on fact \"${factPath}\" of kind \"${kind.kind}\". Allowed operators for this kind: ${allowedOps.join(\", \")}.`,\n });\n }\n },\n literal(factPath, _value) {\n operatorCount++;\n // Bare-value (equality) — always permitted as long as fact exists.\n if (!kindMap.has(factPath)) {\n errors.push({\n path: factPath,\n op: \"$eq\",\n reason: `Unknown fact \"${factPath}\" — not in schema.`,\n });\n }\n },\n strayOperatorKey(key, factPath) {\n errors.push({\n path: factPath,\n op: key,\n reason: `Stray operator key \"${key}\" at \"${factPath}\" — operators must live inside a fact's operator object, not at the predicate top level.`,\n });\n },\n });\n\n if (errors.length === 0) return { ok: true, operatorCount };\n\n return { ok: false, errors, operatorCount };\n}\n\n// ============================================================================\n// Equality\n// ============================================================================\n\n/**\n * Pairwise cycle-guard state shared across a single `deepEqual` traversal.\n *\n * Asymmetric cycles (only one side cyclic) must not short-circuit; we only\n * treat a pair as equal when the same `(a, b)` pair is re-encountered.\n */\ninterface DeepEqualSeen {\n ids: WeakMap<object, number>;\n next: { v: number };\n pairs: Set<string>;\n}\n\nfunction deepEqualSeen(): DeepEqualSeen {\n return { ids: new WeakMap(), next: { v: 1 }, pairs: new Set() };\n}\n\nfunction pairId(seen: DeepEqualSeen, obj: object): number {\n let id = seen.ids.get(obj);\n if (id === undefined) {\n id = seen.next.v++;\n seen.ids.set(obj, id);\n }\n\n return id;\n}\n\n/** Structural equality with NaN/Date handling and a pairwise cycle guard. */\nfunction deepEqual(a: unknown, b: unknown, seen?: DeepEqualSeen): boolean {\n if (Object.is(a, b)) {\n return true;\n }\n\n if (a instanceof Date && b instanceof Date) {\n return a.getTime() === b.getTime();\n }\n\n if (\n typeof a !== \"object\" ||\n typeof b !== \"object\" ||\n a === null ||\n b === null\n ) {\n return false;\n }\n\n const guard = seen ?? deepEqualSeen();\n const key = `${pairId(guard, a)}:${pairId(guard, b)}`;\n if (guard.pairs.has(key)) {\n return true; // same (a, b) pair re-encountered — treat as equal\n }\n guard.pairs.add(key);\n\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {\n return false;\n }\n\n return a.every((v, i) => deepEqual(v, b[i], guard));\n }\n\n // Set equality — same size, every element of `a` has a structurally-equal\n // counterpart in `b`. Must precede the `Object.keys` fallback below because\n // `Object.keys(new Set(...))` is always `[]`, which would otherwise let\n // any two Sets (or any two Maps) compare equal regardless of contents.\n if (a instanceof Set || b instanceof Set) {\n if (!(a instanceof Set) || !(b instanceof Set) || a.size !== b.size) {\n return false;\n }\n const bArr = [...b];\n\n return [...a].every((v) => bArr.some((w) => deepEqual(v, w, guard)));\n }\n\n // Map equality — same size, every key in `a` matches a key in `b` with a\n // structurally-equal value. Greedy match with a used-flag to handle\n // structural (non-reference) key equality correctly.\n if (a instanceof Map || b instanceof Map) {\n if (!(a instanceof Map) || !(b instanceof Map) || a.size !== b.size) {\n return false;\n }\n const bEntries = [...b.entries()];\n const used = new Array<boolean>(bEntries.length).fill(false);\n for (const [ka, va] of a) {\n let found = false;\n for (let i = 0; i < bEntries.length; i++) {\n if (used[i]) {\n continue;\n }\n const [kb, vb] = bEntries[i]!;\n if (deepEqual(ka, kb, guard) && deepEqual(va, vb, guard)) {\n used[i] = true;\n found = true;\n break;\n }\n }\n if (!found) {\n return false;\n }\n }\n\n return true;\n }\n\n const ak = Object.keys(a as object);\n const bk = Object.keys(b as object);\n if (ak.length !== bk.length) {\n return false;\n }\n\n return ak.every(\n (k) =>\n Object.hasOwn(b as object, k) &&\n deepEqual(\n (a as Record<string, unknown>)[k],\n (b as Record<string, unknown>)[k],\n guard,\n ),\n );\n}\n\n// ============================================================================\n// Operators\n// ============================================================================\n\nfunction toComparable(v: unknown): number | bigint | string | undefined {\n if (v instanceof Date) {\n return v.getTime();\n }\n if (typeof v === \"number\" || typeof v === \"bigint\" || typeof v === \"string\") {\n return v;\n }\n\n return undefined;\n}\n\nfunction relational(\n op: PredicateOp,\n actual: unknown,\n operand: unknown,\n): boolean {\n const a = toComparable(actual);\n const b = toComparable(operand);\n if (a === undefined || b === undefined || typeof a !== typeof b) {\n return false;\n }\n\n switch (op) {\n case \"$gt\":\n return a > b;\n case \"$gte\":\n return a >= b;\n case \"$lt\":\n return a < b;\n case \"$lte\":\n return a <= b;\n default:\n return false;\n }\n}\n\n/** Apply one operator. `prevValue` is supplied only for `$changed`. */\nfunction applyOperator(\n op: PredicateOp,\n actual: unknown,\n operand: unknown,\n prevValue: unknown,\n): boolean {\n switch (op) {\n case \"$eq\":\n return deepEqual(actual, operand);\n case \"$ne\":\n return !deepEqual(actual, operand);\n case \"$in\":\n return (\n Array.isArray(operand) && operand.some((v) => deepEqual(actual, v))\n );\n case \"$nin\":\n return (\n Array.isArray(operand) && !operand.some((v) => deepEqual(actual, v))\n );\n case \"$exists\":\n return operand === (actual !== undefined);\n case \"$changed\":\n return !deepEqual(actual, prevValue);\n case \"$gt\":\n case \"$gte\":\n case \"$lt\":\n case \"$lte\":\n return relational(op, actual, operand);\n case \"$between\": {\n if (!Array.isArray(operand) || operand.length !== 2) {\n return false;\n }\n const lo = toComparable(operand[0]);\n const hi = toComparable(operand[1]);\n if (\n lo !== undefined &&\n hi !== undefined &&\n typeof lo === typeof hi &&\n lo > hi\n ) {\n devWarn(\"$between: reversed pair — [min, max] required\");\n\n return false;\n }\n\n return (\n relational(\"$gte\", actual, operand[0]) &&\n relational(\"$lte\", actual, operand[1])\n );\n }\n case \"$matches\": {\n if (!(operand instanceof RegExp)) {\n // String operands are not accepted — a string cannot carry flags\n // (case-insensitivity, dotall, multiline) and would also enable a\n // ReDoS surface for data-loaded predicates. Throw immediately so\n // the bug surfaces at the point of use.\n throw new Error(\n \"[Directive] $matches: operand must be a RegExp (string operands are no longer accepted; pass /pattern/flags directly).\",\n );\n }\n if (typeof actual !== \"string\") {\n return false;\n }\n\n return operand.test(actual);\n }\n case \"$startsWith\":\n if (typeof actual !== \"string\") {\n return false;\n }\n\n return actual.startsWith(String(operand));\n case \"$endsWith\":\n if (typeof actual !== \"string\") {\n return false;\n }\n\n return actual.endsWith(String(operand));\n case \"$contains\":\n if (typeof actual === \"string\") {\n return actual.includes(String(operand));\n }\n if (Array.isArray(actual)) {\n return actual.some((v) => deepEqual(v, operand));\n }\n // Set membership — uses `.has()` which is reference-equality for\n // objects (matches native Set semantics) and value-equality for\n // primitives. Map `$contains` is deferred to v2; users who need it\n // today can fall back to a function-form predicate.\n if (actual instanceof Set) {\n return actual.has(operand);\n }\n\n return false;\n default:\n return false;\n }\n}\n\n// ============================================================================\n// Evaluation\n// ============================================================================\n\nfunction devWarn(message: string): void {\n if (isDevelopment) {\n console.warn(`[Directive] ${message}`);\n }\n}\n\nfunction evalField(\n value: unknown,\n actual: unknown,\n prev: unknown,\n depth: number,\n): boolean {\n if (isOperatorObject(value)) {\n const keys = Object.keys(value);\n // Type rejects multi-operator objects; the runtime ANDs them on a\n // best-effort basis but dev-warns so the author knows to switch to the\n // array form or `$all`.\n if (keys.length > 1) {\n devWarn(\n `predicate: operator object has ${keys.length} operators (${keys.join(\", \")}) — write the array form or $all instead. The runtime ANDs them as a best-effort fallback.`,\n );\n }\n for (const op of keys) {\n if (!applyOperator(op as PredicateOp, actual, value[op], prev)) {\n return false;\n }\n }\n\n return true;\n }\n\n // A plain (non-operator) object recurses — nested / namespaced predicate.\n if (isPlainObject(value)) {\n return evaluatePredicate(\n value,\n isPlainObject(actual) ? actual : Object.create(null),\n isPlainObject(prev) ? prev : undefined,\n depth + 1,\n );\n }\n\n // Bare value → equality.\n return deepEqual(actual, value);\n}\n\n/**\n * Evaluate a {@link FactPredicate} against a fact scope. `prev` (a previous\n * snapshot) is consulted only by the `$changed` operator.\n *\n * @example\n * ```ts\n * evaluatePredicate({ phase: \"red\", elapsed: { $gte: 30 } }, { phase: \"red\", elapsed: 45 });\n * // → true\n * evaluatePredicate({ $any: [{ phase: \"red\" }, { phase: \"yellow\" }] }, { phase: \"green\" });\n * // → false\n * ```\n */\nexport function evaluatePredicate(\n spec: unknown,\n facts: Scope,\n prev?: Scope,\n depth = 0,\n): boolean {\n // `freezeSpec` permits cycles (it uses a WeakSet seen-guard), so a\n // registered spec can be self-referential. Cap recursion to defend the\n // reconcile loop against a stack overflow at evaluation time.\n if (depth > MAX_PREDICATE_DEPTH) {\n devWarn(\n `predicate depth limit (${MAX_PREDICATE_DEPTH}) exceeded — flatten the predicate or split it into multiple constraints. If this is unexpected, check for a cyclic spec object.`,\n );\n\n return false;\n }\n // Array form — clauses AND-ed.\n if (Array.isArray(spec)) {\n return spec.every((clause) => {\n if (!isPlainObject(clause)) {\n return false;\n }\n const { fact, op, value } = clause as {\n fact: string;\n op: PredicateOp;\n value: unknown;\n };\n\n return applyOperator(op, facts?.[fact], value, prev?.[fact]);\n });\n }\n\n if (!isPlainObject(spec)) {\n return Boolean(spec);\n }\n\n // Combinator node.\n if (\"$all\" in spec) {\n return (spec.$all as unknown[]).every((p) =>\n evaluatePredicate(p, facts, prev, depth + 1),\n );\n }\n if (\"$any\" in spec) {\n return (spec.$any as unknown[]).some((p) =>\n evaluatePredicate(p, facts, prev, depth + 1),\n );\n }\n if (\"$not\" in spec) {\n return !evaluatePredicate(spec.$not, facts, prev, depth + 1);\n }\n\n // Object form — every key AND-ed.\n for (const key of Object.keys(spec)) {\n if (PREDICATE_OPERATORS.has(key)) {\n devWarn(\n `predicate: operator \"${key}\" mixed with fact keys — wrap operators in a per-fact object`,\n );\n\n return false;\n }\n if (!evalField(spec[key], facts?.[key], prev?.[key], depth)) {\n return false;\n }\n }\n\n return true;\n}\n\n/**\n * Evaluate a predicate and return a per-clause breakdown — the data feed for\n * devtools, `system.explain()`, and `directive explain`.\n *\n * @example\n * ```ts\n * evaluatePredicateExplained(\n * { phase: \"red\", elapsed: { $gte: 30 } },\n * { phase: \"red\", elapsed: 20 },\n * );\n * // → [\n * // { path: \"phase\", op: \"$eq\", expected: \"red\", actual: \"red\", pass: true },\n * // { path: \"elapsed\", op: \"$gte\", expected: 30, actual: 20, pass: false },\n * // ]\n * ```\n */\nexport function evaluatePredicateExplained(\n spec: unknown,\n facts: Scope,\n prev?: Scope,\n pathPrefix = \"\",\n): ClauseResult[] {\n const out: ClauseResult[] = [];\n\n if (Array.isArray(spec)) {\n for (const clause of spec) {\n if (!isPlainObject(clause)) {\n continue;\n }\n const { fact, op, value } = clause as {\n fact: string;\n op: PredicateOp;\n value: unknown;\n };\n const actual = facts?.[fact];\n out.push({\n path: pathPrefix + fact,\n op,\n expected: value,\n actual,\n pass: applyOperator(op, actual, value, prev?.[fact]),\n });\n }\n\n return out;\n }\n\n if (!isPlainObject(spec)) {\n return out;\n }\n\n for (const key of [\"$all\", \"$any\", \"$not\"] as const) {\n if (key in spec) {\n const childSpecs =\n key === \"$not\" ? [spec.$not] : (spec[key] as unknown[]);\n const children: ClauseResult[] = [];\n for (const child of childSpecs) {\n children.push(\n ...evaluatePredicateExplained(child, facts, prev, pathPrefix),\n );\n }\n const passCount = children.filter((c) => c.pass).length;\n let pass: boolean;\n if (key === \"$all\") {\n pass = children.length === 0 || passCount === children.length;\n } else if (key === \"$any\") {\n pass = children.length > 0 && passCount > 0;\n } else {\n // $not — single child wrapped above\n pass = !children.every((c) => c.pass);\n }\n out.push({\n path: pathPrefix || key,\n op: key,\n expected: childSpecs.length,\n actual: passCount,\n pass,\n children,\n });\n\n return out;\n }\n }\n\n for (const key of Object.keys(spec)) {\n if (PREDICATE_OPERATORS.has(key)) {\n continue;\n }\n const value = spec[key];\n const actual = facts?.[key];\n const path = pathPrefix + key;\n\n if (isOperatorObject(value)) {\n for (const op of Object.keys(value)) {\n out.push({\n path,\n op: op as PredicateOp,\n expected: value[op],\n actual,\n pass: applyOperator(\n op as PredicateOp,\n actual,\n value[op],\n prev?.[key],\n ),\n });\n }\n } else if (isPlainObject(value)) {\n out.push(\n ...evaluatePredicateExplained(\n value,\n isPlainObject(actual) ? actual : Object.create(null),\n isPlainObject(prev?.[key]) ? (prev?.[key] as Scope) : undefined,\n `${path}.`,\n ),\n );\n } else {\n out.push({\n path,\n op: \"$eq\",\n expected: value,\n actual,\n pass: deepEqual(actual, value),\n });\n }\n }\n\n return out;\n}\n\nconst memoizedCache = new WeakMap<\n object,\n (facts: Scope, prev?: Scope) => boolean\n>();\n\n/**\n * Memoize a predicate as a reusable evaluation closure.\n *\n * The returned function accepts any `facts` scope (the reactive proxy in\n * production, a plain object in tests) plus an optional `prev` snapshot for\n * `$changed`. The closure is cached **by predicate identity** in a\n * `WeakMap`, so passing the same `predicate` reference repeatedly is\n * allocation-free; cleanup is automatic once the predicate is no longer\n * reachable.\n *\n * Note: no actual compilation happens — the returned closure re-walks the\n * spec on every call via `evaluatePredicate`. The name reflects what the\n * function does (closure memoization keyed by predicate identity), not a\n * bytecode/AST compile step.\n *\n * Intended for advanced users who want a stable function reference per\n * predicate (custom devtools, batched analyses). Regular module code does\n * not need to call this — the engine wraps data-form `when` / `on` specs\n * automatically at registration.\n *\n * @example\n * ```ts\n * const predicate = { phase: \"red\", elapsed: { $gte: 30 } };\n * const check = memoizePredicate(predicate);\n * check({ phase: \"red\", elapsed: 45 }); // → true\n * check({ phase: \"red\", elapsed: 5 }); // → false\n * ```\n */\nexport function memoizePredicate(\n predicate: object,\n): (facts: Scope, prev?: Scope) => boolean {\n if (predicate === null || typeof predicate !== \"object\") {\n throw new Error(\n `[Directive] memoizePredicate: predicate must be a plain object or array; got ${typeof predicate}`,\n );\n }\n const cached = memoizedCache.get(predicate);\n if (cached) {\n return cached;\n }\n\n const fn = (facts: Scope, prev?: Scope): boolean =>\n evaluatePredicate(predicate, facts, prev);\n memoizedCache.set(predicate, fn);\n\n return fn;\n}\n\n// ============================================================================\n// Dependency extraction\n// ============================================================================\n\n/**\n * Collect the fact keys a predicate references. Used for static analysis,\n * devtools, and effect `on` dependency wiring. Nested predicates contribute\n * dotted keys (`auth.token`).\n *\n * @example\n * ```ts\n * extractDeps({ phase: \"red\", elapsed: { $gte: 30 } });\n * // → Set { \"phase\", \"elapsed\" }\n * extractDeps({ self: { phase: \"red\" }, auth: { token: { $exists: true } } });\n * // → Set { \"self.phase\", \"auth.token\" }\n * ```\n */\nexport function extractDeps(spec: unknown, prefix = \"\"): Set<string> {\n const deps = new Set<string>();\n\n // Single structural traversal — every operator clause and equality leaf\n // contributes its dotted fact path. Combinators and nested objects are\n // descended automatically; stray `$`-keys never synthesize phantom deps.\n walkPredicate(spec, {\n operator(factPath) {\n deps.add(prefix + factPath);\n },\n literal(factPath) {\n deps.add(prefix + factPath);\n },\n strayOperatorKey(key) {\n // A `$`-key at fact position never synthesizes a phantom dep. A typo'd\n // operator (e.g. `$eqq`) additionally dev-warns; a known operator\n // mixed with fact keys is skipped silently (evaluatePredicate warns).\n if (!PREDICATE_OPERATORS.has(key)) {\n devWarn(\n `extractDeps: unknown operator \"${key}\" — skipping. Known operators: ${[...PREDICATE_OPERATORS].join(\", \")}`,\n );\n }\n },\n });\n\n return deps;\n}\n\n// ============================================================================\n// Templates\n// ============================================================================\n\nconst IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/** Stringify a value without dev-warns for null/undefined — used when the\n * caller has already emitted a higher-level diagnostic (e.g. \"unknown key\"). */\nfunction stringifyValueQuiet(v: unknown): string {\n if (typeof v === \"symbol\") {\n return \"\";\n }\n if (v === undefined || v === null) {\n return \"\";\n }\n\n return String(v);\n}\n\nfunction stringifyValue(v: unknown, key?: string): string {\n if (typeof v === \"symbol\") {\n devWarn(\"template: cannot interpolate a symbol value — using empty string\");\n\n return \"\";\n }\n if (v === undefined) {\n devWarn(\n `template: ${key ? `key \"${key}\" is ` : \"\"}undefined — using empty string`,\n );\n\n return \"\";\n }\n if (v === null) {\n devWarn(\n `template: ${key ? `key \"${key}\" is ` : \"\"}null — using empty string`,\n );\n\n return \"\";\n }\n\n return String(v);\n}\n\n/**\n * Interpolate a {@link FactTemplate} against a scope. Single-pass character\n * scanner: `${ident}` interpolates `scope[ident]`; `$${` emits a literal\n * `${`; unknown keys dev-warn and yield an empty string.\n *\n * @example\n * ```ts\n * evaluateTemplate({ $template: \"Hi ${name}!\" }, { name: \"Ada\" });\n * // → \"Hi Ada!\"\n * evaluateTemplate({ $template: \"$${price}\" }, {});\n * // → \"${price}\"\n * ```\n */\nexport function evaluateTemplate(spec: FactTemplate, scope: Scope): string {\n const tpl = spec.$template;\n let out = \"\";\n let i = 0;\n\n while (i < tpl.length) {\n if (tpl[i] === \"$\" && tpl[i + 1] === \"$\" && tpl[i + 2] === \"{\") {\n out += \"${\";\n i += 3;\n continue;\n }\n\n if (tpl[i] === \"$\" && tpl[i + 1] === \"{\") {\n const end = tpl.indexOf(\"}\", i + 2);\n if (end === -1) {\n devWarn(`template: unterminated \"\\${\" in ${JSON.stringify(tpl)}`);\n out += tpl.slice(i);\n break;\n }\n const key = tpl.slice(i + 2, end);\n if (!IDENTIFIER.test(key)) {\n devWarn(\n `template: invalid placeholder \"\\${${key}}\" — not an identifier`,\n );\n } else {\n // `stringifyValue` dev-warns separately for null vs undefined; here\n // we only warn when the key itself is missing from the scope (vs\n // present-but-null), so users see distinct diagnostics. Use\n // Object.hasOwn rather than `in` so prototype-chain keys (e.g.\n // `toString`, `constructor`) are never interpolated.\n const present = scope != null && Object.hasOwn(scope, key);\n const value = present ? scope[key] : undefined;\n if (!present) {\n devWarn(`template: unknown key \"${key}\"`);\n out += stringifyValueQuiet(value);\n } else {\n out += stringifyValue(value, key);\n }\n }\n i = end + 1;\n continue;\n }\n\n out += tpl[i];\n i++;\n }\n\n return out;\n}\n\n/**\n * Collect the placeholder keys referenced by a template. The static-analysis\n * counterpart to {@link extractDeps} — useful for devtools, codegen, and\n * \"which facts does this template read\" inspections. Only valid identifier\n * placeholders are collected; malformed ones are ignored.\n *\n * @example\n * ```ts\n * extractTemplateKeys({ $template: \"${firstName} ${lastName}\" });\n * // → Set { \"firstName\", \"lastName\" }\n * extractTemplateKeys({ $template: \"$${literal}\" });\n * // → Set {} (escaped — not a placeholder)\n * ```\n */\nexport function extractTemplateKeys(spec: FactTemplate): Set<string> {\n const keys = new Set<string>();\n const tpl = spec.$template;\n let i = 0;\n\n while (i < tpl.length) {\n if (tpl[i] === \"$\" && tpl[i + 1] === \"$\" && tpl[i + 2] === \"{\") {\n i += 3;\n continue;\n }\n if (tpl[i] === \"$\" && tpl[i + 1] === \"{\") {\n const end = tpl.indexOf(\"}\", i + 2);\n if (end === -1) {\n break;\n }\n const key = tpl.slice(i + 2, end);\n if (IDENTIFIER.test(key)) {\n keys.add(key);\n }\n i = end + 1;\n continue;\n }\n i++;\n }\n\n return keys;\n}\n\n// ============================================================================\n// Selectors\n// ============================================================================\n\n/**\n * Build a stable dedup key by selecting fields from a requirement payload.\n * Order-as-declared; values are stable-stringified (keys sorted recursively)\n * so two payloads with the same fields in different orders dedupe to the\n * same key.\n *\n * @example\n * ```ts\n * evaluateKeySelector([\"url\", \"method\"], { url: \"/a\", method: \"GET\" });\n * // → '\"/a\"|\"GET\"'\n * evaluateKeySelector([\"id\"], { id: 42 });\n * // → '42'\n * ```\n */\nexport function evaluateKeySelector(\n selector: readonly string[],\n source: Record<string, unknown>,\n): string {\n return selector.map((field) => stableStringify(source?.[field])).join(\"|\");\n}\n\n// ============================================================================\n// Patch\n// ============================================================================\n\n/**\n * Apply a {@link PatchSpec} — assign facts from literals, payload copies\n * (`$ref`), or interpolated strings (`$template`). Mutates through the passed\n * `facts` proxy so change-tracking and downstream invalidation fire.\n *\n * @example\n * ```ts\n * const spec = {\n * $set: {\n * active: true,\n * userId: { $ref: \"id\" },\n * label: { $template: \"user ${name}\" },\n * },\n * };\n * applyPatch(spec, facts, { id: \"u_1\", name: \"Ada\" });\n * // facts.active = true; facts.userId = \"u_1\"; facts.label = \"user Ada\"\n * ```\n */\nexport function applyPatch(\n spec: PatchSpec<Record<string, unknown>, Record<string, unknown>>,\n facts: Record<string, unknown>,\n payload: Record<string, unknown>,\n): void {\n const set = spec.$set;\n const safePayload = payload ?? {};\n for (const key of Object.keys(set)) {\n const value = (set as Record<string, unknown>)[key];\n\n if (isTemplate(value)) {\n facts[key] = evaluateTemplate(value, safePayload);\n } else if (\n isPlainObject(value) &&\n Object.hasOwn(value, \"$ref\") &&\n typeof value.$ref === \"string\"\n ) {\n const refKey = value.$ref;\n // Use Object.hasOwn rather than `in` — tightens defense against\n // prototype-chain lookups so a payload `__proto__` shape can't smuggle\n // an inherited property into the fact assignment. The proxy already\n // blocks writes to dangerous keys, but this keeps the read symmetric.\n if (!Object.hasOwn(safePayload, refKey)) {\n devWarn(\n `applyPatch: $ref \"${refKey}\" is missing from event payload — assigning undefined to fact \"${key}\"`,\n );\n }\n facts[key] = safePayload[refKey];\n } else {\n facts[key] = value;\n }\n }\n}\n"]}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import {p,j as j$1,q,i as i$1,k as k$1,h as h$1,r,u,s,v}from'./chunk-O4GQEV4G.js';import {k,j,l,m,i,h}from'./chunk-3ETCZLAY.js';import {f,e,a,b,c,d,h as h$2}from'./chunk-PXRV64PA.js';var Ie=class extends Error{constructor(x,h,P,g,p=true){super(x);this.source=h;this.sourceId=P;this.context=g;this.recoverable=p;this.name="DirectiveError";}};function St(){return {create(f){return f}}}function Rt(){return {create(f){return f}}}function bt(f){return f}function wt(f){return f}function Kt(f){return f._mode==="single"}function Bt(f){return f._mode==="namespaced"}function fe(f){if(!f)return;let o=Object.assign(Object.create(null),f);return Array.isArray(o.tags)&&Object.freeze(o.tags),Object.freeze(o)}function Wt(f){return typeof f=="object"&&f!==null&&Object.hasOwn(f,"compute")&&typeof f.compute=="function"}function Dt(f){return typeof f=="boolean"?{enabled:f,maxSnapshots:100}:{enabled:true,maxSnapshots:f.maxSnapshots??100}}function Ze(f$1){let{historyOption:o,facts:x,store:h,onSnapshot:P,onHistoryChange:g}=f$1,{enabled:p,maxSnapshots:A}=Dt(o),z=[],M=-1,J=1,N=false,X=false,K=[],C=null,$=-1;function I(){return h.toObject()}function j(){let _=I();try{return structuredClone(_)}catch{try{return JSON.parse(JSON.stringify(_))}catch{return {..._}}}}function Q(_){if(!f(_)){console.error("[Directive] Potential prototype pollution detected in snapshot data, skipping restore");return}h.batch(()=>{for(let[W,te]of Object.entries(_)){if(W==="__proto__"||W==="constructor"||W==="prototype"){console.warn(`[Directive] Skipping dangerous key "${W}" during fact restoration`);continue}x[W]=te;}});}return {get isEnabled(){return p},get isRestoring(){return X},get isPaused(){return N},get snapshots(){return [...z]},get currentIndex(){return M},takeSnapshot(_){if(!p||N)return {id:-1,timestamp:Date.now(),facts:{},trigger:_};let W={id:J++,timestamp:Date.now(),facts:j(),trigger:_};for(M<z.length-1&&z.splice(M+1),z.push(W),M=z.length-1;z.length>A;)z.shift(),M--;return P?.(W),W},restore(_){if(p){N=true,X=true;try{Q(_.facts);}finally{N=false,X=false;}}},goBack(_=1){if(!p||z.length===0)return;let W=M,te=M,ne=K.find(l=>M>l.startIndex&&M<=l.endIndex);if(ne)te=ne.startIndex;else if(K.find(s=>M===s.startIndex)){let s=K.find(y=>y.endIndex<M&&M-y.endIndex<=_);te=s?s.startIndex:Math.max(0,M-_);}else te=Math.max(0,M-_);if(W===te)return;M=te;let c=z[M];c&&(this.restore(c),g?.(W,te));},goForward(_=1){if(!p||z.length===0)return;let W=M,te=M,ne=K.find(l=>M>=l.startIndex&&M<l.endIndex);if(ne?te=ne.endIndex:te=Math.min(z.length-1,M+_),W===te)return;M=te;let c=z[M];c&&(this.restore(c),g?.(W,te));},goTo(_){if(!p)return;let W=z.findIndex(c=>c.id===_);if(W===-1){console.warn(`[Directive] Snapshot ${_} not found`);return}let te=M;M=W;let ne=z[M];ne&&(this.restore(ne),g?.(te,W));},replay(){if(!p||z.length===0)return;M=0;let _=z[0];_&&this.restore(_);},export(){return JSON.stringify({version:1,snapshots:z,currentIndex:M})},import(_){if(p)try{let W=JSON.parse(_);if(typeof W!="object"||W===null)throw new Error("[Directive] Invalid history data: expected object");if(W.version!==1)throw new Error(`[Directive] Unsupported history export version: ${W.version}`);if(!Array.isArray(W.snapshots))throw new Error("[Directive] Invalid history data: snapshots must be an array");if(typeof W.currentIndex!="number")throw new Error("Invalid history data: currentIndex must be a number");for(let ne of W.snapshots){if(typeof ne!="object"||ne===null)throw new Error("[Directive] Invalid snapshot: expected object");if(typeof ne.id!="number"||typeof ne.timestamp!="number"||typeof ne.trigger!="string"||typeof ne.facts!="object")throw new Error("Invalid snapshot structure");if(!f(ne.facts))throw new Error("[Directive] Invalid fact data: potential prototype pollution detected in nested objects")}z.length=0,z.push(...W.snapshots),M=W.currentIndex;let te=z[M];te&&this.restore(te);}catch(W){console.error("[Directive] Failed to import history data:",W);}},beginChangeset(_){p&&(C=_,$=M);},endChangeset(){!p||C===null||(M>$&&K.push({label:C,startIndex:$,endIndex:M}),C=null,$=-1);},pause(){N=true;},resume(){N=false;}}}function Ye(){let f={id:-1,timestamp:0,facts:{},trigger:""};return {isEnabled:false,isRestoring:false,isPaused:false,snapshots:[],currentIndex:-1,takeSnapshot:()=>f,restore:()=>{},goBack:()=>{},goForward:()=>{},goTo:()=>{},replay:()=>{},export:()=>"{}",import:()=>{},beginChangeset:()=>{},endChangeset:()=>{},pause:()=>{},resume:()=>{}}}var Qe=new WeakMap;function kt(f,o){if(o)return o(f);let x=Qe.get(f);if(x!==void 0)return x;let{type:h,...P}=f,g=e(P),p=`${h}:${g}`;return Qe.set(f,p),p}function Ae(f,o,x){return {requirement:f,id:kt(f,x),fromConstraint:o}}function Xt(f){return o=>({type:f,...o})}function Gt(f,o){return f.type===o}function Zt(f){return o=>o.type===f}var ke=class f{map=new Map;add(o){this.map.has(o.id)||this.map.set(o.id,o);}remove(o){return this.map.delete(o)}has(o){return this.map.has(o)}get(o){return this.map.get(o)}all(){return [...this.map.values()]}ids(){return [...this.map.keys()]}get size(){return this.map.size}clear(){this.map.clear();}clone(){let o=new f;for(let x of this.map.values())o.add(x);return o}diff(o){let x=[],h=[];for(let P of this.map.values())o.has(P.id)||x.push(P);for(let P of o.map.values())this.map.has(P.id)||h.push(P);return {added:x,removed:h}}};var Et=5e3;function et(f){let{definitions:o,facts:x,requirementKeys:h$1={},defaultTimeout:P=Et,onEvaluate:g,onError:p$1}=f,A=new Map;function z(t,r){if(!r||typeof r.when=="function")return;let u=r.when;if(a&&(r.async&&console.warn(`[Directive] constraint "${t}": data \`when\` is always sync; \`async: true\` will be ignored`),r.deps&&console.warn(`[Directive] constraint "${t}": data \`when\` cannot be combined with explicit \`deps\` \u2014 deps are tracked automatically`)),r.deps&&(r.deps=void 0),M(u))throw new Error(`[Directive] constraint "${t}": $changed is effects-only \u2014 constraint when has no prev snapshot. Move the change-detection to an effect, or use a boolean derivation as a synthetic prev.`);if(u===null||typeof u!="object")throw new Error(`[Directive] memoizePredicate: predicate must be a plain object or array; got ${typeof u}`);a&&j$1(u)&&console.warn(`[Directive] constraint '${t}': data spec has no operators, combinators, or clauses \u2014 looks like a config object passed by mistake. Either pass a predicate like { phase: 'red' } or a function.`),b(u);let w=q(u);r.when=c("constraint",t,E=>w(E)),A.set(t,u),r.async&&(r.async=false);}function M(t){let r=false;return i$1(t,{operator(u,w){w==="$changed"&&(r=true);},strayOperatorKey(u){u==="$changed"&&(r=true);}}),r}for(let t of Object.keys(o))z(t,o[t]);let J=new Map,N=new Set,X=new Set,K=new Map,C=new Map,$=new Set,I=new Map,j=new Map,Q=false,oe=new Set,_=new Set,W=new Map,te=[],ne=new Map;function c$1(t,r){o[t]&&(W.has(t)||W.set(t,new Set),W.get(t).add(r));}function l(){W.clear();for(let[t,r]of Object.entries(o))if(r.after)for(let u of r.after)c$1(u,t);}function s(t,r,u,w,E){if(u.has(t))return;if(w.has(t)){let ae=r.indexOf(t),ce=[...r.slice(ae),t].join(" \u2192 ");throw new Error(`[Directive] Constraint cycle detected: ${ce}. Remove one of the \`after\` dependencies to break the cycle.`)}w.add(t),r.push(t);let Y=o[t];if(Y?.after)for(let ae of Y.after)o[ae]&&s(ae,r,u,w,E);r.pop(),w.delete(t),u.add(t),E.push(t);}function y(){let t=new Set,r=new Set,u=[];for(let w of Object.keys(o))s(w,[],t,r,u);te=u,ne=new Map(te.map((w,E)=>[w,E]));}y(),l();function O(){for(let[t,r]of Object.entries(o))if(r.after)for(let u of r.after)o[u]||console.warn(`[Directive] Constraint "${t}" references unknown constraint "${u}" in \`after\`. This dependency will be ignored. Check for typos or ensure the constraint exists.`);}a&&O();function G(t,r){return r.async!==void 0?r.async:!!X.has(t)}function re(t){let r=o[t];if(!r)throw new Error(`[Directive] Unknown constraint: ${t}`);let u=G(t,r);u&&X.add(t);let w={id:t,priority:r.priority??0,isAsync:u,lastResult:null,isEvaluating:false,error:null,lastResolvedAt:null,after:r.after??[],hitCount:0,lastActiveAt:null};return J.set(t,w),w}function le(t){return J.get(t)??re(t)}function ve(t,r){if(t.size!==r.size||t.size===0)return false;for(let u of r)if(!t.has(u))return false;return true}function S(t,r){for(let u of r){let w=C.get(u);w&&(w.delete(t),w.size===0&&C.delete(u));}}function i(t,r){for(let u of r)C.has(u)||C.set(u,new Set),C.get(u).add(t);}function D(t){let r=K.get(t);r&&(S(t,r),K.delete(t));}function T(t){W.delete(t);for(let r of W.values())r.delete(t);}function H(t,r){let u=K.get(t)??new Set;ve(u,r)||(S(t,u),i(t,r),K.set(t,r));}function ee(t,r){let u=r.when;if(r.deps)return I.set(t,new Set(r.deps)),u(x);let w=h(()=>u(x));return I.set(t,w.deps),w.value}function ue(t,r,u){r.lastResult=u,u&&(r.hitCount++,r.lastActiveAt=Date.now()),r.isEvaluating=false,g?.(t,u);}function me(t,r,u){r.error=u instanceof Error?u:new Error(String(u)),r.lastResult=false,r.isEvaluating=false,p$1?.(t,u);}function ye(t,r,u){return X.add(t),r.isAsync=true,a&&console.warn(`[Directive] Constraint "${t}" returned a Promise but was not marked as async. Add \`async: true\` to the constraint definition to avoid this warning and improve performance.`),u.then(w=>(ue(t,r,w),w)).catch(w=>(me(t,r,w),false))}function he(t){let r=o[t];if(!r)return false;let u=le(t);u.isEvaluating=true,u.error=null;try{let w=ee(t,r);return w instanceof Promise?ye(t,u,w):(ue(t,u,w),w)}catch(w){return me(t,u,w),false}}async function Se(t){let r=o[t];if(!r)return false;let u=le(t),w=r.timeout??P;if(u.isEvaluating=true,u.error=null,r.deps?.length){let E=new Set(r.deps);H(t,E),I.set(t,E);}try{let E=r.when(x),Y=await d(E,w,`Constraint "${t}" timed out after ${w}ms`);return u.lastResult=Y,Y&&(u.hitCount++,u.lastActiveAt=Date.now()),u.isEvaluating=!1,g?.(t,Y),Y}catch(E){return u.error=E instanceof Error?E:new Error(String(E)),u.lastResult=false,u.isEvaluating=false,p$1?.(t,E),false}}let we=10;function Me(t,r){if(t==null)return [];if(Array.isArray(t)){let u=t.filter(w=>w!=null);return a&&u.length>we&&r&&console.warn(`[Directive] Constraint "${r}" produced ${u.length} requirements. Consider splitting into multiple constraints for better performance.`),u}return [t]}function Re(t){let r=o[t];if(!r)return {requirements:[],deps:new Set};let u=r.require;if(typeof u=="function"){let{value:E,deps:Y}=h(()=>u(x));return {requirements:Me(E,t),deps:Y}}return {requirements:Me(u,t),deps:new Set}}function F(t,r){if(r.size===0)return;let u=K.get(t)??new Set;for(let w of r)u.add(w);i(t,r),K.set(t,u);}let ie=null;function ge(){return ie||(ie=Object.keys(o).sort((t,r)=>{let u=le(t),E=le(r).priority-u.priority;if(E!==0)return E;let Y=ne.get(t)??0,ae=ne.get(r)??0;return Y-ae})),ie}for(let t of Object.keys(o))re(t);function De(t){for(let[r,u]of Object.entries(t))u.async&&!u.deps&&console.warn(`[Directive] Async constraint "${r}" has no \`deps\` declared. Auto-tracking cannot work across async boundaries. Add \`deps: ["key1", "key2"]\` to enable dependency tracking.`);}a&&De(o);function qe(t){return !o[t]||N.has(t)||_.has(t)?true:oe.has(t)}function d$1(t){let r=J.get(t);if(!r||r.after.length===0)return true;for(let u of r.after)if(!qe(u))return false;return true}function m(t){let r=I.get(t);r!==void 0&&H(t,r),_.add(t),j.set(t,[]);}function v(t,r,u){if(r!==void 0){let w=new Set(r);for(let E of u)w.add(E);H(t,w);}else F(t,u);}function q$1(t,r,u){if(r.length===0){j.set(t,[]);return}let w=r.map(E=>Ae(E,t,h$1[E.type]));for(let E of w)u.add(E);j.set(t,w);}function L(t,r){for(let u of t)r.add(u);}function e(t,r,u){if(N.has(t))return;if(!r){m(t);return}_.delete(t);let w=I.get(t),E,Y;try{let ae=Re(t);E=ae.requirements,Y=ae.deps;}catch(ae){p$1?.(t,ae),m(t);return}v(t,w,Y),q$1(t,E,u);}function n(t,r){let u=[],w=[];for(let E of t){if(d$1(E)){w.push(E);continue}u.push(E);let Y=j.get(E);Y&&L(Y,r);}return {blocked:u,ready:w}}function a$1(t,r){let u=[];for(let w of t){let E=he(w);if(E instanceof Promise){u.push({id:w,promise:E});continue}e(w,E,r);}return u}async function b$1(t,r){let u=await Promise.all(t.map(async({id:w,promise:E})=>({id:w,active:await E})));for(let{id:w,active:E}of u)e(w,E,r);}async function R(t,r){let{blocked:u,ready:w}=n(t,r);if(w.length===0)return u;let E=[],Y=[];for(let ce of w)le(ce).isAsync?Y.push(ce):E.push(ce);let ae=a$1(E,r);if(ae.length>0&&await b$1(ae,r),Y.length>0){let ce=Y.map(pe=>({id:pe,promise:Se(pe)}));await b$1(ce,r);}return u}function k(t,r){for(let u of t){let w=C.get(u);if(w)for(let E of w)N.has(E)||r.add(E);}}function B(t){for(let r of $)N.has(r)||t.add(r);$.clear();}function U(t){let r=new Set;return k(t,r),B(r),r}function Z(t,r,u){for(let w of t){if(r.has(w))continue;let E=j.get(w);E&&L(E,u);}}return {async evaluate(t){let r=new ke;_.clear();let u=ge(),w=N.size===0?u:u.filter(ce=>!N.has(ce)),E;if(!Q||!t||t.size===0)E=w,Q=true;else {let ce=U(t);E=[...ce],Z(w,ce,r);}let Y=E,ae=E.length+1;for(;Y.length>0&&ae>0;){let ce=Y.length;if(Y=await R(Y,r),Y.length===ce)break;ae--;}return r.all()},getState(t){return J.get(t)},getDependencies(t){return K.get(t)},getAllStates(){return [...J.values()]},disable(t){if(!J.has(t)){console.warn(`[Directive] constraints.disable("${t}") \u2014 no such constraint`);return}N.add(t),ie=null,j.delete(t),D(t),I.delete(t);},enable(t){if(!J.has(t)){console.warn(`[Directive] constraints.enable("${t}") \u2014 no such constraint`);return}N.delete(t),ie=null,$.add(t);},isDisabled(t){return N.has(t)},invalidate(t){let r=C.get(t);if(r)for(let u of r)$.add(u);},markResolved(t){oe.add(t);let r=J.get(t);r&&(r.lastResolvedAt=Date.now());let u=W.get(t);if(u)for(let w of u)$.add(w);},isResolved(t){return oe.has(t)},registerDefinitions(t){let r=false;for(let[u,w]of Object.entries(t))o[u]=w,z(u,o[u]),re(u),$.add(u),w.after?.length&&(r=true);ie=null,r&&y(),l();},assignDefinition(t,r){if(!o[t])throw new Error(`[Directive] Cannot assign constraint "${t}" \u2014 it does not exist. Use register() to create it.`);o[t]=r,A.delete(t),z(t,o[t]),re(t),$.add(t),ie=null,y(),l();},unregisterDefinition(t){o[t]&&(delete o[t],J.delete(t),N.delete(t),X.delete(t),$.delete(t),_.delete(t),oe.delete(t),j.delete(t),I.delete(t),D(t),T(t),ie=null,y(),l());},async callOne(t,r){if(!o[t])throw new Error(`[Directive] Cannot call constraint "${t}" \u2014 it does not exist.`);if(N.has(t))return [];let w=le(t),E;if(w.isAsync)E=await Se(t);else {let ce=he(t);E=ce instanceof Promise?await ce:ce;}if(!E)return [];let{requirements:Y}=Re(t);if(Y.length===0)return [];let ae=[];for(let ce of Y){let pe=r?{...ce,...r}:ce;ae.push(Ae(pe,t,h$1[pe.type]));}return ae},setRequirementKey(t,r){h$1[t]=r;},removeRequirementKey(t){delete h$1[t];},getWhenSpec(t){return A.get(t)},explainWhen(t){let r=A.get(t);if(r)return p(r,x)}}}function tt(f){let{definitions:o,facts:x,onCompute:h$1,onInvalidate:P,onError:g}=f,p=3,A=new Map;function z(S,i){if(typeof i!="object"||i===null||!Object.hasOwn(i,"compute"))return;let D=i,T=D.compute,H;if(typeof T=="function")H=T;else if(k$1(T))b(T),H=ee=>s(T,ee);else if(typeof T=="object"&&T!==null){b(T);let ee=q(T);H=c("derivation",S,ue=>ee(ue));}else if(T!==void 0)throw new Error(`[Directive] memoizePredicate: predicate must be a plain object or array; got ${typeof T}`);if(H){o[S]=H;let ee=fe(D.meta);ee&&A.set(S,ee);}}for(let[S,i]of Object.entries(o))z(S,i);let M=new Map,J=new Map,N=new Map,X=new Map,K=0,C=new Set,$=false,I=100,j$1;function Q(S,i){let D=M.has(S)?X:N,T=D.get(S);T?.delete(i),T&&T.size===0&&D.delete(S);}function oe(S,i){let D=o[S]?X:N,T=D.get(S);T||(T=new Set,D.set(S,T)),T.add(i);}function _(S){let i=M.get(S);if(i)for(let D of i.dependencies)Q(D,S);}function W(S){let i=X.get(S);if(i){K++;try{for(let D of i)le(D);}finally{K--;}X.delete(S);}}function te(S){delete o[S],M.delete(S),J.delete(S),C.delete(S),A.delete(S);}function ne(S){if(!o[S])throw new Error(`[Directive] Unknown derivation: ${S}`);let D={id:S,compute:()=>l(S),cachedValue:void 0,dependencies:new Set,isStale:true,isComputing:false,stableRunCount:0,depsStable:false};return M.set(S,D),D}function c$1(S){return M.get(S)??ne(S)}function l(S){let i=c$1(S),D=o[S];if(!D)throw new Error(`[Directive] Unknown derivation: ${S}`);if(i.isComputing)throw new Error(`[Directive] Circular dependency detected in derivation: ${S}`);i.isComputing=true;try{let T=i.cachedValue,H,ee;if(i.depsStable&&i.dependencies.size>0)H=D(x,j$1),ee=i.dependencies;else {let ue=h(()=>D(x,j$1));H=ue.value,ee=ue.deps,i.dependencies.size>0&&s$1(ee,i.dependencies)?(i.stableRunCount++,i.stableRunCount>=p&&(i.depsStable=!0)):i.stableRunCount=0;}return i.cachedValue=H,i.isStale=!1,y(S,ee),h$1&&h$1(S,H,T,[...ee]),H}catch(T){throw g?.(S,T),T}finally{i.isComputing=false;}}function s$1(S,i){if(S.size!==i.size)return false;for(let D of i)if(!S.has(D))return false;return true}function y(S,i){let D=c$1(S),T=D.dependencies;if(!s$1(T,i)){for(let H of T)Q(H,S);for(let H of i)oe(H,S);D.dependencies=i;}}function O(S){for(let i of S){let D=J.get(i);if(D)for(let T of D)T();}}function G(){if(!(K>0||$)){$=true;try{let S=0;for(;C.size>0;){if(++S>I){let D=[...C];throw C.clear(),new Error(`[Directive] Infinite derivation notification loop detected after ${I} iterations. Remaining: ${D.join(", ")}. This usually means a derivation listener is mutating facts that re-trigger the same derivation.`)}let i=[...C];C.clear(),O(i);}}finally{$=false;}}}function re(S,i){let D=X.get(S);if(D)for(let T of D)i.push(T);}function le(S,i=new Set){let D=[S];for(;D.length>0;){let T=D.pop();if(i.has(T))continue;i.add(T);let H=M.get(T);!H||H.isStale||(H.isStale=true,H.depsStable=false,H.stableRunCount=0,P?.(T),C.add(T),re(T,D));}}return j$1=new Proxy({},{get(S,i){if(typeof i=="symbol"||k.has(i)||!o[i])return;j(i);let D=c$1(i);return D.isStale&&l(i),D.cachedValue},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),{get(S){let i=c$1(S);return i.isStale&&l(S),i.cachedValue},isStale(S){return M.get(S)?.isStale??true},invalidate(S){let i=N.get(S);if(!i)return;K++;let D=new Set;try{for(let T of i)le(T,D);}finally{K--,G();}},invalidateMany(S){K++;let i=new Set;try{for(let D of S){let T=N.get(D);if(T)for(let H of T)le(H,i);}}finally{K--,G();}},invalidateAll(){K++;try{for(let S of M.values())S.isStale||(S.isStale=!0,S.depsStable=!1,S.stableRunCount=0,C.add(S.id));}finally{K--,G();}},subscribe(S,i){for(let D of S){let T=D;J.has(T)||J.set(T,new Set),J.get(T).add(i);}return ()=>{for(let D of S){let T=D,H=J.get(T);H?.delete(i),H&&H.size===0&&J.delete(T);}}},getProxy(){return j$1},getDependencies(S){return c$1(S).dependencies},registerDefinitions(S){for(let[i,D]of Object.entries(S))typeof D=="function"?o[i]=D:z(i,D),ne(i);},assignDefinition(S,i){if(!o[S])throw new Error(`[Directive] Cannot assign derivation "${S}" \u2014 it does not exist. Use register() to create it.`);typeof i=="function"?(o[S]=i,A.delete(S)):(A.delete(S),z(S,i));let D=M.get(S);D&&(D.isStale=true,D.depsStable=false,D.stableRunCount=0,C.add(S)),G();},unregisterDefinition(S){o[S]&&(_(S),W(S),te(S),G());},getMeta(S){return A.get(S)},callOne(S){if(!o[S])throw new Error(`[Directive] Cannot call derivation "${S}" \u2014 it does not exist.`);return l(S)}}}var Mt=3;function nt(f){let{definitions:o,facts:x,store:h$2,onRun:P,onError:g}=f,p=new Map,A=null,z=false,M=new Map;function J(c$1){let l=o[c$1];if(!l)throw new Error(`[Directive] Unknown effect: ${c$1}`);M.delete(c$1);let s=null,y=false;if(l.deps)s=new Set(l.deps),y=true;else if(l.on!==void 0){if(!h$1(l.on))throw new Error(`[Directive] effect on must be a FactPredicate spec; got ${typeof l.on}`);if(l.on===null||typeof l.on!="object")throw new Error(`[Directive] memoizePredicate: predicate must be a plain object or array; got ${typeof l.on}`);b(l.on),s=r(l.on),y=true;let G=q(l.on);M.set(c$1,c("effect",c$1,(re,le)=>G(re,le)));}let O={id:c$1,enabled:true,hasExplicitDeps:y,dependencies:s,cleanup:null,stableRunCount:0,depsStable:false};return p.set(c$1,O),O}function N(c){return p.get(c)??J(c)}function X(){return h$2.toObject()}function K(c){c.depsStable=false,c.stableRunCount=0;}function C(c,l){for(let s of c)if(l.has(s))return true;return false}function $(c,l){let s=N(c);if(!s.enabled)return false;if(s.dependencies){if(!C(s.dependencies,l))return false;s.depsStable&&K(s);let y=M.get(c);if(y){let O=X();return y(O,A??void 0)}return true}return true}function I(c){if(c.cleanup){try{c.cleanup();}catch(l){g?.(c.id,l),console.error(`[Directive] Effect "${c.id}" cleanup threw an error:`,l);}c.cleanup=null;}}function j(c,l){if(typeof l=="function")if(z)try{l();}catch(s){g?.(c.id,s),console.error(`[Directive] Effect "${c.id}" cleanup threw an error:`,s);}else c.cleanup=l;}async function Q(c,l){let s;if(h$2.batch(()=>{s=l.run(x,A);}),s instanceof Promise){let y=await s;j(c,y);}else j(c,s);}function oe(c,l){if(c.size!==l.size)return false;for(let s of l)if(!c.has(s))return false;return true}function _(c,l){if(!(c.dependencies&&oe(c.dependencies,l))){K(c);return}c.stableRunCount++,c.stableRunCount>=Mt&&(c.depsStable=true);}async function W(c,l){if(c.depsStable&&c.dependencies){await Q(c,l);return}let s,y=h(()=>(h$2.batch(()=>{s=l.run(x,A);}),s)),O=y.deps,G=y.value;G instanceof Promise&&(G=await G),j(c,G),_(c,O),c.dependencies=O.size>0?O:null;}async function te(c){let l=N(c),s=o[c];if(!(!l.enabled||!s)){I(l),P?.(c,l.dependencies?[...l.dependencies]:[]);try{l.hasExplicitDeps?await Q(l,s):await W(l,s);}catch(y){g?.(c,y),console.error(`[Directive] Effect "${c}" threw an error:`,y),l.hasExplicitDeps||K(l);}}}for(let c of Object.keys(o))J(c);return {async runEffects(c){let l=[];for(let s of Object.keys(o))$(s,c)&&l.push(s);await Promise.all(l.map(te)),A=X();},async runAll(){let c=Object.keys(o);await Promise.all(c.map(l=>{let s=N(l);return s.enabled?(K(s),te(l)):Promise.resolve()})),A=X();},disable(c){let l=N(c);l.enabled=false;},enable(c){let l=N(c);l.enabled=true;},isEnabled(c){return N(c).enabled},cleanupAll(){z=true;for(let c of p.values())I(c);},registerDefinitions(c){for(let[l,s]of Object.entries(c))o[l]=s,J(l);},assignDefinition(c,l){if(!o[c])throw new Error(`[Directive] Cannot assign effect "${c}" \u2014 it does not exist. Use register() to create it.`);let s=p.get(c);s&&I(s),o[c]=l,J(c);},unregisterDefinition(c){if(!o[c])return;let l=p.get(c);l&&I(l),delete o[c],p.delete(c),M.delete(c);},async callOne(c){let l=o[c];if(!l)throw new Error(`[Directive] Cannot call effect "${c}" \u2014 it does not exist.`);let s=N(c);if(s.enabled){I(s),P?.(c,s.dependencies?[...s.dependencies]:[]);try{let y;if(h$2.batch(()=>{y=l.run(x,A);}),y instanceof Promise){let O=await y;j(s,O);}else j(s,y);}catch(y){g?.(c,y),console.error(`[Directive] Effect "${c}" threw an error:`,y);}}}}}function Ct(f={}){let{delayMs:o=1e3,maxRetries:x=3,backoffMultiplier:h=2,maxDelayMs:P=3e4}=f,g=new Map;function p(A){let z=o*h**(A-1);return Math.min(z,P)}return {scheduleRetry(A,z,M,J,N){if(J>x)return null;let X=p(J),K={source:A,sourceId:z,context:M,attempt:J,nextRetryTime:Date.now()+X,callback:N};return g.set(z,K),K},getPendingRetries(){return Array.from(g.values())},processDueRetries(){let A=Date.now(),z=[];for(let[M,J]of g)J.nextRetryTime<=A&&(z.push(J),g.delete(M));return z},cancelRetry(A){g.delete(A);},clearAll(){g.clear();}}}var xt={constraint:"skip",resolver:"skip",effect:"skip",derivation:"skip",system:"throw"};function rt(f={}){let{config:o={},onError:x,onRecovery:h}=f,P=[],g=100,p=Ct(o.retryLater),A=new Map,z=1e3;function M(C,$,I,j){if(I instanceof Ie)return I;let Q=I instanceof Error?I.message:String(I),oe=C!=="system";return new Ie(Q,C,$,j,oe)}function J(C,$,I){let j=(()=>{switch(C){case "constraint":return o.onConstraintError;case "resolver":return o.onResolverError;case "effect":return o.onEffectError;case "derivation":return o.onDerivationError;default:return}})();if(typeof j=="function"){try{let Q=j(I,$);if(typeof Q=="string")return Q}catch(Q){console.error("[Directive] Error in error handler callback:",Q);}return "skip"}return typeof j=="string"?j:xt[C]}function N(C){P.push(C),P.length>g&&P.shift();try{x?.(C);}catch($){console.error("[Directive] Error in onError callback:",$);}try{o.onError?.(C);}catch($){console.error("[Directive] Error in config.onError callback:",$);}}function X(C,$,I){let j=(A.get($)??0)+1;if(A.set($,j),A.size>z){let oe=A.keys().next().value;oe!==void 0&&A.delete(oe);}return p.scheduleRetry(C,$,I,j)?"retry-later":(A.delete($),typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[Directive] ${C} "${$}" exceeded max retry-later attempts. Skipping.`),"skip")}return {handleError(C,$,I,j){let Q=M(C,$,I,j);N(Q);let oe=J(C,$,I instanceof Error?I:new Error(String(I)));oe==="retry-later"&&(oe=X(C,$,j));try{h?.(Q,oe);}catch(_){console.error("[Directive] Error in onRecovery callback:",_);}if(oe==="throw")throw Q;return oe},getLastError(){return P[P.length-1]??null},getAllErrors(){return [...P]},clearErrors(){P.length=0;},getRetryLaterManager(){return p},processDueRetries(){return p.processDueRetries()},clearRetryAttempts(C){A.delete(C),p.cancelRetry(C);}}}function It(f,o=100){try{return JSON.stringify(f)?.slice(0,o)??String(f)}catch{return "[circular or non-serializable]"}}function qt(f){let{schema:o,onChange:x,onBatch:h}=f,g=Object.keys(o).length===0,p=f.validate??a,A=f.strictKeys??(a&&!g),z=f.redactErrors??false,M=new Map,J=new Set,N=new Map,X=new Set,K=0,C=[],$=new Set,I=false,j$1=[],Q=100;function oe(i){return i!==null&&typeof i=="object"&&"safeParse"in i&&typeof i.safeParse=="function"&&"_def"in i&&"parse"in i&&typeof i.parse=="function"}function _(i){let D=i;if(D._typeName)return D._typeName;if(oe(i)){let T=i._def;if(T?.typeName)return T.typeName.replace(/^Zod/,"").toLowerCase()}return "unknown"}function W(i){return z?"[redacted]":It(i)}function te(i){return i===null?"null":Array.isArray(i)?"array":typeof i}function ne(i,D,T){let H=T.safeParse(D);if(H.success)return;let ee=te(D),ue=W(D),me=H.error?.message??H.error?.issues?.[0]?.message??"Validation failed",ye=_(T);throw new Error(`[Directive] Validation failed for "${i}": expected ${ye}, got ${ee} ${ue}. ${me}`)}function c(i){if(typeof i._lastFailedIndex=="number"&&i._lastFailedIndex>=0){let D=` (element at index ${i._lastFailedIndex} failed)`;return i._lastFailedIndex=-1,D}return ""}function l(i,D,T){let H=T._validators;if(!H||!Array.isArray(H)||H.length===0)return;let ee=T._typeName??"unknown";for(let ue=0;ue<H.length;ue++){let me=H[ue];if(typeof me!="function"||me(D))continue;let ye=te(D),he=W(D),Se=c(T),we=ue===0?"":` (validator ${ue+1} failed)`;throw new Error(`[Directive] Validation failed for "${i}": expected ${ee}, got ${ye} ${he}${we}${Se}`)}}function s(i){if(A)throw new Error(`[Directive] Unknown fact key: "${i}". Key not defined in schema.`);console.warn(`[Directive] Unknown fact key: "${i}"`);}function y(i,D){if(!p)return;let T=o[i];if(!T){s(i);return}if(oe(T)){ne(i,D,T);return}l(i,D,T);}function O(i){N.get(i)?.forEach(D=>D());}function G(){X.forEach(i=>i());}function re(i,D,T){if(I){j$1.push({key:i,value:D,prev:T});return}I=true;try{x?.(i,D,T),O(i),G(),le(". A listener is repeatedly mutating facts that re-trigger notifications");}finally{I=false;}}function le(i){let D=0;for(;j$1.length>0;){if(++D>Q)throw j$1.length=0,new Error(`[Directive] Infinite notification loop detected after ${Q} iterations${i}.`);let T=[...j$1];j$1.length=0;for(let H of T)x?.(H.key,H.value,H.prev),O(H.key);G();}}function ve(){if(!(K>0)){if(h&&C.length>0&&h([...C]),$.size>0){I=true;try{for(let i of $)O(i);G(),le(" during flush");}finally{I=false;}}C.length=0,$.clear();}}let S={get(i){return j(i),M.get(i)},has(i){return j(i),M.has(i)},set(i,D){a&&y(i,D);let T=M.get(i);Object.is(T,D)||(M.set(i,D),J.add(i),K>0?(C.push({key:i,value:D,prev:T,type:"set"}),$.add(i)):re(i,D,T));},delete(i){let D=M.get(i);M.delete(i),J.delete(i),K>0?(C.push({key:i,value:void 0,prev:D,type:"delete"}),$.add(i)):re(i,void 0,D);},batch(i){K++;try{i();}finally{K--,ve();}},subscribe(i,D){for(let T of i){let H=T;N.has(H)||N.set(H,new Set),N.get(H).add(D);}return ()=>{for(let T of i){let H=N.get(T);H&&(H.delete(D),H.size===0&&N.delete(T));}}},subscribeAll(i){return X.add(i),()=>X.delete(i)},toObject(){let i={};for(let D of J)M.has(D)&&(i[D]=M.get(D));return i}};return S.destroy=()=>{N.clear(),X.clear();},S.registerKeys=i=>{for(let D of Object.keys(i))k.has(D)||(o[D]=i[D],J.add(D));},S}var Fe=new WeakMap;function it(f,o,x=o){return new Proxy(f,{get(h,P){if(typeof P=="string"&&k.has(P))return;if(P===Symbol.for("nodejs.util.inspect.custom"))return ()=>h;let g=Reflect.get(h,P);if(typeof P=="symbol"||typeof g!="object"||g===null)return g;if(Fe.has(g))return Fe.get(g);let p=it(g,o,`${x}.${String(P)}`);return Fe.set(g,p),p},set(h,P,g){return typeof P!="symbol"&&console.warn(`[Directive] Nested mutation on "facts.${x}.${String(P)}" will not trigger reactivity. Use: facts.${o} = { ...facts.${o}, ... }`),Reflect.set(h,P,g)}})}function Tt(f,o){let x=()=>({get:P=>i(()=>f.get(P)),has:P=>i(()=>f.has(P))});return new Proxy({},{get(P,g){if(typeof g=="symbol")return g===Symbol.for("nodejs.util.inspect.custom")?()=>i(()=>f.toObject()):void 0;if(k.has(g))return;if(g==="$store")return f;if(g==="$snapshot")return x;let p=f.get(g);return a&&p!==null&&typeof p=="object"?it(p,g):p},set(P,g,p){if(typeof g=="symbol"||g==="$store"||g==="$snapshot"||k.has(g))return false;if(a){let A=l(p);A&&m(g,A);}return f.set(g,p),true},deleteProperty(P,g){return typeof g=="symbol"||g==="$store"||g==="$snapshot"||k.has(g)?false:(f.delete(g),true)},has(P,g){return g==="$store"||g==="$snapshot"?true:typeof g=="symbol"||k.has(g)?false:f.has(g)},ownKeys(){return Object.keys(o)},getOwnPropertyDescriptor(P,g){if(!(typeof g=="string"&&k.has(g)))return g==="$store"||g==="$snapshot"?{configurable:true,enumerable:false,writable:false}:{configurable:true,enumerable:true,writable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function st(f){let o=qt(f),x=Tt(o,f.schema);return {store:o,facts:x}}function ot(){let f=[];function o(g){if(g)try{return g()}catch(p){console.error("[Directive] Plugin error:",p);return}}async function x(g){if(g)try{return await g()}catch(p){console.error("[Directive] Plugin error:",p);return}}function h(g){return (...p)=>{for(let A of f)o(()=>A[g]?.(...p));}}return {register(g){f.some(p=>p.name===g.name)&&(console.warn(`[Directive] Plugin "${g.name}" is already registered, replacing...`),this.unregister(g.name)),f.push(g);},unregister(g){let p=f.findIndex(A=>A.name===g);p!==-1&&f.splice(p,1);},getPlugins(){return [...f]},async emitInit(g){for(let p of f)await x(()=>p.onInit?.(g));},emitStart:h("onStart"),emitStop:h("onStop"),emitDestroy:h("onDestroy"),emitFactSet:h("onFactSet"),emitFactDelete:h("onFactDelete"),emitFactsBatch:h("onFactsBatch"),emitDerivationCompute:h("onDerivationCompute"),emitDerivationInvalidate:h("onDerivationInvalidate"),emitReconcileStart:h("onReconcileStart"),emitReconcileEnd:h("onReconcileEnd"),emitConstraintEvaluate:h("onConstraintEvaluate"),emitConstraintError:h("onConstraintError"),emitRequirementCreated:h("onRequirementCreated"),emitRequirementMet:h("onRequirementMet"),emitRequirementCanceled:h("onRequirementCanceled"),emitResolverStart:h("onResolverStart"),emitResolverComplete:h("onResolverComplete"),emitResolverError:h("onResolverError"),emitResolverRetry:h("onResolverRetry"),emitResolverCancel:h("onResolverCancel"),emitResolverWriteRejected:h("onResolverWriteRejected"),emitEffectRun:h("onEffectRun"),emitEffectError:h("onEffectError"),emitSnapshot:h("onSnapshot"),emitHistoryNavigate:h("onHistoryNavigate"),emitError:h("onError"),emitErrorRecovery:h("onErrorRecovery"),emitDefinitionRegister:h("onDefinitionRegister"),emitDefinitionAssign:h("onDefinitionAssign"),emitDefinitionUnregister:h("onDefinitionUnregister"),emitDefinitionCall:h("onDefinitionCall"),emitTraceComplete:h("onTraceComplete")}}var at={attempts:1,backoff:"none",initialDelay:100,maxDelay:3e4},ct={enabled:false,windowMs:50};function Pt(f,o){if(!o||o==="none")return f;if(o==="full")return Math.floor(Math.random()*f);if(o==="equal"){let x=f/2;return Math.floor(x+Math.random()*x)}if(typeof o=="object"&&"maxMs"in o){let x=Number.isFinite(o.maxMs)&&o.maxMs>0?o.maxMs:0;return f+Math.floor(Math.random()*x)}return f}function Ot(f,o){let{backoff:x,initialDelay:h=100,maxDelay:P=3e4}=f,g;switch(x){case "none":g=h;break;case "linear":g=h*o;break;case "exponential":g=h*2**(o-1);break;default:g=h;}let p=Math.min(g,P),A=Pt(p,f.jitter);return Math.max(1,A)}function jt(f){if(a)for(let[o,x]of Object.entries(f)){if(!x.resolve&&!x.resolveBatch&&!x.resolveBatchWithResults)throw new Error(`[Directive] Resolver "${o}" must define either resolve() or resolveBatch(). Add one of these methods to handle requirements.`);if(!(!x.batch?.enabled||x.resolveBatch||x.resolveBatchWithResults))if(x.resolve)console.warn(`[Directive] Resolver "${o}" has batch.enabled but no resolveBatch(). Falling back to individual resolve() calls. Add resolveBatch() for true bulk operations.`);else throw new Error(`[Directive] Resolver "${o}" has batch.enabled=true but no resolve(), resolveBatch(), or resolveBatchWithResults() method.`)}}function lt(f){let{definitions:o,facts:x,store:h,getConstraintBinding:P,onStart:g,onComplete:p,onError:A,onRetry:z,onCancel:M,onClobber:J,onClobberSuppressed:N,onResolutionComplete:X,onRequeue:K}=f;jt(o);let C=new Map,$=new Map,I=1e3,j=new Map,Q=new Map,oe=1e3;function _(){if($.size>I){let d=$.size-I,m=$.keys();for(let v=0;v<d;v++){let q=m.next().value;q&&$.delete(q);}}}function W(d){return typeof d=="object"&&d!==null&&"requirement"in d&&typeof d.requirement=="string"}function te(d){return typeof d=="object"&&d!==null&&"requirement"in d&&typeof d.requirement=="function"}function ne(d,m){return W(d)?m.type===d.requirement:te(d)?d.requirement(m):false}function c(d,m){let v=Q.get(d);if(!v)return null;Q.delete(d),Q.set(d,v);for(let q of v){let L=o[q];if(L&&ne(L,m))return q}return null}function l(d,m){if(!Q.has(d)){if(Q.size>=oe){let v=Q.keys().next().value;v!==void 0&&Q.delete(v);}Q.set(d,new Set);}Q.get(d).add(m);}function s(d){let m=d.type,v=c(m,d);if(v)return v;for(let[q,L]of Object.entries(o))if(ne(L,d))return l(m,q),q;return null}function y(d){if(!P||!d||!d.fromConstraint)return null;let m=P(d.fromConstraint);return !m||m.fields.length===0?null:m}function O(d,m,v,q,L){let e=x,n=new Set(d.fields),a=10,b=0,R=false,k=new Map;for(let Z of n){let V=v?v[Z]:e[Z];k.set(Z,V);}let B=new Set;function U(Z){return B.has(Z)?false:Object.is(e[Z],k.get(Z))?true:(B.add(Z),b++,b<=a?q&&q(Z,k.get(Z),e[Z]):R||(R=true,L&&L(b-a)),m.abort(),false)}return new Proxy(x,{get(Z,V,t){return Reflect.get(x,V,t)},set(Z,V,t,r){if(typeof V!="string"||!n.has(V))return Reflect.set(x,V,t);if(!U(V))return true;let u=k.get(V);k.set(V,t);let w=Reflect.set(x,V,t);return w||k.set(V,u),w},deleteProperty(Z,V){if(typeof V!="string"||!n.has(V))return Reflect.deleteProperty(x,V);if(!U(V))return true;let t=k.get(V);k.set(V,void 0);let r=Reflect.deleteProperty(x,V);return r||k.set(V,t),r},has(Z,V){return Reflect.has(x,V)},ownKeys(){return Reflect.ownKeys(x)},getOwnPropertyDescriptor(Z,V){return Reflect.getOwnPropertyDescriptor(x,V)}})}function G(d,m,v,q,L,e){return {facts:v&&q?O(v,q,L,J&&e?(R,k,B)=>{let{resolverId:U,requirements:Z}=e;for(let V of Z)J(U,V,R,k,B);}:void 0,N&&e?R=>{let{resolverId:k,requirements:B}=e;for(let U of B)N(k,U,R);}:void 0):x,signal:d,snapshot:()=>x.$snapshot(),requeue:()=>{if(K)for(let R of m)K(R);}}}async function re(d,m,v,q){let L=d instanceof Error?d:new Error(String(d));if(q.signal.aborted)return {action:"abort",error:L};if(v.shouldRetry&&!v.shouldRetry(L,m))return {action:"break",error:L};if(m<v.attempts){if(q.signal.aborted)return {action:"abort",error:L};let e=Ot(v,m);if(await new Promise(n=>{let a=setTimeout(n,e),b=()=>{clearTimeout(a),n();};q.signal.addEventListener("abort",b,{once:true});}),q.signal.aborted)return {action:"abort",error:L}}return {action:"continue",error:L}}async function le(d$1,m,v,q,L,e){if(!d$1.resolve)return;let n=y(v),a;h.batch(()=>{a=d$1.resolve(v.requirement,G(q,[v.id],n,L,e,{resolverId:m,requirements:[v]}));});let b=d$1.timeout;if(b&&b>0){await d(a,b,`Resolver "${m}" timed out after ${b}ms`);return}await a;}function ve(d,m,v){let q=Date.now()-v;$.set(m.id,{state:"success",requirementId:m.id,completedAt:Date.now(),duration:q}),_(),p?.(d,m,q);}function S(d,m,v,q){$.set(m.id,{state:"error",requirementId:m.id,error:v,failedAt:Date.now(),attempts:q}),_(),A?.(d,m,v);}function i(d,m,v){let q=C.get(d);q&&(q.attempt=m,q.status={state:"running",requirementId:d,startedAt:v,attempt:m});}async function D(d,m,v,q,L){let e=await re(d,m,v,q);return e.action==="continue"&&m<v.attempts&&L(m+1),{lastError:e.error,shouldContinue:e.action==="continue"}}async function T(d,m,v,q){let L=o[d];if(!L)return;let e={...at,...L.retry},n=null,a=C.get(m.id)?.startedAt??Date.now();for(let b=1;b<=e.attempts;b++){if(v.signal.aborted)return;i(m.id,b,a);try{await le(L,d,m,v.signal,v,q),ve(d,m,a);return}catch(R){let k=await D(R,b,e,v,B=>z?.(d,m,B));if(n=k.lastError,!k.shouldContinue)break}}S(d,m,n,e.attempts);}async function H(d$1,m,v){return m&&m>0?d(d$1,m,v):d$1}async function ee(d,m,v,q,L,e,n,a){let b;h.batch(()=>{b=d.resolveBatchWithResults(q,L);});let R=await H(b,e,`Batch resolver "${m}" timed out after ${e}ms`);if(R.length!==v.length)throw new Error(`[Directive] Batch resolver "${m}" returned ${R.length} results but expected ${v.length}. Results array must match input order.`);let k=false;for(let B=0;B<v.length;B++){let U=v[B],Z=R[B];if(Z.success){ve(m,U,n);continue}k=true;let V=Z.error??new Error("Batch item failed");$.set(U.id,{state:"error",requirementId:U.id,error:V,failedAt:Date.now(),attempts:a}),A?.(m,U,V);}return !k||v.some((B,U)=>R[U]?.success)?"done":"retry"}async function ue(d,m,v,q,L,e,n){let a;h.batch(()=>{a=d.resolveBatch(q,L);}),await H(a,e,`Batch resolver "${m}" timed out after ${e}ms`);for(let b of v)ve(m,b,n);}function me(d,m,v,q){for(let L of m)S(d,L,v,q);}async function ye(d,m){await Promise.all(m.map(v=>{let q=new AbortController;return T(d,v,q)}));}async function he(d,m,v,q,L,e,n,a,b){let R=null;if(v.length>0){let U=v[0];v.every(V=>V.fromConstraint===U.fromConstraint)&&(R=y(U));}let k=G(q,v.map(U=>U.id),R,L,b,{resolverId:m,requirements:v}),B=v.map(U=>U.requirement);return d.resolveBatchWithResults?ee(d,m,v,B,k,e,n,a):(await ue(d,m,v,B,k,e,n),"done")}function Se(d,m,v){for(let q of m)z?.(d,q,v);}async function we(d,m,v,q,L,e){let n=new AbortController,a=Date.now(),b=null;for(let R=1;R<=q.attempts;R++){if(n.signal.aborted)return null;try{if(await he(d,m,v,n.signal,n,L,a,R,e)==="done")return null}catch(k){let B=await D(k,R,q,n,U=>Se(m,v,U));if(b=B.lastError,!B.shouldContinue)break}}return b}async function Me(d,m,v){let q=o[d];if(!q)return;if(!q.resolveBatch&&!q.resolveBatchWithResults){await ye(d,m);return}let L={...at,...q.retry},n={...ct,...q.batch}.timeoutMs??q.timeout,a=await we(q,d,m,L,n,v);a&&me(d,m,a,L.attempts);}let Re=1e4;function F(d){d.timer&&(clearTimeout(d.timer),d.timer=null);}function ie(d){return j.has(d)||j.set(d,{resolverId:d,requirements:[],baselines:[],timer:null}),j.get(d)}function ge(d,m,v){let q=o[d];if(!q)return;let L={...ct,...q.batch},e=ie(d),n=L.maxSize||Re;if(e.requirements.length>=n&&(F(e),De(d)),e.requirements.push(m),e.baselines.push(v),L.maxSize&&e.requirements.length>=L.maxSize){F(e),De(d);return}F(e),e.timer=setTimeout(()=>{De(d);},L.windowMs);}function De(d){let m=j.get(d);if(!m||m.requirements.length===0)return;let v=[...m.requirements],q;for(let L=m.baselines.length-1;L>=0;L--){let e=m.baselines[L];if(e!==void 0){q=e;break}}m.requirements=[],m.baselines=[],m.timer=null,Me(d,v,q).then(()=>{X?.();});}return {resolve(d,m){if(C.has(d.id))return;let v=s(d.requirement);if(!v){a&&console.warn(`[Directive] No resolver found for requirement type "${d.requirement.type}" (id: ${d.id})`);return}let q=o[v];if(!q)return;if(q.batch?.enabled){ge(v,d,m?.factsBaseline);return}let L=new AbortController,e=Date.now(),n={requirementId:d.id,resolverId:v,controller:L,startedAt:e,attempt:1,status:{state:"pending",requirementId:d.id,startedAt:e},originalRequirement:d};C.set(d.id,n),g?.(v,d),T(v,d,L,m?.factsBaseline).finally(()=>{C.delete(d.id)&&X?.();});},cancel(d){let m=C.get(d);if(m){m.controller.abort(),C.delete(d),$.set(d,{state:"canceled",requirementId:d,canceledAt:Date.now()}),_(),M?.(m.resolverId,m.originalRequirement);return}for(let v of j.values()){let q=v.requirements.findIndex(L=>L.id===d);if(q!==-1){let[L]=v.requirements.splice(q,1);v.baselines.splice(q,1),$.set(d,{state:"canceled",requirementId:d,canceledAt:Date.now()}),_(),L&&M?.(v.resolverId,L);return}}},detach(d){C.delete(d);},cancelAll(){let d=[...C.keys()];for(let m of d)this.cancel(m);for(let m of j.values()){m.timer&&clearTimeout(m.timer);for(let v of m.requirements)$.set(v.id,{state:"canceled",requirementId:v.id,canceledAt:Date.now()}),M?.(m.resolverId,v);}j.clear(),_();},getStatus(d){let m=C.get(d);if(m)return m.status;let v=$.get(d);return v||{state:"idle"}},getInflight(){return [...C.keys()]},getInflightInfo(){return [...C.values()].map(d=>({id:d.requirementId,resolverId:d.resolverId,startedAt:d.startedAt}))},getInflightCount(){return C.size},isResolving(d){return C.has(d)},processBatches(){for(let d of j.keys())De(d);},hasPendingBatches(){for(let d of j.values())if(d.requirements.length>0)return true;return false},registerDefinitions(d){for(let[m,v]of Object.entries(d))o[m]=v;Q.clear();},assignDefinition(d,m){if(!o[d])throw new Error(`[Directive] Cannot assign resolver "${d}" \u2014 it does not exist. Use register() to create it.`);o[d]=m,Q.clear();},unregisterDefinition(d){if(!o[d])return;for(let[v,q]of C)q.resolverId===d&&(q.controller.abort(),C.delete(v),$.set(v,{state:"canceled",requirementId:v,canceledAt:Date.now()}),M?.(d,q.originalRequirement));let m=j.get(d);if(m){m.timer&&clearTimeout(m.timer);for(let v of m.requirements)$.set(v.id,{state:"canceled",requirementId:v.id,canceledAt:Date.now()}),M?.(d,v);j.delete(d);}delete o[d],Q.clear(),_();},async callOne(d,m){let v=o[d];if(!v)throw new Error(`[Directive] Cannot call resolver "${d}" \u2014 it does not exist.`);let q=new AbortController,L=G(q.signal,[]);if(v.resolve){let e;h.batch(()=>{e=v.resolve(m,L);}),await e;}},destroy(){this.cancelAll(),$.clear(),Q.clear();}}}function dt(f){let{mergedDerive:o,getDerivation:x,definitions:h}=f,P={register:(g,p)=>h.register("derivation",g,p),assign:(g,p)=>h.assign("derivation",g,p),unregister:g=>h.unregister("derivation",g),call:g=>h.call("derivation",g),isDynamic:g=>h.isDynamic("derivation",g),listDynamic:()=>h.listDynamic("derivation")};return new Proxy({},{get(g,p){if(typeof p!="symbol"&&!k.has(p)){if(p in P)return P[p];if(p in o)return x(p)}},has(g,p){return typeof p=="symbol"||k.has(p)?false:p in o||p in P},ownKeys(){return Object.keys(o)},getOwnPropertyDescriptor(g,p){if(typeof p!="symbol"&&!k.has(p)&&(p in o||p in P))return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function ut(f){let{mergedEvents:o,dispatchEvent:x}=f;return new Proxy({},{get(h,P){if(typeof P!="symbol"&&!k.has(P))return g=>{x(P,g);}},has(h,P){return typeof P=="symbol"||k.has(P)?false:P in o},ownKeys(){return Object.keys(o)},getOwnPropertyDescriptor(h,P){if(typeof P!="symbol"&&!k.has(P)&&P in o)return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}var $t=new Set(["register","assign","unregister","call","isDynamic","listDynamic"]);function ft(f){let{mergedConstraints:o,mergedResolvers:x,mergedDerive:h,mergedEffects:P,constraintsManager:g,resolversManager:p,derivationsManager:A,effectsManager:z,pluginManager:M,getState:J,scheduleReconcile:N,maxDeferredRegistrations:X}=f,K={constraints:new Set,resolvers:new Set,derivations:new Set,effects:new Set},C={constraints:new Map,resolvers:new Map,derivations:new Map,effects:new Map},$=[];function I(c){if($t.has(c))throw new Error(`[Directive] Derivation ID "${c}" conflicts with a reserved derive method name.`)}let j={constraint:{label:"Constraint",mergedMap:o,manager:g,dynamicSet:K.constraints,originalsMap:C.constraints,reconciles:true},resolver:{label:"Resolver",mergedMap:x,manager:p,dynamicSet:K.resolvers,originalsMap:C.resolvers,reconciles:true},derivation:{label:"Derivation",mergedMap:h,manager:A,dynamicSet:K.derivations,originalsMap:C.derivations,reconciles:false,validateId:I},effect:{label:"Effect",mergedMap:P,manager:z,dynamicSet:K.effects,originalsMap:C.effects,reconciles:false}};function Q(c){if(typeof c!="string"||c.length===0)throw new Error(`[Directive] Definition ID must be a non-empty string. Received: ${String(c)}`);if(k.has(c))throw new Error(`[Directive] Security: Definition ID "${c}" is a blocked property.`);if(c.includes("::"))throw new Error(`[Directive] Definition ID "${c}" cannot contain "::". This separator is reserved for namespacing.`)}function oe(c,l,s){let y=j[c];if(y.validateId?.(l),l in y.mergedMap)throw new Error(`[Directive] ${y.label} "${l}" already exists. Use assign() to override.`);if(c!=="derivation"){let O=s;O.meta&&(O.meta=fe(O.meta));}y.mergedMap[l]=s,y.manager.registerDefinitions({[l]:s}),y.dynamicSet.add(l),M.emitDefinitionRegister(c,l,s),y.reconciles&&N();}function _(c,l,s){let y=j[c];if(y.validateId?.(l),!(l in y.mergedMap))throw new Error(`[Directive] ${y.label} "${l}" does not exist. Use register() to create it.`);if(c!=="derivation"){let G=s;G.meta&&(G.meta=fe(G.meta));}let O=y.mergedMap[l];y.manager.assignDefinition(l,s),y.originalsMap.set(l,O),y.mergedMap[l]=s,M.emitDefinitionAssign(c,l,s,O),y.reconciles&&N();}function W(c,l){let s=j[c];if(!s.dynamicSet.has(l)){a&&console.warn(`[Directive] Cannot unregister static ${c} "${l}". Only dynamically registered ${c}s can be removed.`);return}s.manager.unregisterDefinition(l),delete s.mergedMap[l],s.dynamicSet.delete(l),s.originalsMap.delete(l),M.emitDefinitionUnregister(c,l),s.reconciles&&N();}function te(){if($.length===0)return;let c=$.splice(0);for(let l of c)try{switch(l.op){case "register":oe(l.type,l.id,l.def);break;case "assign":_(l.type,l.id,l.def);break;case "unregister":W(l.type,l.id);break}}catch(s){a&&console.error(`[Directive] Error in deferred ${l.op} for ${l.type} "${l.id}":`,s);}}function ne(c,l,s,y){let{isDestroyed:O,isReconciling:G}=J();if(O)throw new Error(`[Directive] Cannot ${c} ${l} "${s}" on a destroyed system.`);if(Q(s),G){if($.length>=X)throw new Error(`[Directive] Too many deferred registrations (max ${X}). Avoid calling register/assign/unregister in resolver or effect callbacks during reconciliation.`);c==="unregister"?$.push({op:c,type:l,id:s}):$.push({op:c,type:l,id:s,def:y});return}switch(c){case "register":oe(l,s,y);break;case "assign":_(l,s,y);break;case "unregister":W(l,s);break}}return {register(c,l,s){ne("register",c,l,s);},assign(c,l,s){ne("assign",c,l,s);},unregister(c,l){ne("unregister",c,l);},call(c,l,s){let{isDestroyed:y}=J();if(y)throw new Error(`[Directive] Cannot call ${c} "${l}" on a destroyed system.`);switch(Q(l),M.emitDefinitionCall(c,l,s),c){case "constraint":return g.callOne(l,s);case "resolver":return p.callOne(l,s);case "derivation":return A.callOne(l);case "effect":return z.callOne(l)}},isDynamic(c,l){switch(c){case "constraint":return K.constraints.has(l);case "resolver":return K.resolvers.has(l);case "derivation":return K.derivations.has(l);case "effect":return K.effects.has(l)}},listDynamic(c){switch(c){case "constraint":return [...K.constraints];case "resolver":return [...K.resolvers];case "derivation":return [...K.derivations];case "effect":return [...K.effects]}},flushDeferred:te,getOriginal(c,l){let y={constraint:C.constraints,resolver:C.resolvers,derivation:C.derivations,effect:C.effects}[c];if(y)return y.get(l)},restoreOriginal(c,l){let y={constraint:C.constraints,resolver:C.resolvers,derivation:C.derivations,effect:C.effects}[c];if(!y||!y.has(l))return false;let O=y.get(l);return ne("assign",c,l,O),y.delete(l),true},destroy(){$.length=0,K.constraints.clear(),K.resolvers.clear(),K.derivations.clear(),K.effects.clear(),C.constraints.clear(),C.resolvers.clear(),C.derivations.clear(),C.effects.clear();}}}function gt(f){let{traceConfig:o,pluginManager:x,resolverMetaLookup:h}=f;if(!(o===true||typeof o=="object"&&o!==null))return {enabled:false,recordFactChange(){},startRun(){return 0},currentTrace:null,getEntries(){return null},attributeResolverStart(){},recordResolverComplete(){},recordResolverError(){},decrementInflight(){},finalizeCurrentRun(){},drainPendingChanges(){},destroy(){}};let g=(typeof o=="object"&&o!==null?o.maxRuns:void 0)??100,p=[],A=new Map,z=0,M=null,J=[],N=new Map,X=new Map,K=new Map,C=null,$=0,I=0,j={count:0,totalDuration:0,avgDuration:0,maxDuration:0,avgResolverCount:0,totalResolverCount:0,avgFactChangeCount:0,totalFactChangeCount:0};function Q(s){let y=A.get(s);if(y&&y.status==="pending"){y.status="settled";let O=K.get(s);y.duration=O!==void 0?performance.now()-O:Date.now()-y.timestamp,K.delete(s),X.delete(s),y.causalChain=W(y),te(y),I++,x.emitTraceComplete(y);}}function oe(s){let y=N.get(s);if(N.delete(s),y!==void 0){let O=(X.get(y)??1)-1;O<=0?Q(y):X.set(y,O);}}function _(){let s=p.shift();if(s&&(A.delete(s.id),K.delete(s.id),s.status==="pending")){X.delete(s.id);for(let[y,O]of N)O===s.id&&N.delete(y);}}function W(s){let y=[];for(let O of s.factChanges)y.push(`${O.key} changed`);for(let O of s.derivationsRecomputed)y.push(`${O.id} recomputed`);for(let O of s.constraintsHit)y.push(`${O.id} constraint hit`);for(let O of s.requirementsAdded)y.push(`${O.type} requirement added`);for(let O of s.resolversCompleted)y.push(`${O.resolver} resolved (${O.duration.toFixed(0)}ms)`);for(let O of s.resolversErrored)y.push(`${O.resolver} errored`);for(let O of s.effectsRun)y.push(`${O.id} effect ran`);return y.join(" \u2192 ")}function te(s){j.count++,j.totalDuration+=s.duration,j.avgDuration=j.totalDuration/j.count,s.duration>j.maxDuration&&(j.maxDuration=s.duration);let y=s.resolversStarted.length;j.totalResolverCount+=y,j.avgResolverCount=j.totalResolverCount/j.count;let O=s.factChanges.length;j.totalFactChangeCount+=O,j.avgFactChangeCount=j.totalFactChangeCount/j.count;let G=[];j.count>3&&s.duration>j.avgDuration*5&&G.push(`Duration ${s.duration.toFixed(0)}ms is 5x+ above average (${j.avgDuration.toFixed(0)}ms)`),s.resolversErrored.length>0&&G.push(`${s.resolversErrored.length} resolver(s) errored`),G.length>0&&(s.anomalies=G);}function ne(s){p.push(s),A.set(s.id,s),p.length>g&&_(),I++;}function c(s){return s.factChanges.length>0||s.constraintsHit.length>0||s.requirementsAdded.length>0||s.effectsRun.length>0}return {enabled:true,get currentTrace(){return M},set currentTrace(s){M=s;},recordFactChange(s,y,O){J.push({key:s,oldValue:y,newValue:O});},startRun(){let s=performance.now(),y=++z;return K.set(y,s),M={id:y,timestamp:Date.now(),duration:0,status:"pending",factChanges:J.splice(0),derivationsRecomputed:[],constraintsHit:[],requirementsAdded:[],requirementsRemoved:[],resolversStarted:[],resolversCompleted:[],resolversErrored:[],effectsRun:[],effectErrors:[]},s},getEntries(){return (!C||$!==I)&&(C=[...p],$=I),C},attributeResolverStart(s){M&&N.set(s,M.id);},recordResolverComplete(s,y,O){let G=N.get(s);if(G!==void 0){let re=A.get(G);re&&re.resolversCompleted.push({resolver:y,requirementId:s,duration:O,meta:h?.(y)});}},recordResolverError(s,y,O){let G=N.get(s);if(G!==void 0){let re=A.get(G);re&&re.resolversErrored.push({resolver:y,requirementId:s,error:O,meta:h?.(y)});}},decrementInflight(s){oe(s);},finalizeCurrentRun(s){if(!M)return;if(M.duration=performance.now()-s,!c(M)){K.delete(M.id),M=null;return}let y=M.resolversStarted.length;y===0?(M.status="settled",M.causalChain=W(M),te(M),ne(M),x.emitTraceComplete(M)):(M.status="pending",ne(M),X.set(M.id,y)),M=null;},drainPendingChanges(){J.length=0;},destroy(){p.length=0,A.clear(),N.clear(),X.clear(),K.clear(),J.length=0,M=null,C=null;}}}function mt(f,o){for(let[x,h]of Object.entries(f)){if(typeof h!="object"||h===null)continue;let P=Object.hasOwn(h,"handler"),g=Object.hasOwn(h,"patch");if(P&&g&&a&&console.warn(`[Directive] event "${x}": both \`handler\` and \`patch\` provided \u2014 using \`handler\` (patch is ignored).`),P){let p=h;if(f[x]=p.handler,p.meta){let A=fe(p.meta);A&&o.set(x,A);}continue}if(g){let p=h,A=p.patch;if(b(A),f[x]=(z,M)=>v(A,z,M??{}),p.meta){let z=fe(p.meta);z&&o.set(x,z);}}}}function Jn(f$1){let o=Object.create(null),x=Object.create(null),h=Object.create(null),P=Object.create(null),g=Object.create(null),p=Object.create(null),A=new Map,z=new Map,M=new Map,J=new Map,N=new Map;for(let e of f$1.modules){let n=(b,R)=>{if(b)for(let k$1 of Object.keys(b)){if(k.has(k$1))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${k$1}" in ${R}. This could indicate a prototype pollution attempt.`);if(R==="schema"&&k$1.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${k$1}" starting with "$". Keys starting with $ are reserved for internal accessors ($store, $snapshot).`)}};n(e.schema,"schema"),n(e.events,"events"),n(e.derive,"derive"),n(e.effects,"effects"),n(e.constraints,"constraints"),n(e.resolvers,"resolvers");for(let b of Object.keys(e.schema)){let R=M.get(b);if(R)throw new Error(`[Directive] Schema collision: Fact "${b}" is defined in both module "${R}" and "${e.id}". Use namespacing (e.g., "${e.id}::${b}") or merge into one module.`);M.set(b,e.id);}let a=(b,R)=>{if(b)for(let k of Object.keys(b)){let B=J.get(k);if(B&&B!==e.id)throw new Error(`[Directive] Definition collision: ${R} "${k}" is defined in both module "${B}" and "${e.id}". Use namespacing or rename to avoid conflicts.`);J.set(k,e.id);}};if(a(e.derive,"derivation"),a(e.effects,"effect"),a(e.constraints,"constraint"),a(e.resolvers,"resolver"),a(e.events,"event"),Object.assign(o,e.schema),e.events&&(mt(e.events,z),Object.assign(x,e.events)),e.derive&&Object.assign(h,e.derive),e.effects&&Object.assign(P,e.effects),e.constraints&&Object.assign(g,e.constraints),e.resolvers){Object.assign(p,e.resolvers);for(let b of Object.keys(e.resolvers))N.set(b,e);}if(e.meta){let b=fe(e.meta);b&&A.set(e.id,b);}}for(let e of Object.values(g))e.meta&&(e.meta=fe(e.meta));for(let e of Object.values(p))e.meta&&(e.meta=fe(e.meta));for(let e of Object.values(P)){let n=e;n.meta&&(n.meta=fe(n.meta));}for(let e of Object.values(o)){let n=e;n._meta&&(n._meta=fe(n._meta));}let X=null;if(f$1.modules.some(e=>e.history?.snapshotEvents)){X=new Set;for(let e of f$1.modules){let n=e;if(n.history?.snapshotEvents)for(let a of n.history.snapshotEvents)X.add(a);else if(n.events)for(let a of Object.keys(n.events))X.add(a);}}let C=0,$=false;if(a){let e=new Set(Object.keys(h));for(let n of Object.keys(o))e.has(n)&&console.warn(`[Directive] "${n}" exists as both a fact and a derivation. This may cause unexpected dependency tracking behavior.`);}let I=ot();for(let e of f$1.plugins??[])I.register(e);let j=I.getPlugins().length>0,Q=I.register.bind(I),oe=I.unregister.bind(I);I.register=e=>{Q(e),j=true;},I.unregister=e=>{oe(e),j=I.getPlugins().length>0;};let _=()=>j,W=rt({config:f$1.errorBoundary,onError:e=>I.emitError(e),onRecovery:(e,n)=>I.emitErrorRecovery(e,n)}),te=null,ne=()=>{},c=()=>{},l=null,s=gt({traceConfig:f$1.trace,pluginManager:I,resolverMetaLookup:e=>p[e]?.meta}),y=s.enabled,{store:O,facts:G}=st({schema:o,onChange:(e,n,a)=>{I.emitFactSet(e,n,a),ne(e),y&&s.recordFactChange(String(e),a,n),!l?.isRestoring&&(C===0&&($=true),F.changedKeys.add(e),ge());},onBatch:e=>{I.emitFactsBatch(e);let n=[];for(let a of e)n.push(a.key);if(y)for(let a of e)s.recordFactChange(a.key,a.prev,a.type==="delete"?void 0:a.value);if(c(n),!l?.isRestoring){C===0&&($=true);for(let a of e)F.changedKeys.add(a.key);ge();}}}),re=tt({definitions:h,facts:G,onCompute:(e,n,a,b)=>{_()&&I.emitDerivationCompute(e,n,b),s.currentTrace&&s.currentTrace.derivationsRecomputed.push({id:e,deps:b?[...b]:[],oldValue:a,newValue:n,meta:re.getMeta(e)});},onInvalidate:e=>{_()&&I.emitDerivationInvalidate(e);},onError:(e,n)=>{W.handleError("derivation",e,n)==="retry"&&re.invalidate(e);}});ne=e=>re.invalidate(e),c=e=>re.invalidateMany(e);let le=nt({definitions:P,facts:G,store:O,onRun:(e,n)=>{_()&&I.emitEffectRun(e),s.currentTrace&&s.currentTrace.effectsRun.push({id:e,triggeredBy:n,meta:P[e]?.meta});},onError:(e,n)=>{let a=W.handleError("effect",e,n);_()&&I.emitEffectError(e,n),s.currentTrace&&s.currentTrace.effectErrors.push({id:e,error:String(n),meta:P[e]?.meta}),a==="disable"&&le.disable(e),a==="retry"&&(F.changedKeys.add("*"),ge());}});function ve(e){if(Array.isArray(e)){let n=e;return a=>u(n,a)}return e}let S=Object.create(null);for(let e of Object.values(p))e.key&&typeof e.requirement=="string"&&(S[e.requirement]=ve(e.key));let i=et({definitions:g,facts:G,requirementKeys:S,onEvaluate:(e,n)=>{if(_()){let a=i.explainWhen(e);I.emitConstraintEvaluate(e,n,a);}},onError:(e,n)=>{let a=W.handleError("constraint",e,n);_()&&I.emitConstraintError(e,n),a==="disable"&&i.disable(e);}});function D(e){for(let n of Object.values(e))n.key&&typeof n.requirement=="string"&&i.setRequirementKey(n.requirement,ve(n.key));}function T(e){let n=g[e];if(!n?.owns||n.owns.length===0)return;let a$1=i.getState(e);if(a$1?.isAsync||n.async){a&&(a$1?.isAsync&&!n.async?console.warn(`[Directive] constraint '${e}': owns binding disabled because when() returned a Promise \u2014 convert to a synchronous when, mark the constraint async: true and accept the binding being off, or use a data-form when (always sync).`):console.warn(`[Directive] Constraint "${e}" has \`owns\` but is async. Binding is disabled \u2014 async constraints cannot be bound.`));return}return {fields:n.owns}}let H=new Set,ee=lt({definitions:p,facts:G,store:O,getConstraintBinding:T,onStart:(e,n)=>{_()&&I.emitResolverStart(e,n);},onComplete:(e,n,a)=>{W.clearRetryAttempts(e),_()&&(I.emitResolverComplete(e,n,a),I.emitRequirementMet(n,e)),i.markResolved(n.fromConstraint),y&&(s.recordResolverComplete(n.id,e,a),s.decrementInflight(n.id));},onError:(e,n,a)=>{let b=W.handleError("resolver",e,a,n);if(_()&&I.emitResolverError(e,n,a),b==="disable"&&i.disable(n.fromConstraint),b==="retry"&&(F.previousRequirements.remove(n.id),ge()),b==="retry-later"){let U=W.getRetryLaterManager().getPendingRetries().find(Z=>Z.sourceId===e);U&&!U.callback&&(U.callback=()=>{ge();});}y&&(s.recordResolverError(n.id,e,String(a)),s.decrementInflight(n.id));let R=N.get(e),k=R?.hooks?.onResolverError;if(k){let B=a instanceof Error?a:new Error(String(a));try{k(B,n.requirement,{facts:G});}catch(U){console.error(`[Directive] onResolverError hook for module "${R?.id}" threw:`,U);}}},onRetry:(e,n,a)=>I.emitResolverRetry(e,n,a),onCancel:(e,n)=>{I.emitResolverCancel(e,n),I.emitRequirementCanceled(n),y&&s.decrementInflight(n.id);},onClobber:(e,n,a,b,R)=>{_()&&I.emitResolverWriteRejected({kind:"rejection",resolver:e,req:n,reason:"clobbered",fact:a,expected:b,actual:R});},onClobberSuppressed:(e,n,a)=>{_()&&I.emitResolverWriteRejected({kind:"summary",resolver:e,req:n,reason:"clobbered",dropped:a});},onResolutionComplete:()=>{Se(),ge();},onRequeue:e=>{H.add(e);}}),ue=new Set;function me(){for(let e of ue)e();}let ye=f$1.history?Ze({historyOption:f$1.history,facts:G,store:O,onSnapshot:e=>{I.emitSnapshot(e),me();},onHistoryChange:(e,n)=>{I.emitHistoryNavigate(e,n),me();}}):Ye();l=ye;let he=new Set;function Se(){for(let e of he)e();}let we=50,Me=100,Re=0,F={isRunning:false,isReconciling:false,reconcileScheduled:false,isInitializing:false,isInitialized:false,isReady:false,isDestroyed:false,changedKeys:new Set,previousRequirements:new ke,readyPromise:null,readyResolve:null},ie=ft({mergedConstraints:g,mergedResolvers:p,mergedDerive:h,mergedEffects:P,constraintsManager:i,resolversManager:ee,derivationsManager:re,effectsManager:le,pluginManager:I,getState:()=>F,scheduleReconcile:ge,maxDeferredRegistrations:Me});function ge(){!F.isRunning||F.reconcileScheduled||F.isInitializing||(F.reconcileScheduled=true,Se(),queueMicrotask(()=>{F.reconcileScheduled=false,F.isRunning&&!F.isInitializing&&De().catch(e=>{a&&console.error("[Directive] Unexpected error in reconcile:",e);});}));}async function De(){if(F.isReconciling)return;if(Re++,Re>we){a&&console.warn(`[Directive] Reconcile loop exceeded ${we} iterations. This usually means resolvers are creating circular requirement chains. Check that resolvers aren't mutating facts that re-trigger their own constraints.`),y&&s.drainPendingChanges(),F.previousRequirements=new ke,Re=0;return}F.isReconciling=true,Se();let e=y?s.startRun():0,n=s.currentTrace;if(n)for(let a of n.factChanges){let b=o[a.key];a.meta=b?._meta;}try{if(F.changedKeys.size>0){if(X===null||$){let t=F.changedKeys,r=t.size<=5?`facts-changed:${[...t].join(",")}`:`facts-changed:${[...t].slice(0,5).join(",")}+${t.size-5}more`;ye.takeSnapshot(r);}$=!1;}let a=G.$snapshot();I.emitReconcileStart(a),await le.runEffects(F.changedKeys);let b=new Set(F.changedKeys);F.changedKeys.clear();let R=await i.evaluate(b),k=new ke;for(let t of R)k.add(t),I.emitRequirementCreated(t);if(n){let t=new Set(R.map(r=>r.fromConstraint));for(let r of t){let u=i.getState(r);if(u){let w=i.getDependencies(r);n.constraintsHit.push({id:r,priority:u.priority,deps:w?[...w]:[],meta:g[r]?.meta});}}}let{added:B,removed:U}=k.diff(F.previousRequirements);if(n){for(let t of B)n.requirementsAdded.push({id:t.id,type:t.requirement.type,fromConstraint:t.fromConstraint});for(let t of U)n.requirementsRemoved.push({id:t.id,type:t.requirement.type,fromConstraint:t.fromConstraint});}for(let t of U)(t.fromConstraint?T(t.fromConstraint):void 0)?ee.detach(t.id):ee.cancel(t.id);let Z;if(B.length>0){let t=new Set;for(let r of B){if(!r.fromConstraint)continue;let u=T(r.fromConstraint);if(u)for(let w of u.fields)t.add(w);}if(t.size>0){Z=Object.create(null);for(let r of t)Z[r]=O.get(r);}}for(let t of B)ee.resolve(t,{factsBaseline:Z});if(n){let t=ee.getInflightInfo(),r=new Map(t.map(u=>[u.id,u]));for(let u of B){let E=r.get(u.id)?.resolverId??"unknown";n.resolversStarted.push({resolver:E,requirementId:u.id,meta:p[E]?.meta}),s.attributeResolverStart(u.id);}}if(F.previousRequirements=k,H.size>0){for(let t of H)F.previousRequirements.remove(t);H.clear(),ge();}let V=ee.getInflightInfo();if(f$1.plugins&&f$1.plugins.length>0){let t=U.length>0?new Map(V.map(u=>[u.id,u.resolverId])):void 0,r={unmet:R.filter(u=>!ee.isResolving(u.id)),inflight:V,completed:[],canceled:U.map(u=>({id:u.id,resolverId:t?.get(u.id)??"unknown"}))};I.emitReconcileEnd(r);}F.isReady||(F.isReady=!0,F.readyResolve&&(F.readyResolve(),F.readyResolve=null));}finally{y&&s.finalizeCurrentRun(e),F.isReconciling=false,ie.flushDeferred(),Re=0,F.changedKeys.size>0&&ge(),Se();}}function qe(e,n){let a$1=x[e];if(a$1){C++,(X===null||X.has(e))&&($=true);try{O.batch(()=>{a$1(G,{type:e,...n});});}finally{C--;}}else a&&console.warn(`[Directive] Unknown event type "${e}". No handler is registered for this event. Available events: ${Object.keys(x).join(", ")||"(none)"}`);}let d=dt({mergedDerive:h,getDerivation:e=>re.get(e),definitions:ie}),m=ut({mergedEvents:x,dispatchEvent:qe});function v(){let e=[];for(let[n,a]of A)e.push({type:"module",id:n,meta:a});for(let n of Object.keys(o)){let a=o[n]?._meta;a&&e.push({type:"fact",id:n,meta:a});}for(let[n,a]of z)e.push({type:"event",id:n,meta:a});for(let[n,a]of Object.entries(g))a.meta&&e.push({type:"constraint",id:n,meta:a.meta});for(let[n,a]of Object.entries(p))a.meta&&e.push({type:"resolver",id:n,meta:a.meta});for(let[n,a]of Object.entries(P)){let b=a.meta;b&&e.push({type:"effect",id:n,meta:b});}for(let n of Object.keys(h)){let a=re.getMeta(n);a&&e.push({type:"derivation",id:n,meta:a});}return e}let q={facts:G,history:ye.isEnabled?ye:null,derive:d,events:m,constraints:{disable:e=>i.disable(e),enable:e=>i.enable(e),isDisabled:e=>i.isDisabled(e),register:(e,n)=>{ie.register("constraint",e,n);},assign:(e,n)=>{ie.assign("constraint",e,n);},unregister:e=>{ie.unregister("constraint",e);},call:(e,n)=>ie.call("constraint",e,n),isDynamic:e=>ie.isDynamic("constraint",e),listDynamic:()=>ie.listDynamic("constraint")},effects:{disable:e=>le.disable(e),enable:e=>le.enable(e),isEnabled:e=>le.isEnabled(e),register:(e,n)=>{ie.register("effect",e,n);},assign:(e,n)=>{ie.assign("effect",e,n);},unregister:e=>{ie.unregister("effect",e);},call:e=>ie.call("effect",e),isDynamic:e=>ie.isDynamic("effect",e),listDynamic:()=>ie.listDynamic("effect")},resolvers:{register:(e,n)=>{ie.register("resolver",e,n),D({[e]:n});},assign:(e,n)=>{ie.assign("resolver",e,n),D({[e]:n});},unregister:e=>{let n=p[e];n?.key&&typeof n.requirement=="string"&&i.removeRequirementKey(n.requirement),ie.unregister("resolver",e);},call:(e,n)=>ie.call("resolver",e,n),isDynamic:e=>ie.isDynamic("resolver",e),listDynamic:()=>ie.listDynamic("resolver")},get trace(){return s.getEntries()},meta:{module(e){return A.get(e)},fact(e){return o[e]?._meta},event(e){return z.get(e)},constraint(e){return g[e]?.meta},resolver(e){return p[e]?.meta},effect(e){return P[e]?.meta},derivation(e){return re.getMeta(e)},byCategory(e){return v().filter(n=>n.meta.category===e)},byTag(e){return v().filter(n=>n.meta.tags?.includes(e))}},observe(e){if(I.getPlugins().filter(R=>R.name.startsWith("__observer_")).length>=100)return a&&console.warn("[Directive] Maximum observer limit (100) reached. Call the unsubscribe function returned by observe() to clean up."),()=>{};let a$1=`__observer_${Date.now()}_${Math.random().toString(36).slice(2)}`,b={name:a$1,onInit:()=>e({type:"system.init"}),onStart:()=>e({type:"system.start"}),onStop:()=>e({type:"system.stop"}),onDestroy:()=>e({type:"system.destroy"}),onFactSet:(R,k,B)=>e({type:"fact.change",key:R,prev:B,next:k}),onConstraintEvaluate:(R,k,B)=>{e(B?{type:"constraint.evaluate",id:R,active:k,whenExplain:B}:{type:"constraint.evaluate",id:R,active:k});},onConstraintError:(R,k)=>e({type:"constraint.error",id:R,error:k}),onRequirementCreated:R=>e({type:"requirement.created",id:R.id,requirementType:R.requirement.type}),onRequirementMet:(R,k)=>e({type:"requirement.met",id:R.id,byResolver:k}),onRequirementCanceled:R=>e({type:"requirement.canceled",id:R.id}),onResolverStart:(R,k)=>e({type:"resolver.start",resolver:R,requirementId:k.id}),onResolverComplete:(R,k,B)=>e({type:"resolver.complete",resolver:R,requirementId:k.id,duration:B}),onResolverError:(R,k,B)=>e({type:"resolver.error",resolver:R,requirementId:k.id,error:B}),onResolverWriteRejected:R=>{if(R.kind==="summary"){e({type:"resolver.write.rejected",kind:"summary",resolver:R.resolver,requirementId:R.req.id,reason:R.reason,dropped:R.dropped});return}e({type:"resolver.write.rejected",kind:"rejection",resolver:R.resolver,requirementId:R.req.id,reason:R.reason,fact:R.fact,expected:R.expected,actual:R.actual});},onEffectRun:R=>e({type:"effect.run",id:R}),onEffectError:(R,k)=>e({type:"effect.error",id:R,error:k}),onDerivationCompute:(R,k)=>e({type:"derivation.compute",id:R,value:k}),onReconcileStart:()=>e({type:"reconcile.start"}),onReconcileEnd:R=>{let k=R;e({type:"reconcile.end",resolversCompleted:Array.isArray(k.completed)?k.completed.length:0,resolversCanceled:Array.isArray(k.canceled)?k.canceled.length:0});}};return I.register(b),()=>I.unregister(a$1)},initialize(){if(!F.isInitialized){F.isInitializing=true;for(let e of f$1.modules)e.init&&O.batch(()=>{e.init(G);});f$1.onAfterModuleInit&&O.batch(()=>{f$1.onAfterModuleInit();}),F.isInitializing=false,F.isInitialized=true;for(let e of Object.keys(h))re.get(e);}},start(){if(!F.isRunning){F.isInitialized||this.initialize(),F.isRunning=true;for(let e of f$1.modules)e.hooks?.onStart?.(q);if(I.emitStart(q),f$1.errorBoundary?.retryLater&&!te){let e=Math.max(f$1.errorBoundary.retryLater.delayMs??1e3,250);te=setInterval(()=>{let n=W.processDueRetries();for(let a of n)a.callback?a.callback():ge();},Math.min(e,500));}ge();}},stop(){if(F.isRunning){F.isRunning=false,te!==null&&(clearInterval(te),te=null),W.getRetryLaterManager().clearAll(),ee.cancelAll(),le.cleanupAll();for(let e of f$1.modules)e.hooks?.onStop?.(q);I.emitStop(q);}},destroy(){F.isDestroyed||(this.stop(),F.isDestroyed=true,O.destroy?.(),ee.destroy(),W.clearErrors(),he.clear(),ue.clear(),s.destroy(),ie.destroy(),A.clear(),z.clear(),H.clear(),I.emitDestroy(q));},dispatch(e){k.has(e.type)||qe(e.type,e);},read(e){return re.get(e)},subscribe(e,n){let a$1=[],b=[];for(let k of e)k in h?a$1.push(k):k in o?b.push(k):a&&console.warn(`[Directive] subscribe: unknown key "${k}"`);let R=[];return a$1.length>0&&R.push(re.subscribe(a$1,n)),b.length>0&&R.push(O.subscribe(b,n)),()=>{for(let k of R)k();}},watch(e,n,a$1){let b=a$1?.equalityFn?(k,B)=>a$1.equalityFn(k,B):(k,B)=>Object.is(k,B);if(e in h){let k=re.get(e);return re.subscribe([e],()=>{let B=re.get(e);if(!b(B,k)){let U=k;k=B,n(B,U);}})}a&&(e in o||console.warn(`[Directive] watch: unknown key "${e}"`));let R=O.get(e);return O.subscribe([e],()=>{let k=O.get(e);if(!b(k,R)){let B=R;R=k,n(k,B);}})},when(e,n){return new Promise((a,b)=>{let R=O.toObject();if(e(R)){a();return}let k,B,U=()=>{k?.(),B!==void 0&&clearTimeout(B);};k=O.subscribeAll(()=>{let Z=O.toObject();e(Z)&&(U(),a());}),n?.timeout!==void 0&&n.timeout>0&&(B=setTimeout(()=>{U(),b(new Error(`[Directive] when: timed out after ${n.timeout}ms`));},n.timeout));})},inspect(){return {unmet:F.previousRequirements.all(),inflight:ee.getInflightInfo(),facts:Object.keys(o).map(e=>({key:e,meta:o[e]?._meta})),events:Object.keys(x).map(e=>({name:e,meta:z.get(e)})),constraints:i.getAllStates().map(e=>{let n=i.getWhenSpec(e.id),a=g[e.id],b=a?.owns&&a.owns.length>0?a.owns:void 0;return {id:e.id,active:e.lastResult??false,disabled:i.isDisabled(e.id),priority:e.priority,hitCount:e.hitCount,lastActiveAt:e.lastActiveAt,meta:a?.meta,...n?{whenSpec:n}:{},...b?{owns:b}:{}}}),resolvers:Object.fromEntries(ee.getInflight().map(e=>[e,ee.getStatus(e)])),resolverDefs:Object.entries(p).map(([e,n])=>({id:e,requirement:typeof n.requirement=="string"?n.requirement:"(predicate)",meta:n.meta})),effects:Object.entries(P).map(([e,n])=>({id:e,meta:n.meta})),derivations:Object.keys(h).map(e=>({id:e,meta:re.getMeta(e)})),modules:f$1.modules.map(e=>({id:e.id,meta:A.get(e.id)})),traceEnabled:y,...y?{trace:structuredClone(s.getEntries()??[])}:{}}},explain(e){let a=F.previousRequirements.all().find(E=>E.id===e);if(!a)return null;let b=i.getState(a.fromConstraint),R=ee.getStatus(e),k={},B=i.getDependencies(a.fromConstraint);if(B)for(let E of B)k[E]=O.get(E);else for(let[E,Y]of Object.entries(O.toObject()))k[E]=Y;let U=g[a.fromConstraint],Z=U?.meta?.label??a.fromConstraint,V=[`Requirement "${a.requirement.type}" (id: ${a.id})`,`\u251C\u2500 Produced by constraint: ${Z}`,`\u251C\u2500 Constraint priority: ${b?.priority??0}`,`\u251C\u2500 Constraint active: ${b?.lastResult??"unknown"}`,`\u251C\u2500 Resolver status: ${R.state}`];U?.meta?.description&&V.push(`\u251C\u2500 Description: ${U.meta.description}`);let t=i.explainWhen(a.fromConstraint),r=(E,Y,ae)=>{let ce=ae?"\u2514\u2500":"\u251C\u2500",pe=E.pass?"\u2713":"\u2717";if(E.children){if(E.op==="$not"){let $e=E.pass?" (child failed)":" (child passed)";V.push(`${Y}${ce} ${pe} $not${$e}`);}else V.push(`${Y}${ce} ${pe} ${E.op} (${E.actual}/${E.expected})`);let vt=`${Y}${ae?" ":"\u2502 "}`;E.children.forEach(($e,ht)=>{r($e,vt,ht===E.children.length-1);});return}let yt=typeof E.expected=="object"?JSON.stringify(E.expected):String(E.expected),pt=E.actual===void 0?"undefined":typeof E.actual=="object"?JSON.stringify(E.actual):String(E.actual);V.push(`${Y}${ce} ${pe} ${E.path} ${E.op} ${yt} (actual: ${pt})`);};t&&t.length>0&&(V.push("\u251C\u2500 Predicate clauses:"),t.forEach((E,Y)=>{r(E,"\u2502 ",Y===t.length-1);}));let u=Object.entries(a.requirement).filter(([E])=>E!=="type").map(([E,Y])=>`${E}=${JSON.stringify(Y)}`).join(", ");u&&V.push(`\u251C\u2500 Requirement payload: { ${u} }`);let w=Object.entries(k).slice(0,10);return w.length>0&&(V.push("\u2514\u2500 Relevant facts:"),w.forEach(([E,Y],ae)=>{let ce=ae===w.length-1?" \u2514\u2500":" \u251C\u2500",pe=typeof Y=="object"?JSON.stringify(Y):String(Y);V.push(`${ce} ${E} = ${pe.slice(0,50)}${pe.length>50?"...":""}`);})),V.join(`
|
|
2
|
+
`)},getOriginal(e,n){return ie.getOriginal(e,n)},restoreOriginal(e,n){return ie.restoreOriginal(e,n)},async settle(e=5e3){let n=()=>ee.getInflightCount()===0&&!F.isReconciling&&!F.reconcileScheduled&&!ee.hasPendingBatches();if(ee.hasPendingBatches()&&ee.processBatches(),await new Promise(a=>queueMicrotask(a)),!n())return new Promise((a,b)=>{let R=false,k=()=>{R||(R=true,clearTimeout(B),U());},B=setTimeout(()=>{k();let Z=[],V=ee.getInflightInfo();V.length>0&&Z.push(`${V.length} resolvers inflight: ${V.map(r=>r.resolverId).join(", ")}`),F.isReconciling&&Z.push("reconciliation in progress"),F.reconcileScheduled&&Z.push("reconcile scheduled");let t=F.previousRequirements.all();t.length>0&&Z.push(`${t.length} unmet requirements: ${t.map(r=>r.requirement.type).join(", ")}`),b(new Error(`[Directive] settle() timed out after ${e}ms. ${Z.join("; ")}`));},e),U=this.onSettledChange(()=>{ee.hasPendingBatches()&&ee.processBatches(),queueMicrotask(()=>{!R&&n()&&(k(),a());});});})},getSnapshot(){return {facts:O.toObject(),version:1}},getDistributableSnapshot(e={}){let{includeDerivations:n,excludeDerivations:a$1,includeFacts:b,ttlSeconds:R,metadata:k,includeVersion:B}=e,U={},Z=Object.keys(h),V=new Set(Z),t;if(n){if(t=n.filter(w=>V.has(w)),a){let w=n.filter(E=>!V.has(E));w.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown derivation keys ignored: ${w.join(", ")}. Available: ${Z.join(", ")||"(none)"}`);}}else t=Z;if(a$1){let w=new Set(a$1);t=t.filter(E=>!w.has(E));}for(let w of t)try{U[w]=re.get(w);}catch(E){a&&console.warn(`[Directive] getDistributableSnapshot: Skipping derivation "${w}" due to error:`,E);}if(b&&b.length>0){let w=O.toObject(),E=Object.keys(w);if(a){let Y=b.filter(ae=>!(ae in w));Y.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown fact keys ignored: ${Y.join(", ")}. Available: ${E.join(", ")||"(none)"}`);}for(let Y of b)Y in w&&(U[Y]=w[Y]);}let r=Date.now(),u={data:U,createdAt:r};return R!==void 0&&R>0&&(u.expiresAt=r+R*1e3),B&&(u.version=h$2(U)),k&&(u.metadata=k),u},watchDistributableSnapshot(e,n){let{includeDerivations:a$1,excludeDerivations:b}=e,R=Object.keys(h),k;if(a$1?k=a$1.filter(Z=>R.includes(Z)):k=R,b){let Z=new Set(b);k=k.filter(V=>!Z.has(V));}if(k.length===0)return a&&console.warn("[Directive] watchDistributableSnapshot: No derivations to watch. Callback will never be called."),()=>{};let U=this.getDistributableSnapshot({...e,includeVersion:true}).version;return re.subscribe(k,()=>{let Z=this.getDistributableSnapshot({...e,includeVersion:true});Z.version!==U&&(U=Z.version,n(Z));})},restore(e){if(!e||typeof e!="object")throw new Error("[Directive] restore() requires a valid snapshot object");if(!e.facts||typeof e.facts!="object")throw new Error("[Directive] restore() snapshot must have a facts object");if(!f(e))throw new Error("[Directive] restore() rejected: snapshot contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");O.batch(()=>{for(let[n,a]of Object.entries(e.facts))k.has(n)||O.set(n,a);});},onSettledChange(e){return he.add(e),()=>{he.delete(e);}},onHistoryChange(e){return ue.add(e),()=>{ue.delete(e);}},batch(e){O.batch(e);},get isSettled(){return ee.getInflightCount()===0&&!ee.hasPendingBatches()&&!F.isReconciling&&!F.reconcileScheduled},get isRunning(){return F.isRunning},get isInitialized(){return F.isInitialized},get isReady(){return F.isReady},whenReady(){return F.isReady?Promise.resolve():F.isRunning?(F.readyPromise||(F.readyPromise=new Promise(e=>{F.readyResolve=e;})),F.readyPromise):Promise.reject(new Error("[Directive] whenReady() called before start(). Call system.start() first, then await system.whenReady()."))}};function L(e){if(F.isReconciling)throw new Error(`[Directive] Cannot register module "${e.id}" during reconciliation. Wait for the current reconciliation cycle to complete.`);if(F.isDestroyed)throw new Error(`[Directive] Cannot register module "${e.id}" on a destroyed system.`);let n=(a,b)=>{if(a)for(let R of Object.keys(a)){if(k.has(R))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${R}" in ${b}.`);if(b==="schema"&&R.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${R}" starting with "$". Keys starting with $ are reserved for internal accessors ($store, $snapshot).`)}};n(e.schema,"schema"),n(e.events,"events"),n(e.derive,"derive"),n(e.effects,"effects"),n(e.constraints,"constraints"),n(e.resolvers,"resolvers");for(let a of Object.keys(e.schema))if(a in o)throw new Error(`[Directive] Schema collision: Fact "${a}" already exists. Cannot register module "${e.id}".`);if(a&&e.derive){let a=new Set(Object.keys(o));for(let b of Object.keys(e.derive))a.has(b)&&console.warn(`[Directive] "${b}" exists as both a fact and a derivation after registering module "${e.id}".`);}if(e.history?.snapshotEvents){X===null&&(X=new Set(Object.keys(x)));for(let a of e.history.snapshotEvents)X.add(a);}else if(X!==null&&e.events)for(let a of Object.keys(e.events))X.add(a);Object.assign(o,e.schema);for(let a of Object.values(e.schema)){let b=a;b._meta&&(b._meta=fe(b._meta));}if(e.events&&(mt(e.events,z),Object.assign(x,e.events)),e.derive&&(Object.assign(h,e.derive),re.registerDefinitions(e.derive)),e.effects){for(let a of Object.values(e.effects)){let b=a;b.meta&&(b.meta=fe(b.meta));}Object.assign(P,e.effects),le.registerDefinitions(e.effects);}if(e.constraints){for(let a of Object.values(e.constraints)){let b=a;b.meta&&(b.meta=fe(b.meta));}Object.assign(g,e.constraints),i.registerDefinitions(e.constraints);}if(e.resolvers){for(let a of Object.values(e.resolvers)){let b=a;b.meta&&(b.meta=fe(b.meta));}Object.assign(p,e.resolvers);for(let a of Object.keys(e.resolvers))N.set(a,e);ee.registerDefinitions(e.resolvers),D(e.resolvers);}if(O.registerKeys(e.schema),e.meta){let a=fe(e.meta);a&&A.set(e.id,a);}f$1.modules.push(e),e.init&&O.batch(()=>{e.init(G);}),e.hooks?.onInit?.(q),F.isRunning&&(e.hooks?.onStart?.(q),ge());}q.registerModule=L,I.emitInit(q);for(let e of f$1.modules)e.hooks?.onInit?.(q);return q}export{Wt as a,Ie as b,St as c,Rt as d,bt as e,wt as f,Kt as g,Bt as h,Ze as i,Ye as j,kt as k,Xt as l,Gt as m,Zt as n,ke as o,et as p,tt as q,nt as r,Ct as s,rt as t,qt as u,Tt as v,st as w,ot as x,lt as y,Jn as z};//# sourceMappingURL=chunk-RWJV7QLM.js.map
|
|
3
|
+
//# sourceMappingURL=chunk-RWJV7QLM.js.map
|