@directive-run/core 0.8.1 → 0.8.3
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/LICENSE +5 -0
- package/dist/adapter-utils.cjs +1 -1
- package/dist/adapter-utils.cjs.map +1 -1
- package/dist/adapter-utils.d.cts +1 -1
- package/dist/adapter-utils.d.ts +1 -1
- package/dist/adapter-utils.js +1 -1
- package/dist/adapter-utils.js.map +1 -1
- package/dist/chunk-6WG7FPH7.cjs +3 -0
- package/dist/chunk-6WG7FPH7.cjs.map +1 -0
- package/dist/chunk-DIK3SZBM.js +3 -0
- package/dist/chunk-DIK3SZBM.js.map +1 -0
- package/dist/chunk-GO63IIN5.js +2 -0
- package/dist/chunk-GO63IIN5.js.map +1 -0
- package/dist/chunk-KQKNE23L.cjs +2 -0
- package/dist/chunk-KQKNE23L.cjs.map +1 -0
- package/dist/chunk-LAH2FMON.cjs +16 -0
- package/dist/chunk-LAH2FMON.cjs.map +1 -0
- package/dist/chunk-MAARYRI4.js +16 -0
- package/dist/chunk-MAARYRI4.js.map +1 -0
- package/dist/chunk-O75OISQ2.js +2 -0
- package/dist/chunk-O75OISQ2.js.map +1 -0
- package/dist/chunk-PK2EH26L.cjs +2 -0
- package/dist/chunk-PK2EH26L.cjs.map +1 -0
- package/dist/helpers-50q7yhA9.d.ts +179 -0
- package/dist/helpers-B6SkcKCD.d.cts +179 -0
- package/dist/index.cjs +1 -16
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +42 -1421
- package/dist/index.d.ts +42 -1421
- package/dist/index.js +1 -16
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +2 -0
- package/dist/internals.cjs.map +1 -0
- package/dist/internals.d.cts +1176 -0
- package/dist/internals.d.ts +1176 -0
- package/dist/internals.js +2 -0
- package/dist/internals.js.map +1 -0
- package/dist/plugins/index.cjs +2 -2
- package/dist/plugins/index.cjs.map +1 -1
- package/dist/plugins/index.d.cts +1 -1
- package/dist/plugins/index.d.ts +1 -1
- package/dist/plugins/index.js +2 -2
- package/dist/plugins/index.js.map +1 -1
- package/dist/{plugins-DaglUQVX.d.cts → plugins-Bg_oq2sO.d.cts} +22 -2
- package/dist/{plugins-DaglUQVX.d.ts → plugins-Bg_oq2sO.d.ts} +22 -2
- package/dist/system-L2FVVUSN.js +2 -0
- package/dist/system-L2FVVUSN.js.map +1 -0
- package/dist/system-L45Z2N4U.cjs +2 -0
- package/dist/system-L45Z2N4U.cjs.map +1 -0
- package/dist/testing.cjs +1 -16
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +54 -16
- package/dist/testing.d.ts +54 -16
- package/dist/testing.js +1 -16
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +1 -16
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +1 -1
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +1 -16
- package/dist/worker.js.map +1 -1
- package/package.json +13 -4
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
async function w(n,i,s){let o,a=new Promise((g,d)=>{o=setTimeout(()=>d(new Error(s)),i);});try{return await Promise.race([n,a])}finally{clearTimeout(o);}}function m(n,i=50){let s=new WeakSet;function o(r){if(r===null)return "null";if(r===void 0)return "undefined";let e=typeof r;if(e==="string")return JSON.stringify(r);if(e==="number"||e==="boolean")return String(r);if(e==="function")return '"[function]"';if(e==="symbol")return '"[symbol]"'}function a(r,e){if(s.has(r))return '"[circular]"';s.add(r);let t=e();return s.delete(r),t}function g(r,e){return a(r,()=>`[${r.map(t=>c(t,e+1)).join(",")}]`)}function d(r,e){return a(r,()=>`{${Object.keys(r).sort().map(f=>`${JSON.stringify(f)}:${c(r[f],e+1)}`).join(",")}}`)}function c(r,e){if(e>i)return '"[max depth exceeded]"';let t=o(r);return t!==void 0?t:Array.isArray(r)?g(r,e):typeof r=="object"?d(r,e):'"[unknown]"'}return c(n,0)}function b(n,i=50){let s=new Set(["__proto__","constructor","prototype"]),o=new WeakSet;function a(r,e){if(o.has(r))return true;o.add(r);let t=e();return o.delete(r),t}function g(r,e){for(let t of r)if(!c(t,e+1))return false;return true}function d(r,e){for(let t of Object.keys(r))if(s.has(t)||!c(r[t],e+1))return false;return true}function c(r,e){if(e>i)return false;if(r==null||typeof r!="object")return true;let t=r;return Array.isArray(t)?a(t,()=>g(t,e)):a(t,()=>d(t,e))}return c(n,0)}function S(n,i){if(n===i)return true;if(!n||!i)return false;let s=Object.keys(n),o=Object.keys(i);if(s.length!==o.length)return false;for(let a of s)if(n[a]!==i[a])return false;return true}function A(n){let i=m(n),s=5381;for(let o=0;o<i.length;o++)s=(s<<5)+s^i.charCodeAt(o);return (s>>>0).toString(16)}function k(n,i=Date.now()){return n.expiresAt!==void 0&&i>n.expiresAt}function x(n,i=Date.now()){if(!n||typeof n!="object")throw new Error("[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.");if(!("data"in n))throw new Error("[Directive] Invalid snapshot: missing required 'data' property.");if(!("createdAt"in n)||typeof n.createdAt!="number")throw new Error("[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).");if(k(n,i)){let s=new Date(n.expiresAt).toISOString();throw new Error(`[Directive] Snapshot expired at ${s}. Obtain a fresh snapshot from the source.`)}return n.data}function T(n,i){let s=[];function o(e,t,u,f){s.push({path:e,oldValue:t,newValue:u,type:f});}function a(e,t,u){return e==null?(t!=null&&o(u,e,t,"added"),true):t==null?(o(u,e,t,"removed"),true):false}function g(e,t,u){if(e.length!==t.length){o(u,e,t,"changed");return}for(let f=0;f<e.length;f++)c(e[f],t[f],`${u}[${f}]`);}function d(e,t,u){let f=new Set([...Object.keys(e),...Object.keys(t)]);for(let y of f){let l=u?`${u}.${y}`:y;y in e?y in t?c(e[y],t[y],l):o(l,e[y],void 0,"removed"):o(l,void 0,t[y],"added");}}function c(e,t,u){if(!a(e,t,u)){if(typeof e!="object"||typeof t!="object"){Object.is(e,t)||o(u,e,t,"changed");return}if(Array.isArray(e)&&Array.isArray(t)){g(e,t,u);return}d(e,t,u);}}c(n.data,i.data,"");let r=n.version!==i.version&&(n.version!==void 0||i.version!==void 0);return {identical:s.length===0,changes:s,versionChanged:r,oldVersion:n.version,newVersion:i.version}}function v(n){return "signature"in n&&typeof n.signature=="string"}async function D(n,i){let s=m({data:n.data,createdAt:n.createdAt,expiresAt:n.expiresAt,version:n.version,metadata:n.metadata}),o=await p(s,i);return {...n,signature:o,algorithm:"hmac-sha256"}}async function E(n,i){if(!n.signature||n.algorithm!=="hmac-sha256")return false;let s=m({data:n.data,createdAt:n.createdAt,expiresAt:n.expiresAt,version:n.version,metadata:n.metadata}),o=await p(s,i);return h(n.signature,o)}async function p(n,i){let s=typeof i=="string"?new TextEncoder().encode(i):i,o={name:"HMAC",hash:{name:"SHA-256"}},a=await crypto.subtle.importKey("raw",s,o,false,["sign"]),g=new TextEncoder().encode(n),d=await crypto.subtle.sign("HMAC",a,g);return Array.from(new Uint8Array(d)).map(c=>c.toString(16).padStart(2,"0")).join("")}function h(n,i){if(n.length!==i.length)return false;let s=0;for(let o=0;o<n.length;o++)s|=n.charCodeAt(o)^i.charCodeAt(o);return s===0}export{w as a,m as b,b as c,S as d,A as e,k as f,x as g,T as h,v as i,D as j,E as k};//# sourceMappingURL=chunk-GO63IIN5.js.map
|
|
2
|
+
//# sourceMappingURL=chunk-GO63IIN5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/utils.ts"],"names":["withTimeout","promise","ms","errorMessage","timeoutId","timeoutPromise","_","reject","stableStringify","value","maxDepth","seen","stringifyPrimitive","val","type","withCircularGuard","obj","fn","result","stringifyArray","depth","v","stringify","stringifyObject","k","primitive","isPrototypeSafe","dangerousKeys","objVal","checkArray","arr","item","check","checkObject","key","shallowEqual","a","b","keysA","keysB","hashObject","str","hash","i","isSnapshotExpired","snapshot","now","validateSnapshot","expiredAt","diffSnapshots","oldSnapshot","newSnapshot","changes","pushChange","path","oldValue","newValue","compareNullish","oldObj","newObj","compareArrays","oldArr","newArr","compare","compareObjects","oldRecord","newRecord","allKeys","childPath","versionChanged","isSignedSnapshot","signSnapshot","secret","payload","signature","hmacSha256","verifySnapshotSignature","signedSnapshot","expectedSignature","timingSafeEqual","message","secretBytes","algorithm","messageBytes"],"mappings":"AAcA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAIC,CAAAA,CAEEC,CAAAA,CAAiB,IAAI,OAAA,CAAe,CAACC,CAAAA,CAAGC,CAAAA,GAAW,CACvDH,CAAAA,CAAY,UAAA,CAAW,IAAMG,CAAAA,CAAO,IAAI,KAAA,CAAMJ,CAAY,CAAC,CAAA,CAAGD,CAAE,EAClE,CAAC,CAAA,CAED,GAAI,CACF,OAAO,MAAM,OAAA,CAAQ,IAAA,CAAK,CAACD,CAAAA,CAASI,CAAc,CAAC,CACrD,CAAA,OAAE,CACA,YAAA,CAAaD,CAAU,EACzB,CACF,CAwBO,SAASI,CAAAA,CAAgBC,CAAAA,CAAgBC,CAAAA,CAAW,EAAA,CAAY,CACrE,IAAMC,CAAAA,CAAO,IAAI,OAAA,CAGjB,SAASC,CAAAA,CAAmBC,CAAAA,CAAkC,CAC5D,GAAIA,CAAAA,GAAQ,IAAA,CAAM,OAAO,MAAA,CACzB,GAAIA,CAAAA,GAAQ,MAAA,CAAW,OAAO,WAAA,CAE9B,IAAMC,CAAAA,CAAO,OAAOD,CAAAA,CACpB,GAAIC,CAAAA,GAAS,QAAA,CAAU,OAAO,IAAA,CAAK,SAAA,CAAUD,CAAG,CAAA,CAChD,GAAIC,CAAAA,GAAS,QAAA,EAAYA,CAAAA,GAAS,SAAA,CAAW,OAAO,MAAA,CAAOD,CAAG,CAAA,CAC9D,GAAIC,CAAAA,GAAS,UAAA,CAAY,OAAO,cAAA,CAChC,GAAIA,CAAAA,GAAS,QAAA,CAAU,OAAO,YAGhC,CAGA,SAASC,CAAAA,CACPC,CAAAA,CACAC,CAAAA,CACQ,CACR,GAA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AAAA,CAAE,UAAA,CAAWM,CAAC,CAAA,CAE5C,OAAOzB,CAAAA,GAAW,CACpB","file":"chunk-GO63IIN5.js","sourcesContent":["/**\n * Shared utilities for Directive\n */\n\n/**\n * Execute a promise with a timeout, properly cleaning up the timer.\n * Used by both constraints and resolvers for timeout handling.\n *\n * @param promise - The promise to wrap with a timeout\n * @param ms - Timeout duration in milliseconds\n * @param errorMessage - Error message if timeout occurs\n * @returns The promise result\n * @throws Error if timeout is exceeded\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n errorMessage: string,\n): Promise<T> {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(errorMessage)), ms);\n });\n\n try {\n return await Promise.race([promise, timeoutPromise]);\n } finally {\n clearTimeout(timeoutId!);\n }\n}\n\n/**\n * Normalize an error to an Error instance.\n * Ensures consistent error handling throughout the library.\n *\n * @param error - The error to normalize (can be anything)\n * @returns An Error instance\n */\nexport function normalizeError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\n\n/**\n * Create a stable JSON string with sorted keys.\n * Handles circular references and deeply nested objects safely.\n *\n * @param value - The value to stringify\n * @param maxDepth - Maximum nesting depth (default: 50)\n * @returns A stable JSON string\n */\nexport function stableStringify(value: unknown, maxDepth = 50): string {\n const seen = new WeakSet();\n\n /** Stringify a primitive value (null, undefined, string, number, boolean, function, symbol). */\n function stringifyPrimitive(val: unknown): string | undefined {\n if (val === null) return \"null\";\n if (val === undefined) return \"undefined\";\n\n const type = typeof val;\n if (type === \"string\") return JSON.stringify(val);\n if (type === \"number\" || type === \"boolean\") return String(val);\n if (type === \"function\") return '\"[function]\"';\n if (type === \"symbol\") return '\"[symbol]\"';\n\n return undefined;\n }\n\n /** Guard against circular references using a seen-set, then delegate to fn. */\n function withCircularGuard(\n obj: object,\n fn: () => string,\n ): string {\n if (seen.has(obj)) {\n return '\"[circular]\"';\n }\n seen.add(obj);\n const result = fn();\n seen.delete(obj);\n\n return result;\n }\n\n /** Stringify an array with circular reference protection. */\n function stringifyArray(val: unknown[], depth: number): string {\n return withCircularGuard(val, () =>\n `[${val.map((v) => stringify(v, depth + 1)).join(\",\")}]`,\n );\n }\n\n /** Stringify an object with sorted keys and circular reference protection. */\n function stringifyObject(obj: Record<string, unknown>, depth: number): string {\n return withCircularGuard(obj, () => {\n const keys = Object.keys(obj).sort();\n const pairs = keys.map(\n (k) => `${JSON.stringify(k)}:${stringify(obj[k], depth + 1)}`,\n );\n\n return `{${pairs.join(\",\")}}`;\n });\n }\n\n /** Recursively stringify a value with depth limit and circular detection. */\n function stringify(val: unknown, depth: number): string {\n if (depth > maxDepth) {\n return '\"[max depth exceeded]\"';\n }\n\n const primitive = stringifyPrimitive(val);\n if (primitive !== undefined) {\n return primitive;\n }\n\n if (Array.isArray(val)) {\n return stringifyArray(val, depth);\n }\n\n if (typeof val === \"object\") {\n return stringifyObject(val as Record<string, unknown>, depth);\n }\n\n return '\"[unknown]\"';\n }\n\n return stringify(value, 0);\n}\n\n/**\n * Check for prototype pollution in an object, including nested objects.\n * Returns true if the object is safe, false if dangerous keys are found.\n *\n * @param obj - The object to check\n * @param maxDepth - Maximum nesting depth to check (default: 50)\n * @returns True if safe, false if dangerous keys found\n */\nexport function isPrototypeSafe(obj: unknown, maxDepth = 50): boolean {\n const dangerousKeys = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n const seen = new WeakSet();\n\n /** Guard against circular references using a seen-set, then delegate to fn. */\n function withCircularGuard(\n objVal: object,\n fn: () => boolean,\n ): boolean {\n if (seen.has(objVal)) return true;\n seen.add(objVal);\n const result = fn();\n seen.delete(objVal);\n\n return result;\n }\n\n /** Check array elements for prototype pollution keys. */\n function checkArray(arr: unknown[], depth: number): boolean {\n for (const item of arr) {\n if (!check(item, depth + 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Check object keys and values for prototype pollution. */\n function checkObject(objVal: Record<string, unknown>, depth: number): boolean {\n for (const key of Object.keys(objVal)) {\n if (dangerousKeys.has(key)) {\n return false;\n }\n if (!check(objVal[key], depth + 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Recursively check a value tree for dangerous prototype keys. */\n function check(val: unknown, depth: number): boolean {\n if (depth > maxDepth) return false; // Fail safe at max depth - don't assume safety\n if (val === null || val === undefined) return true;\n if (typeof val !== \"object\") return true;\n\n const objVal = val as Record<string, unknown>;\n\n if (Array.isArray(objVal)) {\n return withCircularGuard(objVal, () => checkArray(objVal, depth));\n }\n\n return withCircularGuard(objVal, () => checkObject(objVal, depth));\n }\n\n return check(obj, 0);\n}\n\n/**\n * Shallow equality comparison for objects.\n * Used by React hooks to avoid unnecessary re-renders.\n *\n * @param a - First object\n * @param b - Second object\n * @returns True if objects are shallowly equal\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n a: T,\n b: T,\n): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (a[key] !== b[key]) return false;\n }\n\n return true;\n}\n\n/**\n * Generate a simple hash string from an object.\n * Uses djb2 algorithm on the stable stringified value.\n *\n * **Limitations:**\n * - 32-bit hash output means collision probability increases with data set size\n * (birthday paradox: ~50% collision chance at ~77,000 distinct values)\n * - Suitable for: cache invalidation, change detection, deduplication of small sets\n * - NOT suitable for: cryptographic use, security-sensitive operations, large-scale deduplication\n *\n * For security-sensitive use cases requiring stronger collision resistance,\n * consider using a cryptographic hash like SHA-256.\n *\n * @param value - The value to hash\n * @returns A hex hash string (8 characters, 32 bits)\n */\nexport function hashObject(value: unknown): string {\n const str = stableStringify(value);\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n }\n // Convert to unsigned 32-bit and then to hex\n return (hash >>> 0).toString(16);\n}\n\n// ============================================================================\n// Distributable Snapshot Utilities\n// ============================================================================\n\n/**\n * Distributable snapshot type for type-safe helper functions.\n */\nexport interface DistributableSnapshotLike<T = Record<string, unknown>> {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Check if a distributable snapshot has expired.\n * Returns false if the snapshot has no expiresAt field.\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({ ttlSeconds: 3600 });\n * // ... later ...\n * if (isSnapshotExpired(snapshot)) {\n * // Refresh the snapshot\n * }\n * ```\n *\n * @param snapshot - The snapshot to check\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns True if the snapshot has expired, false otherwise\n */\nexport function isSnapshotExpired<T>(\n snapshot: DistributableSnapshotLike<T>,\n now: number = Date.now(),\n): boolean {\n return snapshot.expiresAt !== undefined && now > snapshot.expiresAt;\n}\n\n/**\n * Validate a distributable snapshot and return its data.\n * Throws if the snapshot is malformed or has expired.\n *\n * @example\n * ```typescript\n * const cached = JSON.parse(await redis.get(`entitlements:${userId}`));\n * try {\n * const data = validateSnapshot(cached);\n * // Use data.canUseFeature, etc.\n * } catch (e) {\n * // Snapshot invalid or expired, refresh it\n * }\n * ```\n *\n * @example Using custom timestamp for testing\n * ```typescript\n * const snapshot = { data: { test: true }, createdAt: 1000, expiresAt: 2000 };\n * validateSnapshot(snapshot, 1500); // Returns { test: true }\n * validateSnapshot(snapshot, 2500); // Throws: Snapshot expired\n * ```\n *\n * @param snapshot - The snapshot to validate\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns The snapshot data if valid\n * @throws Error if the snapshot is malformed or has expired\n */\nexport function validateSnapshot<T>(\n snapshot: DistributableSnapshotLike<T>,\n now: number = Date.now(),\n): T {\n // Structural validation\n if (!snapshot || typeof snapshot !== \"object\") {\n throw new Error(\n \"[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.\",\n );\n }\n if (!(\"data\" in snapshot)) {\n throw new Error(\n \"[Directive] Invalid snapshot: missing required 'data' property.\",\n );\n }\n if (!(\"createdAt\" in snapshot) || typeof snapshot.createdAt !== \"number\") {\n throw new Error(\n \"[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).\",\n );\n }\n\n // Expiration validation\n if (isSnapshotExpired(snapshot, now)) {\n const expiredAt = new Date(snapshot.expiresAt!).toISOString();\n throw new Error(\n `[Directive] Snapshot expired at ${expiredAt}. Obtain a fresh snapshot from the source.`,\n );\n }\n return snapshot.data;\n}\n\n/**\n * Diff result for a single changed value.\n */\nexport interface SnapshotDiffEntry {\n /** The key path that changed (e.g., \"canUseApi\" or \"limits.apiCalls\") */\n path: string;\n /** The value in the old snapshot */\n oldValue: unknown;\n /** The value in the new snapshot */\n newValue: unknown;\n /** Type of change: \"added\", \"removed\", or \"changed\" */\n type: \"added\" | \"removed\" | \"changed\";\n}\n\n/**\n * Result of diffing two snapshots.\n */\nexport interface SnapshotDiff {\n /** Whether the snapshots are identical */\n identical: boolean;\n /** List of changes between snapshots */\n changes: SnapshotDiffEntry[];\n /** Whether the version changed (if both have versions) */\n versionChanged: boolean;\n /** Old version (if available) */\n oldVersion?: string;\n /** New version (if available) */\n newVersion?: string;\n}\n\n/**\n * Compare two distributable snapshots and return the differences.\n * Useful for debugging, audit logs, and webhook payloads.\n *\n * @example\n * ```typescript\n * const oldSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n * system.dispatch({ type: \"upgradePlan\", plan: \"pro\" });\n * const newSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n *\n * const diff = diffSnapshots(oldSnapshot, newSnapshot);\n * if (!diff.identical) {\n * console.log(\"Changes:\", diff.changes);\n * // [{ path: \"canUseApi\", oldValue: false, newValue: true, type: \"changed\" }]\n * }\n * ```\n *\n * @param oldSnapshot - The previous snapshot\n * @param newSnapshot - The new snapshot\n * @returns A diff result with all changes\n */\nexport function diffSnapshots<T = Record<string, unknown>>(\n oldSnapshot: DistributableSnapshotLike<T>,\n newSnapshot: DistributableSnapshotLike<T>,\n): SnapshotDiff {\n const changes: SnapshotDiffEntry[] = [];\n\n /** Push a change entry to the diff results. */\n function pushChange(\n path: string,\n oldValue: unknown,\n newValue: unknown,\n type: SnapshotDiffEntry[\"type\"],\n ): void {\n changes.push({ path, oldValue, newValue, type });\n }\n\n /** Handle null/undefined comparison cases. Returns true if fully handled. */\n function compareNullish(\n oldObj: unknown,\n newObj: unknown,\n path: string,\n ): boolean {\n if (oldObj === null || oldObj === undefined) {\n if (newObj !== null && newObj !== undefined) {\n pushChange(path, oldObj, newObj, \"added\");\n }\n\n return true;\n }\n if (newObj === null || newObj === undefined) {\n pushChange(path, oldObj, newObj, \"removed\");\n\n return true;\n }\n\n return false;\n }\n\n /** Compare two arrays element by element, recursing into each. */\n function compareArrays(\n oldArr: unknown[],\n newArr: unknown[],\n path: string,\n ): void {\n if (oldArr.length !== newArr.length) {\n pushChange(path, oldArr, newArr, \"changed\");\n\n return;\n }\n for (let i = 0; i < oldArr.length; i++) {\n compare(oldArr[i], newArr[i], `${path}[${i}]`);\n }\n }\n\n /** Compare two objects by key union, detecting added/removed/changed. */\n function compareObjects(\n oldRecord: Record<string, unknown>,\n newRecord: Record<string, unknown>,\n path: string,\n ): void {\n const allKeys = new Set([\n ...Object.keys(oldRecord),\n ...Object.keys(newRecord),\n ]);\n\n for (const key of allKeys) {\n const childPath = path ? `${path}.${key}` : key;\n if (!(key in oldRecord)) {\n pushChange(childPath, undefined, newRecord[key], \"added\");\n } else if (!(key in newRecord)) {\n pushChange(childPath, oldRecord[key], undefined, \"removed\");\n } else {\n compare(oldRecord[key], newRecord[key], childPath);\n }\n }\n }\n\n /** Recursively compare two values and record differences. */\n function compare(oldObj: unknown, newObj: unknown, path: string): void {\n if (compareNullish(oldObj, newObj, path)) {\n return;\n }\n\n // Handle primitives\n if (typeof oldObj !== \"object\" || typeof newObj !== \"object\") {\n if (!Object.is(oldObj, newObj)) {\n pushChange(path, oldObj, newObj, \"changed\");\n }\n\n return;\n }\n\n // Handle arrays\n if (Array.isArray(oldObj) && Array.isArray(newObj)) {\n compareArrays(oldObj, newObj, path);\n\n return;\n }\n\n // Handle objects\n compareObjects(\n oldObj as Record<string, unknown>,\n newObj as Record<string, unknown>,\n path,\n );\n }\n\n // Compare data\n compare(oldSnapshot.data, newSnapshot.data, \"\");\n\n // Check version change\n const versionChanged =\n oldSnapshot.version !== newSnapshot.version &&\n (oldSnapshot.version !== undefined || newSnapshot.version !== undefined);\n\n return {\n identical: changes.length === 0,\n changes,\n versionChanged,\n oldVersion: oldSnapshot.version,\n newVersion: newSnapshot.version,\n };\n}\n\n// ============================================================================\n// Snapshot Signing (HMAC)\n// ============================================================================\n\n/**\n * A signed distributable snapshot.\n * Contains the original snapshot plus a cryptographic signature.\n */\nexport interface SignedSnapshot<T = Record<string, unknown>>\n extends DistributableSnapshotLike<T> {\n /** HMAC-SHA256 signature in hex format */\n signature: string;\n /** Signing algorithm used */\n algorithm: \"hmac-sha256\";\n}\n\n/**\n * Check if a snapshot is signed.\n *\n * @param snapshot - The snapshot to check\n * @returns True if the snapshot has a signature\n */\nexport function isSignedSnapshot<T>(\n snapshot: DistributableSnapshotLike<T> | SignedSnapshot<T>,\n): snapshot is SignedSnapshot<T> {\n return \"signature\" in snapshot && typeof snapshot.signature === \"string\";\n}\n\n/**\n * Sign a distributable snapshot using HMAC-SHA256.\n * Creates a tamper-proof signature that can be verified later.\n *\n * **Security Notes:**\n * - Use a cryptographically random secret of at least 32 bytes\n * - Store the secret securely (environment variable, secrets manager)\n * - Never expose the secret to clients\n * - The signature covers all snapshot fields for integrity\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({\n * includeDerivations: ['canUseFeature', 'limits'],\n * ttlSeconds: 3600,\n * });\n *\n * // Sign the snapshot (server-side only)\n * const signed = await signSnapshot(snapshot, process.env.SNAPSHOT_SECRET);\n *\n * // Store in JWT, Redis, or send to client\n * const jwt = createJWT({ snapshot: signed });\n *\n * // Later, verify the signature\n * const isValid = await verifySnapshotSignature(signed, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Snapshot has been tampered with');\n * }\n * ```\n *\n * @param snapshot - The snapshot to sign\n * @param secret - The HMAC secret (string or Uint8Array)\n * @returns A signed snapshot with the signature attached\n */\nexport async function signSnapshot<T>(\n snapshot: DistributableSnapshotLike<T>,\n secret: string | Uint8Array,\n): Promise<SignedSnapshot<T>> {\n // Create a canonical representation for signing\n const payload = stableStringify({\n data: snapshot.data,\n createdAt: snapshot.createdAt,\n expiresAt: snapshot.expiresAt,\n version: snapshot.version,\n metadata: snapshot.metadata,\n });\n\n const signature = await hmacSha256(payload, secret);\n\n return {\n ...snapshot,\n signature,\n algorithm: \"hmac-sha256\",\n };\n}\n\n/**\n * Verify the signature of a signed snapshot.\n * Returns true if the signature is valid, false otherwise.\n *\n * **Important:** Always verify signatures before trusting snapshot data,\n * especially if the snapshot was received from an untrusted source (client, cache).\n *\n * @example\n * ```typescript\n * // Receive signed snapshot from client or cache\n * const snapshot = JSON.parse(cachedData);\n *\n * // Verify before using\n * const isValid = await verifySnapshotSignature(snapshot, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Invalid snapshot signature - possible tampering');\n * }\n *\n * // Now safe to use snapshot.data\n * if (snapshot.data.canUseFeature.api) {\n * // Grant access\n * }\n * ```\n *\n * @param signedSnapshot - The signed snapshot to verify\n * @param secret - The HMAC secret (must match the signing secret)\n * @returns True if signature is valid, false otherwise\n */\nexport async function verifySnapshotSignature<T>(\n signedSnapshot: SignedSnapshot<T>,\n secret: string | Uint8Array,\n): Promise<boolean> {\n if (!signedSnapshot.signature || signedSnapshot.algorithm !== \"hmac-sha256\") {\n return false;\n }\n\n // Recreate the canonical payload (same as signing)\n const payload = stableStringify({\n data: signedSnapshot.data,\n createdAt: signedSnapshot.createdAt,\n expiresAt: signedSnapshot.expiresAt,\n version: signedSnapshot.version,\n metadata: signedSnapshot.metadata,\n });\n\n const expectedSignature = await hmacSha256(payload, secret);\n\n // Use timing-safe comparison\n return timingSafeEqual(signedSnapshot.signature, expectedSignature);\n}\n\n/**\n * Create HMAC-SHA256 signature of a message.\n * Uses Web Crypto API for cross-platform support (Node.js, browsers, Deno, Bun).\n */\nasync function hmacSha256(\n message: string,\n secret: string | Uint8Array,\n): Promise<string> {\n // Convert secret to Uint8Array if string\n const secretBytes: Uint8Array =\n typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\n // Import key for HMAC\n const algorithm: HmacImportParams = {\n name: \"HMAC\",\n hash: { name: \"SHA-256\" },\n };\n const key = await crypto.subtle.importKey(\n \"raw\",\n secretBytes as unknown as ArrayBuffer,\n algorithm,\n false,\n [\"sign\"],\n );\n\n // Sign the message\n const messageBytes = new TextEncoder().encode(message);\n const signature = await crypto.subtle.sign(\"HMAC\", key, messageBytes);\n\n // Convert to hex string\n return Array.from(new Uint8Array(signature))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Timing-safe string comparison to prevent timing attacks.\n * Both strings should be the same length (hex signatures from same algorithm).\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return result === 0;\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
'use strict';async function w(n,i,s){let o,a=new Promise((g,d)=>{o=setTimeout(()=>d(new Error(s)),i);});try{return await Promise.race([n,a])}finally{clearTimeout(o);}}function m(n,i=50){let s=new WeakSet;function o(r){if(r===null)return "null";if(r===void 0)return "undefined";let e=typeof r;if(e==="string")return JSON.stringify(r);if(e==="number"||e==="boolean")return String(r);if(e==="function")return '"[function]"';if(e==="symbol")return '"[symbol]"'}function a(r,e){if(s.has(r))return '"[circular]"';s.add(r);let t=e();return s.delete(r),t}function g(r,e){return a(r,()=>`[${r.map(t=>c(t,e+1)).join(",")}]`)}function d(r,e){return a(r,()=>`{${Object.keys(r).sort().map(f=>`${JSON.stringify(f)}:${c(r[f],e+1)}`).join(",")}}`)}function c(r,e){if(e>i)return '"[max depth exceeded]"';let t=o(r);return t!==void 0?t:Array.isArray(r)?g(r,e):typeof r=="object"?d(r,e):'"[unknown]"'}return c(n,0)}function b(n,i=50){let s=new Set(["__proto__","constructor","prototype"]),o=new WeakSet;function a(r,e){if(o.has(r))return true;o.add(r);let t=e();return o.delete(r),t}function g(r,e){for(let t of r)if(!c(t,e+1))return false;return true}function d(r,e){for(let t of Object.keys(r))if(s.has(t)||!c(r[t],e+1))return false;return true}function c(r,e){if(e>i)return false;if(r==null||typeof r!="object")return true;let t=r;return Array.isArray(t)?a(t,()=>g(t,e)):a(t,()=>d(t,e))}return c(n,0)}function S(n,i){if(n===i)return true;if(!n||!i)return false;let s=Object.keys(n),o=Object.keys(i);if(s.length!==o.length)return false;for(let a of s)if(n[a]!==i[a])return false;return true}function A(n){let i=m(n),s=5381;for(let o=0;o<i.length;o++)s=(s<<5)+s^i.charCodeAt(o);return (s>>>0).toString(16)}function k(n,i=Date.now()){return n.expiresAt!==void 0&&i>n.expiresAt}function x(n,i=Date.now()){if(!n||typeof n!="object")throw new Error("[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.");if(!("data"in n))throw new Error("[Directive] Invalid snapshot: missing required 'data' property.");if(!("createdAt"in n)||typeof n.createdAt!="number")throw new Error("[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).");if(k(n,i)){let s=new Date(n.expiresAt).toISOString();throw new Error(`[Directive] Snapshot expired at ${s}. Obtain a fresh snapshot from the source.`)}return n.data}function T(n,i){let s=[];function o(e,t,u,f){s.push({path:e,oldValue:t,newValue:u,type:f});}function a(e,t,u){return e==null?(t!=null&&o(u,e,t,"added"),true):t==null?(o(u,e,t,"removed"),true):false}function g(e,t,u){if(e.length!==t.length){o(u,e,t,"changed");return}for(let f=0;f<e.length;f++)c(e[f],t[f],`${u}[${f}]`);}function d(e,t,u){let f=new Set([...Object.keys(e),...Object.keys(t)]);for(let y of f){let l=u?`${u}.${y}`:y;y in e?y in t?c(e[y],t[y],l):o(l,e[y],void 0,"removed"):o(l,void 0,t[y],"added");}}function c(e,t,u){if(!a(e,t,u)){if(typeof e!="object"||typeof t!="object"){Object.is(e,t)||o(u,e,t,"changed");return}if(Array.isArray(e)&&Array.isArray(t)){g(e,t,u);return}d(e,t,u);}}c(n.data,i.data,"");let r=n.version!==i.version&&(n.version!==void 0||i.version!==void 0);return {identical:s.length===0,changes:s,versionChanged:r,oldVersion:n.version,newVersion:i.version}}function v(n){return "signature"in n&&typeof n.signature=="string"}async function D(n,i){let s=m({data:n.data,createdAt:n.createdAt,expiresAt:n.expiresAt,version:n.version,metadata:n.metadata}),o=await p(s,i);return {...n,signature:o,algorithm:"hmac-sha256"}}async function E(n,i){if(!n.signature||n.algorithm!=="hmac-sha256")return false;let s=m({data:n.data,createdAt:n.createdAt,expiresAt:n.expiresAt,version:n.version,metadata:n.metadata}),o=await p(s,i);return h(n.signature,o)}async function p(n,i){let s=typeof i=="string"?new TextEncoder().encode(i):i,o={name:"HMAC",hash:{name:"SHA-256"}},a=await crypto.subtle.importKey("raw",s,o,false,["sign"]),g=new TextEncoder().encode(n),d=await crypto.subtle.sign("HMAC",a,g);return Array.from(new Uint8Array(d)).map(c=>c.toString(16).padStart(2,"0")).join("")}function h(n,i){if(n.length!==i.length)return false;let s=0;for(let o=0;o<n.length;o++)s|=n.charCodeAt(o)^i.charCodeAt(o);return s===0}exports.a=w;exports.b=m;exports.c=b;exports.d=S;exports.e=A;exports.f=k;exports.g=x;exports.h=T;exports.i=v;exports.j=D;exports.k=E;//# sourceMappingURL=chunk-KQKNE23L.cjs.map
|
|
2
|
+
//# sourceMappingURL=chunk-KQKNE23L.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/utils.ts"],"names":["withTimeout","promise","ms","errorMessage","timeoutId","timeoutPromise","_","reject","stableStringify","value","maxDepth","seen","stringifyPrimitive","val","type","withCircularGuard","obj","fn","result","stringifyArray","depth","v","stringify","stringifyObject","k","primitive","isPrototypeSafe","dangerousKeys","objVal","checkArray","arr","item","check","checkObject","key","shallowEqual","a","b","keysA","keysB","hashObject","str","hash","i","isSnapshotExpired","snapshot","now","validateSnapshot","expiredAt","diffSnapshots","oldSnapshot","newSnapshot","changes","pushChange","path","oldValue","newValue","compareNullish","oldObj","newObj","compareArrays","oldArr","newArr","compare","compareObjects","oldRecord","newRecord","allKeys","childPath","versionChanged","isSignedSnapshot","signSnapshot","secret","payload","signature","hmacSha256","verifySnapshotSignature","signedSnapshot","expectedSignature","timingSafeEqual","message","secretBytes","algorithm","messageBytes"],"mappings":"aAcA,eAAsBA,CAAAA,CACpBC,CAAAA,CACAC,CAAAA,CACAC,CAAAA,CACY,CACZ,IAAIC,CAAAA,CAEEC,CAAAA,CAAiB,IAAI,OAAA,CAAe,CAACC,CAAAA,CAAGC,CAAAA,GAAW,CACvDH,CAAAA,CAAY,UAAA,CAAW,IAAMG,CAAAA,CAAO,IAAI,KAAA,CAAMJ,CAAY,CAAC,CAAA,CAAGD,CAAE,EAClE,CAAC,CAAA,CAED,GAAI,CACF,OAAO,MAAM,OAAA,CAAQ,IAAA,CAAK,CAACD,CAAAA,CAASI,CAAc,CAAC,CACrD,CAAA,OAAE,CACA,YAAA,CAAaD,CAAU,EACzB,CACF,CAwBO,SAASI,CAAAA,CAAgBC,CAAAA,CAAgBC,CAAAA,CAAW,EAAA,CAAY,CACrE,IAAMC,CAAAA,CAAO,IAAI,OAAA,CAGjB,SAASC,CAAAA,CAAmBC,CAAAA,CAAkC,CAC5D,GAAIA,CAAAA,GAAQ,IAAA,CAAM,OAAO,MAAA,CACzB,GAAIA,CAAAA,GAAQ,MAAA,CAAW,OAAO,WAAA,CAE9B,IAAMC,CAAAA,CAAO,OAAOD,CAAAA,CACpB,GAAIC,CAAAA,GAAS,QAAA,CAAU,OAAO,IAAA,CAAK,SAAA,CAAUD,C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ID,CAAAA,CAAE,MAAA,GAAWC,CAAAA,CAAE,MAAA,CACjB,OAAO,MAAA,CAGT,IAAInB,CAAAA,CAAS,CAAA,CACb,IAAA,IAASyB,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAIP,CAAAA,CAAE,MAAA,CAAQO,CAAAA,EAAAA,CAC5BzB,CAAAA,EAAUkB,CAAAA,CAAE,UAAA,CAAWO,CAAC,CAAA,CAAIN,CAAAA,CAAE,UAAA,CAAWM,CAAC,CAAA,CAE5C,OAAOzB,CAAAA,GAAW,CACpB","file":"chunk-KQKNE23L.cjs","sourcesContent":["/**\n * Shared utilities for Directive\n */\n\n/**\n * Execute a promise with a timeout, properly cleaning up the timer.\n * Used by both constraints and resolvers for timeout handling.\n *\n * @param promise - The promise to wrap with a timeout\n * @param ms - Timeout duration in milliseconds\n * @param errorMessage - Error message if timeout occurs\n * @returns The promise result\n * @throws Error if timeout is exceeded\n */\nexport async function withTimeout<T>(\n promise: Promise<T>,\n ms: number,\n errorMessage: string,\n): Promise<T> {\n let timeoutId: ReturnType<typeof setTimeout>;\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n timeoutId = setTimeout(() => reject(new Error(errorMessage)), ms);\n });\n\n try {\n return await Promise.race([promise, timeoutPromise]);\n } finally {\n clearTimeout(timeoutId!);\n }\n}\n\n/**\n * Normalize an error to an Error instance.\n * Ensures consistent error handling throughout the library.\n *\n * @param error - The error to normalize (can be anything)\n * @returns An Error instance\n */\nexport function normalizeError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n return new Error(String(error));\n}\n\n/**\n * Create a stable JSON string with sorted keys.\n * Handles circular references and deeply nested objects safely.\n *\n * @param value - The value to stringify\n * @param maxDepth - Maximum nesting depth (default: 50)\n * @returns A stable JSON string\n */\nexport function stableStringify(value: unknown, maxDepth = 50): string {\n const seen = new WeakSet();\n\n /** Stringify a primitive value (null, undefined, string, number, boolean, function, symbol). */\n function stringifyPrimitive(val: unknown): string | undefined {\n if (val === null) return \"null\";\n if (val === undefined) return \"undefined\";\n\n const type = typeof val;\n if (type === \"string\") return JSON.stringify(val);\n if (type === \"number\" || type === \"boolean\") return String(val);\n if (type === \"function\") return '\"[function]\"';\n if (type === \"symbol\") return '\"[symbol]\"';\n\n return undefined;\n }\n\n /** Guard against circular references using a seen-set, then delegate to fn. */\n function withCircularGuard(\n obj: object,\n fn: () => string,\n ): string {\n if (seen.has(obj)) {\n return '\"[circular]\"';\n }\n seen.add(obj);\n const result = fn();\n seen.delete(obj);\n\n return result;\n }\n\n /** Stringify an array with circular reference protection. */\n function stringifyArray(val: unknown[], depth: number): string {\n return withCircularGuard(val, () =>\n `[${val.map((v) => stringify(v, depth + 1)).join(\",\")}]`,\n );\n }\n\n /** Stringify an object with sorted keys and circular reference protection. */\n function stringifyObject(obj: Record<string, unknown>, depth: number): string {\n return withCircularGuard(obj, () => {\n const keys = Object.keys(obj).sort();\n const pairs = keys.map(\n (k) => `${JSON.stringify(k)}:${stringify(obj[k], depth + 1)}`,\n );\n\n return `{${pairs.join(\",\")}}`;\n });\n }\n\n /** Recursively stringify a value with depth limit and circular detection. */\n function stringify(val: unknown, depth: number): string {\n if (depth > maxDepth) {\n return '\"[max depth exceeded]\"';\n }\n\n const primitive = stringifyPrimitive(val);\n if (primitive !== undefined) {\n return primitive;\n }\n\n if (Array.isArray(val)) {\n return stringifyArray(val, depth);\n }\n\n if (typeof val === \"object\") {\n return stringifyObject(val as Record<string, unknown>, depth);\n }\n\n return '\"[unknown]\"';\n }\n\n return stringify(value, 0);\n}\n\n/**\n * Check for prototype pollution in an object, including nested objects.\n * Returns true if the object is safe, false if dangerous keys are found.\n *\n * @param obj - The object to check\n * @param maxDepth - Maximum nesting depth to check (default: 50)\n * @returns True if safe, false if dangerous keys found\n */\nexport function isPrototypeSafe(obj: unknown, maxDepth = 50): boolean {\n const dangerousKeys = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n const seen = new WeakSet();\n\n /** Guard against circular references using a seen-set, then delegate to fn. */\n function withCircularGuard(\n objVal: object,\n fn: () => boolean,\n ): boolean {\n if (seen.has(objVal)) return true;\n seen.add(objVal);\n const result = fn();\n seen.delete(objVal);\n\n return result;\n }\n\n /** Check array elements for prototype pollution keys. */\n function checkArray(arr: unknown[], depth: number): boolean {\n for (const item of arr) {\n if (!check(item, depth + 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Check object keys and values for prototype pollution. */\n function checkObject(objVal: Record<string, unknown>, depth: number): boolean {\n for (const key of Object.keys(objVal)) {\n if (dangerousKeys.has(key)) {\n return false;\n }\n if (!check(objVal[key], depth + 1)) {\n return false;\n }\n }\n\n return true;\n }\n\n /** Recursively check a value tree for dangerous prototype keys. */\n function check(val: unknown, depth: number): boolean {\n if (depth > maxDepth) return false; // Fail safe at max depth - don't assume safety\n if (val === null || val === undefined) return true;\n if (typeof val !== \"object\") return true;\n\n const objVal = val as Record<string, unknown>;\n\n if (Array.isArray(objVal)) {\n return withCircularGuard(objVal, () => checkArray(objVal, depth));\n }\n\n return withCircularGuard(objVal, () => checkObject(objVal, depth));\n }\n\n return check(obj, 0);\n}\n\n/**\n * Shallow equality comparison for objects.\n * Used by React hooks to avoid unnecessary re-renders.\n *\n * @param a - First object\n * @param b - Second object\n * @returns True if objects are shallowly equal\n */\nexport function shallowEqual<T extends Record<string, unknown>>(\n a: T,\n b: T,\n): boolean {\n if (a === b) return true;\n if (!a || !b) return false;\n\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) return false;\n\n for (const key of keysA) {\n if (a[key] !== b[key]) return false;\n }\n\n return true;\n}\n\n/**\n * Generate a simple hash string from an object.\n * Uses djb2 algorithm on the stable stringified value.\n *\n * **Limitations:**\n * - 32-bit hash output means collision probability increases with data set size\n * (birthday paradox: ~50% collision chance at ~77,000 distinct values)\n * - Suitable for: cache invalidation, change detection, deduplication of small sets\n * - NOT suitable for: cryptographic use, security-sensitive operations, large-scale deduplication\n *\n * For security-sensitive use cases requiring stronger collision resistance,\n * consider using a cryptographic hash like SHA-256.\n *\n * @param value - The value to hash\n * @returns A hex hash string (8 characters, 32 bits)\n */\nexport function hashObject(value: unknown): string {\n const str = stableStringify(value);\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n }\n // Convert to unsigned 32-bit and then to hex\n return (hash >>> 0).toString(16);\n}\n\n// ============================================================================\n// Distributable Snapshot Utilities\n// ============================================================================\n\n/**\n * Distributable snapshot type for type-safe helper functions.\n */\nexport interface DistributableSnapshotLike<T = Record<string, unknown>> {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Check if a distributable snapshot has expired.\n * Returns false if the snapshot has no expiresAt field.\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({ ttlSeconds: 3600 });\n * // ... later ...\n * if (isSnapshotExpired(snapshot)) {\n * // Refresh the snapshot\n * }\n * ```\n *\n * @param snapshot - The snapshot to check\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns True if the snapshot has expired, false otherwise\n */\nexport function isSnapshotExpired<T>(\n snapshot: DistributableSnapshotLike<T>,\n now: number = Date.now(),\n): boolean {\n return snapshot.expiresAt !== undefined && now > snapshot.expiresAt;\n}\n\n/**\n * Validate a distributable snapshot and return its data.\n * Throws if the snapshot is malformed or has expired.\n *\n * @example\n * ```typescript\n * const cached = JSON.parse(await redis.get(`entitlements:${userId}`));\n * try {\n * const data = validateSnapshot(cached);\n * // Use data.canUseFeature, etc.\n * } catch (e) {\n * // Snapshot invalid or expired, refresh it\n * }\n * ```\n *\n * @example Using custom timestamp for testing\n * ```typescript\n * const snapshot = { data: { test: true }, createdAt: 1000, expiresAt: 2000 };\n * validateSnapshot(snapshot, 1500); // Returns { test: true }\n * validateSnapshot(snapshot, 2500); // Throws: Snapshot expired\n * ```\n *\n * @param snapshot - The snapshot to validate\n * @param now - Optional current timestamp (defaults to Date.now())\n * @returns The snapshot data if valid\n * @throws Error if the snapshot is malformed or has expired\n */\nexport function validateSnapshot<T>(\n snapshot: DistributableSnapshotLike<T>,\n now: number = Date.now(),\n): T {\n // Structural validation\n if (!snapshot || typeof snapshot !== \"object\") {\n throw new Error(\n \"[Directive] Invalid snapshot: expected an object with 'data' and 'createdAt' properties.\",\n );\n }\n if (!(\"data\" in snapshot)) {\n throw new Error(\n \"[Directive] Invalid snapshot: missing required 'data' property.\",\n );\n }\n if (!(\"createdAt\" in snapshot) || typeof snapshot.createdAt !== \"number\") {\n throw new Error(\n \"[Directive] Invalid snapshot: missing or invalid 'createdAt' property (expected number).\",\n );\n }\n\n // Expiration validation\n if (isSnapshotExpired(snapshot, now)) {\n const expiredAt = new Date(snapshot.expiresAt!).toISOString();\n throw new Error(\n `[Directive] Snapshot expired at ${expiredAt}. Obtain a fresh snapshot from the source.`,\n );\n }\n return snapshot.data;\n}\n\n/**\n * Diff result for a single changed value.\n */\nexport interface SnapshotDiffEntry {\n /** The key path that changed (e.g., \"canUseApi\" or \"limits.apiCalls\") */\n path: string;\n /** The value in the old snapshot */\n oldValue: unknown;\n /** The value in the new snapshot */\n newValue: unknown;\n /** Type of change: \"added\", \"removed\", or \"changed\" */\n type: \"added\" | \"removed\" | \"changed\";\n}\n\n/**\n * Result of diffing two snapshots.\n */\nexport interface SnapshotDiff {\n /** Whether the snapshots are identical */\n identical: boolean;\n /** List of changes between snapshots */\n changes: SnapshotDiffEntry[];\n /** Whether the version changed (if both have versions) */\n versionChanged: boolean;\n /** Old version (if available) */\n oldVersion?: string;\n /** New version (if available) */\n newVersion?: string;\n}\n\n/**\n * Compare two distributable snapshots and return the differences.\n * Useful for debugging, audit logs, and webhook payloads.\n *\n * @example\n * ```typescript\n * const oldSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n * system.dispatch({ type: \"upgradePlan\", plan: \"pro\" });\n * const newSnapshot = system.getDistributableSnapshot({ includeVersion: true });\n *\n * const diff = diffSnapshots(oldSnapshot, newSnapshot);\n * if (!diff.identical) {\n * console.log(\"Changes:\", diff.changes);\n * // [{ path: \"canUseApi\", oldValue: false, newValue: true, type: \"changed\" }]\n * }\n * ```\n *\n * @param oldSnapshot - The previous snapshot\n * @param newSnapshot - The new snapshot\n * @returns A diff result with all changes\n */\nexport function diffSnapshots<T = Record<string, unknown>>(\n oldSnapshot: DistributableSnapshotLike<T>,\n newSnapshot: DistributableSnapshotLike<T>,\n): SnapshotDiff {\n const changes: SnapshotDiffEntry[] = [];\n\n /** Push a change entry to the diff results. */\n function pushChange(\n path: string,\n oldValue: unknown,\n newValue: unknown,\n type: SnapshotDiffEntry[\"type\"],\n ): void {\n changes.push({ path, oldValue, newValue, type });\n }\n\n /** Handle null/undefined comparison cases. Returns true if fully handled. */\n function compareNullish(\n oldObj: unknown,\n newObj: unknown,\n path: string,\n ): boolean {\n if (oldObj === null || oldObj === undefined) {\n if (newObj !== null && newObj !== undefined) {\n pushChange(path, oldObj, newObj, \"added\");\n }\n\n return true;\n }\n if (newObj === null || newObj === undefined) {\n pushChange(path, oldObj, newObj, \"removed\");\n\n return true;\n }\n\n return false;\n }\n\n /** Compare two arrays element by element, recursing into each. */\n function compareArrays(\n oldArr: unknown[],\n newArr: unknown[],\n path: string,\n ): void {\n if (oldArr.length !== newArr.length) {\n pushChange(path, oldArr, newArr, \"changed\");\n\n return;\n }\n for (let i = 0; i < oldArr.length; i++) {\n compare(oldArr[i], newArr[i], `${path}[${i}]`);\n }\n }\n\n /** Compare two objects by key union, detecting added/removed/changed. */\n function compareObjects(\n oldRecord: Record<string, unknown>,\n newRecord: Record<string, unknown>,\n path: string,\n ): void {\n const allKeys = new Set([\n ...Object.keys(oldRecord),\n ...Object.keys(newRecord),\n ]);\n\n for (const key of allKeys) {\n const childPath = path ? `${path}.${key}` : key;\n if (!(key in oldRecord)) {\n pushChange(childPath, undefined, newRecord[key], \"added\");\n } else if (!(key in newRecord)) {\n pushChange(childPath, oldRecord[key], undefined, \"removed\");\n } else {\n compare(oldRecord[key], newRecord[key], childPath);\n }\n }\n }\n\n /** Recursively compare two values and record differences. */\n function compare(oldObj: unknown, newObj: unknown, path: string): void {\n if (compareNullish(oldObj, newObj, path)) {\n return;\n }\n\n // Handle primitives\n if (typeof oldObj !== \"object\" || typeof newObj !== \"object\") {\n if (!Object.is(oldObj, newObj)) {\n pushChange(path, oldObj, newObj, \"changed\");\n }\n\n return;\n }\n\n // Handle arrays\n if (Array.isArray(oldObj) && Array.isArray(newObj)) {\n compareArrays(oldObj, newObj, path);\n\n return;\n }\n\n // Handle objects\n compareObjects(\n oldObj as Record<string, unknown>,\n newObj as Record<string, unknown>,\n path,\n );\n }\n\n // Compare data\n compare(oldSnapshot.data, newSnapshot.data, \"\");\n\n // Check version change\n const versionChanged =\n oldSnapshot.version !== newSnapshot.version &&\n (oldSnapshot.version !== undefined || newSnapshot.version !== undefined);\n\n return {\n identical: changes.length === 0,\n changes,\n versionChanged,\n oldVersion: oldSnapshot.version,\n newVersion: newSnapshot.version,\n };\n}\n\n// ============================================================================\n// Snapshot Signing (HMAC)\n// ============================================================================\n\n/**\n * A signed distributable snapshot.\n * Contains the original snapshot plus a cryptographic signature.\n */\nexport interface SignedSnapshot<T = Record<string, unknown>>\n extends DistributableSnapshotLike<T> {\n /** HMAC-SHA256 signature in hex format */\n signature: string;\n /** Signing algorithm used */\n algorithm: \"hmac-sha256\";\n}\n\n/**\n * Check if a snapshot is signed.\n *\n * @param snapshot - The snapshot to check\n * @returns True if the snapshot has a signature\n */\nexport function isSignedSnapshot<T>(\n snapshot: DistributableSnapshotLike<T> | SignedSnapshot<T>,\n): snapshot is SignedSnapshot<T> {\n return \"signature\" in snapshot && typeof snapshot.signature === \"string\";\n}\n\n/**\n * Sign a distributable snapshot using HMAC-SHA256.\n * Creates a tamper-proof signature that can be verified later.\n *\n * **Security Notes:**\n * - Use a cryptographically random secret of at least 32 bytes\n * - Store the secret securely (environment variable, secrets manager)\n * - Never expose the secret to clients\n * - The signature covers all snapshot fields for integrity\n *\n * @example\n * ```typescript\n * const snapshot = system.getDistributableSnapshot({\n * includeDerivations: ['canUseFeature', 'limits'],\n * ttlSeconds: 3600,\n * });\n *\n * // Sign the snapshot (server-side only)\n * const signed = await signSnapshot(snapshot, process.env.SNAPSHOT_SECRET);\n *\n * // Store in JWT, Redis, or send to client\n * const jwt = createJWT({ snapshot: signed });\n *\n * // Later, verify the signature\n * const isValid = await verifySnapshotSignature(signed, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Snapshot has been tampered with');\n * }\n * ```\n *\n * @param snapshot - The snapshot to sign\n * @param secret - The HMAC secret (string or Uint8Array)\n * @returns A signed snapshot with the signature attached\n */\nexport async function signSnapshot<T>(\n snapshot: DistributableSnapshotLike<T>,\n secret: string | Uint8Array,\n): Promise<SignedSnapshot<T>> {\n // Create a canonical representation for signing\n const payload = stableStringify({\n data: snapshot.data,\n createdAt: snapshot.createdAt,\n expiresAt: snapshot.expiresAt,\n version: snapshot.version,\n metadata: snapshot.metadata,\n });\n\n const signature = await hmacSha256(payload, secret);\n\n return {\n ...snapshot,\n signature,\n algorithm: \"hmac-sha256\",\n };\n}\n\n/**\n * Verify the signature of a signed snapshot.\n * Returns true if the signature is valid, false otherwise.\n *\n * **Important:** Always verify signatures before trusting snapshot data,\n * especially if the snapshot was received from an untrusted source (client, cache).\n *\n * @example\n * ```typescript\n * // Receive signed snapshot from client or cache\n * const snapshot = JSON.parse(cachedData);\n *\n * // Verify before using\n * const isValid = await verifySnapshotSignature(snapshot, process.env.SNAPSHOT_SECRET);\n * if (!isValid) {\n * throw new Error('Invalid snapshot signature - possible tampering');\n * }\n *\n * // Now safe to use snapshot.data\n * if (snapshot.data.canUseFeature.api) {\n * // Grant access\n * }\n * ```\n *\n * @param signedSnapshot - The signed snapshot to verify\n * @param secret - The HMAC secret (must match the signing secret)\n * @returns True if signature is valid, false otherwise\n */\nexport async function verifySnapshotSignature<T>(\n signedSnapshot: SignedSnapshot<T>,\n secret: string | Uint8Array,\n): Promise<boolean> {\n if (!signedSnapshot.signature || signedSnapshot.algorithm !== \"hmac-sha256\") {\n return false;\n }\n\n // Recreate the canonical payload (same as signing)\n const payload = stableStringify({\n data: signedSnapshot.data,\n createdAt: signedSnapshot.createdAt,\n expiresAt: signedSnapshot.expiresAt,\n version: signedSnapshot.version,\n metadata: signedSnapshot.metadata,\n });\n\n const expectedSignature = await hmacSha256(payload, secret);\n\n // Use timing-safe comparison\n return timingSafeEqual(signedSnapshot.signature, expectedSignature);\n}\n\n/**\n * Create HMAC-SHA256 signature of a message.\n * Uses Web Crypto API for cross-platform support (Node.js, browsers, Deno, Bun).\n */\nasync function hmacSha256(\n message: string,\n secret: string | Uint8Array,\n): Promise<string> {\n // Convert secret to Uint8Array if string\n const secretBytes: Uint8Array =\n typeof secret === \"string\" ? new TextEncoder().encode(secret) : secret;\n\n // Import key for HMAC\n const algorithm: HmacImportParams = {\n name: \"HMAC\",\n hash: { name: \"SHA-256\" },\n };\n const key = await crypto.subtle.importKey(\n \"raw\",\n secretBytes as unknown as ArrayBuffer,\n algorithm,\n false,\n [\"sign\"],\n );\n\n // Sign the message\n const messageBytes = new TextEncoder().encode(message);\n const signature = await crypto.subtle.sign(\"HMAC\", key, messageBytes);\n\n // Convert to hex string\n return Array.from(new Uint8Array(signature))\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Timing-safe string comparison to prevent timing attacks.\n * Both strings should be the same length (hex signatures from same algorithm).\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) {\n return false;\n }\n\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a.charCodeAt(i) ^ b.charCodeAt(i);\n }\n return result === 0;\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
'use strict';var chunk6WG7FPH7_cjs=require('./chunk-6WG7FPH7.cjs'),chunkPK2EH26L_cjs=require('./chunk-PK2EH26L.cjs'),chunkKQKNE23L_cjs=require('./chunk-KQKNE23L.cjs');var f="::";function R(n){return new Proxy({},{get(e,t){if(typeof t!="symbol"&&!chunkPK2EH26L_cjs.k.has(t))return n.get(t)},set(e,t,o){return typeof t=="symbol"||chunkPK2EH26L_cjs.k.has(t)?false:n.set?n.set(t,o):false},has(e,t){return typeof t=="symbol"||chunkPK2EH26L_cjs.k.has(t)?false:n.has?n.has(t):false},deleteProperty(e,t){return typeof t=="symbol"||chunkPK2EH26L_cjs.k.has(t)?false:n.delete?n.delete(t):false},ownKeys(){return n.ownKeys?n.ownKeys():[]},getOwnPropertyDescriptor(e,t){if(typeof t!="symbol"&&n.has&&typeof t=="string"&&n.has(t))return {configurable:true,enumerable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}var q=new WeakMap,I=new WeakMap,H=new WeakMap,V=new WeakMap,W=new WeakMap,z=new WeakMap;function S(n,e){let t=q.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,q.set(n,t);let o=R({get:r=>r==="$store"||r==="$snapshot"?n[r]:n[`${e}${f}${r}`],set:(r,a)=>(n[`${e}${f}${r}`]=a,true),has:r=>`${e}${f}${r}`in n,delete:r=>(delete n[`${e}${f}${r}`],true)});return t.set(e,o),o}function U(n,e,t){let o=I.get(n);if(o)return o;let r=R({get:a=>{if(Object.hasOwn(e,a))return S(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return I.set(n,r),r}function G(n,e,t){let o=`${e}|${t.join(",")}`,r=W.get(n);if(r){let i=r.get(o);if(i)return i}else r=new Map,W.set(n,r);let a=new Set(t),u=["self",...t],y=R({get:i=>{if(i==="self")return S(n,e);if(a.has(i))return S(n,i);process.env.NODE_ENV!=="production"&&console.warn(`[Directive] Module "${e}" accessed undeclared cross-module property "${i}". Add it to crossModuleDeps or use "facts.self.${i}" for own module facts.`);},has:i=>i==="self"||a.has(i),ownKeys:()=>u});return r.set(o,y),y}function A(n,e){let t=V.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,V.set(n,t);let o=R({get:r=>n[`${e}${f}${r}`],has:r=>`${e}${f}${r}`in n});return t.set(e,o),o}function L(n,e,t){let o=H.get(n);if(o)return o;let r=R({get:a=>{if(Object.hasOwn(e,a))return A(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return H.set(n,r),r}function Z(n,e,t){let o=z.get(n);return o||(o=new Map,z.set(n,o)),R({get:r=>{if(!Object.hasOwn(e,r))return;let a=o.get(r);if(a)return a;let u=R({get:y=>i=>{n.dispatch({type:`${r}${f}${y}`,...i});}});return o.set(r,u),u},has:r=>Object.hasOwn(e,r),ownKeys:()=>t()})}function v(n){if(n.includes(".")){let[e,...t]=n.split(".");return `${e}${f}${t.join(f)}`}return n}function F(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.indexOf(f);if(r>0){let a=t.slice(0,r),u=t.slice(r+f.length);e[a]||(e[a]={}),e[a][u]=o;}else e._root||(e._root={}),e._root[t]=o;}return e}function O(n,e,t,o){return t?G(n,e,o):S(n,e)}function M(n,e){return `${n}${f}${e}`}function $(n){return Object.keys(n).length>0?n:void 0}function te(n,e){let t={};for(let[o,r]of Object.entries(n.schema.facts))t[M(e,o)]=r;return t}function re(n,e){if(n.init)return t=>{let o=S(t,e);n.init(o);}}function se(n,e,t,o){if(!n.derive)return;let r={};for(let[a,u]of Object.entries(n.derive))r[M(e,a)]=(y,i)=>{let k=O(y,e,t,o),g=A(i,e);return u(k,g)};return $(r)}function oe(n,e){if(!n.events)return;let t={};for(let[o,r]of Object.entries(n.events))t[M(e,o)]=(a,u)=>{let y=S(a,e);r(y,u);};return $(t)}function ie(n,e,t,o){if(!n.constraints)return;let r={};for(let[a,u]of Object.entries(n.constraints)){let y=u;r[M(e,a)]={...y,deps:y.deps?.map(i=>M(e,i)),after:y.after?.map(i=>i.includes(f)?i:M(e,i)),when:i=>{let k=O(i,e,t,o);return y.when(k)},require:typeof y.require=="function"?i=>{let k=O(i,e,t,o);return y.require(k)}:y.require};}return $(r)}function ae(n,e,t,o){if(!n.resolvers)return;let r={};for(let[u,y]of Object.entries(n.resolvers)){let k=function(g){return {facts:O(g.facts,e,t,o),signal:g.signal}};let i=y;r[M(e,u)]={...i,...i.resolve&&{resolve:async(g,d)=>{await i.resolve(g,k(d));}},...i.resolveBatch&&{resolveBatch:async(g,d)=>{await i.resolveBatch(g,k(d));}},...i.resolveBatchWithResults&&{resolveBatchWithResults:async(g,d)=>i.resolveBatchWithResults(g,k(d))}};}return $(r)}function ce(n,e,t,o){if(!n.effects)return;let r={};for(let[a,u]of Object.entries(n.effects)){let y=u;r[M(e,a)]={...y,run:(i,k)=>{let g=O(i,e,t,o),d=k?O(k,e,t,o):void 0;return y.run(g,d)},deps:y.deps?.map(i=>M(e,i))};}return $(r)}function ue(n,e,t){return {snapshotEvents:t&&!t.has(e)?[]:n.history?.snapshotEvents?.map(o=>M(e,o))}}function T(n){let{mod:e,namespace:t,snapshotModulesSet:o}=n,r=!!(e.crossModuleDeps&&Object.keys(e.crossModuleDeps).length>0),a=r?Object.keys(e.crossModuleDeps):[];return {id:e.id,schema:te(e,t),requirements:e.schema.requirements??{},init:re(e,t),derive:se(e,t,r,a),events:oe(e,t),effects:ce(e,t,r,a),constraints:ie(e,t,r,a),resolvers:ae(e,t,r,a),hooks:e.hooks,history:ue(e,t,o)}}function de(n){let e=Object.keys(n),t=new Set(e),o=new Set,r=new Set,a=[],u=[];function y(i){if(o.has(i))return;if(r.has(i)){let g=u.indexOf(i),d=[...u.slice(g),i].join(" \u2192 ");throw new Error(`[Directive] Circular dependency detected: ${d}. Modules cannot have circular crossModuleDeps. Break the cycle by removing one of the cross-module references.`)}r.add(i),u.push(i);let k=n[i];if(k?.crossModuleDeps)for(let g of Object.keys(k.crossModuleDeps))t.has(g)&&y(g);u.pop(),r.delete(i),o.add(i),a.push(i);}for(let i of e)y(i);return a}function J(n,e){let t=[];for(let o of Object.keys(e.schema.facts))t.push(`${n}${f}${o}`);if(e.schema.derivations)for(let o of Object.keys(e.schema.derivations))t.push(`${n}${f}${o}`);return t}function be(n){if("module"in n){if(!n.module)throw new Error("[Directive] createSystem requires a module. Got: "+typeof n.module);return fe(n)}let e=n;if(Array.isArray(e.modules))throw new Error(`[Directive] createSystem expects modules as an object, not an array.
|
|
2
|
+
|
|
3
|
+
Instead of:
|
|
4
|
+
createSystem({ modules: [authModule, dataModule] })
|
|
5
|
+
|
|
6
|
+
Use:
|
|
7
|
+
createSystem({ modules: { auth: authModule, data: dataModule } })
|
|
8
|
+
|
|
9
|
+
Or for a single module:
|
|
10
|
+
createSystem({ module: counterModule })`);let t=e.modules;if(t&&typeof t=="object"&&"id"in t&&"schema"in t)throw new Error(`[Directive] A single module was passed to \`modules:\`. For a single module, use \`module:\` instead:
|
|
11
|
+
|
|
12
|
+
createSystem({ module: myModule })
|
|
13
|
+
|
|
14
|
+
For multiple modules, wrap in an object:
|
|
15
|
+
createSystem({ modules: { myName: myModule } })`);return le(e)}function le(n){let e=n.modules,t=new Set(Object.keys(e)),o=typeof n.history=="object"?n.history:null,r=o?.snapshotModules?new Set(o.snapshotModules):null;if(n.tickMs!==void 0&&n.tickMs<=0)throw new Error("[Directive] tickMs must be a positive number");if(process.env.NODE_ENV!=="production"){for(let[s,c]of Object.entries(e))if(c.crossModuleDeps)for(let l of Object.keys(c.crossModuleDeps))l===s?console.warn(`[Directive] Module "${s}" references itself in crossModuleDeps. Use "facts.self" to access own module's facts instead.`):t.has(l)||console.warn(`[Directive] Module "${s}" declares crossModuleDeps.${l}, but no module with namespace "${l}" exists in the system. Available modules: ${[...t].join(", ")}`);}if(process.env.NODE_ENV!=="production"&&o?.snapshotModules)for(let s of o.snapshotModules)t.has(s)||console.warn(`[Directive] history.snapshotModules entry "${s}" doesn't match any module. Available modules: ${[...t].join(", ")}`);let a,u=n.initOrder??"auto";if(Array.isArray(u)){let s=u,c=Object.keys(e).filter(l=>!s.includes(l));if(c.length>0)throw new Error(`[Directive] initOrder is missing modules: ${c.join(", ")}. All modules must be included in the explicit order.`);a=s;}else u==="declaration"?a=Object.keys(e):a=de(e);let{history:y,trace:i,errorBoundary:k}=Q(n);for(let s of Object.keys(e)){if(s.includes(f))throw new Error(`[Directive] Module name "${s}" contains the reserved separator "${f}". Module names cannot contain "${f}".`);let c=e[s];if(c){for(let l of Object.keys(c.schema.facts))if(l.includes(f))throw new Error(`[Directive] Schema key "${l}" in module "${s}" contains the reserved separator "${f}". Schema keys cannot contain "${f}".`)}}let g={names:null};function d(){return g.names===null&&(g.names=Object.keys(e)),g.names}let w=a.map(s=>{let c=e[s];return c?T({mod:c,namespace:s,snapshotModulesSet:r}):null}).filter(s=>s!==null);process.env.NODE_ENV!=="production"&&n.tickMs&&n.tickMs>0&&(w.some(c=>c.events&&Object.keys(c.events).some(l=>l.endsWith(`${f}tick`)))||console.warn(`[Directive] tickMs is set to ${n.tickMs}ms but no module defines a "tick" event handler.`));let D=null,h=null;function _(s){for(let[c,l]of Object.entries(s)){if(chunkPK2EH26L_cjs.k.has(c)){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] initialFacts/hydrate contains blocked namespace "${c}". Skipping.`);continue}if(!t.has(c)){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] initialFacts/hydrate contains unknown namespace "${c}". Available modules: ${[...t].join(", ")}`);continue}if(l&&typeof l=="object"&&!chunkKQKNE23L_cjs.c(l))throw new Error(`[Directive] initialFacts/hydrate for namespace "${c}" contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.`);for(let[p,b]of Object.entries(l))chunkPK2EH26L_cjs.k.has(p)||(h.facts[`${c}${f}${p}`]=b);}}h=chunk6WG7FPH7_cjs.y({modules:w,plugins:n.plugins,history:y,trace:i,errorBoundary:k,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{n.initialFacts&&_(n.initialFacts),D&&(_(D),D=null);}});let x=new Map;for(let s of Object.keys(e)){let c=e[s];c&&x.set(s,J(s,c));}let B=U(h.facts,e,d),ee=L(h.derive,e,d),ne=Z(h,e,d),E=null,j=n.tickMs,N={_mode:"namespaced",facts:B,history:h.history,derive:ee,events:ne,constraints:h.constraints,effects:h.effects,resolvers:h.resolvers,async hydrate(s){if(h.isRunning)throw new Error("[Directive] hydrate() must be called before start(). The system is already running.");let c=await s();c&&typeof c=="object"&&(D=c);},initialize(){h.initialize();},start(){if(h.start(),j&&j>0){let s;for(let c of w)if(c?.events&&(s=Object.keys(c.events).find(l=>l.endsWith(`${f}tick`)),s))break;if(s){let c=s;E=setInterval(()=>{h.dispatch({type:c});},j);}}},stop(){E&&(clearInterval(E),E=null),h.stop();},destroy(){this.stop(),h.destroy();},dispatch(s){h.dispatch(s);},read(s){return h.read(v(s))},subscribe(s,c){let l=[];for(let p of s)if(p.endsWith(".*")){let b=p.slice(0,-2),K=x.get(b);K?l.push(...K):process.env.NODE_ENV!=="production"&&console.warn(`[Directive] subscribe wildcard "${p}" \u2014 namespace "${b}" not found.`);}else l.push(v(p));return h.subscribe(l,c)},subscribeModule(s,c){let l=x.get(s);return !l||l.length===0?(process.env.NODE_ENV!=="production"&&console.warn(`[Directive] subscribeModule("${s}") \u2014 namespace not found. Available: ${[...x.keys()].join(", ")}`),()=>{}):h.subscribe(l,c)},watch(s,c,l){return h.watch(v(s),c,l)},when(s,c){return h.when(()=>s(B),c)},getDistributableSnapshot(s){let c={...s,includeDerivations:s?.includeDerivations?.map(v),excludeDerivations:s?.excludeDerivations?.map(v),includeFacts:s?.includeFacts?.map(v)},l=h.getDistributableSnapshot(c);return {...l,data:F(l.data)}},watchDistributableSnapshot(s,c){let l={...s,includeDerivations:s?.includeDerivations?.map(v),excludeDerivations:s?.excludeDerivations?.map(v),includeFacts:s?.includeFacts?.map(v)};return h.watchDistributableSnapshot(l,p=>{c({...p,data:F(p.data)});})},registerModule(s,c){if(t.has(s))throw new Error(`[Directive] Module namespace "${s}" already exists. Cannot register a duplicate namespace.`);if(s.includes(f))throw new Error(`[Directive] Module name "${s}" contains the reserved separator "${f}".`);if(chunkPK2EH26L_cjs.k.has(s))throw new Error(`[Directive] Module name "${s}" is a blocked property.`);for(let b of Object.keys(c.schema.facts))if(b.includes(f))throw new Error(`[Directive] Schema key "${b}" in module "${s}" contains the reserved separator "${f}".`);let l=c,p=T({mod:l,namespace:s,snapshotModulesSet:r});t.add(s),e[s]=l,g.names=null,x.set(s,J(s,l)),h.registerModule(p);}};return X(N,h),Y(N),N}function Q(n){let e=n.history,t=n.trace,o=n.errorBoundary;if(n.zeroConfig){let r=process.env.NODE_ENV!=="production";e=e??r,o={onConstraintError:"skip",onResolverError:"skip",onEffectError:"skip",onDerivationError:"skip",...n.errorBoundary};}return {history:e,trace:t,errorBoundary:o}}function X(n,e){Object.defineProperties(n,{trace:{get(){return e.trace},enumerable:true,configurable:true},isRunning:{get(){return e.isRunning},enumerable:true,configurable:true},isSettled:{get(){return e.isSettled},enumerable:true,configurable:true},isInitialized:{get(){return e.isInitialized},enumerable:true,configurable:true},isReady:{get(){return e.isReady},enumerable:true,configurable:true}}),n.whenReady=e.whenReady.bind(e),n.batch=e.batch.bind(e),n.onSettledChange=e.onSettledChange.bind(e),n.onHistoryChange=e.onHistoryChange.bind(e),n.inspect=e.inspect.bind(e),n.settle=e.settle.bind(e),n.explain=e.explain.bind(e),n.getSnapshot=e.getSnapshot.bind(e),n.restore=e.restore.bind(e);let t=["dispatch","read","subscribe","watch","when","getDistributableSnapshot","watchDistributableSnapshot"];for(let o of t)o in n||(n[o]=e[o].bind(e));}function Y(n){process.env.NODE_ENV!=="production"&&process.env.NODE_ENV!=="test"&&setTimeout(()=>{!n.isRunning&&!n.isInitialized&&console.warn("[Directive] System created but start() was never called. Constraints, resolvers, and effects will not run until you call system.start().");},0);}function fe(n){let e=n.module;if(!e)throw new Error("[Directive] createSystem requires a module. Got: "+typeof e);if(n.tickMs!==void 0&&n.tickMs<=0)throw new Error("[Directive] tickMs must be a positive number");if(n.initialFacts&&!chunkKQKNE23L_cjs.c(n.initialFacts))throw new Error("[Directive] initialFacts contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");process.env.NODE_ENV!=="production"&&(e.crossModuleDeps&&Object.keys(e.crossModuleDeps).length>0&&console.warn("[Directive] Single module mode ignores crossModuleDeps. Use multiple modules if cross-module access is needed: createSystem({ modules: { ... } })"),n.tickMs&&n.tickMs>0&&(e.events&&"tick"in e.events||console.warn(`[Directive] tickMs is set to ${n.tickMs}ms but module has no "tick" event handler.`)),(typeof n.history=="object"?n.history:null)?.snapshotModules&&console.warn("[Directive] history.snapshotModules has no effect in single-module mode. Use history.snapshotEvents on the module definition instead, or switch to createSystem({ modules: { ... } }) for multi-module filtering."));let{history:t,trace:o,errorBoundary:r}=Q(n),a=null,u=null;u=chunk6WG7FPH7_cjs.y({modules:[{id:e.id,schema:e.schema.facts,requirements:e.schema.requirements,init:e.init,derive:e.derive,events:e.events,effects:e.effects,constraints:e.constraints,resolvers:e.resolvers,hooks:e.hooks,history:e.history}],plugins:n.plugins,history:t,trace:o,errorBoundary:r,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{if(n.initialFacts)for(let[d,w]of Object.entries(n.initialFacts))chunkPK2EH26L_cjs.k.has(d)||(u.facts[d]=w);if(a){if(!chunkKQKNE23L_cjs.c(a))process.env.NODE_ENV!=="production"&&console.warn("[Directive] hydrate() data contains potentially dangerous keys. Skipping.");else for(let[d,w]of Object.entries(a))chunkPK2EH26L_cjs.k.has(d)||(u.facts[d]=w);a=null;}}});let y=new Proxy({},{get(d,w){if(typeof w!="symbol"&&!chunkPK2EH26L_cjs.k.has(w))return D=>{u.dispatch({type:w,...D});}},has(d,w){return typeof w=="symbol"||chunkPK2EH26L_cjs.k.has(w)?false:e.events?w in e.events:false},ownKeys(){return e.events?Object.keys(e.events):[]},getOwnPropertyDescriptor(d,w){if(typeof w!="symbol"&&!chunkPK2EH26L_cjs.k.has(w)&&e.events&&w in e.events)return {configurable:true,enumerable:true}},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),i=null,k=n.tickMs,g={_mode:"single",facts:u.facts,history:u.history,derive:u.derive,events:y,constraints:u.constraints,effects:u.effects,resolvers:u.resolvers,async hydrate(d){if(u.isRunning)throw new Error("[Directive] hydrate() must be called before start(). The system is already running.");let w=await d();w&&typeof w=="object"&&(a=w);},initialize(){u.initialize();},start(){u.start(),k&&k>0&&e.events&&"tick"in e.events&&(i=setInterval(()=>{u.dispatch({type:"tick"});},k));},stop(){i&&(clearInterval(i),i=null),u.stop();},destroy(){this.stop(),u.destroy();},registerModule(d){u.registerModule({id:d.id,schema:d.schema.facts,requirements:d.schema.requirements,init:d.init,derive:d.derive,events:d.events,effects:d.effects,constraints:d.constraints,resolvers:d.resolvers,hooks:d.hooks,history:d.history});}};return X(g,u),Y(g),g}exports.a=be;//# sourceMappingURL=chunk-LAH2FMON.cjs.map
|
|
16
|
+
//# sourceMappingURL=chunk-LAH2FMON.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/core/system-proxies.ts","../src/core/system-module-transform.ts","../src/core/system.ts"],"names":["SEPARATOR","createHardenedProxy","config","_","prop","BLOCKED_PROPS","value","moduleFactsProxyCache","namespacedFactsProxyCache","namespacedDeriveProxyCache","moduleDeriveProxyCache","crossModuleFactsProxyCache","moduleEventsProxyCache","createModuleFactsProxy","facts","namespace","namespaceCache","cached","proxy","createNamespacedFactsProxy","modulesMap","getModuleNames","createCrossModuleFactsProxy","selfNamespace","depNamespaces","cacheKey","depNamesSet","allKeys","key","createModuleDeriveProxy","derive","createNamespacedDeriveProxy","createNamespacedEventsProxy","engine","moduleEventsProxy","eventName","payload","toInternalKey","rest","denormalizeFlatKeys","flatData","result","sepIndex","ns","local","createScopedFactsProxy","hasCrossModuleDeps","prefixKey","nonEmpty","rec","prefixSchema","mod","prefixInit","moduleFactsProxy","prefixDerive","fn","factsProxy","deriveProxy","prefixEventHandlers","handler","event","prefixConstraints","constraint","constraintDef","dep","prefixResolvers","resolver","wrapCtx","ctx","resolverDef","req","reqs","prefixEffects","effect","effectDef","prev","prevProxy","prefixHistory","snapshotModulesSet","e","prefixModuleDefinition","options","topologicalSort","namespaces","namespacesSet","visited","visiting","path","visit","cycleStart","cycle","depNamespace","collectNamespaceKeys","keys","createSystem","createSingleModuleSystem","namedOptions","mods","createNamespacedSystem","moduleNamespaces","historyConfig","name","orderedNamespaces","initOrder","explicitOrder","missingModules","history","trace","errorBoundary","applyZeroConfigDefaults","moduleNamesCache","flatModules","m","k","hydratedFacts","applyNamespacedFacts","namespacedFacts","isPrototypeSafe","createEngine","namespaceKeysMap","namespacedFactsProxy","namespacedDeriveProxy","namespacedEventsProxy","tickInterval","tickMs","system","loader","tickEventKey","derivationId","ids","listener","internalIds","id","callback","predicate","internalOptions","snapshot","moduleDef","flat","bindEnginePassthroughs","warnIfNotStarted","isDev","overridableMethods","method","eventsProxy"],"mappings":"uKAkBO,IAAMA,CAAAA,CAAY,KAoCzB,SAASC,CAAAA,CAAsCC,EAAgC,CAC7E,OAAO,IAAI,KAAA,CAAM,GAAS,CACxB,GAAA,CAAIC,EAAGC,CAAAA,CAAuB,CAC5B,GAAI,OAAOA,CAAAA,EAAS,QAAA,EAGhB,CAAAC,mBAAAA,CAAc,GAAA,CAAID,CAAI,CAAA,CAI1B,OAAOF,EAAO,GAAA,CAAIE,CAAI,CACxB,CAAA,CACA,GAAA,CAAID,CAAAA,CAAGC,CAAAA,CAAuBE,CAAAA,CAAgB,CAI5C,OAHI,OAAOF,CAAAA,EAAS,UAGhBC,mBAAAA,CAAc,GAAA,CAAID,CAAI,CAAA,CACjB,KAAA,CAGFF,CAAAA,CAAO,GAAA,CAAMA,CAAAA,CAAO,GAAA,CAAIE,EAAME,CAAK,CAAA,CAAI,KAChD,CAAA,CACA,GAAA,CAAIH,EAAGC,CAAAA,CAAuB,CAI5B,OAHI,OAAOA,CAAAA,EAAS,UAGhBC,mBAAAA,CAAc,GAAA,CAAID,CAAI,CAAA,CACjB,K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A,EAAU,SAAA,CACrB,KAAA,CAAOA,CAAAA,CAAU,KAAA,CACjB,OAAA,CAASA,CAAAA,CAAU,OACrB,CAAC,EACH,CAEF,CAAA,CAEA,OAAAE,CAAAA,CAAuBd,CAAAA,CAAQ5F,CAAM,CAAA,CACrC2G,CAAAA,CAAiBf,CAAM,CAAA,CAEhBA,CACT","file":"chunk-LAH2FMON.cjs","sourcesContent":["/**\n * Proxy factory functions for system-level namespace translation.\n *\n * Extracted from system.ts to reduce file size. All functions are pure\n * proxy factories — they create proxies that translate between unprefixed\n * module keys and prefixed internal keys (e.g., `token` ↔ `auth::token`).\n *\n * @internal\n */\n\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type { ModulesMap } from \"./types.js\";\n\n/**\n * Namespace separator for internal key prefixing (e.g., \"auth::token\").\n *\n * @internal\n */\nexport const SEPARATOR = \"::\";\n\n// ============================================================================\n// Hardened Proxy Factory\n// ============================================================================\n\n/**\n * Configuration for creating a hardened proxy with consistent security traps.\n *\n * @internal\n */\ninterface HardenedProxyConfig {\n /** Return the value for a string property access */\n get: (prop: string) => unknown;\n /** Handle property assignment. Omit for read-only proxies (returns false). */\n set?: (prop: string, value: unknown) => boolean;\n /** Check if a string property exists */\n has?: (prop: string) => boolean;\n /** Return all own keys for enumeration */\n ownKeys?: () => string[];\n /** Handle property deletion. Omit to reject deletions. */\n delete?: (prop: string) => boolean;\n}\n\n/**\n * Create a proxy with consistent security hardening.\n *\n * Every proxy created by this factory includes:\n * - Symbol access returns `undefined`\n * - BLOCKED_PROPS (`__proto__`, `constructor`, `prototype`) rejected\n * - `defineProperty` returns `false`\n * - `getPrototypeOf` returns `null`\n * - `setPrototypeOf` returns `false`\n *\n * @internal\n */\nfunction createHardenedProxy<T extends object>(config: HardenedProxyConfig): T {\n return new Proxy({} as T, {\n get(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n\n return config.get(prop);\n },\n set(_, prop: string | symbol, value: unknown) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.set ? config.set(prop, value) : false;\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.has ? config.has(prop) : false;\n },\n deleteProperty(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return config.delete ? config.delete(prop) : false;\n },\n ownKeys() {\n return config.ownKeys ? config.ownKeys() : [];\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (config.has && typeof prop === \"string\" && config.has(prop)) {\n return { configurable: true, enumerable: true };\n }\n\n return undefined;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n });\n}\n\n// ============================================================================\n// Proxy Cache (Performance)\n// ============================================================================\n\n/**\n * WeakMap to cache module facts proxies. Keyed by the facts store object.\n * Inner map is keyed by namespace string.\n */\nconst moduleFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced facts proxies.\n */\nconst namespacedFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Record<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache namespaced derive proxies.\n */\nconst namespacedDeriveProxyCache = new WeakMap<\n Record<string, unknown>,\n Record<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache module derive proxies.\n */\nconst moduleDeriveProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, unknown>>\n>();\n\n/**\n * WeakMap to cache cross-module facts proxies.\n * Keyed by facts store, then by \"selfNamespace|depKeys\" string.\n */\nconst crossModuleFactsProxyCache = new WeakMap<\n Record<string, unknown>,\n Map<string, Record<string, Record<string, unknown>>>\n>();\n\n/**\n * WeakMap to cache module events proxies.\n */\nconst moduleEventsProxyCache = new WeakMap<\n // biome-ignore lint/suspicious/noExplicitAny: Engine type for cache key\n any,\n Map<string, Record<string, (payload?: Record<string, unknown>) => void>>\n>();\n\n// ============================================================================\n// Module Facts Proxy\n// ============================================================================\n\n/**\n * Create a proxy for a single module's facts (used in init, event handlers).\n * Translates unprefixed keys to prefixed: `token` → `auth::token`\n *\n * Proxies are cached per facts store and namespace for performance.\n *\n * @param facts - The flat facts store\n * @param namespace - The module namespace for key prefixing\n * @returns A proxy that translates property access to prefixed keys\n *\n * @internal\n */\nexport function createModuleFactsProxy(\n facts: Record<string, unknown>,\n namespace: string,\n): Record<string, unknown> {\n // Check cache first\n let namespaceCache = moduleFactsProxyCache.get(facts);\n if (namespaceCache) {\n const cached = namespaceCache.get(namespace);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n moduleFactsProxyCache.set(facts, namespaceCache);\n }\n\n const proxy = createHardenedProxy<Record<string, unknown>>({\n get: (prop) => {\n // Reserved properties bypass namespace prefixing (used by engine internals)\n if (prop === \"$store\" || prop === \"$snapshot\") {\n return facts[prop];\n }\n\n return facts[`${namespace}${SEPARATOR}${prop}`];\n },\n set: (prop, value) => {\n facts[`${namespace}${SEPARATOR}${prop}`] = value;\n\n return true;\n },\n has: (prop) => `${namespace}${SEPARATOR}${prop}` in facts,\n delete: (prop) => {\n delete facts[`${namespace}${SEPARATOR}${prop}`];\n\n return true;\n },\n });\n\n namespaceCache.set(namespace, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Facts Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced facts access.\n * `facts.auth.token` → reads `auth::token` from flat store\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n *\n * @param facts - The flat facts store\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names (supports dynamic registration)\n * @returns A proxy that delegates to per-module facts proxies\n *\n * @internal\n */\nexport function createNamespacedFactsProxy(\n facts: Record<string, unknown>,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n // Check cache first\n const cached = namespacedFactsProxyCache.get(facts);\n if (cached) {\n return cached;\n }\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n return createModuleFactsProxy(facts, namespace);\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n\n namespacedFactsProxyCache.set(facts, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Cross-Module Facts Proxy\n// ============================================================================\n\n/**\n * Create a proxy for cross-module facts access with \"self\" for own module.\n * `facts.self.users` → reads own module's facts\n * `facts.auth.token` → reads dependency module's facts\n *\n * Used when a module has crossModuleDeps defined.\n *\n * @param facts - The flat facts store\n * @param selfNamespace - The namespace of the module that owns this proxy\n * @param depNamespaces - Array of declared dependency namespaces\n * @returns A proxy that provides `self` and declared dependency access\n *\n * @internal\n */\nexport function createCrossModuleFactsProxy(\n facts: Record<string, unknown>,\n selfNamespace: string,\n depNamespaces: string[],\n): Record<string, Record<string, unknown>> {\n // depNamespaces comes from Object.keys() which has stable order per module,\n // so join is sufficient (no need to sort)\n const cacheKey = `${selfNamespace}|${depNamespaces.join(\",\")}`;\n\n // Check cache first\n let namespaceCache = crossModuleFactsProxyCache.get(facts);\n if (namespaceCache) {\n const cached = namespaceCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n crossModuleFactsProxyCache.set(facts, namespaceCache);\n }\n\n const depNamesSet = new Set(depNamespaces);\n const allKeys = [\"self\", ...depNamespaces];\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (key) => {\n // \"self\" maps to own module's namespace\n if (key === \"self\") {\n return createModuleFactsProxy(facts, selfNamespace);\n }\n\n // Check if it's a declared dependency\n if (depNamesSet.has(key)) {\n return createModuleFactsProxy(facts, key);\n }\n\n // Dev-mode warning for undeclared cross-module access\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] Module \"${selfNamespace}\" accessed undeclared cross-module property \"${key}\". ` +\n `Add it to crossModuleDeps or use \"facts.self.${key}\" for own module facts.`,\n );\n }\n\n return undefined;\n },\n has: (key) => key === \"self\" || depNamesSet.has(key),\n ownKeys: () => allKeys,\n });\n\n namespaceCache.set(cacheKey, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Module Derive Proxy\n// ============================================================================\n\n/**\n * Create a proxy for a single module's derivations.\n * Translates unprefixed keys to prefixed: `status` → `auth::status`\n *\n * Proxies are cached per derive store and namespace for performance.\n *\n * @param derive - The flat derivations store\n * @param namespace - The module namespace for key prefixing\n * @returns A read-only proxy that translates property access to prefixed keys\n *\n * @internal\n */\nexport function createModuleDeriveProxy(\n derive: Record<string, unknown>,\n namespace: string,\n): Record<string, unknown> {\n // Check cache first\n let namespaceCache = moduleDeriveProxyCache.get(derive);\n if (namespaceCache) {\n const cached = namespaceCache.get(namespace);\n if (cached) {\n return cached;\n }\n } else {\n namespaceCache = new Map();\n moduleDeriveProxyCache.set(derive, namespaceCache);\n }\n\n const proxy = createHardenedProxy<Record<string, unknown>>({\n get: (prop) => derive[`${namespace}${SEPARATOR}${prop}`],\n has: (prop) => `${namespace}${SEPARATOR}${prop}` in derive,\n });\n\n namespaceCache.set(namespace, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Derive Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced derivations access.\n * `derive.auth.status` → reads `auth::status` from flat derive\n *\n * Uses Set for O(1) namespace lookups and caches the outer proxy.\n *\n * @param derive - The flat derivations store\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names\n * @returns A read-only proxy that delegates to per-module derive proxies\n *\n * @internal\n */\nexport function createNamespacedDeriveProxy(\n derive: Record<string, unknown>,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, unknown>> {\n // Check cache first\n const cached = namespacedDeriveProxyCache.get(derive);\n if (cached) {\n return cached;\n }\n\n const proxy = createHardenedProxy<Record<string, Record<string, unknown>>>({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n return createModuleDeriveProxy(derive, namespace);\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n\n namespacedDeriveProxyCache.set(derive, proxy);\n\n return proxy;\n}\n\n// ============================================================================\n// Namespaced Events Proxy\n// ============================================================================\n\n/**\n * Create a nested proxy for namespaced events access.\n * `events.auth.login({ token })` → dispatches `{ type: \"auth::login\", token }`\n *\n * Uses Set for O(1) namespace lookups and caches proxies for performance.\n *\n * @param engine - The engine instance (used for dispatch)\n * @param modulesMap - Map of module namespaces to module definitions\n * @param getModuleNames - Function returning current module names\n * @returns A read-only proxy that returns event dispatcher functions per namespace\n *\n * @internal\n */\nexport function createNamespacedEventsProxy(\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n engine: any,\n modulesMap: ModulesMap,\n getModuleNames: () => string[],\n): Record<string, Record<string, (payload?: Record<string, unknown>) => void>> {\n // Get or create the namespace cache for this engine\n let namespaceCache = moduleEventsProxyCache.get(engine);\n if (!namespaceCache) {\n namespaceCache = new Map();\n moduleEventsProxyCache.set(engine, namespaceCache);\n }\n\n return createHardenedProxy<\n Record<string, Record<string, (payload?: Record<string, unknown>) => void>>\n >({\n get: (namespace) => {\n if (!Object.hasOwn(modulesMap, namespace)) {\n return undefined;\n }\n\n // Check cache for this namespace's event proxy\n const cached = namespaceCache!.get(namespace);\n if (cached) {\n return cached;\n }\n\n // Create and cache the module events proxy\n const moduleEventsProxy = createHardenedProxy<\n Record<string, (payload?: Record<string, unknown>) => void>\n >({\n get: (eventName) => {\n return (payload?: Record<string, unknown>) => {\n engine.dispatch({\n type: `${namespace}${SEPARATOR}${eventName}`,\n ...payload,\n });\n };\n },\n });\n\n namespaceCache!.set(namespace, moduleEventsProxy);\n\n return moduleEventsProxy;\n },\n has: (namespace) => Object.hasOwn(modulesMap, namespace),\n ownKeys: () => getModuleNames(),\n });\n}\n\n// ============================================================================\n// Key Conversion Helpers\n// ============================================================================\n\n/**\n * Convert a namespaced key (e.g., \"auth.status\") to internal prefixed format (\"auth::status\").\n * If the key is already in prefixed format, returns it unchanged.\n *\n * @param key - The key to convert (dot-separated or already prefixed)\n * @returns The internal prefixed key\n *\n * @example\n * toInternalKey(\"auth.status\") // → \"auth::status\"\n * toInternalKey(\"auth::status\") // → \"auth::status\" (unchanged)\n * toInternalKey(\"status\") // → \"status\" (unchanged)\n *\n * @internal\n */\nexport function toInternalKey(key: string): string {\n // If key contains a dot, convert to separator format\n if (key.includes(\".\")) {\n const [namespace, ...rest] = key.split(\".\");\n\n return `${namespace}${SEPARATOR}${rest.join(SEPARATOR)}`;\n }\n // Already in internal format or simple key\n\n return key;\n}\n\n// ============================================================================\n// Snapshot Helpers\n// ============================================================================\n\n/**\n * Convert flat internal keys (e.g., `\"auth::token\"`) to nested namespaced\n * format (e.g., `{ auth: { token: ... } }`).\n *\n * Keys without a separator are grouped under `_root`.\n *\n * @param flatData - Object with internal prefixed keys\n * @returns Nested object grouped by namespace\n *\n * @internal\n */\nexport function denormalizeFlatKeys(\n flatData: Record<string, unknown>,\n): Record<string, Record<string, unknown>> {\n const result: Record<string, Record<string, unknown>> = {};\n\n for (const [key, value] of Object.entries(flatData)) {\n const sepIndex = key.indexOf(SEPARATOR);\n if (sepIndex > 0) {\n const ns = key.slice(0, sepIndex);\n const local = key.slice(sepIndex + SEPARATOR.length);\n if (!result[ns]) {\n result[ns] = {};\n }\n result[ns][local] = value;\n } else {\n if (!result._root) {\n result._root = {};\n }\n result._root[key] = value;\n }\n }\n\n return result;\n}\n","/**\n * Module transformation for namespaced systems.\n *\n * Converts a module's unprefixed keys to prefixed internal format\n * (e.g., `token` → `auth::token`). Used by both the initial system\n * setup loop and `registerModule()`.\n *\n * @internal\n */\n\nimport {\n SEPARATOR,\n createCrossModuleFactsProxy,\n createModuleDeriveProxy,\n createModuleFactsProxy,\n} from \"./system-proxies.js\";\nimport type { ModuleDef, ModuleSchema } from \"./types.js\";\n\n/**\n * The flat engine module format produced by prefixModuleDefinition.\n * Ready to be passed to createEngine or engine.registerModule.\n *\n * @internal\n */\nexport interface FlatModuleDefinition {\n id: string;\n schema: Record<string, unknown>;\n requirements: Record<string, unknown>;\n init: ((facts: Record<string, unknown>) => void) | undefined;\n derive:\n | Record<string, (facts: unknown, derive: unknown) => unknown>\n | undefined;\n events: Record<string, (facts: unknown, event: unknown) => void> | undefined;\n effects: Record<string, unknown> | undefined;\n constraints: Record<string, unknown> | undefined;\n resolvers: Record<string, unknown> | undefined;\n hooks: ModuleDef<ModuleSchema>[\"hooks\"];\n history: { snapshotEvents?: string[] };\n}\n\n/**\n * Options for prefixModuleDefinition.\n *\n * @internal\n */\nexport interface PrefixModuleOptions {\n /** The module to transform */\n mod: ModuleDef<ModuleSchema>;\n /** The namespace to prefix keys with */\n namespace: string;\n /** Set of modules to snapshot (null = all). Used for history filtering. */\n snapshotModulesSet: Set<string> | null;\n}\n\n/**\n * Create a facts proxy appropriate for the module's cross-module configuration.\n * Returns a cross-module proxy when deps are declared, otherwise a module proxy.\n *\n * @internal\n */\nfunction createScopedFactsProxy(\n facts: Record<string, unknown>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> {\n return hasCrossModuleDeps\n ? createCrossModuleFactsProxy(facts, namespace, depNamespaces)\n : createModuleFactsProxy(facts, namespace);\n}\n\n/** Prefix a key with the namespace separator */\nfunction prefixKey(namespace: string, key: string): string {\n return `${namespace}${SEPARATOR}${key}`;\n}\n\n/** Return a non-empty record or undefined */\nfunction nonEmpty<T extends Record<string, unknown>>(rec: T): T | undefined {\n return Object.keys(rec).length > 0 ? rec : undefined;\n}\n\n/** Prefix schema fact keys */\nfunction prefixSchema(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(mod.schema.facts)) {\n result[prefixKey(namespace, key)] = value;\n }\n\n return result;\n}\n\n/** Create a prefixed init function */\nfunction prefixInit(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): ((facts: Record<string, unknown>) => void) | undefined {\n if (!mod.init) {\n return undefined;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Facts proxy type coercion\n return (facts: any) => {\n const moduleFactsProxy = createModuleFactsProxy(facts, namespace);\n // biome-ignore lint/suspicious/noExplicitAny: Module init type coercion\n (mod.init as any)(moduleFactsProxy);\n };\n}\n\n/** Prefix derivation keys and wrap derivation functions with scoped proxies */\nfunction prefixDerive(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, (facts: unknown, derive: unknown) => unknown> | undefined {\n if (!mod.derive) {\n return undefined;\n }\n\n const result: Record<string, (facts: unknown, derive: unknown) => unknown> =\n {};\n for (const [key, fn] of Object.entries(mod.derive)) {\n result[prefixKey(namespace, key)] = (facts: unknown, derive: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n const deriveProxy = createModuleDeriveProxy(\n derive as Record<string, unknown>,\n namespace,\n );\n // biome-ignore lint/suspicious/noExplicitAny: Derive function type coercion\n return (fn as any)(factsProxy, deriveProxy);\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix event handler keys and wrap handlers with module-scoped proxies */\nfunction prefixEventHandlers(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n): Record<string, (facts: unknown, event: unknown) => void> | undefined {\n if (!mod.events) {\n return undefined;\n }\n\n const result: Record<string, (facts: unknown, event: unknown) => void> = {};\n for (const [key, handler] of Object.entries(mod.events)) {\n result[prefixKey(namespace, key)] = (facts: unknown, event: unknown) => {\n const moduleFactsProxy = createModuleFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n );\n // biome-ignore lint/suspicious/noExplicitAny: Event handler type coercion\n (handler as any)(moduleFactsProxy, event);\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix constraint keys and wrap when/require with scoped proxies */\nfunction prefixConstraints(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.constraints) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, constraint] of Object.entries(mod.constraints)) {\n const constraintDef = constraint as {\n when: (facts: unknown) => boolean | Promise<boolean>;\n require: unknown | ((facts: unknown) => unknown);\n priority?: number;\n async?: boolean;\n timeout?: number;\n deps?: string[];\n after?: string[];\n };\n\n result[prefixKey(namespace, key)] = {\n ...constraintDef,\n deps: constraintDef.deps?.map((dep) => prefixKey(namespace, dep)),\n after: constraintDef.after?.map((dep) =>\n dep.includes(SEPARATOR) ? dep : prefixKey(namespace, dep),\n ),\n when: (facts: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n\n return constraintDef.when(factsProxy);\n },\n require:\n typeof constraintDef.require === \"function\"\n ? (facts: unknown) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n\n return (constraintDef.require as (facts: unknown) => unknown)(\n factsProxy,\n );\n }\n : constraintDef.require,\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix resolver keys and wrap resolve/resolveBatch/resolveBatchWithResults with scoped proxies */\nfunction prefixResolvers(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.resolvers) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, resolver] of Object.entries(mod.resolvers)) {\n const resolverDef = resolver as {\n requirement: string;\n resolve?: (\n req: unknown,\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<void>;\n resolveBatch?: (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<void>;\n resolveBatchWithResults?: (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => Promise<unknown>;\n key?: (req: unknown) => string;\n retry?: unknown;\n timeout?: number;\n };\n\n /** Wrap resolver ctx.facts with the module-scoped proxy */\n function wrapCtx(ctx: { facts: unknown; signal: AbortSignal }): {\n facts: unknown;\n signal: AbortSignal;\n } {\n return {\n facts: createScopedFactsProxy(\n ctx.facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n signal: ctx.signal,\n };\n }\n\n result[prefixKey(namespace, key)] = {\n ...resolverDef,\n ...(resolverDef.resolve && {\n resolve: async (\n req: unknown,\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n await resolverDef.resolve!(req, wrapCtx(ctx));\n },\n }),\n ...(resolverDef.resolveBatch && {\n resolveBatch: async (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n await resolverDef.resolveBatch!(reqs, wrapCtx(ctx));\n },\n }),\n ...(resolverDef.resolveBatchWithResults && {\n resolveBatchWithResults: async (\n reqs: unknown[],\n ctx: { facts: unknown; signal: AbortSignal },\n ) => {\n return resolverDef.resolveBatchWithResults!(reqs, wrapCtx(ctx));\n },\n }),\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Prefix effect keys and wrap run functions with scoped proxies */\nfunction prefixEffects(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n hasCrossModuleDeps: boolean,\n depNamespaces: string[],\n): Record<string, unknown> | undefined {\n if (!mod.effects) {\n return undefined;\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, effect] of Object.entries(mod.effects)) {\n const effectDef = effect as {\n // biome-ignore lint/suspicious/noExplicitAny: Effect run function type\n run: (facts: any, prev: any) => void | Promise<void>;\n deps?: string[];\n };\n\n result[prefixKey(namespace, key)] = {\n ...effectDef,\n // biome-ignore lint/suspicious/noExplicitAny: Effect run function wrapper\n run: (facts: any, prev: any) => {\n const factsProxy = createScopedFactsProxy(\n facts as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n );\n const prevProxy = prev\n ? createScopedFactsProxy(\n prev as Record<string, unknown>,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n )\n : undefined;\n\n return effectDef.run(factsProxy, prevProxy);\n },\n deps: effectDef.deps?.map((dep) => prefixKey(namespace, dep)),\n };\n }\n\n return nonEmpty(result);\n}\n\n/** Compute history config with prefixed snapshot events */\nfunction prefixHistory(\n mod: ModuleDef<ModuleSchema>,\n namespace: string,\n snapshotModulesSet: Set<string> | null,\n): { snapshotEvents?: string[] } {\n return {\n snapshotEvents:\n snapshotModulesSet && !snapshotModulesSet.has(namespace)\n ? [] // Module excluded from snapshots\n : mod.history?.snapshotEvents?.map((e: string) =>\n prefixKey(namespace, e),\n ),\n };\n}\n\n/**\n * Transform a module definition by prefixing all keys with a namespace.\n *\n * Handles: facts, derivations, events schema, init, derive, events handlers,\n * constraints (with deps/after), resolvers, and effects.\n *\n * @returns A flat module definition ready for the engine\n *\n * @internal\n */\nexport function prefixModuleDefinition(\n options: PrefixModuleOptions,\n): FlatModuleDefinition {\n const { mod, namespace, snapshotModulesSet } = options;\n\n // Compute cross-module deps info once (used by derive, constraints, effects)\n const hasCrossModuleDeps = !!(\n mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0\n );\n const depNamespaces = hasCrossModuleDeps\n ? Object.keys(mod.crossModuleDeps!)\n : [];\n\n return {\n id: mod.id,\n schema: prefixSchema(mod, namespace),\n requirements: mod.schema.requirements ?? {},\n init: prefixInit(mod, namespace),\n derive: prefixDerive(mod, namespace, hasCrossModuleDeps, depNamespaces),\n events: prefixEventHandlers(mod, namespace),\n effects: prefixEffects(mod, namespace, hasCrossModuleDeps, depNamespaces),\n constraints: prefixConstraints(\n mod,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n resolvers: prefixResolvers(\n mod,\n namespace,\n hasCrossModuleDeps,\n depNamespaces,\n ),\n hooks: mod.hooks,\n history: prefixHistory(mod, namespace, snapshotModulesSet),\n };\n}\n","/**\n * System - The top-level API for creating a Directive runtime\n *\n * A system combines modules with plugins and configuration.\n * Modules are passed as an object with namespaced access:\n *\n * @example\n * ```typescript\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n *\n * system.facts.auth.token // Namespaced facts\n * system.derive.data.userCount // Namespaced derivations\n * system.events.auth.login() // Namespaced events\n * ```\n */\n\nimport { isPrototypeSafe } from \"../utils/utils.js\";\nimport { createEngine } from \"./engine.js\";\nimport { prefixModuleDefinition } from \"./system-module-transform.js\";\nimport {\n SEPARATOR,\n createNamespacedDeriveProxy,\n createNamespacedEventsProxy,\n createNamespacedFactsProxy,\n denormalizeFlatKeys,\n toInternalKey,\n} from \"./system-proxies.js\";\nimport { BLOCKED_PROPS } from \"./tracking.js\";\nimport type {\n CreateSystemOptionsNamed,\n CreateSystemOptionsSingle,\n ErrorBoundaryConfig,\n HistoryOption,\n ModuleDef,\n ModuleSchema,\n ModulesMap,\n NamespacedSystem,\n SingleModuleSystem,\n TraceOption,\n} from \"./types.js\";\n\n// ============================================================================\n// Topological Sort for Module Dependencies\n// ============================================================================\n\n/**\n * Perform topological sort on modules based on crossModuleDeps.\n * Returns module namespaces in dependency order (dependencies first).\n *\n * @throws Error if circular dependency detected\n */\nfunction topologicalSort<Modules extends ModulesMap>(\n modulesMap: Modules,\n): Array<keyof Modules & string> {\n const namespaces = Object.keys(modulesMap) as Array<keyof Modules & string>;\n const namespacesSet = new Set<string>(namespaces);\n const visited = new Set<string>();\n const visiting = new Set<string>(); // For cycle detection\n const result: Array<keyof Modules & string> = [];\n const path: string[] = []; // Reuse array to avoid O(n²) memory\n\n function visit(namespace: string): void {\n if (visited.has(namespace)) return;\n\n // Cycle detection\n if (visiting.has(namespace)) {\n const cycleStart = path.indexOf(namespace);\n const cycle = [...path.slice(cycleStart), namespace].join(\" → \");\n throw new Error(\n `[Directive] Circular dependency detected: ${cycle}. ` +\n \"Modules cannot have circular crossModuleDeps. \" +\n \"Break the cycle by removing one of the cross-module references.\",\n );\n }\n\n visiting.add(namespace);\n path.push(namespace);\n\n // Visit dependencies first\n const mod = modulesMap[namespace];\n if (mod?.crossModuleDeps) {\n for (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n if (namespacesSet.has(depNamespace)) {\n visit(depNamespace);\n }\n }\n }\n\n path.pop();\n visiting.delete(namespace);\n visited.add(namespace);\n result.push(namespace as keyof Modules & string);\n }\n\n for (const namespace of namespaces) {\n visit(namespace);\n }\n\n return result;\n}\n\n/**\n * Build the list of internal prefixed keys (facts + derivations) for a module namespace.\n * Used by subscribe/subscribeModule to map namespaces to their engine keys.\n */\nfunction collectNamespaceKeys(\n namespace: string,\n mod: ModuleDef<ModuleSchema>,\n): string[] {\n const keys: string[] = [];\n for (const key of Object.keys(mod.schema.facts)) {\n keys.push(`${namespace}${SEPARATOR}${key}`);\n }\n if (mod.schema.derivations) {\n for (const key of Object.keys(mod.schema.derivations)) {\n keys.push(`${namespace}${SEPARATOR}${key}`);\n }\n }\n\n return keys;\n}\n\n// ============================================================================\n// createSystem\n// ============================================================================\n\n/**\n * Create a Directive system.\n *\n * Supports two modes:\n * - **Single module**: Use `module` prop for direct access without namespace\n * - **Multiple modules**: Use `modules` prop for namespaced access\n *\n * @remarks\n * The system is the top-level runtime object. It owns the reconciliation loop,\n * manages plugins, and exposes reactive accessors for facts, derivations, and events.\n * Call `system.start()` to begin the lifecycle (init → ready → running → settled).\n *\n * @param options - System configuration with either `module` (single) or `modules` (namespaced)\n * @returns A fully-typed {@link System} instance with reactive accessors\n *\n * @example Single module (direct access)\n * ```ts\n * const system = createSystem({ module: counterModule });\n * system.facts.count // Direct access\n * system.events.increment() // Direct events\n * ```\n *\n * @example Multiple modules (namespaced access)\n * ```ts\n * const system = createSystem({\n * modules: { auth: authModule, data: dataModule },\n * });\n * system.facts.auth.token // Namespaced access\n * system.events.auth.login() // Namespaced events\n * ```\n *\n * @public\n */\nexport function createSystem<S extends ModuleSchema>(\n options: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S>;\nexport function createSystem<const Modules extends ModulesMap>(\n options: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules>;\n/** @internal Implementation overload — see public overloads above. */\nexport function createSystem<\n S extends ModuleSchema,\n Modules extends ModulesMap,\n>(\n options: CreateSystemOptionsSingle<S> | CreateSystemOptionsNamed<Modules>,\n): SingleModuleSystem<S> | NamespacedSystem<Modules> {\n // Single module mode (module prop)\n if (\"module\" in options) {\n if (!options.module) {\n throw new Error(\n \"[Directive] createSystem requires a module. Got: \" +\n typeof options.module,\n );\n }\n return createSingleModuleSystem(\n options as CreateSystemOptionsSingle<S>,\n ) as SingleModuleSystem<S>;\n }\n\n // Namespaced mode (modules prop)\n const namedOptions = options as CreateSystemOptionsNamed<Modules>;\n\n // Validate not an array\n if (Array.isArray(namedOptions.modules)) {\n throw new Error(\n \"[Directive] createSystem expects modules as an object, not an array.\\n\\n\" +\n \"Instead of:\\n\" +\n \" createSystem({ modules: [authModule, dataModule] })\\n\\n\" +\n \"Use:\\n\" +\n \" createSystem({ modules: { auth: authModule, data: dataModule } })\\n\\n\" +\n \"Or for a single module:\\n\" +\n \" createSystem({ module: counterModule })\",\n );\n }\n\n // Detect single ModuleDef accidentally passed to `modules:` instead of `module:`\n const mods = namedOptions.modules as Record<string, unknown>;\n if (mods && typeof mods === \"object\" && \"id\" in mods && \"schema\" in mods) {\n throw new Error(\n \"[Directive] A single module was passed to `modules:`. \" +\n \"For a single module, use `module:` instead:\\n\\n\" +\n \" createSystem({ module: myModule })\\n\\n\" +\n \"For multiple modules, wrap in an object:\\n\" +\n \" createSystem({ modules: { myName: myModule } })\",\n );\n }\n\n return createNamespacedSystem(namedOptions) as NamespacedSystem<Modules>;\n}\n\n// ============================================================================\n// Internal Implementation\n// ============================================================================\n\nfunction createNamespacedSystem<Modules extends ModulesMap>(\n options: CreateSystemOptionsNamed<Modules>,\n): NamespacedSystem<Modules> {\n const modulesMap = options.modules;\n const moduleNamespaces = new Set(Object.keys(modulesMap));\n\n // Build snapshot module filter set (null = all modules snapshot)\n const historyConfig =\n typeof options.history === \"object\" ? options.history : null;\n const snapshotModulesSet = historyConfig?.snapshotModules\n ? new Set(historyConfig.snapshotModules)\n : null;\n\n // Validate tickMs if provided\n if (options.tickMs !== undefined && options.tickMs <= 0) {\n throw new Error(\"[Directive] tickMs must be a positive number\");\n }\n\n // Dev-mode: Validate crossModuleDeps reference existing modules\n if (process.env.NODE_ENV !== \"production\") {\n for (const [namespace, mod] of Object.entries(modulesMap)) {\n if (mod.crossModuleDeps) {\n for (const depNamespace of Object.keys(mod.crossModuleDeps)) {\n if (depNamespace === namespace) {\n console.warn(\n `[Directive] Module \"${namespace}\" references itself in crossModuleDeps. ` +\n `Use \"facts.self\" to access own module's facts instead.`,\n );\n } else if (!moduleNamespaces.has(depNamespace)) {\n console.warn(\n `[Directive] Module \"${namespace}\" declares crossModuleDeps.${depNamespace}, ` +\n `but no module with namespace \"${depNamespace}\" exists in the system. ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n }\n }\n }\n }\n\n // Dev-mode: Validate snapshotModules references existing modules\n if (process.env.NODE_ENV !== \"production\" && historyConfig?.snapshotModules) {\n for (const name of historyConfig.snapshotModules) {\n if (!moduleNamespaces.has(name)) {\n console.warn(\n `[Directive] history.snapshotModules entry \"${name}\" doesn't match any module. ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n }\n }\n\n // Determine module initialization order\n let orderedNamespaces: Array<keyof Modules & string>;\n const initOrder = options.initOrder ?? \"auto\";\n\n if (Array.isArray(initOrder)) {\n // Explicit order provided - validate it includes all modules\n const explicitOrder = initOrder as Array<keyof Modules & string>;\n const missingModules = Object.keys(modulesMap).filter(\n (ns) => !explicitOrder.includes(ns as keyof Modules & string),\n );\n if (missingModules.length > 0) {\n throw new Error(\n `[Directive] initOrder is missing modules: ${missingModules.join(\", \")}. ` +\n \"All modules must be included in the explicit order.\",\n );\n }\n orderedNamespaces = explicitOrder;\n } else if (initOrder === \"declaration\") {\n // Use object key order (current behavior)\n orderedNamespaces = Object.keys(modulesMap) as Array<\n keyof Modules & string\n >;\n } else {\n // \"auto\" - use topological sort based on crossModuleDeps\n orderedNamespaces = topologicalSort(modulesMap);\n }\n\n // Apply zero-config defaults if enabled\n const { history, trace, errorBoundary } = applyZeroConfigDefaults(options);\n\n // Validate module names and schema keys don't contain the separator\n for (const namespace of Object.keys(modulesMap)) {\n if (namespace.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n `Module names cannot contain \"${SEPARATOR}\".`,\n );\n }\n const mod = modulesMap[namespace];\n if (mod) {\n for (const key of Object.keys(mod.schema.facts)) {\n if (key.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\". ` +\n `Schema keys cannot contain \"${SEPARATOR}\".`,\n );\n }\n }\n }\n }\n\n // Cached module names array, shared by all namespaced proxies.\n // Set to null on registerModule to lazily recompute.\n const moduleNamesCache: { names: string[] | null } = { names: null };\n function getModuleNames(): string[] {\n if (moduleNamesCache.names === null) {\n moduleNamesCache.names = Object.keys(modulesMap);\n }\n\n return moduleNamesCache.names;\n }\n\n // Transform modules to flat format with prefixed keys\n // auth.token → auth::token internally\n // Process in dependency order (determined above)\n const flatModules = orderedNamespaces\n .map((namespace) => {\n const mod = modulesMap[namespace];\n if (!mod) return null; // TypeScript guard - should never happen\n\n return prefixModuleDefinition({\n mod,\n namespace,\n snapshotModulesSet,\n });\n })\n .filter((m): m is NonNullable<typeof m> => m !== null);\n\n // Dev-mode warning: tickMs set without tick event handler\n if (\n process.env.NODE_ENV !== \"production\" &&\n options.tickMs &&\n options.tickMs > 0\n ) {\n const hasTickHandler = flatModules.some(\n (m) =>\n m.events &&\n Object.keys(m.events).some((k) => k.endsWith(`${SEPARATOR}tick`)),\n );\n if (!hasTickHandler) {\n console.warn(\n `[Directive] tickMs is set to ${options.tickMs}ms but no module defines a \"tick\" event handler.`,\n );\n }\n }\n\n // Store for hydrated facts (set by hydrate(), applied during init)\n let hydratedFacts: Record<string, Record<string, unknown>> | null = null;\n\n // Engine reference (set after creation, used by applyNamespacedFacts)\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n let engine: any = null;\n\n /**\n * Apply namespaced facts to the engine's flat store.\n * Converts { auth: { token: \"x\" } } to { \"auth::token\": \"x\" }\n * Includes prototype pollution protection.\n */\n function applyNamespacedFacts(\n namespacedFacts: Record<string, Record<string, unknown>>,\n ): void {\n for (const [namespace, facts] of Object.entries(namespacedFacts)) {\n // Skip blocked property names\n if (BLOCKED_PROPS.has(namespace)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] initialFacts/hydrate contains blocked namespace \"${namespace}\". Skipping.`,\n );\n }\n continue;\n }\n\n if (!moduleNamespaces.has(namespace)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] initialFacts/hydrate contains unknown namespace \"${namespace}\". ` +\n `Available modules: ${[...moduleNamespaces].join(\", \")}`,\n );\n }\n continue;\n }\n\n // Validate facts object for prototype pollution\n if (facts && typeof facts === \"object\" && !isPrototypeSafe(facts)) {\n throw new Error(\n `[Directive] initialFacts/hydrate for namespace \"${namespace}\" contains potentially ` +\n \"dangerous keys (__proto__, constructor, or prototype). This may indicate a \" +\n \"prototype pollution attack.\",\n );\n }\n\n for (const [key, value] of Object.entries(facts)) {\n // Skip blocked keys\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[\n `${namespace}${SEPARATOR}${key}`\n ] = value;\n }\n }\n }\n\n // Create engine with flat modules\n engine = createEngine({\n // biome-ignore lint/suspicious/noExplicitAny: Module format conversion\n modules: flatModules as any,\n plugins: options.plugins,\n history,\n trace,\n errorBoundary,\n tickMs: options.tickMs,\n cloud: options.cloud,\n // Callback to apply initialFacts/hydrate during init phase (after module inits, before reconcile)\n onAfterModuleInit: () => {\n // Apply initialFacts first\n if (options.initialFacts) {\n applyNamespacedFacts(\n options.initialFacts as Record<string, Record<string, unknown>>,\n );\n }\n // Apply hydrated facts second (takes precedence)\n if (hydratedFacts) {\n applyNamespacedFacts(hydratedFacts);\n hydratedFacts = null;\n }\n },\n });\n\n // Build namespace → internal keys map (for subscribeModule / wildcard support)\n const namespaceKeysMap = new Map<string, string[]>();\n for (const namespace of Object.keys(modulesMap)) {\n const mod = modulesMap[namespace];\n if (!mod) continue;\n namespaceKeysMap.set(namespace, collectNamespaceKeys(namespace, mod));\n }\n\n // Create namespaced proxies for external access\n const namespacedFactsProxy = createNamespacedFactsProxy(\n engine.facts as unknown as Record<string, unknown>,\n modulesMap,\n getModuleNames,\n );\n const namespacedDeriveProxy = createNamespacedDeriveProxy(\n engine.derive as unknown as Record<string, unknown>,\n modulesMap,\n getModuleNames,\n );\n const namespacedEventsProxy = createNamespacedEventsProxy(\n engine,\n modulesMap,\n getModuleNames,\n );\n\n // Build the namespaced system\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n const tickMs = options.tickMs;\n\n const system: NamespacedSystem<Modules> = {\n _mode: \"namespaced\",\n facts: namespacedFactsProxy,\n history: engine.history,\n derive: namespacedDeriveProxy,\n events: namespacedEventsProxy,\n constraints: engine.constraints,\n effects: engine.effects,\n resolvers: engine.resolvers,\n\n async hydrate(\n loader: () =>\n | Promise<Record<string, Record<string, unknown>>>\n | Record<string, Record<string, unknown>>,\n ) {\n if (engine.isRunning) {\n throw new Error(\n \"[Directive] hydrate() must be called before start(). \" +\n \"The system is already running.\",\n );\n }\n\n const result = await loader();\n if (result && typeof result === \"object\") {\n hydratedFacts = result;\n }\n },\n\n initialize(): void {\n engine.initialize();\n },\n\n start(): void {\n // Engine.start() runs module inits, then applies initialFacts/hydrate via callback\n engine.start();\n\n if (tickMs && tickMs > 0) {\n // Find the first module with a tick event and dispatch to it\n let tickEventKey: string | undefined;\n for (const m of flatModules) {\n if (m?.events) {\n tickEventKey = Object.keys(m.events).find((k) =>\n k.endsWith(`${SEPARATOR}tick`),\n );\n if (tickEventKey) break;\n }\n }\n if (tickEventKey) {\n const key = tickEventKey;\n tickInterval = setInterval(() => {\n engine.dispatch({ type: key });\n }, tickMs);\n }\n }\n },\n\n stop(): void {\n if (tickInterval) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n engine.stop();\n },\n\n destroy(): void {\n this.stop();\n engine.destroy();\n },\n\n dispatch(event: { type: string; [key: string]: unknown }) {\n engine.dispatch(event);\n },\n\n /**\n * Read a derivation value using namespaced syntax.\n * Accepts \"namespace.key\" format.\n *\n * @example\n * system.read(\"auth.status\") // → \"authenticated\"\n * system.read(\"data.count\") // → 5\n */\n read<T = unknown>(derivationId: string): T {\n return engine.read(toInternalKey(derivationId));\n },\n\n /**\n * Subscribe to derivation changes using namespaced syntax.\n * Accepts \"namespace.key\" format.\n * Supports wildcard \"namespace.*\" to subscribe to all keys in a module.\n *\n * @example\n * system.subscribe([\"auth.status\", \"data.count\"], () => {\n * console.log(\"Auth or data changed\");\n * });\n *\n * @example Wildcard\n * system.subscribe([\"game.*\", \"chat.*\"], () => render());\n */\n subscribe(ids: string[], listener: () => void): () => void {\n const internalIds: string[] = [];\n for (const id of ids) {\n if (id.endsWith(\".*\")) {\n const ns = id.slice(0, -2);\n const keys = namespaceKeysMap.get(ns);\n if (keys) {\n internalIds.push(...keys);\n } else if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] subscribe wildcard \"${id}\" — namespace \"${ns}\" not found.`,\n );\n }\n } else {\n internalIds.push(toInternalKey(id));\n }\n }\n return engine.subscribe(internalIds, listener);\n },\n\n /**\n * Subscribe to ALL fact and derivation changes in a module namespace.\n * Shorthand for subscribing to every key in a module.\n *\n * @example\n * const unsub = system.subscribeModule(\"game\", () => render());\n */\n subscribeModule(namespace: string, listener: () => void): () => void {\n const keys = namespaceKeysMap.get(namespace);\n if (!keys || keys.length === 0) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[Directive] subscribeModule(\"${namespace}\") — namespace not found. ` +\n `Available: ${[...namespaceKeysMap.keys()].join(\", \")}`,\n );\n }\n return () => {};\n }\n return engine.subscribe(keys, listener);\n },\n\n /**\n * Watch a fact or derivation for changes using namespaced syntax.\n * The key is auto-detected -- works with both fact keys and derivation keys.\n * Accepts \"namespace.key\" format.\n *\n * @example\n * system.watch(\"auth.token\", (newVal, oldVal) => { ... }) // fact\n * system.watch(\"auth.status\", (newVal, oldVal) => { ... }) // derivation\n */\n watch<T = unknown>(\n id: string,\n callback: (newValue: T, previousValue: T | undefined) => void,\n options?: { equalityFn?: (a: T, b: T | undefined) => boolean },\n ): () => void {\n return engine.watch(toInternalKey(id), callback, options);\n },\n\n /**\n * Returns a promise that resolves when the predicate becomes true.\n * The predicate receives namespaced facts (e.g., facts.auth.token).\n */\n when(\n predicate: (facts: Record<string, unknown>) => boolean,\n options?: { timeout?: number },\n ): Promise<void> {\n // Wrap predicate to provide namespaced facts view\n return engine.when(\n () =>\n predicate(namespacedFactsProxy as unknown as Record<string, unknown>),\n options,\n );\n },\n\n /**\n * Get a distributable snapshot with namespaced key translation.\n * Accepts \"namespace.key\" format in options (e.g., \"auth.effectivePlan\").\n * Returns data with namespaced keys (e.g., { auth: { effectivePlan: ... } }).\n */\n getDistributableSnapshot<T = Record<string, unknown>>(options?: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n }): {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n } {\n // Translate namespaced keys to internal format\n const internalOptions = {\n ...options,\n includeDerivations: options?.includeDerivations?.map(toInternalKey),\n excludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n includeFacts: options?.includeFacts?.map(toInternalKey),\n };\n\n const snapshot = engine.getDistributableSnapshot(internalOptions);\n\n // Transform data keys from internal format (auth::status) to namespaced format (auth: { status })\n return {\n ...snapshot,\n data: denormalizeFlatKeys(\n snapshot.data as Record<string, unknown>,\n ) as T,\n };\n },\n\n /**\n * Watch for changes to distributable snapshot derivations.\n * Accepts \"namespace.key\" format in options.\n * Callback receives data with namespaced keys.\n */\n watchDistributableSnapshot<T = Record<string, unknown>>(\n options: {\n includeDerivations?: string[];\n excludeDerivations?: string[];\n includeFacts?: string[];\n ttlSeconds?: number;\n metadata?: Record<string, unknown>;\n includeVersion?: boolean;\n },\n callback: (snapshot: {\n data: T;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => void,\n ): () => void {\n // Translate namespaced keys to internal format\n const internalOptions = {\n ...options,\n includeDerivations: options?.includeDerivations?.map(toInternalKey),\n excludeDerivations: options?.excludeDerivations?.map(toInternalKey),\n includeFacts: options?.includeFacts?.map(toInternalKey),\n };\n\n return engine.watchDistributableSnapshot(\n internalOptions,\n (snapshot: {\n data: Record<string, unknown>;\n createdAt: number;\n expiresAt?: number;\n version?: string;\n metadata?: Record<string, unknown>;\n }) => {\n // Transform data keys from internal format to namespaced format\n callback({\n ...snapshot,\n data: denormalizeFlatKeys(\n snapshot.data as Record<string, unknown>,\n ) as T,\n });\n },\n );\n },\n registerModule(\n namespace: string,\n moduleDef: ModuleDef<ModuleSchema>,\n ): void {\n // Validate namespace\n if (moduleNamespaces.has(namespace)) {\n throw new Error(\n `[Directive] Module namespace \"${namespace}\" already exists. ` +\n \"Cannot register a duplicate namespace.\",\n );\n }\n if (namespace.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n );\n }\n if (BLOCKED_PROPS.has(namespace)) {\n throw new Error(\n `[Directive] Module name \"${namespace}\" is a blocked property.`,\n );\n }\n\n // Validate schema keys\n for (const key of Object.keys(moduleDef.schema.facts)) {\n if (key.includes(SEPARATOR)) {\n throw new Error(\n `[Directive] Schema key \"${key}\" in module \"${namespace}\" contains the reserved separator \"${SEPARATOR}\".`,\n );\n }\n }\n\n const mod = moduleDef;\n\n // Transform module definition with namespace prefixing\n const flat = prefixModuleDefinition({\n mod,\n namespace,\n snapshotModulesSet,\n });\n\n // Register namespace\n moduleNamespaces.add(namespace);\n (modulesMap as Record<string, ModuleDef<ModuleSchema>>)[namespace] = mod;\n // Invalidate cached module names so proxies see the new namespace\n moduleNamesCache.names = null;\n\n // Update namespace keys map\n namespaceKeysMap.set(namespace, collectNamespaceKeys(namespace, mod));\n\n // Delegate to engine's registerModule\n // biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n (engine as any).registerModule(flat);\n },\n\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing for NamespacedSystem\n } as any;\n\n bindEnginePassthroughs(system, engine);\n warnIfNotStarted(system);\n\n return system;\n}\n\n// ============================================================================\n// Shared Helpers (deduplication between single-module and namespaced systems)\n// ============================================================================\n\n/**\n * Apply zero-config defaults to system options (history, trace, errorBoundary).\n * Returns the resolved values; does not mutate the options object.\n */\nfunction applyZeroConfigDefaults(options: {\n zeroConfig?: boolean;\n history?: HistoryOption;\n trace?: TraceOption;\n errorBoundary?: ErrorBoundaryConfig;\n}): {\n history: HistoryOption | undefined;\n trace: TraceOption | undefined;\n errorBoundary: ErrorBoundaryConfig | undefined;\n} {\n let history: HistoryOption | undefined = options.history;\n const trace: TraceOption | undefined = options.trace;\n let errorBoundary: ErrorBoundaryConfig | undefined = options.errorBoundary;\n\n if (options.zeroConfig) {\n const isDev = process.env.NODE_ENV !== \"production\";\n\n history = history ?? isDev;\n\n errorBoundary = {\n onConstraintError: \"skip\",\n onResolverError: \"skip\",\n onEffectError: \"skip\",\n onDerivationError: \"skip\",\n ...options.errorBoundary,\n };\n }\n\n return { history, trace, errorBoundary };\n}\n\n/**\n * Bind shared engine passthrough properties and methods onto a system object.\n * These are identical between single-module and namespaced systems.\n *\n * For methods that namespaced systems override (dispatch, read, subscribe,\n * watch, when, getDistributableSnapshot, watchDistributableSnapshot),\n * only binds them if not already defined on the system object.\n */\nfunction bindEnginePassthroughs(\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n system: any,\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n engine: any,\n): void {\n Object.defineProperties(system, {\n trace: {\n get() {\n return engine.trace;\n },\n enumerable: true,\n configurable: true,\n },\n isRunning: {\n get() {\n return engine.isRunning;\n },\n enumerable: true,\n configurable: true,\n },\n isSettled: {\n get() {\n return engine.isSettled;\n },\n enumerable: true,\n configurable: true,\n },\n isInitialized: {\n get() {\n return engine.isInitialized;\n },\n enumerable: true,\n configurable: true,\n },\n isReady: {\n get() {\n return engine.isReady;\n },\n enumerable: true,\n configurable: true,\n },\n });\n\n system.whenReady = engine.whenReady.bind(engine);\n system.batch = engine.batch.bind(engine);\n system.onSettledChange = engine.onSettledChange.bind(engine);\n system.onHistoryChange = engine.onHistoryChange.bind(engine);\n system.inspect = engine.inspect.bind(engine);\n system.settle = engine.settle.bind(engine);\n system.explain = engine.explain.bind(engine);\n system.getSnapshot = engine.getSnapshot.bind(engine);\n system.restore = engine.restore.bind(engine);\n\n // Direct engine passthroughs — only bind if not already defined\n // (namespaced systems override these with key-translating versions)\n const overridableMethods = [\n \"dispatch\",\n \"read\",\n \"subscribe\",\n \"watch\",\n \"when\",\n \"getDistributableSnapshot\",\n \"watchDistributableSnapshot\",\n ] as const;\n for (const method of overridableMethods) {\n if (!(method in system)) {\n system[method] = engine[method].bind(engine);\n }\n }\n}\n\n/**\n * Emit a dev-mode warning if system.start() is never called.\n */\nfunction warnIfNotStarted(\n // biome-ignore lint/suspicious/noExplicitAny: System type\n system: any,\n): void {\n if (\n process.env.NODE_ENV !== \"production\" &&\n process.env.NODE_ENV !== \"test\"\n ) {\n setTimeout(() => {\n if (!system.isRunning && !system.isInitialized) {\n console.warn(\n \"[Directive] System created but start() was never called. \" +\n \"Constraints, resolvers, and effects will not run until you call system.start().\",\n );\n }\n }, 0);\n }\n}\n\n// Proxy helpers and key conversion utilities are in system-proxies.ts\n\n// ============================================================================\n// Single Module System\n// ============================================================================\n\n/**\n * Create a system with a single module (no namespacing).\n * Facts, derivations, and events are accessed directly.\n */\nfunction createSingleModuleSystem<S extends ModuleSchema>(\n options: CreateSystemOptionsSingle<S>,\n): SingleModuleSystem<S> {\n const mod = options.module;\n\n // Validate module is provided\n if (!mod) {\n throw new Error(\n \"[Directive] createSystem requires a module. Got: \" + typeof mod,\n );\n }\n\n // Validate tickMs if provided\n if (options.tickMs !== undefined && options.tickMs <= 0) {\n throw new Error(\"[Directive] tickMs must be a positive number\");\n }\n\n // Validate initialFacts for prototype pollution\n if (options.initialFacts && !isPrototypeSafe(options.initialFacts)) {\n throw new Error(\n \"[Directive] initialFacts contains potentially dangerous keys \" +\n \"(__proto__, constructor, or prototype). This may indicate a \" +\n \"prototype pollution attack.\",\n );\n }\n\n // Dev-mode warnings\n if (process.env.NODE_ENV !== \"production\") {\n // Warn if crossModuleDeps is defined (ignored in single module mode)\n if (mod.crossModuleDeps && Object.keys(mod.crossModuleDeps).length > 0) {\n console.warn(\n \"[Directive] Single module mode ignores crossModuleDeps. \" +\n \"Use multiple modules if cross-module access is needed: \" +\n \"createSystem({ modules: { ... } })\",\n );\n }\n\n // Warn if tickMs set without tick event handler\n if (options.tickMs && options.tickMs > 0) {\n const hasTickHandler = mod.events && \"tick\" in mod.events;\n if (!hasTickHandler) {\n console.warn(\n `[Directive] tickMs is set to ${options.tickMs}ms but module has no \"tick\" event handler.`,\n );\n }\n }\n\n // Warn if snapshotModules is set (has no effect in single-module mode)\n const singleHistoryConfig =\n typeof options.history === \"object\" ? options.history : null;\n if (singleHistoryConfig?.snapshotModules) {\n console.warn(\n \"[Directive] history.snapshotModules has no effect in single-module mode. \" +\n \"Use history.snapshotEvents on the module definition instead, or switch to \" +\n \"createSystem({ modules: { ... } }) for multi-module filtering.\",\n );\n }\n }\n\n // Apply zero-config defaults if enabled\n const { history, trace, errorBoundary } = applyZeroConfigDefaults(options);\n\n // Store for hydrated facts\n let hydratedFacts: Record<string, unknown> | null = null;\n\n // Engine reference\n // biome-ignore lint/suspicious/noExplicitAny: Engine type\n let engine: any = null;\n\n // Create engine with the module directly (no prefixing needed)\n engine = createEngine({\n modules: [\n {\n id: mod.id,\n schema: mod.schema.facts,\n requirements: mod.schema.requirements,\n init: mod.init,\n derive: mod.derive,\n events: mod.events,\n effects: mod.effects,\n constraints: mod.constraints,\n resolvers: mod.resolvers,\n hooks: mod.hooks,\n history: mod.history,\n },\n // biome-ignore lint/suspicious/noExplicitAny: Module format\n ] as any,\n plugins: options.plugins,\n history,\n trace,\n errorBoundary,\n tickMs: options.tickMs,\n cloud: options.cloud,\n onAfterModuleInit: () => {\n // Apply initialFacts (already validated for prototype safety above)\n if (options.initialFacts) {\n for (const [key, value] of Object.entries(options.initialFacts)) {\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[key] = value;\n }\n }\n // Apply hydrated facts (takes precedence)\n if (hydratedFacts) {\n if (!isPrototypeSafe(hydratedFacts)) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n \"[Directive] hydrate() data contains potentially dangerous keys. Skipping.\",\n );\n }\n } else {\n for (const [key, value] of Object.entries(hydratedFacts)) {\n if (BLOCKED_PROPS.has(key)) continue;\n (engine.facts as Record<string, unknown>)[key] = value;\n }\n }\n hydratedFacts = null;\n }\n },\n });\n\n // Create events proxy for direct access\n const eventsProxy = new Proxy(\n {} as Record<string, (payload?: Record<string, unknown>) => void>,\n {\n get(_, eventName: string | symbol) {\n if (typeof eventName === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(eventName)) {\n return undefined;\n }\n\n return (payload?: Record<string, unknown>) => {\n engine.dispatch({ type: eventName, ...payload });\n };\n },\n has(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return false;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return false;\n }\n\n return mod.events ? prop in mod.events : false;\n },\n ownKeys() {\n return mod.events ? Object.keys(mod.events) : [];\n },\n getOwnPropertyDescriptor(_, prop: string | symbol) {\n if (typeof prop === \"symbol\") {\n return undefined;\n }\n if (BLOCKED_PROPS.has(prop)) {\n return undefined;\n }\n if (mod.events && prop in mod.events) {\n return { configurable: true, enumerable: true };\n }\n\n return undefined;\n },\n set() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n defineProperty() {\n return false;\n },\n getPrototypeOf() {\n return null;\n },\n setPrototypeOf() {\n return false;\n },\n },\n );\n\n // Build the single module system\n let tickInterval: ReturnType<typeof setInterval> | null = null;\n const tickMs = options.tickMs;\n\n const system: SingleModuleSystem<S> = {\n _mode: \"single\",\n facts: engine.facts,\n history: engine.history,\n derive: engine.derive,\n events: eventsProxy as SingleModuleSystem<S>[\"events\"],\n constraints: engine.constraints,\n effects: engine.effects,\n resolvers: engine.resolvers,\n\n async hydrate(\n loader: () => Promise<Record<string, unknown>> | Record<string, unknown>,\n ) {\n if (engine.isRunning) {\n throw new Error(\n \"[Directive] hydrate() must be called before start(). \" +\n \"The system is already running.\",\n );\n }\n\n const result = await loader();\n if (result && typeof result === \"object\") {\n hydratedFacts = result as Record<string, unknown>;\n }\n },\n\n initialize(): void {\n engine.initialize();\n },\n\n start(): void {\n engine.start();\n\n if (tickMs && tickMs > 0) {\n const hasTickHandler = mod.events && \"tick\" in mod.events;\n if (hasTickHandler) {\n tickInterval = setInterval(() => {\n engine.dispatch({ type: \"tick\" });\n }, tickMs);\n }\n }\n },\n\n stop(): void {\n if (tickInterval) {\n clearInterval(tickInterval);\n tickInterval = null;\n }\n engine.stop();\n },\n\n destroy(): void {\n this.stop();\n engine.destroy();\n },\n\n registerModule(moduleDef: ModuleDef<ModuleSchema>): void {\n // biome-ignore lint/suspicious/noExplicitAny: Engine registerModule type\n (engine as any).registerModule({\n id: moduleDef.id,\n schema: moduleDef.schema.facts,\n requirements: moduleDef.schema.requirements,\n init: moduleDef.init,\n derive: moduleDef.derive,\n events: moduleDef.events,\n effects: moduleDef.effects,\n constraints: moduleDef.constraints,\n resolvers: moduleDef.resolvers,\n hooks: moduleDef.hooks,\n history: moduleDef.history,\n });\n },\n // biome-ignore lint/suspicious/noExplicitAny: Type narrowing\n } as any;\n\n bindEnginePassthroughs(system, engine);\n warnIfNotStarted(system);\n\n return system;\n}\n"]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import {y}from'./chunk-DIK3SZBM.js';import {k}from'./chunk-O75OISQ2.js';import {c}from'./chunk-GO63IIN5.js';var f="::";function R(n){return new Proxy({},{get(e,t){if(typeof t!="symbol"&&!k.has(t))return n.get(t)},set(e,t,o){return typeof t=="symbol"||k.has(t)?false:n.set?n.set(t,o):false},has(e,t){return typeof t=="symbol"||k.has(t)?false:n.has?n.has(t):false},deleteProperty(e,t){return typeof t=="symbol"||k.has(t)?false:n.delete?n.delete(t):false},ownKeys(){return n.ownKeys?n.ownKeys():[]},getOwnPropertyDescriptor(e,t){if(typeof t!="symbol"&&n.has&&typeof t=="string"&&n.has(t))return {configurable:true,enumerable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}var q=new WeakMap,I=new WeakMap,H=new WeakMap,V=new WeakMap,W=new WeakMap,z=new WeakMap;function S(n,e){let t=q.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,q.set(n,t);let o=R({get:r=>r==="$store"||r==="$snapshot"?n[r]:n[`${e}${f}${r}`],set:(r,a)=>(n[`${e}${f}${r}`]=a,true),has:r=>`${e}${f}${r}`in n,delete:r=>(delete n[`${e}${f}${r}`],true)});return t.set(e,o),o}function U(n,e,t){let o=I.get(n);if(o)return o;let r=R({get:a=>{if(Object.hasOwn(e,a))return S(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return I.set(n,r),r}function G(n,e,t){let o=`${e}|${t.join(",")}`,r=W.get(n);if(r){let i=r.get(o);if(i)return i}else r=new Map,W.set(n,r);let a=new Set(t),u=["self",...t],y=R({get:i=>{if(i==="self")return S(n,e);if(a.has(i))return S(n,i);process.env.NODE_ENV!=="production"&&console.warn(`[Directive] Module "${e}" accessed undeclared cross-module property "${i}". Add it to crossModuleDeps or use "facts.self.${i}" for own module facts.`);},has:i=>i==="self"||a.has(i),ownKeys:()=>u});return r.set(o,y),y}function A(n,e){let t=V.get(n);if(t){let r=t.get(e);if(r)return r}else t=new Map,V.set(n,t);let o=R({get:r=>n[`${e}${f}${r}`],has:r=>`${e}${f}${r}`in n});return t.set(e,o),o}function L(n,e,t){let o=H.get(n);if(o)return o;let r=R({get:a=>{if(Object.hasOwn(e,a))return A(n,a)},has:a=>Object.hasOwn(e,a),ownKeys:()=>t()});return H.set(n,r),r}function Z(n,e,t){let o=z.get(n);return o||(o=new Map,z.set(n,o)),R({get:r=>{if(!Object.hasOwn(e,r))return;let a=o.get(r);if(a)return a;let u=R({get:y=>i=>{n.dispatch({type:`${r}${f}${y}`,...i});}});return o.set(r,u),u},has:r=>Object.hasOwn(e,r),ownKeys:()=>t()})}function v(n){if(n.includes(".")){let[e,...t]=n.split(".");return `${e}${f}${t.join(f)}`}return n}function F(n){let e={};for(let[t,o]of Object.entries(n)){let r=t.indexOf(f);if(r>0){let a=t.slice(0,r),u=t.slice(r+f.length);e[a]||(e[a]={}),e[a][u]=o;}else e._root||(e._root={}),e._root[t]=o;}return e}function O(n,e,t,o){return t?G(n,e,o):S(n,e)}function M(n,e){return `${n}${f}${e}`}function $(n){return Object.keys(n).length>0?n:void 0}function te(n,e){let t={};for(let[o,r]of Object.entries(n.schema.facts))t[M(e,o)]=r;return t}function re(n,e){if(n.init)return t=>{let o=S(t,e);n.init(o);}}function se(n,e,t,o){if(!n.derive)return;let r={};for(let[a,u]of Object.entries(n.derive))r[M(e,a)]=(y,i)=>{let k=O(y,e,t,o),g=A(i,e);return u(k,g)};return $(r)}function oe(n,e){if(!n.events)return;let t={};for(let[o,r]of Object.entries(n.events))t[M(e,o)]=(a,u)=>{let y=S(a,e);r(y,u);};return $(t)}function ie(n,e,t,o){if(!n.constraints)return;let r={};for(let[a,u]of Object.entries(n.constraints)){let y=u;r[M(e,a)]={...y,deps:y.deps?.map(i=>M(e,i)),after:y.after?.map(i=>i.includes(f)?i:M(e,i)),when:i=>{let k=O(i,e,t,o);return y.when(k)},require:typeof y.require=="function"?i=>{let k=O(i,e,t,o);return y.require(k)}:y.require};}return $(r)}function ae(n,e,t,o){if(!n.resolvers)return;let r={};for(let[u,y]of Object.entries(n.resolvers)){let k=function(g){return {facts:O(g.facts,e,t,o),signal:g.signal}};let i=y;r[M(e,u)]={...i,...i.resolve&&{resolve:async(g,d)=>{await i.resolve(g,k(d));}},...i.resolveBatch&&{resolveBatch:async(g,d)=>{await i.resolveBatch(g,k(d));}},...i.resolveBatchWithResults&&{resolveBatchWithResults:async(g,d)=>i.resolveBatchWithResults(g,k(d))}};}return $(r)}function ce(n,e,t,o){if(!n.effects)return;let r={};for(let[a,u]of Object.entries(n.effects)){let y=u;r[M(e,a)]={...y,run:(i,k)=>{let g=O(i,e,t,o),d=k?O(k,e,t,o):void 0;return y.run(g,d)},deps:y.deps?.map(i=>M(e,i))};}return $(r)}function ue(n,e,t){return {snapshotEvents:t&&!t.has(e)?[]:n.history?.snapshotEvents?.map(o=>M(e,o))}}function T(n){let{mod:e,namespace:t,snapshotModulesSet:o}=n,r=!!(e.crossModuleDeps&&Object.keys(e.crossModuleDeps).length>0),a=r?Object.keys(e.crossModuleDeps):[];return {id:e.id,schema:te(e,t),requirements:e.schema.requirements??{},init:re(e,t),derive:se(e,t,r,a),events:oe(e,t),effects:ce(e,t,r,a),constraints:ie(e,t,r,a),resolvers:ae(e,t,r,a),hooks:e.hooks,history:ue(e,t,o)}}function de(n){let e=Object.keys(n),t=new Set(e),o=new Set,r=new Set,a=[],u=[];function y(i){if(o.has(i))return;if(r.has(i)){let g=u.indexOf(i),d=[...u.slice(g),i].join(" \u2192 ");throw new Error(`[Directive] Circular dependency detected: ${d}. Modules cannot have circular crossModuleDeps. Break the cycle by removing one of the cross-module references.`)}r.add(i),u.push(i);let k=n[i];if(k?.crossModuleDeps)for(let g of Object.keys(k.crossModuleDeps))t.has(g)&&y(g);u.pop(),r.delete(i),o.add(i),a.push(i);}for(let i of e)y(i);return a}function J(n,e){let t=[];for(let o of Object.keys(e.schema.facts))t.push(`${n}${f}${o}`);if(e.schema.derivations)for(let o of Object.keys(e.schema.derivations))t.push(`${n}${f}${o}`);return t}function be(n){if("module"in n){if(!n.module)throw new Error("[Directive] createSystem requires a module. Got: "+typeof n.module);return fe(n)}let e=n;if(Array.isArray(e.modules))throw new Error(`[Directive] createSystem expects modules as an object, not an array.
|
|
2
|
+
|
|
3
|
+
Instead of:
|
|
4
|
+
createSystem({ modules: [authModule, dataModule] })
|
|
5
|
+
|
|
6
|
+
Use:
|
|
7
|
+
createSystem({ modules: { auth: authModule, data: dataModule } })
|
|
8
|
+
|
|
9
|
+
Or for a single module:
|
|
10
|
+
createSystem({ module: counterModule })`);let t=e.modules;if(t&&typeof t=="object"&&"id"in t&&"schema"in t)throw new Error(`[Directive] A single module was passed to \`modules:\`. For a single module, use \`module:\` instead:
|
|
11
|
+
|
|
12
|
+
createSystem({ module: myModule })
|
|
13
|
+
|
|
14
|
+
For multiple modules, wrap in an object:
|
|
15
|
+
createSystem({ modules: { myName: myModule } })`);return le(e)}function le(n){let e=n.modules,t=new Set(Object.keys(e)),o=typeof n.history=="object"?n.history:null,r=o?.snapshotModules?new Set(o.snapshotModules):null;if(n.tickMs!==void 0&&n.tickMs<=0)throw new Error("[Directive] tickMs must be a positive number");if(process.env.NODE_ENV!=="production"){for(let[s,c]of Object.entries(e))if(c.crossModuleDeps)for(let l of Object.keys(c.crossModuleDeps))l===s?console.warn(`[Directive] Module "${s}" references itself in crossModuleDeps. Use "facts.self" to access own module's facts instead.`):t.has(l)||console.warn(`[Directive] Module "${s}" declares crossModuleDeps.${l}, but no module with namespace "${l}" exists in the system. Available modules: ${[...t].join(", ")}`);}if(process.env.NODE_ENV!=="production"&&o?.snapshotModules)for(let s of o.snapshotModules)t.has(s)||console.warn(`[Directive] history.snapshotModules entry "${s}" doesn't match any module. Available modules: ${[...t].join(", ")}`);let a,u=n.initOrder??"auto";if(Array.isArray(u)){let s=u,c=Object.keys(e).filter(l=>!s.includes(l));if(c.length>0)throw new Error(`[Directive] initOrder is missing modules: ${c.join(", ")}. All modules must be included in the explicit order.`);a=s;}else u==="declaration"?a=Object.keys(e):a=de(e);let{history:y$1,trace:i,errorBoundary:k$1}=Q(n);for(let s of Object.keys(e)){if(s.includes(f))throw new Error(`[Directive] Module name "${s}" contains the reserved separator "${f}". Module names cannot contain "${f}".`);let c=e[s];if(c){for(let l of Object.keys(c.schema.facts))if(l.includes(f))throw new Error(`[Directive] Schema key "${l}" in module "${s}" contains the reserved separator "${f}". Schema keys cannot contain "${f}".`)}}let g={names:null};function d(){return g.names===null&&(g.names=Object.keys(e)),g.names}let w=a.map(s=>{let c=e[s];return c?T({mod:c,namespace:s,snapshotModulesSet:r}):null}).filter(s=>s!==null);process.env.NODE_ENV!=="production"&&n.tickMs&&n.tickMs>0&&(w.some(c=>c.events&&Object.keys(c.events).some(l=>l.endsWith(`${f}tick`)))||console.warn(`[Directive] tickMs is set to ${n.tickMs}ms but no module defines a "tick" event handler.`));let D=null,h=null;function _(s){for(let[c$1,l]of Object.entries(s)){if(k.has(c$1)){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] initialFacts/hydrate contains blocked namespace "${c$1}". Skipping.`);continue}if(!t.has(c$1)){process.env.NODE_ENV!=="production"&&console.warn(`[Directive] initialFacts/hydrate contains unknown namespace "${c$1}". Available modules: ${[...t].join(", ")}`);continue}if(l&&typeof l=="object"&&!c(l))throw new Error(`[Directive] initialFacts/hydrate for namespace "${c$1}" contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.`);for(let[p,b]of Object.entries(l))k.has(p)||(h.facts[`${c$1}${f}${p}`]=b);}}h=y({modules:w,plugins:n.plugins,history:y$1,trace:i,errorBoundary:k$1,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{n.initialFacts&&_(n.initialFacts),D&&(_(D),D=null);}});let x=new Map;for(let s of Object.keys(e)){let c=e[s];c&&x.set(s,J(s,c));}let B=U(h.facts,e,d),ee=L(h.derive,e,d),ne=Z(h,e,d),E=null,j=n.tickMs,N={_mode:"namespaced",facts:B,history:h.history,derive:ee,events:ne,constraints:h.constraints,effects:h.effects,resolvers:h.resolvers,async hydrate(s){if(h.isRunning)throw new Error("[Directive] hydrate() must be called before start(). The system is already running.");let c=await s();c&&typeof c=="object"&&(D=c);},initialize(){h.initialize();},start(){if(h.start(),j&&j>0){let s;for(let c of w)if(c?.events&&(s=Object.keys(c.events).find(l=>l.endsWith(`${f}tick`)),s))break;if(s){let c=s;E=setInterval(()=>{h.dispatch({type:c});},j);}}},stop(){E&&(clearInterval(E),E=null),h.stop();},destroy(){this.stop(),h.destroy();},dispatch(s){h.dispatch(s);},read(s){return h.read(v(s))},subscribe(s,c){let l=[];for(let p of s)if(p.endsWith(".*")){let b=p.slice(0,-2),K=x.get(b);K?l.push(...K):process.env.NODE_ENV!=="production"&&console.warn(`[Directive] subscribe wildcard "${p}" \u2014 namespace "${b}" not found.`);}else l.push(v(p));return h.subscribe(l,c)},subscribeModule(s,c){let l=x.get(s);return !l||l.length===0?(process.env.NODE_ENV!=="production"&&console.warn(`[Directive] subscribeModule("${s}") \u2014 namespace not found. Available: ${[...x.keys()].join(", ")}`),()=>{}):h.subscribe(l,c)},watch(s,c,l){return h.watch(v(s),c,l)},when(s,c){return h.when(()=>s(B),c)},getDistributableSnapshot(s){let c={...s,includeDerivations:s?.includeDerivations?.map(v),excludeDerivations:s?.excludeDerivations?.map(v),includeFacts:s?.includeFacts?.map(v)},l=h.getDistributableSnapshot(c);return {...l,data:F(l.data)}},watchDistributableSnapshot(s,c){let l={...s,includeDerivations:s?.includeDerivations?.map(v),excludeDerivations:s?.excludeDerivations?.map(v),includeFacts:s?.includeFacts?.map(v)};return h.watchDistributableSnapshot(l,p=>{c({...p,data:F(p.data)});})},registerModule(s,c){if(t.has(s))throw new Error(`[Directive] Module namespace "${s}" already exists. Cannot register a duplicate namespace.`);if(s.includes(f))throw new Error(`[Directive] Module name "${s}" contains the reserved separator "${f}".`);if(k.has(s))throw new Error(`[Directive] Module name "${s}" is a blocked property.`);for(let b of Object.keys(c.schema.facts))if(b.includes(f))throw new Error(`[Directive] Schema key "${b}" in module "${s}" contains the reserved separator "${f}".`);let l=c,p=T({mod:l,namespace:s,snapshotModulesSet:r});t.add(s),e[s]=l,g.names=null,x.set(s,J(s,l)),h.registerModule(p);}};return X(N,h),Y(N),N}function Q(n){let e=n.history,t=n.trace,o=n.errorBoundary;if(n.zeroConfig){let r=process.env.NODE_ENV!=="production";e=e??r,o={onConstraintError:"skip",onResolverError:"skip",onEffectError:"skip",onDerivationError:"skip",...n.errorBoundary};}return {history:e,trace:t,errorBoundary:o}}function X(n,e){Object.defineProperties(n,{trace:{get(){return e.trace},enumerable:true,configurable:true},isRunning:{get(){return e.isRunning},enumerable:true,configurable:true},isSettled:{get(){return e.isSettled},enumerable:true,configurable:true},isInitialized:{get(){return e.isInitialized},enumerable:true,configurable:true},isReady:{get(){return e.isReady},enumerable:true,configurable:true}}),n.whenReady=e.whenReady.bind(e),n.batch=e.batch.bind(e),n.onSettledChange=e.onSettledChange.bind(e),n.onHistoryChange=e.onHistoryChange.bind(e),n.inspect=e.inspect.bind(e),n.settle=e.settle.bind(e),n.explain=e.explain.bind(e),n.getSnapshot=e.getSnapshot.bind(e),n.restore=e.restore.bind(e);let t=["dispatch","read","subscribe","watch","when","getDistributableSnapshot","watchDistributableSnapshot"];for(let o of t)o in n||(n[o]=e[o].bind(e));}function Y(n){process.env.NODE_ENV!=="production"&&process.env.NODE_ENV!=="test"&&setTimeout(()=>{!n.isRunning&&!n.isInitialized&&console.warn("[Directive] System created but start() was never called. Constraints, resolvers, and effects will not run until you call system.start().");},0);}function fe(n){let e=n.module;if(!e)throw new Error("[Directive] createSystem requires a module. Got: "+typeof e);if(n.tickMs!==void 0&&n.tickMs<=0)throw new Error("[Directive] tickMs must be a positive number");if(n.initialFacts&&!c(n.initialFacts))throw new Error("[Directive] initialFacts contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");process.env.NODE_ENV!=="production"&&(e.crossModuleDeps&&Object.keys(e.crossModuleDeps).length>0&&console.warn("[Directive] Single module mode ignores crossModuleDeps. Use multiple modules if cross-module access is needed: createSystem({ modules: { ... } })"),n.tickMs&&n.tickMs>0&&(e.events&&"tick"in e.events||console.warn(`[Directive] tickMs is set to ${n.tickMs}ms but module has no "tick" event handler.`)),(typeof n.history=="object"?n.history:null)?.snapshotModules&&console.warn("[Directive] history.snapshotModules has no effect in single-module mode. Use history.snapshotEvents on the module definition instead, or switch to createSystem({ modules: { ... } }) for multi-module filtering."));let{history:t,trace:o,errorBoundary:r}=Q(n),a=null,u=null;u=y({modules:[{id:e.id,schema:e.schema.facts,requirements:e.schema.requirements,init:e.init,derive:e.derive,events:e.events,effects:e.effects,constraints:e.constraints,resolvers:e.resolvers,hooks:e.hooks,history:e.history}],plugins:n.plugins,history:t,trace:o,errorBoundary:r,tickMs:n.tickMs,cloud:n.cloud,onAfterModuleInit:()=>{if(n.initialFacts)for(let[d,w]of Object.entries(n.initialFacts))k.has(d)||(u.facts[d]=w);if(a){if(!c(a))process.env.NODE_ENV!=="production"&&console.warn("[Directive] hydrate() data contains potentially dangerous keys. Skipping.");else for(let[d,w]of Object.entries(a))k.has(d)||(u.facts[d]=w);a=null;}}});let y$1=new Proxy({},{get(d,w){if(typeof w!="symbol"&&!k.has(w))return D=>{u.dispatch({type:w,...D});}},has(d,w){return typeof w=="symbol"||k.has(w)?false:e.events?w in e.events:false},ownKeys(){return e.events?Object.keys(e.events):[]},getOwnPropertyDescriptor(d,w){if(typeof w!="symbol"&&!k.has(w)&&e.events&&w in e.events)return {configurable:true,enumerable:true}},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),i=null,k$1=n.tickMs,g={_mode:"single",facts:u.facts,history:u.history,derive:u.derive,events:y$1,constraints:u.constraints,effects:u.effects,resolvers:u.resolvers,async hydrate(d){if(u.isRunning)throw new Error("[Directive] hydrate() must be called before start(). The system is already running.");let w=await d();w&&typeof w=="object"&&(a=w);},initialize(){u.initialize();},start(){u.start(),k$1&&k$1>0&&e.events&&"tick"in e.events&&(i=setInterval(()=>{u.dispatch({type:"tick"});},k$1));},stop(){i&&(clearInterval(i),i=null),u.stop();},destroy(){this.stop(),u.destroy();},registerModule(d){u.registerModule({id:d.id,schema:d.schema.facts,requirements:d.schema.requirements,init:d.init,derive:d.derive,events:d.events,effects:d.effects,constraints:d.constraints,resolvers:d.resolvers,hooks:d.hooks,history:d.history});}};return X(g,u),Y(g),g}export{be as a};//# sourceMappingURL=chunk-MAARYRI4.js.map
|
|
16
|
+
//# sourceMappingURL=chunk-MAARYRI4.js.map
|