@directive-run/core 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/adapter-utils.cjs +1 -1
  2. package/dist/adapter-utils.d.cts +1 -1
  3. package/dist/adapter-utils.d.ts +1 -1
  4. package/dist/adapter-utils.js +1 -1
  5. package/dist/{chunk-FK7BD7XT.js → chunk-EH2Q754B.js} +3 -3
  6. package/dist/chunk-EH2Q754B.js.map +1 -0
  7. package/dist/chunk-HAF5JCET.js +16 -0
  8. package/dist/chunk-HAF5JCET.js.map +1 -0
  9. package/dist/{chunk-4CMO5OVZ.js → chunk-M5KZXNZX.js} +2 -2
  10. package/dist/chunk-M5KZXNZX.js.map +1 -0
  11. package/dist/chunk-PGUTGWUI.cjs +3 -0
  12. package/dist/chunk-PGUTGWUI.cjs.map +1 -0
  13. package/dist/{chunk-DDUARSUH.cjs → chunk-S3CFYDIB.cjs} +3 -3
  14. package/dist/chunk-S3CFYDIB.cjs.map +1 -0
  15. package/dist/chunk-SQVKCJHE.cjs +16 -0
  16. package/dist/chunk-SQVKCJHE.cjs.map +1 -0
  17. package/dist/chunk-YCCQ73C6.js +3 -0
  18. package/dist/chunk-YCCQ73C6.js.map +1 -0
  19. package/dist/{chunk-BEJ6ICA7.cjs → chunk-ZHS3EW2Z.cjs} +2 -2
  20. package/dist/chunk-ZHS3EW2Z.cjs.map +1 -0
  21. package/dist/{helpers-D6LcRum7.d.ts → helpers-B1MiHave.d.cts} +12 -2
  22. package/dist/{helpers-BUY1lYCX.d.cts → helpers-h9PR2JSJ.d.ts} +12 -2
  23. package/dist/index.cjs +1 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +183 -5
  26. package/dist/index.d.ts +183 -5
  27. package/dist/index.js +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/internals.cjs +1 -1
  30. package/dist/internals.d.cts +49 -39
  31. package/dist/internals.d.ts +49 -39
  32. package/dist/internals.js +1 -1
  33. package/dist/plugins/index.cjs +1 -1
  34. package/dist/plugins/index.cjs.map +1 -1
  35. package/dist/plugins/index.d.cts +11 -8
  36. package/dist/plugins/index.d.ts +11 -8
  37. package/dist/plugins/index.js +1 -1
  38. package/dist/plugins/index.js.map +1 -1
  39. package/dist/{plugins-Dy1C8GtT.d.cts → plugins-Bakr7js6.d.cts} +369 -69
  40. package/dist/{plugins-Dy1C8GtT.d.ts → plugins-Bakr7js6.d.ts} +369 -69
  41. package/dist/system-744ZPPES.js +2 -0
  42. package/dist/{system-JIO36ALC.js.map → system-744ZPPES.js.map} +1 -1
  43. package/dist/system-CK3SHMXZ.cjs +2 -0
  44. package/dist/{system-2THXJBFM.cjs.map → system-CK3SHMXZ.cjs.map} +1 -1
  45. package/dist/testing.cjs +1 -1
  46. package/dist/testing.cjs.map +1 -1
  47. package/dist/testing.d.cts +1 -1
  48. package/dist/testing.d.ts +1 -1
  49. package/dist/testing.js +1 -1
  50. package/dist/testing.js.map +1 -1
  51. package/dist/worker.cjs +1 -1
  52. package/dist/worker.cjs.map +1 -1
  53. package/dist/worker.d.cts +1 -1
  54. package/dist/worker.d.ts +1 -1
  55. package/dist/worker.js +1 -1
  56. package/dist/worker.js.map +1 -1
  57. package/package.json +1 -1
  58. package/dist/chunk-4CMO5OVZ.js.map +0 -1
  59. package/dist/chunk-BEJ6ICA7.cjs.map +0 -1
  60. package/dist/chunk-DDUARSUH.cjs.map +0 -1
  61. package/dist/chunk-E2WETPLH.js +0 -3
  62. package/dist/chunk-E2WETPLH.js.map +0 -1
  63. package/dist/chunk-FK7BD7XT.js.map +0 -1
  64. package/dist/chunk-LFMRWCIG.js +0 -16
  65. package/dist/chunk-LFMRWCIG.js.map +0 -1
  66. package/dist/chunk-TUS5WDVE.cjs +0 -3
  67. package/dist/chunk-TUS5WDVE.cjs.map +0 -1
  68. package/dist/chunk-VSHSYVSY.cjs +0 -16
  69. package/dist/chunk-VSHSYVSY.cjs.map +0 -1
  70. package/dist/system-2THXJBFM.cjs +0 -2
  71. package/dist/system-JIO36ALC.js +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/worker.ts"],"names":["createWorkerClient","options","worker","onFactChange","onDerivationChange","onRequirementCreated","onRequirementMet","onError","pendingRequests","requestIdCounter","initResolve","startResolve","stopResolve","destroyResolve","resolveLifecycle","resolve","resolvePendingRequest","requestId","value","pending","handleReady","handleStarted","handleStopped","handleDestroyed","handleFactChanged","message","handleDerivationChanged","handleRequirementCreated","handleRequirementMet","handleError","handleSnapshotResult","handleInspectResult","handleSettleResult","event","send","request","reject","config","key","facts","timeout","workerModuleRegistry","getWorkerModuleRegistry","registerWorkerModule","name","module","handleWorkerMessages","system","handleInit","created","createWorkerSystem","handleStart","sys","handleStop","handleDestroy","handleGetSnapshot","snapshot","handleInspect","inspection","handleSettle","error","dispatchMessage","createSystem","registry","modules","prev","id","req","resolverId","factsProxy"],"mappings":"AAwJO,SAASA,CAAAA,CAAmBC,CAAAA,CAA4C,CAC7E,GAAM,CACJ,MAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,kBAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CACF,CAAA,CAAIN,CAAAA,CAGEO,CAAAA,CAAkB,IAAI,GAAA,CAIxBC,CAAAA,CAAmB,CAAA,CAGnBC,CAAAA,CAAmC,IAAA,CACnCC,CAAAA,CAAoC,IAAA,CACpCC,EAAmC,IAAA,CACnCC,CAAAA,CAAsC,IAAA,CAI1C,SAASC,CAAAA,CACPC,CAAAA,CACqB,CACrB,OAAAA,CAAAA,IAAU,CAEH,IACT,CAEA,SAASC,CAAAA,CAAsBC,CAAAA,CAAmBC,CAAAA,CAAsB,CACtE,IAAMC,CAAAA,CAAUX,CAAAA,CAAgB,GAAA,CAAIS,CAAS,CAAA,CACzCE,CAAAA,GACFA,CAAAA,CAAQ,OA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IAAA,GAAW,CAACoB,CAAAA,CAAKpB,CAAK,IAAK,MAAA,CAAO,OAAA,CAAQqB,CAAK,CAAA,CAC7C8B,CAAAA,CAAW/B,CAAG,CAAA,CAAIpB,EAGxB,CAAA,CACA,QAAA,CAAWe,CAAAA,EAA4B,CAEpCc,CAAAA,CAAe,QAAA,CAASd,CAAK,EAChC,EACA,WAAA,CAAchC,CAAAA,EACL8C,CAAAA,CAAO,wBAAA,CAAyB9C,CAAO,CAAA,CAEhD,OAAA,CAAS,IAAM8C,CAAAA,CAAO,OAAA,EAAQ,CAC9B,MAAA,CAASP,CAAAA,EAAqBO,CAAAA,CAAO,MAAA,CAAOP,CAAO,CACrD,CACF","file":"worker.js","sourcesContent":["/**\n * Web Worker Adapter - Run Directive engine off the main thread\n *\n * Features:\n * - Run computations in a dedicated worker\n * - Synchronized state between main thread and worker\n * - Automatic serialization of facts and derivations\n * - Event-based communication\n */\n\nimport type {\n DistributableSnapshot,\n DistributableSnapshotOptions,\n ModuleSchema,\n Requirement,\n SystemInspection,\n} from \"../core/types.js\";\n\n// ============================================================================\n// Message Types\n// ============================================================================\n\n/** Messages sent from main thread to worker */\nexport type WorkerInboundMessage =\n | { type: \"INIT\"; config: WorkerSystemConfig }\n | { type: \"START\" }\n | { type: \"STOP\" }\n | { type: \"DESTROY\" }\n | { type: \"SET_FACT\"; key: string; value: unknown }\n | { type: \"SET_FACTS\"; facts: Record<string, unknown> }\n | { type: \"DISPATCH\"; event: { type: string; [key: string]: unknown } }\n | {\n type: \"GET_SNAPSHOT\";\n options?: DistributableSnapshotOptions;\n requestId: string;\n }\n | { type: \"INSPECT\"; requestId: string }\n | { type: \"SETTLE\"; timeout?: number; requestId: string };\n\n/** Messages sent from worker to main thread */\nexport type WorkerOutboundMessage =\n | { type: \"READY\" }\n | { type: \"STARTED\" }\n | { type: \"STOPPED\" }\n | { type: \"DESTROYED\" }\n | { type: \"FACT_CHANGED\"; key: string; value: unknown; prev: unknown }\n | { type: \"DERIVATION_CHANGED\"; key: string; value: unknown }\n | { type: \"REQUIREMENT_CREATED\"; requirement: Requirement & { id: string } }\n | { type: \"REQUIREMENT_MET\"; requirementId: string; resolverId: string }\n | { type: \"ERROR\"; error: string; source?: string }\n | {\n type: \"SNAPSHOT_RESULT\";\n requestId: string;\n snapshot: DistributableSnapshot;\n }\n | { type: \"INSPECT_RESULT\"; requestId: string; inspection: SystemInspection }\n | {\n type: \"SETTLE_RESULT\";\n requestId: string;\n success: boolean;\n error?: string;\n };\n\n// ============================================================================\n// Worker System Config\n// ============================================================================\n\n/**\n * Configuration for creating a system inside a worker.\n * Note: Functions cannot be serialized, so modules must be defined\n * in the worker script itself using createWorkerModule.\n */\nexport interface WorkerSystemConfig {\n /** Module names to initialize (modules must be registered in worker) */\n moduleNames: string[];\n /** History configuration for snapshot-based state history */\n history?:\n | boolean\n | {\n maxSnapshots?: number;\n };\n}\n\n// ============================================================================\n// Main Thread API\n// ============================================================================\n\n/**\n * Options for creating a worker client.\n */\nexport interface WorkerClientOptions {\n /** The web worker instance */\n worker: Worker;\n /** Callback when a fact changes in the worker */\n onFactChange?: (key: string, value: unknown, prev: unknown) => void;\n /** Callback when a derivation changes in the worker */\n onDerivationChange?: (key: string, value: unknown) => void;\n /** Callback when a requirement is created */\n onRequirementCreated?: (requirement: Requirement & { id: string }) => void;\n /** Callback when a requirement is met */\n onRequirementMet?: (requirementId: string, resolverId: string) => void;\n /** Callback when an error occurs */\n onError?: (error: string, source?: string) => void;\n}\n\n/**\n * Client for interacting with a Directive system running in a Web Worker.\n */\nexport interface WorkerClient {\n /** Initialize the worker system */\n init(config: WorkerSystemConfig): Promise<void>;\n /** Start the worker system */\n start(): Promise<void>;\n /** Stop the worker system */\n stop(): Promise<void>;\n /** Destroy the worker system and terminate the worker */\n destroy(): Promise<void>;\n /** Set a single fact */\n setFact(key: string, value: unknown): void;\n /** Set multiple facts at once */\n setFacts(facts: Record<string, unknown>): void;\n /** Dispatch an event */\n dispatch(event: { type: string; [key: string]: unknown }): void;\n /** Get a distributable snapshot */\n getSnapshot(\n options?: DistributableSnapshotOptions,\n ): Promise<DistributableSnapshot>;\n /** Inspect the system state */\n inspect(): Promise<SystemInspection>;\n /** Wait for the system to settle */\n settle(timeout?: number): Promise<void>;\n /** Terminate the worker */\n terminate(): void;\n}\n\n/**\n * Create a client for communicating with a Directive worker.\n *\n * @example\n * ```typescript\n * // main.ts\n * const worker = new Worker(new URL('./directive.worker.ts', import.meta.url));\n * const client = createWorkerClient({\n * worker,\n * onFactChange: (key, value) => console.log(`Fact ${key} = ${value}`),\n * });\n *\n * await client.init({ moduleNames: ['myModule'] });\n * await client.start();\n * client.setFact('userId', '123');\n * ```\n */\nexport function createWorkerClient(options: WorkerClientOptions): WorkerClient {\n const {\n worker,\n onFactChange,\n onDerivationChange,\n onRequirementCreated,\n onRequirementMet,\n onError,\n } = options;\n\n // Pending request callbacks\n const pendingRequests = new Map<\n string,\n { resolve: (value: unknown) => void; reject: (error: Error) => void }\n >();\n let requestIdCounter = 0;\n\n // Promise resolvers for lifecycle events\n let initResolve: (() => void) | null = null;\n let startResolve: (() => void) | null = null;\n let stopResolve: (() => void) | null = null;\n let destroyResolve: (() => void) | null = null;\n\n // ---- Outbound message handlers ----\n\n function resolveLifecycle(\n resolve: (() => void) | null,\n ): (() => void) | null {\n resolve?.();\n\n return null;\n }\n\n function resolvePendingRequest(requestId: string, value: unknown): void {\n const pending = pendingRequests.get(requestId);\n if (pending) {\n pending.resolve(value);\n pendingRequests.delete(requestId);\n }\n }\n\n function handleReady(): void {\n initResolve = resolveLifecycle(initResolve);\n }\n\n function handleStarted(): void {\n startResolve = resolveLifecycle(startResolve);\n }\n\n function handleStopped(): void {\n stopResolve = resolveLifecycle(stopResolve);\n }\n\n function handleDestroyed(): void {\n destroyResolve = resolveLifecycle(destroyResolve);\n }\n\n function handleFactChanged(message: Extract<WorkerOutboundMessage, { type: \"FACT_CHANGED\" }>): void {\n onFactChange?.(message.key, message.value, message.prev);\n }\n\n function handleDerivationChanged(message: Extract<WorkerOutboundMessage, { type: \"DERIVATION_CHANGED\" }>): void {\n onDerivationChange?.(message.key, message.value);\n }\n\n function handleRequirementCreated(message: Extract<WorkerOutboundMessage, { type: \"REQUIREMENT_CREATED\" }>): void {\n onRequirementCreated?.(message.requirement);\n }\n\n function handleRequirementMet(message: Extract<WorkerOutboundMessage, { type: \"REQUIREMENT_MET\" }>): void {\n onRequirementMet?.(message.requirementId, message.resolverId);\n }\n\n function handleError(message: Extract<WorkerOutboundMessage, { type: \"ERROR\" }>): void {\n onError?.(message.error, message.source);\n }\n\n function handleSnapshotResult(message: Extract<WorkerOutboundMessage, { type: \"SNAPSHOT_RESULT\" }>): void {\n resolvePendingRequest(message.requestId, message.snapshot);\n }\n\n function handleInspectResult(message: Extract<WorkerOutboundMessage, { type: \"INSPECT_RESULT\" }>): void {\n resolvePendingRequest(message.requestId, message.inspection);\n }\n\n function handleSettleResult(message: Extract<WorkerOutboundMessage, { type: \"SETTLE_RESULT\" }>): void {\n const pending = pendingRequests.get(message.requestId);\n if (pending) {\n if (message.success) {\n pending.resolve(undefined);\n } else {\n pending.reject(new Error(message.error || \"Settle failed\"));\n }\n pendingRequests.delete(message.requestId);\n }\n }\n\n // Handle messages from worker\n worker.onmessage = (event: MessageEvent<WorkerOutboundMessage>) => {\n const message = event.data;\n\n switch (message.type) {\n case \"READY\": return handleReady();\n case \"STARTED\": return handleStarted();\n case \"STOPPED\": return handleStopped();\n case \"DESTROYED\": return handleDestroyed();\n case \"FACT_CHANGED\": return handleFactChanged(message);\n case \"DERIVATION_CHANGED\": return handleDerivationChanged(message);\n case \"REQUIREMENT_CREATED\": return handleRequirementCreated(message);\n case \"REQUIREMENT_MET\": return handleRequirementMet(message);\n case \"ERROR\": return handleError(message);\n case \"SNAPSHOT_RESULT\": return handleSnapshotResult(message);\n case \"INSPECT_RESULT\": return handleInspectResult(message);\n case \"SETTLE_RESULT\": return handleSettleResult(message);\n }\n };\n\n worker.onerror = (event) => {\n onError?.(event.message, \"worker\");\n };\n\n function send(message: WorkerInboundMessage): void {\n worker.postMessage(message);\n }\n\n function request<T>(\n message: WorkerInboundMessage & { requestId: string },\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n pendingRequests.set(message.requestId, {\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n send(message);\n });\n }\n\n return {\n init(config: WorkerSystemConfig): Promise<void> {\n return new Promise((resolve) => {\n initResolve = resolve;\n send({ type: \"INIT\", config });\n });\n },\n\n start(): Promise<void> {\n return new Promise((resolve) => {\n startResolve = resolve;\n send({ type: \"START\" });\n });\n },\n\n stop(): Promise<void> {\n return new Promise((resolve) => {\n stopResolve = resolve;\n send({ type: \"STOP\" });\n });\n },\n\n destroy(): Promise<void> {\n return new Promise((resolve) => {\n destroyResolve = resolve;\n send({ type: \"DESTROY\" });\n });\n },\n\n setFact(key: string, value: unknown): void {\n send({ type: \"SET_FACT\", key, value });\n },\n\n setFacts(facts: Record<string, unknown>): void {\n send({ type: \"SET_FACTS\", facts });\n },\n\n dispatch(event: { type: string; [key: string]: unknown }): void {\n send({ type: \"DISPATCH\", event });\n },\n\n getSnapshot(\n options?: DistributableSnapshotOptions,\n ): Promise<DistributableSnapshot> {\n const requestId = `snapshot-${++requestIdCounter}`;\n return request({ type: \"GET_SNAPSHOT\", options, requestId });\n },\n\n inspect(): Promise<SystemInspection> {\n const requestId = `inspect-${++requestIdCounter}`;\n return request({ type: \"INSPECT\", requestId });\n },\n\n settle(timeout?: number): Promise<void> {\n const requestId = `settle-${++requestIdCounter}`;\n return request({ type: \"SETTLE\", timeout, requestId });\n },\n\n terminate(): void {\n worker.terminate();\n },\n };\n}\n\n// ============================================================================\n// Worker-Side API\n// ============================================================================\n\n/**\n * Module registration for worker-side systems.\n * Since functions can't be serialized, modules must be registered in the worker.\n */\n// biome-ignore lint/suspicious/noExplicitAny: Module types vary\ntype ModuleRegistry = Map<string, any>;\n\nlet workerModuleRegistry: ModuleRegistry | null = null;\n\n/**\n * Get or create the module registry for worker-side modules.\n */\nexport function getWorkerModuleRegistry(): ModuleRegistry {\n if (!workerModuleRegistry) {\n workerModuleRegistry = new Map();\n }\n return workerModuleRegistry;\n}\n\n/**\n * Register a module for use in workers.\n * Call this in your worker script before handling INIT messages.\n *\n * @example\n * ```typescript\n * // directive.worker.ts\n * import { registerWorkerModule, handleWorkerMessages } from '@directive-run/core/worker';\n * import { myModule } from './modules/my-module';\n *\n * registerWorkerModule('myModule', myModule);\n * handleWorkerMessages();\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Module type varies\nexport function registerWorkerModule(name: string, module: any): void {\n getWorkerModuleRegistry().set(name, module);\n}\n\n/**\n * Handler for worker-side message processing.\n * Sets up the message listener and creates/manages the Directive system.\n *\n * @example\n * ```typescript\n * // directive.worker.ts\n * import { registerWorkerModule, handleWorkerMessages } from '@directive-run/core/worker';\n *\n * registerWorkerModule('myModule', myModule);\n * handleWorkerMessages();\n * ```\n */\nexport function handleWorkerMessages(): void {\n // Dynamic import to avoid issues in non-worker contexts\n // The actual system creation happens when messages are received\n type WorkerSystem = Awaited<ReturnType<typeof createWorkerSystem>>;\n let system: WorkerSystem | null = null;\n\n // ---- Inbound message handlers ----\n\n async function handleInit(\n message: Extract<WorkerInboundMessage, { type: \"INIT\" }>,\n ): Promise<WorkerSystem> {\n const created = await createWorkerSystem(message.config);\n postMessage({ type: \"READY\" } satisfies WorkerOutboundMessage);\n\n return created;\n }\n\n function handleStart(sys: WorkerSystem): void {\n sys.start();\n postMessage({ type: \"STARTED\" } satisfies WorkerOutboundMessage);\n }\n\n function handleStop(sys: WorkerSystem): void {\n sys.stop();\n postMessage({ type: \"STOPPED\" } satisfies WorkerOutboundMessage);\n }\n\n function handleDestroy(sys: WorkerSystem): void {\n sys.destroy();\n postMessage({ type: \"DESTROYED\" } satisfies WorkerOutboundMessage);\n }\n\n function handleGetSnapshot(\n sys: WorkerSystem,\n message: Extract<WorkerInboundMessage, { type: \"GET_SNAPSHOT\" }>,\n ): void {\n const snapshot = sys.getSnapshot(message.options);\n postMessage({\n type: \"SNAPSHOT_RESULT\",\n requestId: message.requestId,\n snapshot,\n } satisfies WorkerOutboundMessage);\n }\n\n function handleInspect(\n sys: WorkerSystem,\n message: Extract<WorkerInboundMessage, { type: \"INSPECT\" }>,\n ): void {\n const inspection = sys.inspect();\n postMessage({\n type: \"INSPECT_RESULT\",\n requestId: message.requestId,\n inspection,\n } satisfies WorkerOutboundMessage);\n }\n\n async function handleSettle(\n sys: WorkerSystem,\n message: Extract<WorkerInboundMessage, { type: \"SETTLE\" }>,\n ): Promise<void> {\n try {\n await sys.settle(message.timeout);\n postMessage({\n type: \"SETTLE_RESULT\",\n requestId: message.requestId,\n success: true,\n } satisfies WorkerOutboundMessage);\n } catch (error) {\n postMessage({\n type: \"SETTLE_RESULT\",\n requestId: message.requestId,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n } satisfies WorkerOutboundMessage);\n }\n }\n\n // ---- Message dispatch ----\n\n async function dispatchMessage(\n message: WorkerInboundMessage,\n ): Promise<void> {\n if (message.type === \"INIT\") {\n system = await handleInit(message);\n\n return;\n }\n\n if (!system) {\n return;\n }\n\n switch (message.type) {\n case \"START\":\n handleStart(system);\n break;\n case \"STOP\":\n handleStop(system);\n break;\n case \"DESTROY\":\n handleDestroy(system);\n system = null;\n break;\n case \"SET_FACT\":\n system.setFact(message.key, message.value);\n break;\n case \"SET_FACTS\":\n system.setFacts(message.facts);\n break;\n case \"DISPATCH\":\n system.dispatch(message.event);\n break;\n case \"GET_SNAPSHOT\":\n handleGetSnapshot(system, message);\n break;\n case \"INSPECT\":\n handleInspect(system, message);\n break;\n case \"SETTLE\":\n await handleSettle(system, message);\n break;\n }\n }\n\n self.onmessage = async (event: MessageEvent<WorkerInboundMessage>) => {\n try {\n await dispatchMessage(event.data);\n } catch (error) {\n postMessage({\n type: \"ERROR\",\n error: error instanceof Error ? error.message : String(error),\n source: event.data.type,\n } satisfies WorkerOutboundMessage);\n }\n };\n}\n\n/**\n * Internal: Create a system inside the worker.\n */\nasync function createWorkerSystem(config: WorkerSystemConfig) {\n // Dynamically import createSystem to avoid circular dependencies\n const { createSystem } = await import(\"../core/system.js\");\n\n const registry = getWorkerModuleRegistry();\n const modules: Record<string, unknown> = {};\n\n for (const name of config.moduleNames) {\n const module = registry.get(name);\n if (!module) {\n throw new Error(\n `[Directive Worker] Module \"${name}\" not registered. ` +\n `Call registerWorkerModule('${name}', module) before handling messages.`,\n );\n }\n modules[name] = module;\n }\n\n // Create tracking plugin to notify main thread\n const trackingPlugin = {\n name: \"__worker-tracking__\",\n onFactSet: (key: string, value: unknown, prev: unknown) => {\n postMessage({\n type: \"FACT_CHANGED\",\n key,\n value,\n prev,\n } satisfies WorkerOutboundMessage);\n },\n onDerivationCompute: (id: string, value: unknown) => {\n postMessage({\n type: \"DERIVATION_CHANGED\",\n key: id,\n value,\n } satisfies WorkerOutboundMessage);\n },\n onRequirementCreated: (req: { id: string; requirement: Requirement }) => {\n postMessage({\n type: \"REQUIREMENT_CREATED\",\n requirement: { ...req.requirement, id: req.id },\n } satisfies WorkerOutboundMessage);\n },\n onRequirementMet: (req: { id: string }, resolverId: string) => {\n postMessage({\n type: \"REQUIREMENT_MET\",\n requirementId: req.id,\n resolverId,\n } satisfies WorkerOutboundMessage);\n },\n };\n\n const system = createSystem({\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic module types\n modules: modules as any,\n plugins: [trackingPlugin],\n history: config.history,\n });\n\n return {\n start: () => system.start(),\n stop: () => system.stop(),\n destroy: () => system.destroy(),\n setFact: (key: string, value: unknown) => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic facts access\n (system.facts as any)[key] = value;\n },\n setFacts: (facts: Record<string, unknown>) => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic facts access\n const factsProxy = system.facts as any;\n if (factsProxy.$store?.batch) {\n factsProxy.$store.batch(() => {\n for (const [key, value] of Object.entries(facts)) {\n factsProxy[key] = value;\n }\n });\n } else {\n // Fallback: set facts one by one\n for (const [key, value] of Object.entries(facts)) {\n factsProxy[key] = value;\n }\n }\n },\n dispatch: (event: { type: string }) => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic dispatch\n (system as any).dispatch(event);\n },\n getSnapshot: (options?: DistributableSnapshotOptions) => {\n return system.getDistributableSnapshot(options);\n },\n inspect: () => system.inspect(),\n settle: (timeout?: number) => system.settle(timeout),\n };\n}\n\n// ============================================================================\n// Type Helpers\n// ============================================================================\n\n/**\n * Type helper for creating type-safe worker clients.\n * Use this to get proper typing for facts and events.\n *\n * @example\n * ```typescript\n * type MyWorkerClient = TypedWorkerClient<typeof myModuleSchema>;\n * const client = createWorkerClient(options) as MyWorkerClient;\n * client.setFact('userId', '123'); // Type-checked!\n * ```\n */\nexport type TypedWorkerClient<M extends ModuleSchema> = Omit<\n WorkerClient,\n \"setFact\" | \"setFacts\" | \"dispatch\"\n> & {\n setFact<K extends keyof M[\"facts\"]>(\n key: K,\n value: M[\"facts\"][K] extends { _type: infer T } ? T : M[\"facts\"][K],\n ): void;\n setFacts(\n facts: Partial<{\n [K in keyof M[\"facts\"]]: M[\"facts\"][K] extends { _type: infer T }\n ? T\n : M[\"facts\"][K];\n }>,\n ): void;\n dispatch(\n event: M[\"events\"] extends Record<string, unknown>\n ? {\n [K in keyof M[\"events\"]]: { type: K } & M[\"events\"][K];\n }[keyof M[\"events\"]]\n : { type: string },\n ): void;\n};\n"]}
1
+ {"version":3,"sources":["../src/adapters/worker.ts"],"names":["createWorkerClient","options","worker","onFactChange","onDerivationChange","onRequirementCreated","onRequirementMet","onError","pendingRequests","requestIdCounter","initResolve","startResolve","stopResolve","destroyResolve","resolveLifecycle","resolve","resolvePendingRequest","requestId","value","pending","handleReady","handleStarted","handleStopped","handleDestroyed","handleFactChanged","message","handleDerivationChanged","handleRequirementCreated","handleRequirementMet","handleError","handleSnapshotResult","handleInspectResult","handleSettleResult","event","send","request","reject","config","key","facts","timeout","workerModuleRegistry","getWorkerModuleRegistry","registerWorkerModule","name","module","handleWorkerMessages","system","handleInit","created","createWorkerSystem","handleStart","sys","handleStop","handleDestroy","handleGetSnapshot","snapshot","handleInspect","inspection","handleSettle","error","dispatchMessage","createSystem","registry","modules","prev","id","req","resolverId","factsProxy"],"mappings":"AAwJO,SAASA,CAAAA,CAAmBC,CAAAA,CAA4C,CAC7E,GAAM,CACJ,MAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,kBAAA,CAAAC,CAAAA,CACA,oBAAA,CAAAC,CAAAA,CACA,gBAAA,CAAAC,CAAAA,CACA,OAAA,CAAAC,CACF,CAAA,CAAIN,CAAAA,CAGEO,CAAAA,CAAkB,IAAI,GAAA,CAIxBC,CAAAA,CAAmB,CAAA,CAGnBC,CAAAA,CAAmC,IAAA,CACnCC,CAAAA,CAAoC,IAAA,CACpCC,EAAmC,IAAA,CACnCC,CAAAA,CAAsC,IAAA,CAI1C,SAASC,CAAAA,CAAiBC,CAAAA,CAAmD,CAC3E,OAAAA,CAAAA,IAAU,CAEH,IACT,CAEA,SAASC,CAAAA,CAAsBC,CAAAA,CAAmBC,CAAAA,CAAsB,CACtE,IAAMC,CAAAA,CAAUX,CAAAA,CAAgB,GAAA,CAAIS,CAAS,CAAA,CACzCE,CAAAA,GACFA,CAAAA,CAAQ,OAAA,CAAQD,CAAK,CAAA,CACrBV,CAAAA,CAAgB,MAAA,CAAOS,CAAS,CAAA,EAEpC,CAEA,SAASG,CAAAA,EAAoB,CAC3BV,CAAAA,CAAcI,CAAAA,CAAiBJ,CAAW,EAC5C,CAEA,SAASW,CAAAA,EAAsB,CAC7BV,CAAAA,CAAeG,CAAAA,CAAiBH,CAAY,EAC9C,CAEA,SAASW,CAAAA,EAAsB,CAC7BV,CAAAA,CAAcE,CAAAA,CAAiBF,CAAW,EAC5C,CAEA,SAASW,CAAAA,EAAwB,CAC/BV,CAAAA,CAAiBC,CAAAA,CAAiBD,CAAc,EAClD,CAEA,SAASW,CAAAA,CACPC,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\n *\n * Features:\n * - Run computations in a dedicated worker\n * - Synchronized state between main thread and worker\n * - Automatic serialization of facts and derivations\n * - Event-based communication\n */\n\nimport type {\n DistributableSnapshot,\n DistributableSnapshotOptions,\n ModuleSchema,\n Requirement,\n SystemInspection,\n} from \"../core/types.js\";\n\n// ============================================================================\n// Message Types\n// ============================================================================\n\n/** Messages sent from main thread to worker */\nexport type WorkerInboundMessage =\n | { type: \"INIT\"; config: WorkerSystemConfig }\n | { type: \"START\" }\n | { type: \"STOP\" }\n | { type: \"DESTROY\" }\n | { type: \"SET_FACT\"; key: string; value: unknown }\n | { type: \"SET_FACTS\"; facts: Record<string, unknown> }\n | { type: \"DISPATCH\"; event: { type: string; [key: string]: unknown } }\n | {\n type: \"GET_SNAPSHOT\";\n options?: DistributableSnapshotOptions;\n requestId: string;\n }\n | { type: \"INSPECT\"; requestId: string }\n | { type: \"SETTLE\"; timeout?: number; requestId: string };\n\n/** Messages sent from worker to main thread */\nexport type WorkerOutboundMessage =\n | { type: \"READY\" }\n | { type: \"STARTED\" }\n | { type: \"STOPPED\" }\n | { type: \"DESTROYED\" }\n | { type: \"FACT_CHANGED\"; key: string; value: unknown; prev: unknown }\n | { type: \"DERIVATION_CHANGED\"; key: string; value: unknown }\n | { type: \"REQUIREMENT_CREATED\"; requirement: Requirement & { id: string } }\n | { type: \"REQUIREMENT_MET\"; requirementId: string; resolverId: string }\n | { type: \"ERROR\"; error: string; source?: string }\n | {\n type: \"SNAPSHOT_RESULT\";\n requestId: string;\n snapshot: DistributableSnapshot;\n }\n | { type: \"INSPECT_RESULT\"; requestId: string; inspection: SystemInspection }\n | {\n type: \"SETTLE_RESULT\";\n requestId: string;\n success: boolean;\n error?: string;\n };\n\n// ============================================================================\n// Worker System Config\n// ============================================================================\n\n/**\n * Configuration for creating a system inside a worker.\n * Note: Functions cannot be serialized, so modules must be defined\n * in the worker script itself using createWorkerModule.\n */\nexport interface WorkerSystemConfig {\n /** Module names to initialize (modules must be registered in worker) */\n moduleNames: string[];\n /** History configuration for snapshot-based state history */\n history?:\n | boolean\n | {\n maxSnapshots?: number;\n };\n}\n\n// ============================================================================\n// Main Thread API\n// ============================================================================\n\n/**\n * Options for creating a worker client.\n */\nexport interface WorkerClientOptions {\n /** The web worker instance */\n worker: Worker;\n /** Callback when a fact changes in the worker */\n onFactChange?: (key: string, value: unknown, prev: unknown) => void;\n /** Callback when a derivation changes in the worker */\n onDerivationChange?: (key: string, value: unknown) => void;\n /** Callback when a requirement is created */\n onRequirementCreated?: (requirement: Requirement & { id: string }) => void;\n /** Callback when a requirement is met */\n onRequirementMet?: (requirementId: string, resolverId: string) => void;\n /** Callback when an error occurs */\n onError?: (error: string, source?: string) => void;\n}\n\n/**\n * Client for interacting with a Directive system running in a Web Worker.\n */\nexport interface WorkerClient {\n /** Initialize the worker system */\n init(config: WorkerSystemConfig): Promise<void>;\n /** Start the worker system */\n start(): Promise<void>;\n /** Stop the worker system */\n stop(): Promise<void>;\n /** Destroy the worker system and terminate the worker */\n destroy(): Promise<void>;\n /** Set a single fact */\n setFact(key: string, value: unknown): void;\n /** Set multiple facts at once */\n setFacts(facts: Record<string, unknown>): void;\n /** Dispatch an event */\n dispatch(event: { type: string; [key: string]: unknown }): void;\n /** Get a distributable snapshot */\n getSnapshot(\n options?: DistributableSnapshotOptions,\n ): Promise<DistributableSnapshot>;\n /** Inspect the system state */\n inspect(): Promise<SystemInspection>;\n /** Wait for the system to settle */\n settle(timeout?: number): Promise<void>;\n /** Terminate the worker */\n terminate(): void;\n}\n\n/**\n * Create a client for communicating with a Directive worker.\n *\n * @example\n * ```typescript\n * // main.ts\n * const worker = new Worker(new URL('./directive.worker.ts', import.meta.url));\n * const client = createWorkerClient({\n * worker,\n * onFactChange: (key, value) => console.log(`Fact ${key} = ${value}`),\n * });\n *\n * await client.init({ moduleNames: ['myModule'] });\n * await client.start();\n * client.setFact('userId', '123');\n * ```\n */\nexport function createWorkerClient(options: WorkerClientOptions): WorkerClient {\n const {\n worker,\n onFactChange,\n onDerivationChange,\n onRequirementCreated,\n onRequirementMet,\n onError,\n } = options;\n\n // Pending request callbacks\n const pendingRequests = new Map<\n string,\n { resolve: (value: unknown) => void; reject: (error: Error) => void }\n >();\n let requestIdCounter = 0;\n\n // Promise resolvers for lifecycle events\n let initResolve: (() => void) | null = null;\n let startResolve: (() => void) | null = null;\n let stopResolve: (() => void) | null = null;\n let destroyResolve: (() => void) | null = null;\n\n // ---- Outbound message handlers ----\n\n function resolveLifecycle(resolve: (() => void) | null): (() => void) | null {\n resolve?.();\n\n return null;\n }\n\n function resolvePendingRequest(requestId: string, value: unknown): void {\n const pending = pendingRequests.get(requestId);\n if (pending) {\n pending.resolve(value);\n pendingRequests.delete(requestId);\n }\n }\n\n function handleReady(): void {\n initResolve = resolveLifecycle(initResolve);\n }\n\n function handleStarted(): void {\n startResolve = resolveLifecycle(startResolve);\n }\n\n function handleStopped(): void {\n stopResolve = resolveLifecycle(stopResolve);\n }\n\n function handleDestroyed(): void {\n destroyResolve = resolveLifecycle(destroyResolve);\n }\n\n function handleFactChanged(\n message: Extract<WorkerOutboundMessage, { type: \"FACT_CHANGED\" }>,\n ): void {\n onFactChange?.(message.key, message.value, message.prev);\n }\n\n function handleDerivationChanged(\n message: Extract<WorkerOutboundMessage, { type: \"DERIVATION_CHANGED\" }>,\n ): void {\n onDerivationChange?.(message.key, message.value);\n }\n\n function handleRequirementCreated(\n message: Extract<WorkerOutboundMessage, { type: \"REQUIREMENT_CREATED\" }>,\n ): void {\n onRequirementCreated?.(message.requirement);\n }\n\n function handleRequirementMet(\n message: Extract<WorkerOutboundMessage, { type: \"REQUIREMENT_MET\" }>,\n ): void {\n onRequirementMet?.(message.requirementId, message.resolverId);\n }\n\n function handleError(\n message: Extract<WorkerOutboundMessage, { type: \"ERROR\" }>,\n ): void {\n onError?.(message.error, message.source);\n }\n\n function handleSnapshotResult(\n message: Extract<WorkerOutboundMessage, { type: \"SNAPSHOT_RESULT\" }>,\n ): void {\n resolvePendingRequest(message.requestId, message.snapshot);\n }\n\n function handleInspectResult(\n message: Extract<WorkerOutboundMessage, { type: \"INSPECT_RESULT\" }>,\n ): void {\n resolvePendingRequest(message.requestId, message.inspection);\n }\n\n function handleSettleResult(\n message: Extract<WorkerOutboundMessage, { type: \"SETTLE_RESULT\" }>,\n ): void {\n const pending = pendingRequests.get(message.requestId);\n if (pending) {\n if (message.success) {\n pending.resolve(undefined);\n } else {\n pending.reject(new Error(message.error || \"Settle failed\"));\n }\n pendingRequests.delete(message.requestId);\n }\n }\n\n // Handle messages from worker\n worker.onmessage = (event: MessageEvent<WorkerOutboundMessage>) => {\n const message = event.data;\n\n switch (message.type) {\n case \"READY\":\n return handleReady();\n case \"STARTED\":\n return handleStarted();\n case \"STOPPED\":\n return handleStopped();\n case \"DESTROYED\":\n return handleDestroyed();\n case \"FACT_CHANGED\":\n return handleFactChanged(message);\n case \"DERIVATION_CHANGED\":\n return handleDerivationChanged(message);\n case \"REQUIREMENT_CREATED\":\n return handleRequirementCreated(message);\n case \"REQUIREMENT_MET\":\n return handleRequirementMet(message);\n case \"ERROR\":\n return handleError(message);\n case \"SNAPSHOT_RESULT\":\n return handleSnapshotResult(message);\n case \"INSPECT_RESULT\":\n return handleInspectResult(message);\n case \"SETTLE_RESULT\":\n return handleSettleResult(message);\n }\n };\n\n worker.onerror = (event) => {\n onError?.(event.message, \"worker\");\n };\n\n function send(message: WorkerInboundMessage): void {\n worker.postMessage(message);\n }\n\n function request<T>(\n message: WorkerInboundMessage & { requestId: string },\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n pendingRequests.set(message.requestId, {\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n send(message);\n });\n }\n\n return {\n init(config: WorkerSystemConfig): Promise<void> {\n return new Promise((resolve) => {\n initResolve = resolve;\n send({ type: \"INIT\", config });\n });\n },\n\n start(): Promise<void> {\n return new Promise((resolve) => {\n startResolve = resolve;\n send({ type: \"START\" });\n });\n },\n\n stop(): Promise<void> {\n return new Promise((resolve) => {\n stopResolve = resolve;\n send({ type: \"STOP\" });\n });\n },\n\n destroy(): Promise<void> {\n return new Promise((resolve) => {\n destroyResolve = resolve;\n send({ type: \"DESTROY\" });\n });\n },\n\n setFact(key: string, value: unknown): void {\n send({ type: \"SET_FACT\", key, value });\n },\n\n setFacts(facts: Record<string, unknown>): void {\n send({ type: \"SET_FACTS\", facts });\n },\n\n dispatch(event: { type: string; [key: string]: unknown }): void {\n send({ type: \"DISPATCH\", event });\n },\n\n getSnapshot(\n options?: DistributableSnapshotOptions,\n ): Promise<DistributableSnapshot> {\n const requestId = `snapshot-${++requestIdCounter}`;\n return request({ type: \"GET_SNAPSHOT\", options, requestId });\n },\n\n inspect(): Promise<SystemInspection> {\n const requestId = `inspect-${++requestIdCounter}`;\n return request({ type: \"INSPECT\", requestId });\n },\n\n settle(timeout?: number): Promise<void> {\n const requestId = `settle-${++requestIdCounter}`;\n return request({ type: \"SETTLE\", timeout, requestId });\n },\n\n terminate(): void {\n worker.terminate();\n },\n };\n}\n\n// ============================================================================\n// Worker-Side API\n// ============================================================================\n\n/**\n * Module registration for worker-side systems.\n * Since functions can't be serialized, modules must be registered in the worker.\n */\n// biome-ignore lint/suspicious/noExplicitAny: Module types vary\ntype ModuleRegistry = Map<string, any>;\n\nlet workerModuleRegistry: ModuleRegistry | null = null;\n\n/**\n * Get or create the module registry for worker-side modules.\n */\nexport function getWorkerModuleRegistry(): ModuleRegistry {\n if (!workerModuleRegistry) {\n workerModuleRegistry = new Map();\n }\n return workerModuleRegistry;\n}\n\n/**\n * Register a module for use in workers.\n * Call this in your worker script before handling INIT messages.\n *\n * @example\n * ```typescript\n * // directive.worker.ts\n * import { registerWorkerModule, handleWorkerMessages } from '@directive-run/core/worker';\n * import { myModule } from './modules/my-module';\n *\n * registerWorkerModule('myModule', myModule);\n * handleWorkerMessages();\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Module type varies\nexport function registerWorkerModule(name: string, module: any): void {\n getWorkerModuleRegistry().set(name, module);\n}\n\n/**\n * Handler for worker-side message processing.\n * Sets up the message listener and creates/manages the Directive system.\n *\n * @example\n * ```typescript\n * // directive.worker.ts\n * import { registerWorkerModule, handleWorkerMessages } from '@directive-run/core/worker';\n *\n * registerWorkerModule('myModule', myModule);\n * handleWorkerMessages();\n * ```\n */\nexport function handleWorkerMessages(): void {\n // Dynamic import to avoid issues in non-worker contexts\n // The actual system creation happens when messages are received\n type WorkerSystem = Awaited<ReturnType<typeof createWorkerSystem>>;\n let system: WorkerSystem | null = null;\n\n // ---- Inbound message handlers ----\n\n async function handleInit(\n message: Extract<WorkerInboundMessage, { type: \"INIT\" }>,\n ): Promise<WorkerSystem> {\n const created = await createWorkerSystem(message.config);\n postMessage({ type: \"READY\" } satisfies WorkerOutboundMessage);\n\n return created;\n }\n\n function handleStart(sys: WorkerSystem): void {\n sys.start();\n postMessage({ type: \"STARTED\" } satisfies WorkerOutboundMessage);\n }\n\n function handleStop(sys: WorkerSystem): void {\n sys.stop();\n postMessage({ type: \"STOPPED\" } satisfies WorkerOutboundMessage);\n }\n\n function handleDestroy(sys: WorkerSystem): void {\n sys.destroy();\n postMessage({ type: \"DESTROYED\" } satisfies WorkerOutboundMessage);\n }\n\n function handleGetSnapshot(\n sys: WorkerSystem,\n message: Extract<WorkerInboundMessage, { type: \"GET_SNAPSHOT\" }>,\n ): void {\n const snapshot = sys.getSnapshot(message.options);\n postMessage({\n type: \"SNAPSHOT_RESULT\",\n requestId: message.requestId,\n snapshot,\n } satisfies WorkerOutboundMessage);\n }\n\n function handleInspect(\n sys: WorkerSystem,\n message: Extract<WorkerInboundMessage, { type: \"INSPECT\" }>,\n ): void {\n const inspection = sys.inspect();\n postMessage({\n type: \"INSPECT_RESULT\",\n requestId: message.requestId,\n inspection,\n } satisfies WorkerOutboundMessage);\n }\n\n async function handleSettle(\n sys: WorkerSystem,\n message: Extract<WorkerInboundMessage, { type: \"SETTLE\" }>,\n ): Promise<void> {\n try {\n await sys.settle(message.timeout);\n postMessage({\n type: \"SETTLE_RESULT\",\n requestId: message.requestId,\n success: true,\n } satisfies WorkerOutboundMessage);\n } catch (error) {\n postMessage({\n type: \"SETTLE_RESULT\",\n requestId: message.requestId,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n } satisfies WorkerOutboundMessage);\n }\n }\n\n // ---- Message dispatch ----\n\n async function dispatchMessage(message: WorkerInboundMessage): Promise<void> {\n if (message.type === \"INIT\") {\n system = await handleInit(message);\n\n return;\n }\n\n if (!system) {\n return;\n }\n\n switch (message.type) {\n case \"START\":\n handleStart(system);\n break;\n case \"STOP\":\n handleStop(system);\n break;\n case \"DESTROY\":\n handleDestroy(system);\n system = null;\n break;\n case \"SET_FACT\":\n system.setFact(message.key, message.value);\n break;\n case \"SET_FACTS\":\n system.setFacts(message.facts);\n break;\n case \"DISPATCH\":\n system.dispatch(message.event);\n break;\n case \"GET_SNAPSHOT\":\n handleGetSnapshot(system, message);\n break;\n case \"INSPECT\":\n handleInspect(system, message);\n break;\n case \"SETTLE\":\n await handleSettle(system, message);\n break;\n }\n }\n\n self.onmessage = async (event: MessageEvent<WorkerInboundMessage>) => {\n try {\n await dispatchMessage(event.data);\n } catch (error) {\n postMessage({\n type: \"ERROR\",\n error: error instanceof Error ? error.message : String(error),\n source: event.data.type,\n } satisfies WorkerOutboundMessage);\n }\n };\n}\n\n/**\n * Internal: Create a system inside the worker.\n */\nasync function createWorkerSystem(config: WorkerSystemConfig) {\n // Dynamically import createSystem to avoid circular dependencies\n const { createSystem } = await import(\"../core/system.js\");\n\n const registry = getWorkerModuleRegistry();\n const modules: Record<string, unknown> = {};\n\n for (const name of config.moduleNames) {\n const module = registry.get(name);\n if (!module) {\n throw new Error(\n `[Directive Worker] Module \"${name}\" not registered. ` +\n `Call registerWorkerModule('${name}', module) before handling messages.`,\n );\n }\n modules[name] = module;\n }\n\n // Create tracking plugin to notify main thread\n const trackingPlugin = {\n name: \"__worker-tracking__\",\n onFactSet: (key: string, value: unknown, prev: unknown) => {\n postMessage({\n type: \"FACT_CHANGED\",\n key,\n value,\n prev,\n } satisfies WorkerOutboundMessage);\n },\n onDerivationCompute: (id: string, value: unknown) => {\n postMessage({\n type: \"DERIVATION_CHANGED\",\n key: id,\n value,\n } satisfies WorkerOutboundMessage);\n },\n onRequirementCreated: (req: { id: string; requirement: Requirement }) => {\n postMessage({\n type: \"REQUIREMENT_CREATED\",\n requirement: { ...req.requirement, id: req.id },\n } satisfies WorkerOutboundMessage);\n },\n onRequirementMet: (req: { id: string }, resolverId: string) => {\n postMessage({\n type: \"REQUIREMENT_MET\",\n requirementId: req.id,\n resolverId,\n } satisfies WorkerOutboundMessage);\n },\n };\n\n const system = createSystem({\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic module types\n modules: modules as any,\n plugins: [trackingPlugin],\n history: config.history,\n });\n\n return {\n start: () => system.start(),\n stop: () => system.stop(),\n destroy: () => system.destroy(),\n setFact: (key: string, value: unknown) => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic facts access\n (system.facts as any)[key] = value;\n },\n setFacts: (facts: Record<string, unknown>) => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic facts access\n const factsProxy = system.facts as any;\n if (factsProxy.$store?.batch) {\n factsProxy.$store.batch(() => {\n for (const [key, value] of Object.entries(facts)) {\n factsProxy[key] = value;\n }\n });\n } else {\n // Fallback: set facts one by one\n for (const [key, value] of Object.entries(facts)) {\n factsProxy[key] = value;\n }\n }\n },\n dispatch: (event: { type: string }) => {\n // biome-ignore lint/suspicious/noExplicitAny: Dynamic dispatch\n (system as any).dispatch(event);\n },\n getSnapshot: (options?: DistributableSnapshotOptions) => {\n return system.getDistributableSnapshot(options);\n },\n inspect: () => system.inspect(),\n settle: (timeout?: number) => system.settle(timeout),\n };\n}\n\n// ============================================================================\n// Type Helpers\n// ============================================================================\n\n/**\n * Type helper for creating type-safe worker clients.\n * Use this to get proper typing for facts and events.\n *\n * @example\n * ```typescript\n * type MyWorkerClient = TypedWorkerClient<typeof myModuleSchema>;\n * const client = createWorkerClient(options) as MyWorkerClient;\n * client.setFact('userId', '123'); // Type-checked!\n * ```\n */\nexport type TypedWorkerClient<M extends ModuleSchema> = Omit<\n WorkerClient,\n \"setFact\" | \"setFacts\" | \"dispatch\"\n> & {\n setFact<K extends keyof M[\"facts\"]>(\n key: K,\n value: M[\"facts\"][K] extends { _type: infer T } ? T : M[\"facts\"][K],\n ): void;\n setFacts(\n facts: Partial<{\n [K in keyof M[\"facts\"]]: M[\"facts\"][K] extends { _type: infer T }\n ? T\n : M[\"facts\"][K];\n }>,\n ): void;\n dispatch(\n event: M[\"events\"] extends Record<string, unknown>\n ? {\n [K in keyof M[\"events\"]]: { type: K } & M[\"events\"][K];\n }[keyof M[\"events\"]]\n : { type: string },\n ): void;\n};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@directive-run/core",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "imports": {
5
5
  "#is-development": {
6
6
  "production": "./src/dev-false.ts",
@@ -1 +0,0 @@
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","safeStringify","data","maxLen","_key"],"mappings":"AAcA,eAAsBA,CAAAA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CAAA,CACA,OAAKgC,CAAAA,CAGDA,CAAAA,CAAI,MAAA,EAAU6C,CAAAA,CACT7C,CAAAA,CAGF,CAAA,EAAGA,CAAAA,CAAI,KAAA,CAAM,CAAA,CAAG6C,CAAM,CAAC;AAAA,gBAAA,EAAqB7C,CAAAA,CAAI,MAAM,CAAA,aAAA,CAAA,CANpD,aAOX,MAAQ,CACN,OAAO,kBACT,CACF","file":"chunk-4CMO5OVZ.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\n/**\n * Safely stringify any value for display. Handles circular references,\n * BigInt, throwing toJSON, and optional truncation.\n *\n * This is the canonical implementation – all packages should import this\n * instead of maintaining local copies.\n */\nexport function safeStringify(\n data: unknown,\n maxLen = 500,\n): string {\n try {\n const str = JSON.stringify(\n data,\n (_key, value) => {\n if (typeof value === \"bigint\") {\n return `${value}n`;\n }\n\n return value;\n },\n 2,\n );\n if (!str) {\n return \"[undefined]\";\n }\n if (str.length <= maxLen) {\n return str;\n }\n\n return `${str.slice(0, maxLen)}\\n... (truncated, ${str.length} chars total)`;\n } catch {\n return \"[unserializable]\";\n }\n}\n"]}
@@ -1 +0,0 @@
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","safeStringify","data","maxLen","_key"],"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,I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AE,QAAA,CAAS,CAAA,CAAG,GAAG,CAAC,CAAA,CAC1C,IAAA,CAAK,EAAE,CACZ,CAMA,SAAS0C,CAAAA,CAAgB3C,CAAAA,CAAWC,EAAoB,CACtD,GAAID,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,CASO,SAASkE,EACdC,CAAAA,CACAC,CAAAA,CAAS,GAAA,CACD,CACR,GAAI,CACF,IAAM7C,CAAAA,CAAM,IAAA,CAAK,SAAA,CACf4C,CAAAA,CACA,CAACE,CAAAA,CAAM9E,CAAAA,GACD,OAAOA,CAAAA,EAAU,SACZ,CAAA,EAAGA,CAAK,CAAA,CAAA,CAAA,CAGVA,CAAAA,CAET,CACF,CAAA,CACA,OAAKgC,CAAAA,CAGDA,CAAAA,CAAI,MAAA,EAAU6C,CAAAA,CACT7C,CAAAA,CAGF,CAAA,EAAGA,CAAAA,CAAI,KAAA,CAAM,CAAA,CAAG6C,CAAM,CAAC;AAAA,gBAAA,EAAqB7C,CAAAA,CAAI,MAAM,CAAA,aAAA,CAAA,CANpD,aAOX,MAAQ,CACN,OAAO,kBACT,CACF","file":"chunk-BEJ6ICA7.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\n/**\n * Safely stringify any value for display. Handles circular references,\n * BigInt, throwing toJSON, and optional truncation.\n *\n * This is the canonical implementation – all packages should import this\n * instead of maintaining local copies.\n */\nexport function safeStringify(\n data: unknown,\n maxLen = 500,\n): string {\n try {\n const str = JSON.stringify(\n data,\n (_key, value) => {\n if (typeof value === \"bigint\") {\n return `${value}n`;\n }\n\n return value;\n },\n 2,\n );\n if (!str) {\n return \"[undefined]\";\n }\n if (str.length <= maxLen) {\n return str;\n }\n\n return `${str.slice(0, maxLen)}\\n... (truncated, ${str.length} chars total)`;\n } catch {\n return \"[unserializable]\";\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/core/types/adapter-utils.ts","../src/dev-true.ts","../src/core/tracking.ts"],"names":["setBridgeFact","facts","key","value","getBridgeFact","createCallbackPlugin","name","callbacks","req","requirementGuard","type","requirementGuardMultiple","types","typeSet","dev_true_default","depStack","getCurrentDeps","len","isTracking","withTracking","fn","deps","withoutTracking","saved","ctx","trackAccess","BLOCKED_PROPS","detectNonJsonValueType","proto","nonJsonWarningCache","nonJsonHints","warnNonJsonFactAssignment","factPath","valueType","cacheKey","hint"],"mappings":"aA8FO,SAASA,CAA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IACT,CASA,IAAMC,CAAAA,CAAsB,IAAI,GAAA,CAE1BC,CAAAA,CAAuC,CAC3C,IAAA,CAAM,2BAAA,CACN,GAAA,CAAK,qBAAA,CACL,IAAK,2CAAA,CACL,IAAA,CAAM,iDAAA,CACN,aAAA,CAAe,yBACjB,CAAA,CAeO,SAASC,CAAAA,CACdC,EACAC,CAAAA,CACM,CACN,IAAMC,CAAAA,CAAW,GAAGF,CAAQ,CAAA,CAAA,EAAIC,CAAS,CAAA,CAAA,CACzC,GAAIJ,CAAAA,CAAoB,GAAA,CAAIK,CAAQ,CAAA,CAClC,OAEFL,CAAAA,CAAoB,GAAA,CAAIK,CAAQ,CAAA,CAEhC,IAAMC,CAAAA,CAAOL,CAAAA,CAAaG,CAAS,CAAA,EAAK,8BACxC,OAAA,CAAQ,IAAA,CACN,CAAA,kBAAA,EAAqBD,CAAQ,gBAAgBC,CAAS,CAAA;AAAA;AAAA,EAEjDA,CAAS,CAAA;AAAA,IAAA,EACLE,CAAI,CAAA;AAAA,+CAAA,CAEf,EACF","file":"chunk-DDUARSUH.cjs","sourcesContent":["/**\n * Adapter Type Utilities - Shared types and helpers for framework adapters\n *\n * These utilities reduce type assertions in adapters by providing:\n * - Schema composition types\n * - Constraint/resolver converters\n * - Plugin factory helpers\n */\n\nimport type { Facts } from \"./facts.js\";\nimport type { Plugin } from \"./plugins.js\";\nimport type { ConstraintDef, Requirement } from \"./requirements.js\";\nimport type { ResolverContext, ResolverDef } from \"./resolvers.js\";\nimport type { InferSchema, Schema } from \"./schema.js\";\n\n// ============================================================================\n// Schema Composition Types\n// ============================================================================\n\n/**\n * Merge two schemas into one.\n * Useful for adapters that add bridge-specific facts to user schemas.\n *\n * @example\n * ```typescript\n * type BridgeFields = { __state: SchemaType<Record<string, unknown>> };\n * type Combined = MergedSchema<UserSchema, BridgeFields>;\n * ```\n */\nexport type MergedSchema<Base extends Schema, Extra extends Schema> = Base &\n Extra;\n\n/**\n * Create a schema type from a fields definition.\n * Helper for defining adapter bridge schemas.\n *\n * @example\n * ```typescript\n * type AdapterBridgeSchema = BridgeSchema<{\n * __adapterState: SchemaType<Record<string, unknown>>;\n * }>;\n * ```\n */\nexport type BridgeSchema<Fields extends Schema> = Fields;\n\n// ============================================================================\n// Bridge Schema Helper\n// ============================================================================\n\n/**\n * Create a bridge schema definition for adapters.\n * Returns a schema object compatible with createModule().\n *\n * @example\n * ```typescript\n * const bridgeSchema = createBridgeSchema({\n * __state: t.object<Record<string, unknown>>(),\n * });\n * ```\n */\nexport function createBridgeSchema<S extends Schema>(schema: S): S {\n return schema;\n}\n\n// ============================================================================\n// Type-Safe Fact Mutation\n// ============================================================================\n\n/**\n * Type-safe fact setter for known schema keys.\n * Use when you have a typed schema and want to set a specific fact.\n *\n * @example\n * ```typescript\n * setFact(facts, \"count\", 10); // Type-checked\n * ```\n */\nexport function setFact<S extends Schema, K extends keyof InferSchema<S>>(\n facts: Facts<S>,\n key: K,\n value: InferSchema<S>[K],\n): void {\n (facts as Record<string, unknown>)[key as string] = value;\n}\n\n/**\n * Set a bridge fact without strict typing.\n * Use for adapter-internal bridge fields like `__adapterState`.\n *\n * @example\n * ```typescript\n * setBridgeFact(facts, \"__adapterState\", currentState);\n * ```\n */\nexport function setBridgeFact<V>(\n facts: Facts<Schema>,\n key: string,\n value: V,\n): void {\n (facts as Record<string, unknown>)[key] = value;\n}\n\n/**\n * Get a bridge fact without strict typing.\n * Use for adapter-internal bridge fields.\n *\n * @example\n * ```typescript\n * const state = getBridgeFact<MyState>(facts, \"__adapterState\");\n * ```\n */\nexport function getBridgeFact<V>(facts: Facts<Schema>, key: string): V {\n return (facts as Record<string, unknown>)[key] as V;\n}\n\n// ============================================================================\n// Constraint Converters\n// ============================================================================\n\n/**\n * Adapter constraint definition (generic form used by adapters).\n */\nexport interface AdapterConstraint<TState> {\n when: (state: TState) => boolean | Promise<boolean>;\n require: Requirement | ((state: TState) => Requirement | null);\n priority?: number;\n}\n\n/**\n * Convert adapter-style constraints to Directive format.\n * Maps adapter constraints that work with external state (TState) to\n * Directive constraints that work with Facts<Schema>.\n *\n * @param constraints - Adapter constraints keyed by name\n * @param extractState - Function to extract adapter state from facts\n *\n * @example\n * ```typescript\n * const directiveConstraints = convertConstraints<MyState, BridgeSchema>(\n * adapterConstraints,\n * (facts) => getBridgeFact<MyState>(facts, \"__state\"),\n * );\n * ```\n */\nexport function convertConstraints<TState, S extends Schema>(\n constraints: Record<string, AdapterConstraint<TState>>,\n extractState: (facts: Facts<S>) => TState,\n): Record<string, ConstraintDef<S, Requirement>> {\n const result: Record<string, ConstraintDef<S, Requirement>> = {};\n\n for (const [id, constraint] of Object.entries(constraints)) {\n result[id] = {\n priority: constraint.priority ?? 0,\n when: (facts) => constraint.when(extractState(facts)),\n require: (facts) => {\n const req =\n typeof constraint.require === \"function\"\n ? constraint.require(extractState(facts))\n : constraint.require;\n return req;\n },\n };\n }\n\n return result;\n}\n\n// ============================================================================\n// Resolver Converters\n// ============================================================================\n\n/**\n * Adapter resolver context (generic form used by adapters).\n */\nexport interface AdapterResolverContext<TContext> {\n context: TContext;\n signal: AbortSignal;\n}\n\n/**\n * Adapter resolver definition (generic form used by adapters).\n */\nexport interface AdapterResolver<\n TContext,\n R extends Requirement = Requirement,\n> {\n requirement: (req: Requirement) => req is R;\n key?: (req: R) => string;\n resolve: (\n req: R,\n ctx: AdapterResolverContext<TContext>,\n ) => void | Promise<void>;\n}\n\n/**\n * Convert adapter-style resolvers to Directive format.\n * Maps adapter resolvers that work with external context (TContext) to\n * Directive resolvers that work with ResolverContext<Schema>.\n *\n * @param resolvers - Adapter resolvers keyed by name\n * @param createContext - Function to create adapter context from Directive context\n *\n * @example\n * ```typescript\n * const directiveResolvers = convertResolvers<MyContext, BridgeSchema>(\n * adapterResolvers,\n * (ctx) => ({\n * getState: () => getBridgeFact<MyState>(ctx.facts, \"__state\"),\n * setState: (update) => setBridgeFact(ctx.facts, \"__state\", update),\n * signal: ctx.signal,\n * }),\n * );\n * ```\n */\nexport function convertResolvers<TContext, S extends Schema>(\n resolvers: Record<string, AdapterResolver<TContext, Requirement>>,\n createContext: (ctx: ResolverContext<S>) => TContext,\n): Record<string, ResolverDef<S, Requirement>> {\n const result: Record<string, ResolverDef<S, Requirement>> = {};\n\n for (const [id, resolver] of Object.entries(resolvers)) {\n result[id] = {\n requirement: resolver.requirement,\n key: resolver.key,\n resolve: async (req, ctx) => {\n const adapterCtx = createContext(ctx);\n await resolver.resolve(req, {\n context: adapterCtx,\n signal: ctx.signal,\n });\n },\n };\n }\n\n return result;\n}\n\n// ============================================================================\n// Plugin Factory\n// ============================================================================\n\n/**\n * Callback definitions for adapter plugins.\n */\nexport interface AdapterCallbacks {\n onRequirementCreated?: (req: Requirement) => void;\n onRequirementResolved?: (req: Requirement) => void;\n onError?: (error: Error) => void;\n}\n\n/**\n * Create a callback plugin for adapter events.\n * Wraps adapter callbacks in a Directive plugin.\n *\n * @param name - Plugin name (for debugging)\n * @param callbacks - Callback functions to invoke\n *\n * @example\n * ```typescript\n * const callbackPlugin = createCallbackPlugin(\"adapter-callbacks\", {\n * onRequirementCreated: (req) => console.log(\"Created:\", req),\n * onRequirementResolved: (req) => console.log(\"Resolved:\", req),\n * });\n * ```\n */\n// biome-ignore lint/suspicious/noExplicitAny: Plugins work with any schema type\nexport function createCallbackPlugin(\n name: string,\n callbacks: AdapterCallbacks,\n): Plugin<any> {\n return {\n name,\n onRequirementCreated: callbacks.onRequirementCreated\n ? (req) => callbacks.onRequirementCreated!(req.requirement)\n : undefined,\n onRequirementMet: callbacks.onRequirementResolved\n ? (req) => callbacks.onRequirementResolved!(req.requirement)\n : undefined,\n onError: callbacks.onError,\n };\n}\n\n// ============================================================================\n// Module Config Helpers\n// ============================================================================\n\n/**\n * Cast constraints to the correct type for createModule.\n * Use this when TypeScript can't infer the constraint types correctly.\n */\nexport function asConstraints<S extends Schema>(\n constraints: Record<string, ConstraintDef<S, Requirement>>,\n): Record<string, ConstraintDef<S, Requirement>> {\n return constraints;\n}\n\n/**\n * Cast resolvers to the correct type for createModule.\n * Use this when TypeScript can't infer the resolver types correctly.\n */\nexport function asResolvers<S extends Schema>(\n resolvers: Record<string, ResolverDef<S, Requirement>>,\n): Record<string, ResolverDef<S, Requirement>> {\n return resolvers;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Create a type guard for a specific requirement type.\n * Simplifies the common pattern of checking req.type.\n *\n * @example\n * ```typescript\n * const isResetReq = requirementGuard<ResetReq>(\"RESET\");\n * // Use in resolver:\n * { requirement: isResetReq, resolve: ... }\n * ```\n */\nexport function requirementGuard<R extends Requirement>(\n type: R[\"type\"],\n): (req: Requirement) => req is R {\n return (req): req is R => req.type === type;\n}\n\n/**\n * Create a type guard that matches multiple requirement types.\n *\n * @example\n * ```typescript\n * const isDataReq = requirementGuardMultiple<FetchReq | RefreshReq>([\"FETCH\", \"REFRESH\"]);\n * ```\n */\nexport function requirementGuardMultiple<R extends Requirement>(\n types: Array<R[\"type\"]>,\n): (req: Requirement) => req is R {\n const typeSet = new Set(types);\n return (req): req is R => typeSet.has(req.type);\n}\n","export default true;\n","/**\n * Dependency tracking context for auto-tracking derivations\n *\n * Uses a stack-based approach to handle nested derivation computations.\n * When a derivation accesses a fact, the tracking context records it.\n */\n\n/** Stack of active dependency sets (bare Sets for zero-allocation hot path) */\nconst depStack: Set<string>[] = [];\n\n/**\n * Get the current dependency set, or null if not tracking.\n *\n * @returns The active dependency Set, or `null` if no tracking is active.\n *\n * @internal\n */\nexport function getCurrentDeps(): Set<string> | null {\n const len = depStack.length;\n return len === 0 ? null : depStack[len - 1]!;\n}\n\n/**\n * Check if dependency tracking is currently active.\n *\n * @returns `true` if inside a {@link withTracking} call, `false` otherwise.\n *\n * @internal\n */\nexport function isTracking(): boolean {\n return depStack.length > 0;\n}\n\n/**\n * Run a function with dependency tracking.\n *\n * @remarks\n * Pushes a fresh Set onto the stack, executes `fn`, then pops it.\n * Any fact reads inside `fn` are recorded as dependencies.\n * Nesting is supported — inner calls get their own independent Set.\n *\n * @param fn - The function to execute under tracking.\n * @returns An object with the computed `value` and a `deps` Set of accessed\n * fact keys.\n *\n * @internal\n */\nexport function withTracking<T>(fn: () => T): { value: T; deps: Set<string> } {\n const deps = new Set<string>();\n depStack.push(deps);\n\n try {\n const value = fn();\n return { value, deps };\n } finally {\n depStack.pop();\n }\n}\n\n/**\n * Run a function without tracking.\n *\n * @remarks\n * Temporarily clears the tracking stack so that fact reads inside `fn` do\n * not register as dependencies. The stack is restored after `fn` returns\n * (even on error). Useful for side-effect reads that should not trigger\n * derivation invalidation.\n *\n * @param fn - The function to execute without tracking.\n * @returns The return value of `fn`.\n *\n * @internal\n */\nexport function withoutTracking<T>(fn: () => T): T {\n const saved = depStack.splice(0, depStack.length);\n\n try {\n return fn();\n } finally {\n for (const ctx of saved) {\n depStack.push(ctx);\n }\n }\n}\n\n/**\n * Track a specific key in the current context.\n *\n * @remarks\n * No-op if no tracking context is active.\n *\n * @param key - The fact key to record as a dependency.\n *\n * @internal\n */\nexport function trackAccess(key: string): void {\n const len = depStack.length;\n if (len === 0) {\n return;\n }\n depStack[len - 1]!.add(key);\n}\n\n/**\n * Prototype pollution guard — shared across all proxy handlers.\n *\n * @remarks\n * Contains `__proto__`, `constructor`, and `prototype`. Every proxy `get`\n * and `has` trap checks this set and returns `undefined` / `false` for\n * matching keys, preventing prototype pollution via proxy-based objects.\n *\n * @internal\n */\nexport const BLOCKED_PROPS: ReadonlySet<string> = Object.freeze(\n new Set([\"__proto__\", \"constructor\", \"prototype\"]),\n);\n\n// ============================================================================\n// Non-JSON value-type detection (MIGRATION_FEEDBACK item 20)\n// ============================================================================\n\n/**\n * Detect whether `value` is a non-JSON-roundtrippable type whose mutations\n * the facts proxy cannot track for reactivity.\n *\n * Returns the kind label (`\"Date\"`, `\"Set\"`, `\"Map\"`, `\"File\"`, or\n * `\"ClassInstance\"`) when one is detected, or `null` for plain objects,\n * arrays, primitives, and `null`/`undefined`.\n *\n * The `File` check is SSR-safe: if the runtime has no `File` global the\n * branch is skipped without throwing.\n *\n * The `ClassInstance` check fires for any object whose prototype is not\n * `Object.prototype` and which is not an array — e.g. instances of user\n * classes whose mutations bypass reactivity.\n *\n * @internal\n */\nexport function detectNonJsonValueType(value: unknown): string | null {\n if (value === null || typeof value !== \"object\") {\n return null;\n }\n if (value instanceof Date) {\n return \"Date\";\n }\n if (value instanceof Set) {\n return \"Set\";\n }\n if (value instanceof Map) {\n return \"Map\";\n }\n if (typeof File !== \"undefined\" && value instanceof File) {\n return \"File\";\n }\n // Plain objects and arrays are JSON-friendly.\n if (Array.isArray(value)) {\n return null;\n }\n // Class instances: prototype is not Object.prototype.\n // Plain `{}` literals have prototype `Object.prototype`; objects created\n // via `Object.create(null)` have a `null` prototype which we treat as\n // \"plain\" (it's still JSON-roundtrippable).\n const proto = Object.getPrototypeOf(value);\n if (proto !== null && proto !== Object.prototype) {\n return \"ClassInstance\";\n }\n\n return null;\n}\n\n/**\n * Per-(path, valueType) dedupe cache — once a warning fires for a given\n * combo we never re-emit. Keeps the dev console quiet under loops that\n * assign the same Date 100 times in a row.\n *\n * @internal\n */\nconst nonJsonWarningCache = new Set<string>();\n\nconst nonJsonHints: Record<string, string> = {\n Date: \".getTime() for timestamps\",\n Set: \"[...set] for arrays\",\n Map: \"Object.fromEntries(map) for plain objects\",\n File: \"{ name, size, type, lastModified } for metadata\",\n ClassInstance: \"a plain-object snapshot\",\n};\n\n/**\n * Emit a one-time dev-mode warning when a non-JSON value is assigned to a\n * fact. Called from the proxy `set` traps in both `createFactsProxy`\n * (single-module / standalone facts) and `createModuleFactsProxy`\n * (system-namespaced facts). No-ops in production builds — the call sites\n * are gated on `isDevelopment` so this entire helper is tree-shakable.\n *\n * @param factPath - Display path for the warning (e.g. `auth.token` or\n * bare `token` for non-namespaced stores).\n * @param valueType - The label returned from {@link detectNonJsonValueType}.\n *\n * @internal\n */\nexport function warnNonJsonFactAssignment(\n factPath: string,\n valueType: string,\n): void {\n const cacheKey = `${factPath}|${valueType}`;\n if (nonJsonWarningCache.has(cacheKey)) {\n return;\n }\n nonJsonWarningCache.add(cacheKey);\n\n const hint = nonJsonHints[valueType] ?? \"a JSON-roundtrippable value\";\n console.warn(\n `[Directive] Fact \"${factPath}\" assigned a ${valueType} instance.\\n` +\n `Facts must be JSON-roundtrippable for reactivity to work correctly.\\n` +\n `${valueType} mutations are not tracked.\\n` +\n `Use ${hint} instead.\\n` +\n `See: https://directive.run/docs/facts#json-rule`,\n );\n}\n\n/**\n * Reset the warning dedupe cache. Test-only — exported via internals for\n * vitest spec setup. Not part of the public API.\n *\n * @internal\n */\nexport function _resetNonJsonWarningCache(): void {\n nonJsonWarningCache.clear();\n}\n"]}
@@ -1,3 +0,0 @@
1
- import {f,l,k,m,n,j,i}from'./chunk-FK7BD7XT.js';import {c,b,a,e}from'./chunk-4CMO5OVZ.js';var De=class extends Error{constructor(P,S,O,m,p=true){super(P);this.source=S;this.sourceId=O;this.context=m;this.recoverable=p;this.name="DirectiveError";}};function Qe(){return {create(d){return d}}}function et(){return {create(d){return d}}}function tt(d){return d}function nt(d){return d}function ht(d){return d._mode==="single"}function St(d){return d._mode==="namespaced"}function le(d){if(!d)return;let r=Object.assign(Object.create(null),d);return Array.isArray(r.tags)&&Object.freeze(r.tags),Object.freeze(r)}function Ie(d){return typeof d=="object"&&d!==null&&Object.hasOwn(d,"compute")&&typeof d.compute=="function"}function rt(d){return typeof d=="boolean"?{enabled:d,maxSnapshots:100}:{enabled:true,maxSnapshots:d.maxSnapshots??100}}function $e(d){let{historyOption:r,facts:P,store:S,onSnapshot:O,onHistoryChange:m}=d,{enabled:p,maxSnapshots:_}=rt(r),B=[],w=-1,J=1,U=false,F=false,j=[],K=null,W=-1;function k(){return S.toObject()}function N(){let V=k();try{return structuredClone(V)}catch{try{return JSON.parse(JSON.stringify(V))}catch{return {...V}}}}function G(V){if(!c(V)){console.error("[Directive] Potential prototype pollution detected in snapshot data, skipping restore");return}S.batch(()=>{for(let[H,X]of Object.entries(V)){if(H==="__proto__"||H==="constructor"||H==="prototype"){console.warn(`[Directive] Skipping dangerous key "${H}" during fact restoration`);continue}P[H]=X;}});}return {get isEnabled(){return p},get isRestoring(){return F},get isPaused(){return U},get snapshots(){return [...B]},get currentIndex(){return w},takeSnapshot(V){if(!p||U)return {id:-1,timestamp:Date.now(),facts:{},trigger:V};let H={id:J++,timestamp:Date.now(),facts:N(),trigger:V};for(w<B.length-1&&B.splice(w+1),B.push(H),w=B.length-1;B.length>_;)B.shift(),w--;return O?.(H),H},restore(V){if(p){U=true,F=true;try{G(V.facts);}finally{U=false,F=false;}}},goBack(V=1){if(!p||B.length===0)return;let H=w,X=w,g=j.find(u=>w>u.startIndex&&w<=u.endIndex);if(g)X=g.startIndex;else if(j.find(a=>w===a.startIndex)){let a=j.find(R=>R.endIndex<w&&w-R.endIndex<=V);X=a?a.startIndex:Math.max(0,w-V);}else X=Math.max(0,w-V);if(H===X)return;w=X;let f=B[w];f&&(this.restore(f),m?.(H,X));},goForward(V=1){if(!p||B.length===0)return;let H=w,X=w,g=j.find(u=>w>=u.startIndex&&w<u.endIndex);if(g?X=g.endIndex:X=Math.min(B.length-1,w+V),H===X)return;w=X;let f=B[w];f&&(this.restore(f),m?.(H,X));},goTo(V){if(!p)return;let H=B.findIndex(f=>f.id===V);if(H===-1){console.warn(`[Directive] Snapshot ${V} not found`);return}let X=w;w=H;let g=B[w];g&&(this.restore(g),m?.(X,H));},replay(){if(!p||B.length===0)return;w=0;let V=B[0];V&&this.restore(V);},export(){return JSON.stringify({version:1,snapshots:B,currentIndex:w})},import(V){if(p)try{let H=JSON.parse(V);if(typeof H!="object"||H===null)throw new Error("[Directive] Invalid history data: expected object");if(H.version!==1)throw new Error(`[Directive] Unsupported history export version: ${H.version}`);if(!Array.isArray(H.snapshots))throw new Error("[Directive] Invalid history data: snapshots must be an array");if(typeof H.currentIndex!="number")throw new Error("Invalid history data: currentIndex must be a number");for(let g of H.snapshots){if(typeof g!="object"||g===null)throw new Error("[Directive] Invalid snapshot: expected object");if(typeof g.id!="number"||typeof g.timestamp!="number"||typeof g.trigger!="string"||typeof g.facts!="object")throw new Error("Invalid snapshot structure");if(!c(g.facts))throw new Error("[Directive] Invalid fact data: potential prototype pollution detected in nested objects")}B.length=0,B.push(...H.snapshots),w=H.currentIndex;let X=B[w];X&&this.restore(X);}catch(H){console.error("[Directive] Failed to import history data:",H);}},beginChangeset(V){p&&(K=V,W=w);},endChangeset(){!p||K===null||(w>W&&j.push({label:K,startIndex:W,endIndex:w}),K=null,W=-1);},pause(){U=true;},resume(){U=false;}}}function Fe(){let d={id:-1,timestamp:0,facts:{},trigger:""};return {isEnabled:false,isRestoring:false,isPaused:false,snapshots:[],currentIndex:-1,takeSnapshot:()=>d,restore:()=>{},goBack:()=>{},goForward:()=>{},goTo:()=>{},replay:()=>{},export:()=>"{}",import:()=>{},beginChangeset:()=>{},endChangeset:()=>{},pause:()=>{},resume:()=>{}}}var Ke=new WeakMap;function it(d,r){if(r)return r(d);let P=Ke.get(d);if(P!==void 0)return P;let{type:S,...O}=d,m=b(O),p=`${S}:${m}`;return Ke.set(d,p),p}function qe(d,r,P){return {requirement:d,id:it(d,P),fromConstraint:r}}function xt(d){return r=>({type:d,...r})}function It(d,r){return d.type===r}function qt(d){return r=>r.type===d}var Re=class d{map=new Map;add(r){this.map.has(r.id)||this.map.set(r.id,r);}remove(r){return this.map.delete(r)}has(r){return this.map.has(r)}get(r){return this.map.get(r)}all(){return [...this.map.values()]}ids(){return [...this.map.keys()]}get size(){return this.map.size}clear(){this.map.clear();}clone(){let r=new d;for(let P of this.map.values())r.add(P);return r}diff(r){let P=[],S=[];for(let O of this.map.values())r.has(O.id)||P.push(O);for(let O of r.map.values())this.map.has(O.id)||S.push(O);return {added:P,removed:S}}};var st=5e3;function Be(d){let{definitions:r,facts:P,requirementKeys:S={},defaultTimeout:O=st,onEvaluate:m,onError:p}=d,_=new Map,B=new Set,w=new Set,J=new Map,U=new Map,F=new Set,j=new Map,K=new Map,W=false,k=new Set,N=new Set,G=new Map,ie=[],V=new Map;function H(t,i){r[t]&&(G.has(t)||G.set(t,new Set),G.get(t).add(i));}function X(){G.clear();for(let[t,i]of Object.entries(r))if(i.after)for(let l of i.after)H(l,t);}function g(t,i,l,C,T){if(l.has(t))return;if(C.has(t)){let se=i.indexOf(t),ae=[...i.slice(se),t].join(" \u2192 ");throw new Error(`[Directive] Constraint cycle detected: ${ae}. Remove one of the \`after\` dependencies to break the cycle.`)}C.add(t),i.push(t);let Z=r[t];if(Z?.after)for(let se of Z.after)r[se]&&g(se,i,l,C,T);i.pop(),C.delete(t),l.add(t),T.push(t);}function f$1(){let t=new Set,i=new Set,l=[];for(let C of Object.keys(r))g(C,[],t,i,l);ie=l,V=new Map(ie.map((C,T)=>[C,T]));}f$1(),X();function u(){for(let[t,i]of Object.entries(r))if(i.after)for(let l of i.after)r[l]||console.warn(`[Directive] Constraint "${t}" references unknown constraint "${l}" in \`after\`. This dependency will be ignored. Check for typos or ensure the constraint exists.`);}f&&u();function a$1(t,i){return i.async!==void 0?i.async:!!w.has(t)}function R(t){let i=r[t];if(!i)throw new Error(`[Directive] Unknown constraint: ${t}`);let l=a$1(t,i);l&&w.add(t);let C={id:t,priority:i.priority??0,isAsync:l,lastResult:null,isEvaluating:false,error:null,lastResolvedAt:null,after:i.after??[],hitCount:0,lastActiveAt:null};return _.set(t,C),C}function I(t){return _.get(t)??R(t)}function Q(t,i){if(t.size!==i.size||t.size===0)return false;for(let l of i)if(!t.has(l))return false;return true}function ee(t,i){for(let l of i){let C=U.get(l);C&&(C.delete(t),C.size===0&&U.delete(l));}}function ue(t,i){for(let l of i)U.has(l)||U.set(l,new Set),U.get(l).add(t);}function h(t){let i=J.get(t);i&&(ee(t,i),J.delete(t));}function b(t){G.delete(t);for(let i of G.values())i.delete(t);}function c(t,i){let l=J.get(t)??new Set;Q(l,i)||(ee(t,l),ue(t,i),J.set(t,i));}function E(t,i$1){if(i$1.deps)return j.set(t,new Set(i$1.deps)),i$1.when(P);let l=i(()=>i$1.when(P));return j.set(t,l.deps),l.value}function A(t,i,l){i.lastResult=l,l&&(i.hitCount++,i.lastActiveAt=Date.now()),i.isEvaluating=false,m?.(t,l);}function te(t,i,l){i.error=l instanceof Error?l:new Error(String(l)),i.lastResult=false,i.isEvaluating=false,p?.(t,l);}function me(t,i,l){return w.add(t),i.isAsync=true,f&&console.warn(`[Directive] Constraint "${t}" returned a Promise but was not marked as async. Add \`async: true\` to the constraint definition to avoid this warning and improve performance.`),l.then(C=>(A(t,i,C),C)).catch(C=>(te(t,i,C),false))}function fe(t){let i=r[t];if(!i)return false;let l=I(t);l.isEvaluating=true,l.error=null;try{let C=E(t,i);return C instanceof Promise?me(t,l,C):(A(t,l,C),C)}catch(C){return te(t,l,C),false}}async function ge(t){let i=r[t];if(!i)return false;let l=I(t),C=i.timeout??O;if(l.isEvaluating=true,l.error=null,i.deps?.length){let T=new Set(i.deps);c(t,T),j.set(t,T);}try{let T=i.when(P),Z=await a(T,C,`Constraint "${t}" timed out after ${C}ms`);return l.lastResult=Z,Z&&(l.hitCount++,l.lastActiveAt=Date.now()),l.isEvaluating=!1,m?.(t,Z),Z}catch(T){return l.error=T instanceof Error?T:new Error(String(T)),l.lastResult=false,l.isEvaluating=false,p?.(t,T),false}}let ve=10;function pe(t,i){if(t==null)return [];if(Array.isArray(t)){let l=t.filter(C=>C!=null);return f&&l.length>ve&&i&&console.warn(`[Directive] Constraint "${i}" produced ${l.length} requirements. Consider splitting into multiple constraints for better performance.`),l}return [t]}function he(t){let i$1=r[t];if(!i$1)return {requirements:[],deps:new Set};let l=i$1.require;if(typeof l=="function"){let{value:T,deps:Z}=i(()=>l(P));return {requirements:pe(T,t),deps:Z}}return {requirements:pe(l,t),deps:new Set}}function ye(t,i){if(i.size===0)return;let l=J.get(t)??new Set;for(let C of i)l.add(C);ue(t,i),J.set(t,l);}let $=null;function oe(){return $||($=Object.keys(r).sort((t,i)=>{let l=I(t),T=I(i).priority-l.priority;if(T!==0)return T;let Z=V.get(t)??0,se=V.get(i)??0;return Z-se})),$}for(let t of Object.keys(r))R(t);function de(t){for(let[i,l]of Object.entries(t))l.async&&!l.deps&&console.warn(`[Directive] Async constraint "${i}" has no \`deps\` declared. Auto-tracking cannot work across async boundaries. Add \`deps: ["key1", "key2"]\` to enable dependency tracking.`);}f&&de(r);function Se(t){return !r[t]||B.has(t)||N.has(t)?true:k.has(t)}function we(t){let i=_.get(t);if(!i||i.after.length===0)return true;for(let l of i.after)if(!Se(l))return false;return true}function o(t){let i=j.get(t);i!==void 0&&c(t,i),N.add(t),K.set(t,[]);}function v(t,i,l){if(i!==void 0){let C=new Set(i);for(let T of l)C.add(T);c(t,C);}else ye(t,l);}function y(t,i,l){if(i.length===0){K.set(t,[]);return}let C=i.map(T=>qe(T,t,S[T.type]));for(let T of C)l.add(T);K.set(t,C);}function q(t,i){for(let l of t)i.add(l);}function z(t,i,l){if(B.has(t))return;if(!i){o(t);return}N.delete(t);let C=j.get(t),T,Z;try{let se=he(t);T=se.requirements,Z=se.deps;}catch(se){p?.(t,se),o(t);return}v(t,C,Z),y(t,T,l);}function e(t,i){let l=[],C=[];for(let T of t){if(we(T)){C.push(T);continue}l.push(T);let Z=K.get(T);Z&&q(Z,i);}return {blocked:l,ready:C}}function n(t,i){let l=[];for(let C of t){let T=fe(C);if(T instanceof Promise){l.push({id:C,promise:T});continue}z(C,T,i);}return l}async function s(t,i){let l=await Promise.all(t.map(async({id:C,promise:T})=>({id:C,active:await T})));for(let{id:C,active:T}of l)z(C,T,i);}async function D(t,i){let{blocked:l,ready:C}=e(t,i);if(C.length===0)return l;let T=[],Z=[];for(let ae of C)I(ae).isAsync?Z.push(ae):T.push(ae);let se=n(T,i);if(se.length>0&&await s(se,i),Z.length>0){let ae=Z.map(ke=>({id:ke,promise:ge(ke)}));await s(ae,i);}return l}function x(t,i){for(let l of t){let C=U.get(l);if(C)for(let T of C)B.has(T)||i.add(T);}}function M(t){for(let i of F)B.has(i)||t.add(i);F.clear();}function L(t){let i=new Set;return x(t,i),M(i),i}function Y(t,i,l){for(let C of t){if(i.has(C))continue;let T=K.get(C);T&&q(T,l);}}return {async evaluate(t){let i=new Re;N.clear();let l=oe(),C=B.size===0?l:l.filter(ae=>!B.has(ae)),T;if(!W||!t||t.size===0)T=C,W=true;else {let ae=L(t);T=[...ae],Y(C,ae,i);}let Z=T,se=T.length+1;for(;Z.length>0&&se>0;){let ae=Z.length;if(Z=await D(Z,i),Z.length===ae)break;se--;}return i.all()},getState(t){return _.get(t)},getDependencies(t){return J.get(t)},getAllStates(){return [..._.values()]},disable(t){if(!_.has(t)){console.warn(`[Directive] constraints.disable("${t}") \u2014 no such constraint`);return}B.add(t),$=null,K.delete(t),h(t),j.delete(t);},enable(t){if(!_.has(t)){console.warn(`[Directive] constraints.enable("${t}") \u2014 no such constraint`);return}B.delete(t),$=null,F.add(t);},isDisabled(t){return B.has(t)},invalidate(t){let i=U.get(t);if(i)for(let l of i)F.add(l);},markResolved(t){k.add(t);let i=_.get(t);i&&(i.lastResolvedAt=Date.now());let l=G.get(t);if(l)for(let C of l)F.add(C);},isResolved(t){return k.has(t)},registerDefinitions(t){let i=false;for(let[l,C]of Object.entries(t))r[l]=C,R(l),F.add(l),C.after?.length&&(i=true);$=null,i&&f$1(),X();},assignDefinition(t,i){if(!r[t])throw new Error(`[Directive] Cannot assign constraint "${t}" \u2014 it does not exist. Use register() to create it.`);r[t]=i,R(t),F.add(t),$=null,f$1(),X();},unregisterDefinition(t){r[t]&&(delete r[t],_.delete(t),B.delete(t),w.delete(t),F.delete(t),N.delete(t),k.delete(t),K.delete(t),j.delete(t),h(t),b(t),$=null,f$1(),X());},async callOne(t,i){if(!r[t])throw new Error(`[Directive] Cannot call constraint "${t}" \u2014 it does not exist.`);if(B.has(t))return [];let C=I(t),T;if(C.isAsync)T=await ge(t);else {let ae=fe(t);T=ae instanceof Promise?await ae:ae;}if(!T)return [];let{requirements:Z}=he(t);if(Z.length===0)return [];let se=[];for(let ae of Z){let ke=i?{...ae,...i}:ae;se.push(qe(ke,t,S[ke.type]));}return se},setRequirementKey(t,i){S[t]=i;},removeRequirementKey(t){delete S[t];}}}function _e(d){let{definitions:r,facts:P,onCompute:S,onInvalidate:O,onError:m}=d,p=3,_=new Map;for(let[h,b]of Object.entries(r))if(Ie(b)){r[h]=b.compute;let c=le(b.meta);c&&_.set(h,c);}let B=new Map,w=new Map,J=new Map,U=new Map,F=0,j=new Set,K=false,W=100,k$1;function N(h,b){let c=B.has(h)?U:J,E=c.get(h);E?.delete(b),E&&E.size===0&&c.delete(h);}function G(h,b){let c=r[h]?U:J,E=c.get(h);E||(E=new Set,c.set(h,E)),E.add(b);}function ie(h){let b=B.get(h);if(b)for(let c of b.dependencies)N(c,h);}function V(h){let b=U.get(h);if(b){F++;try{for(let c of b)ee(c);}finally{F--;}U.delete(h);}}function H(h){delete r[h],B.delete(h),w.delete(h),j.delete(h),_.delete(h);}function X(h){if(!r[h])throw new Error(`[Directive] Unknown derivation: ${h}`);let c={id:h,compute:()=>f(h),cachedValue:void 0,dependencies:new Set,isStale:true,isComputing:false,stableRunCount:0,depsStable:false};return B.set(h,c),c}function g(h){return B.get(h)??X(h)}function f(h){let b=g(h),c=r[h];if(!c)throw new Error(`[Directive] Unknown derivation: ${h}`);if(b.isComputing)throw new Error(`[Directive] Circular dependency detected in derivation: ${h}`);b.isComputing=true;try{let E=b.cachedValue,A,te;if(b.depsStable&&b.dependencies.size>0)A=c(P,k$1),te=b.dependencies;else {let me=i(()=>c(P,k$1));A=me.value,te=me.deps,b.dependencies.size>0&&u(te,b.dependencies)?(b.stableRunCount++,b.stableRunCount>=p&&(b.depsStable=!0)):b.stableRunCount=0;}return b.cachedValue=A,b.isStale=!1,a(h,te),S&&S(h,A,E,[...te]),A}catch(E){throw m?.(h,E),E}finally{b.isComputing=false;}}function u(h,b){if(h.size!==b.size)return false;for(let c of b)if(!h.has(c))return false;return true}function a(h,b){let c=g(h),E=c.dependencies;if(!u(E,b)){for(let A of E)N(A,h);for(let A of b)G(A,h);c.dependencies=b;}}function R(h){for(let b of h){let c=w.get(b);if(c)for(let E of c)E();}}function I(){if(!(F>0||K)){K=true;try{let h=0;for(;j.size>0;){if(++h>W){let c=[...j];throw j.clear(),new Error(`[Directive] Infinite derivation notification loop detected after ${W} iterations. Remaining: ${c.join(", ")}. This usually means a derivation listener is mutating facts that re-trigger the same derivation.`)}let b=[...j];j.clear(),R(b);}}finally{K=false;}}}function Q(h,b){let c=U.get(h);if(c)for(let E of c)b.push(E);}function ee(h,b=new Set){let c=[h];for(;c.length>0;){let E=c.pop();if(b.has(E))continue;b.add(E);let A=B.get(E);!A||A.isStale||(A.isStale=true,A.depsStable=false,A.stableRunCount=0,O?.(E),j.add(E),Q(E,c));}}return k$1=new Proxy({},{get(h,b){if(typeof b=="symbol"||l.has(b)||!r[b])return;k(b);let c=g(b);return c.isStale&&f(b),c.cachedValue},set(){return false},deleteProperty(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}}),{get(h){let b=g(h);return b.isStale&&f(h),b.cachedValue},isStale(h){return B.get(h)?.isStale??true},invalidate(h){let b=J.get(h);if(!b)return;F++;let c=new Set;try{for(let E of b)ee(E,c);}finally{F--,I();}},invalidateMany(h){F++;let b=new Set;try{for(let c of h){let E=J.get(c);if(E)for(let A of E)ee(A,b);}}finally{F--,I();}},invalidateAll(){F++;try{for(let h of B.values())h.isStale||(h.isStale=!0,h.depsStable=!1,h.stableRunCount=0,j.add(h.id));}finally{F--,I();}},subscribe(h,b){for(let c of h){let E=c;w.has(E)||w.set(E,new Set),w.get(E).add(b);}return ()=>{for(let c of h){let E=c,A=w.get(E);A?.delete(b),A&&A.size===0&&w.delete(E);}}},getProxy(){return k$1},getDependencies(h){return g(h).dependencies},registerDefinitions(h){for(let[b,c]of Object.entries(h)){if(Ie(c)){r[b]=c.compute;let E=le(c.meta);E&&_.set(b,E);}else r[b]=c;X(b);}},assignDefinition(h,b){if(!r[h])throw new Error(`[Directive] Cannot assign derivation "${h}" \u2014 it does not exist. Use register() to create it.`);if(Ie(b)){r[h]=b.compute;let E=le(b.meta);E?_.set(h,E):_.delete(h);}else r[h]=b;let c=B.get(h);c&&(c.isStale=true,c.depsStable=false,c.stableRunCount=0,j.add(h)),I();},unregisterDefinition(h){r[h]&&(ie(h),V(h),H(h),I());},getMeta(h){return _.get(h)},callOne(h){if(!r[h])throw new Error(`[Directive] Cannot call derivation "${h}" \u2014 it does not exist.`);return f(h)}}}var ot=3;function We(d){let{definitions:r,facts:P,store:S,onRun:O,onError:m}=d,p=new Map,_=null,B=false;function w(g){let f=r[g];if(!f)throw new Error(`[Directive] Unknown effect: ${g}`);let u={id:g,enabled:true,hasExplicitDeps:!!f.deps,dependencies:f.deps?new Set(f.deps):null,cleanup:null,stableRunCount:0,depsStable:false};return p.set(g,u),u}function J(g){return p.get(g)??w(g)}function U(){return S.toObject()}function F(g){g.depsStable=false,g.stableRunCount=0;}function j(g,f){for(let u of g)if(f.has(u))return true;return false}function K(g,f){let u=J(g);return u.enabled?u.dependencies?j(u.dependencies,f)?(u.depsStable&&F(u),true):false:true:false}function W(g){if(g.cleanup){try{g.cleanup();}catch(f){m?.(g.id,f),console.error(`[Directive] Effect "${g.id}" cleanup threw an error:`,f);}g.cleanup=null;}}function k(g,f){if(typeof f=="function")if(B)try{f();}catch(u){m?.(g.id,u),console.error(`[Directive] Effect "${g.id}" cleanup threw an error:`,u);}else g.cleanup=f;}async function N(g,f){let u;if(S.batch(()=>{u=f.run(P,_);}),u instanceof Promise){let a=await u;k(g,a);}else k(g,u);}function G(g,f){if(g.size!==f.size)return false;for(let u of f)if(!g.has(u))return false;return true}function ie(g,f){if(!(g.dependencies&&G(g.dependencies,f))){F(g);return}g.stableRunCount++,g.stableRunCount>=ot&&(g.depsStable=true);}async function V(g,f){if(g.depsStable&&g.dependencies){await N(g,f);return}let u,a=i(()=>(S.batch(()=>{u=f.run(P,_);}),u)),R=a.deps,I=a.value;I instanceof Promise&&(I=await I),k(g,I),ie(g,R),g.dependencies=R.size>0?R:null;}async function H(g){let f=J(g),u=r[g];if(!(!f.enabled||!u)){W(f),O?.(g,f.dependencies?[...f.dependencies]:[]);try{f.hasExplicitDeps?await N(f,u):await V(f,u);}catch(a){m?.(g,a),console.error(`[Directive] Effect "${g}" threw an error:`,a),f.hasExplicitDeps||F(f);}}}for(let g of Object.keys(r))w(g);return {async runEffects(g){let f=[];for(let u of Object.keys(r))K(u,g)&&f.push(u);await Promise.all(f.map(H)),_=U();},async runAll(){let g=Object.keys(r);await Promise.all(g.map(f=>{let u=J(f);return u.enabled?(F(u),H(f)):Promise.resolve()})),_=U();},disable(g){let f=J(g);f.enabled=false;},enable(g){let f=J(g);f.enabled=true;},isEnabled(g){return J(g).enabled},cleanupAll(){B=true;for(let g of p.values())W(g);},registerDefinitions(g){for(let[f,u]of Object.entries(g))r[f]=u,w(f);},assignDefinition(g,f){if(!r[g])throw new Error(`[Directive] Cannot assign effect "${g}" \u2014 it does not exist. Use register() to create it.`);let u=p.get(g);u&&W(u),r[g]=f,w(g);},unregisterDefinition(g){if(!r[g])return;let f=p.get(g);f&&W(f),delete r[g],p.delete(g);},async callOne(g){let f=r[g];if(!f)throw new Error(`[Directive] Cannot call effect "${g}" \u2014 it does not exist.`);let u=J(g);if(u.enabled){W(u),O?.(g,u.dependencies?[...u.dependencies]:[]);try{let a;if(S.batch(()=>{a=f.run(P,_);}),a instanceof Promise){let R=await a;k(u,R);}else k(u,a);}catch(a){m?.(g,a),console.error(`[Directive] Effect "${g}" threw an error:`,a);}}}}}function at(d={}){let{delayMs:r=1e3,maxRetries:P=3,backoffMultiplier:S=2,maxDelayMs:O=3e4}=d,m=new Map;function p(_){let B=r*S**(_-1);return Math.min(B,O)}return {scheduleRetry(_,B,w,J,U){if(J>P)return null;let F=p(J),j={source:_,sourceId:B,context:w,attempt:J,nextRetryTime:Date.now()+F,callback:U};return m.set(B,j),j},getPendingRetries(){return Array.from(m.values())},processDueRetries(){let _=Date.now(),B=[];for(let[w,J]of m)J.nextRetryTime<=_&&(B.push(J),m.delete(w));return B},cancelRetry(_){m.delete(_);},clearAll(){m.clear();}}}var ct={constraint:"skip",resolver:"skip",effect:"skip",derivation:"skip",system:"throw"};function ze(d={}){let{config:r={},onError:P,onRecovery:S}=d,O=[],m=100,p=at(r.retryLater),_=new Map,B=1e3;function w(K,W,k,N){if(k instanceof De)return k;let G=k instanceof Error?k.message:String(k),ie=K!=="system";return new De(G,K,W,N,ie)}function J(K,W,k){let N=(()=>{switch(K){case "constraint":return r.onConstraintError;case "resolver":return r.onResolverError;case "effect":return r.onEffectError;case "derivation":return r.onDerivationError;default:return}})();if(typeof N=="function"){try{let G=N(k,W);if(typeof G=="string")return G}catch(G){console.error("[Directive] Error in error handler callback:",G);}return "skip"}return typeof N=="string"?N:ct[K]}function U(K){O.push(K),O.length>m&&O.shift();try{P?.(K);}catch(W){console.error("[Directive] Error in onError callback:",W);}try{r.onError?.(K);}catch(W){console.error("[Directive] Error in config.onError callback:",W);}}function F(K,W,k){let N=(_.get(W)??0)+1;if(_.set(W,N),_.size>B){let ie=_.keys().next().value;ie!==void 0&&_.delete(ie);}return p.scheduleRetry(K,W,k,N)?"retry-later":(_.delete(W),typeof process<"u"&&process.env?.NODE_ENV!=="production"&&console.warn(`[Directive] ${K} "${W}" exceeded max retry-later attempts. Skipping.`),"skip")}return {handleError(K,W,k,N){let G=w(K,W,k,N);U(G);let ie=J(K,W,k instanceof Error?k:new Error(String(k)));ie==="retry-later"&&(ie=F(K,W,N));try{S?.(G,ie);}catch(V){console.error("[Directive] Error in onRecovery callback:",V);}if(ie==="throw")throw G;return ie},getLastError(){return O[O.length-1]??null},getAllErrors(){return [...O]},clearErrors(){O.length=0;},getRetryLaterManager(){return p},processDueRetries(){return p.processDueRetries()},clearRetryAttempts(K){_.delete(K),p.cancelRetry(K);}}}function lt(d,r=100){try{return JSON.stringify(d)?.slice(0,r)??String(d)}catch{return "[circular or non-serializable]"}}function ut(d){let{schema:r,onChange:P,onBatch:S}=d,m=Object.keys(r).length===0,p=d.validate??f,_=d.strictKeys??(f&&!m),B=d.redactErrors??false,w=new Map,J=new Set,U=new Map,F=new Set,j=0,K=[],W=new Set,k$1=false,N=[],G=100;function ie(c){return c!==null&&typeof c=="object"&&"safeParse"in c&&typeof c.safeParse=="function"&&"_def"in c&&"parse"in c&&typeof c.parse=="function"}function V(c){let E=c;if(E._typeName)return E._typeName;if(ie(c)){let A=c._def;if(A?.typeName)return A.typeName.replace(/^Zod/,"").toLowerCase()}return "unknown"}function H(c){return B?"[redacted]":lt(c)}function X(c){return c===null?"null":Array.isArray(c)?"array":typeof c}function g(c,E,A){let te=A.safeParse(E);if(te.success)return;let me=X(E),fe=H(E),ge=te.error?.message??te.error?.issues?.[0]?.message??"Validation failed",ve=V(A);throw new Error(`[Directive] Validation failed for "${c}": expected ${ve}, got ${me} ${fe}. ${ge}`)}function f$1(c){if(typeof c._lastFailedIndex=="number"&&c._lastFailedIndex>=0){let E=` (element at index ${c._lastFailedIndex} failed)`;return c._lastFailedIndex=-1,E}return ""}function u(c,E,A){let te=A._validators;if(!te||!Array.isArray(te)||te.length===0)return;let me=A._typeName??"unknown";for(let fe=0;fe<te.length;fe++){let ge=te[fe];if(typeof ge!="function"||ge(E))continue;let ve=X(E),pe=H(E),he=f$1(A),ye=fe===0?"":` (validator ${fe+1} failed)`;throw new Error(`[Directive] Validation failed for "${c}": expected ${me}, got ${ve} ${pe}${ye}${he}`)}}function a(c){if(_)throw new Error(`[Directive] Unknown fact key: "${c}". Key not defined in schema.`);console.warn(`[Directive] Unknown fact key: "${c}"`);}function R(c,E){if(!p)return;let A=r[c];if(!A){a(c);return}if(ie(A)){g(c,E,A);return}u(c,E,A);}function I(c){U.get(c)?.forEach(E=>E());}function Q(){F.forEach(c=>c());}function ee(c,E,A){if(k$1){N.push({key:c,value:E,prev:A});return}k$1=true;try{P?.(c,E,A),I(c),Q(),ue(". A listener is repeatedly mutating facts that re-trigger notifications");}finally{k$1=false;}}function ue(c){let E=0;for(;N.length>0;){if(++E>G)throw N.length=0,new Error(`[Directive] Infinite notification loop detected after ${G} iterations${c}.`);let A=[...N];N.length=0;for(let te of A)P?.(te.key,te.value,te.prev),I(te.key);Q();}}function h(){if(!(j>0)){if(S&&K.length>0&&S([...K]),W.size>0){k$1=true;try{for(let c of W)I(c);Q(),ue(" during flush");}finally{k$1=false;}}K.length=0,W.clear();}}let b={get(c){return k(c),w.get(c)},has(c){return k(c),w.has(c)},set(c,E){f&&R(c,E);let A=w.get(c);Object.is(A,E)||(w.set(c,E),J.add(c),j>0?(K.push({key:c,value:E,prev:A,type:"set"}),W.add(c)):ee(c,E,A));},delete(c){let E=w.get(c);w.delete(c),J.delete(c),j>0?(K.push({key:c,value:void 0,prev:E,type:"delete"}),W.add(c)):ee(c,void 0,E);},batch(c){j++;try{c();}finally{j--,h();}},subscribe(c,E){for(let A of c){let te=A;U.has(te)||U.set(te,new Set),U.get(te).add(E);}return ()=>{for(let A of c){let te=U.get(A);te&&(te.delete(E),te.size===0&&U.delete(A));}}},subscribeAll(c){return F.add(c),()=>F.delete(c)},toObject(){let c={};for(let E of J)w.has(E)&&(c[E]=w.get(E));return c}};return b.destroy=()=>{U.clear(),F.clear();},b.registerKeys=c=>{for(let E of Object.keys(c))l.has(E)||(r[E]=c[E],J.add(E));},b}var Te=new WeakMap;function Ne(d,r,P=r){return new Proxy(d,{get(S,O){if(typeof O=="string"&&l.has(O))return;if(O===Symbol.for("nodejs.util.inspect.custom"))return ()=>S;let m=Reflect.get(S,O);if(typeof O=="symbol"||typeof m!="object"||m===null)return m;if(Te.has(m))return Te.get(m);let p=Ne(m,r,`${P}.${String(O)}`);return Te.set(m,p),p},set(S,O,m){return typeof O!="symbol"&&console.warn(`[Directive] Nested mutation on "facts.${P}.${String(O)}" will not trigger reactivity. Use: facts.${r} = { ...facts.${r}, ... }`),Reflect.set(S,O,m)}})}function ft(d,r){let P=()=>({get:O=>j(()=>d.get(O)),has:O=>j(()=>d.has(O))});return new Proxy({},{get(O,m){if(typeof m=="symbol")return m===Symbol.for("nodejs.util.inspect.custom")?()=>j(()=>d.toObject()):void 0;if(l.has(m))return;if(m==="$store")return d;if(m==="$snapshot")return P;let p=d.get(m);return f&&p!==null&&typeof p=="object"?Ne(p,m):p},set(O,m$1,p){if(typeof m$1=="symbol"||m$1==="$store"||m$1==="$snapshot"||l.has(m$1))return false;if(f){let _=m(p);_&&n(m$1,_);}return d.set(m$1,p),true},deleteProperty(O,m){return typeof m=="symbol"||m==="$store"||m==="$snapshot"||l.has(m)?false:(d.delete(m),true)},has(O,m){return m==="$store"||m==="$snapshot"?true:typeof m=="symbol"||l.has(m)?false:d.has(m)},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(O,m){return m==="$store"||m==="$snapshot"?{configurable:true,enumerable:false,writable:false}:{configurable:true,enumerable:true,writable:true}},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function He(d){let r=ut(d),P=ft(r,d.schema);return {store:r,facts:P}}function Le(){let d=[];function r(m){if(m)try{return m()}catch(p){console.error("[Directive] Plugin error:",p);return}}async function P(m){if(m)try{return await m()}catch(p){console.error("[Directive] Plugin error:",p);return}}function S(m){return (...p)=>{for(let _ of d)r(()=>_[m]?.(...p));}}return {register(m){d.some(p=>p.name===m.name)&&(console.warn(`[Directive] Plugin "${m.name}" is already registered, replacing...`),this.unregister(m.name)),d.push(m);},unregister(m){let p=d.findIndex(_=>_.name===m);p!==-1&&d.splice(p,1);},getPlugins(){return [...d]},async emitInit(m){for(let p of d)await P(()=>p.onInit?.(m));},emitStart:S("onStart"),emitStop:S("onStop"),emitDestroy:S("onDestroy"),emitFactSet:S("onFactSet"),emitFactDelete:S("onFactDelete"),emitFactsBatch:S("onFactsBatch"),emitDerivationCompute:S("onDerivationCompute"),emitDerivationInvalidate:S("onDerivationInvalidate"),emitReconcileStart:S("onReconcileStart"),emitReconcileEnd:S("onReconcileEnd"),emitConstraintEvaluate:S("onConstraintEvaluate"),emitConstraintError:S("onConstraintError"),emitRequirementCreated:S("onRequirementCreated"),emitRequirementMet:S("onRequirementMet"),emitRequirementCanceled:S("onRequirementCanceled"),emitResolverStart:S("onResolverStart"),emitResolverComplete:S("onResolverComplete"),emitResolverError:S("onResolverError"),emitResolverRetry:S("onResolverRetry"),emitResolverCancel:S("onResolverCancel"),emitEffectRun:S("onEffectRun"),emitEffectError:S("onEffectError"),emitSnapshot:S("onSnapshot"),emitHistoryNavigate:S("onHistoryNavigate"),emitError:S("onError"),emitErrorRecovery:S("onErrorRecovery"),emitDefinitionRegister:S("onDefinitionRegister"),emitDefinitionAssign:S("onDefinitionAssign"),emitDefinitionUnregister:S("onDefinitionUnregister"),emitDefinitionCall:S("onDefinitionCall"),emitTraceComplete:S("onTraceComplete")}}var Ve={attempts:1,backoff:"none",initialDelay:100,maxDelay:3e4},Ue={enabled:false,windowMs:50};function dt(d,r){if(!r||r==="none")return d;if(r==="full")return Math.floor(Math.random()*d);if(r==="equal"){let P=d/2;return Math.floor(P+Math.random()*P)}if(typeof r=="object"&&"maxMs"in r){let P=Number.isFinite(r.maxMs)&&r.maxMs>0?r.maxMs:0;return d+Math.floor(Math.random()*P)}return d}function gt(d,r){let{backoff:P,initialDelay:S=100,maxDelay:O=3e4}=d,m;switch(P){case "none":m=S;break;case "linear":m=S*r;break;case "exponential":m=S*2**(r-1);break;default:m=S;}let p=Math.min(m,O),_=dt(p,d.jitter);return Math.max(1,_)}function mt(d){if(f)for(let[r,P]of Object.entries(d)){if(!P.resolve&&!P.resolveBatch&&!P.resolveBatchWithResults)throw new Error(`[Directive] Resolver "${r}" must define either resolve() or resolveBatch(). Add one of these methods to handle requirements.`);if(!(!P.batch?.enabled||P.resolveBatch||P.resolveBatchWithResults))if(P.resolve)console.warn(`[Directive] Resolver "${r}" has batch.enabled but no resolveBatch(). Falling back to individual resolve() calls. Add resolveBatch() for true bulk operations.`);else throw new Error(`[Directive] Resolver "${r}" has batch.enabled=true but no resolve(), resolveBatch(), or resolveBatchWithResults() method.`)}}function Je(d){let{definitions:r,facts:P,store:S,getConstraintBinding:O,onStart:m,onComplete:p,onError:_,onRetry:B,onCancel:w,onResolutionComplete:J,onRequeue:U}=d;mt(r);let F=new Map,j=new Map,K=1e3,W=new Map,k=new Map,N=1e3;function G(){if(j.size>K){let o=j.size-K,v=j.keys();for(let y=0;y<o;y++){let q=v.next().value;q&&j.delete(q);}}}function ie(o){return typeof o=="object"&&o!==null&&"requirement"in o&&typeof o.requirement=="string"}function V(o){return typeof o=="object"&&o!==null&&"requirement"in o&&typeof o.requirement=="function"}function H(o,v){return ie(o)?v.type===o.requirement:V(o)?o.requirement(v):false}function X(o,v){let y=k.get(o);if(!y)return null;k.delete(o),k.set(o,y);for(let q of y){let z=r[q];if(z&&H(z,v))return q}return null}function g(o,v){if(!k.has(o)){if(k.size>=N){let y=k.keys().next().value;y!==void 0&&k.delete(y);}k.set(o,new Set);}k.get(o).add(v);}function f$1(o){let v=o.type,y=X(v,o);if(y)return y;for(let[q,z]of Object.entries(r))if(H(z,o))return g(v,q),q;return null}function u(o){if(!O||!o||!o.fromConstraint)return null;let v=O(o.fromConstraint);return !v||v.mode!=="auto"||!v.when?null:v}function a$1(o,v){let y=false;return new Proxy(P,{get(q,z,e){return Reflect.get(P,z,e)},set(q,z,e,n){if(y)return true;if(z==="$store"||z==="$snapshot")return Reflect.set(P,z,e);let s;try{s=o.when(P);}catch{s=false;}return s?Reflect.set(P,z,e):(y=true,v.abort(),true)},deleteProperty(q,z){if(y)return true;let e;try{e=o.when(P);}catch{e=false;}return e?Reflect.deleteProperty(P,z):(y=true,v.abort(),true)},has(q,z){return Reflect.has(P,z)},ownKeys(){return Reflect.ownKeys(P)},getOwnPropertyDescriptor(q,z){return Reflect.getOwnPropertyDescriptor(P,z)}})}function R(o,v,y,q){return {facts:y&&q?a$1(y,q):P,signal:o,snapshot:()=>P.$snapshot(),requeue:()=>{if(U)for(let e of v)U(e);}}}async function I(o,v,y,q){let z=o instanceof Error?o:new Error(String(o));if(q.signal.aborted)return {action:"abort",error:z};if(y.shouldRetry&&!y.shouldRetry(z,v))return {action:"break",error:z};if(v<y.attempts){if(q.signal.aborted)return {action:"abort",error:z};let e=gt(y,v);if(await new Promise(n=>{let s=setTimeout(n,e),D=()=>{clearTimeout(s),n();};q.signal.addEventListener("abort",D,{once:true});}),q.signal.aborted)return {action:"abort",error:z}}return {action:"continue",error:z}}async function Q(o,v,y,q,z){if(!o.resolve)return;let e=u(y),n;S.batch(()=>{n=o.resolve(y.requirement,R(q,[y.id],e,z));});let s=o.timeout;if(s&&s>0){await a(n,s,`Resolver "${v}" timed out after ${s}ms`);return}await n;}function ee(o,v,y){let q=Date.now()-y;j.set(v.id,{state:"success",requirementId:v.id,completedAt:Date.now(),duration:q}),G(),p?.(o,v,q);}function ue(o,v,y,q){j.set(v.id,{state:"error",requirementId:v.id,error:y,failedAt:Date.now(),attempts:q}),G(),_?.(o,v,y);}function h(o,v,y){let q=F.get(o);q&&(q.attempt=v,q.status={state:"running",requirementId:o,startedAt:y,attempt:v});}async function b(o,v,y,q,z){let e=await I(o,v,y,q);return e.action==="continue"&&v<y.attempts&&z(v+1),{lastError:e.error,shouldContinue:e.action==="continue"}}async function c(o,v,y){let q=r[o];if(!q)return;let z={...Ve,...q.retry},e=null,n=F.get(v.id)?.startedAt??Date.now();for(let s=1;s<=z.attempts;s++){if(y.signal.aborted)return;h(v.id,s,n);try{await Q(q,o,v,y.signal,y),ee(o,v,n);return}catch(D){let x=await b(D,s,z,y,M=>B?.(o,v,M));if(e=x.lastError,!x.shouldContinue)break}}ue(o,v,e,z.attempts);}async function E(o,v,y){return v&&v>0?a(o,v,y):o}async function A(o,v,y,q,z,e,n,s){let D;S.batch(()=>{D=o.resolveBatchWithResults(q,z);});let x=await E(D,e,`Batch resolver "${v}" timed out after ${e}ms`);if(x.length!==y.length)throw new Error(`[Directive] Batch resolver "${v}" returned ${x.length} results but expected ${y.length}. Results array must match input order.`);let M=false;for(let L=0;L<y.length;L++){let Y=y[L],ne=x[L];if(ne.success){ee(v,Y,n);continue}M=true;let t=ne.error??new Error("Batch item failed");j.set(Y.id,{state:"error",requirementId:Y.id,error:t,failedAt:Date.now(),attempts:s}),_?.(v,Y,t);}return !M||y.some((L,Y)=>x[Y]?.success)?"done":"retry"}async function te(o,v,y,q,z,e,n){let s;S.batch(()=>{s=o.resolveBatch(q,z);}),await E(s,e,`Batch resolver "${v}" timed out after ${e}ms`);for(let D of y)ee(v,D,n);}function me(o,v,y,q){for(let z of v)ue(o,z,y,q);}async function fe(o,v){await Promise.all(v.map(y=>{let q=new AbortController;return c(o,y,q)}));}async function ge(o,v,y,q,z,e,n,s){let D=null;if(y.length>0){let L=y[0];y.every(ne=>ne.fromConstraint===L.fromConstraint)&&(D=u(L));}let x=R(q,y.map(L=>L.id),D,z),M=y.map(L=>L.requirement);return o.resolveBatchWithResults?A(o,v,y,M,x,e,n,s):(await te(o,v,y,M,x,e,n),"done")}function ve(o,v,y){for(let q of v)B?.(o,q,y);}async function pe(o,v,y,q,z){let e=new AbortController,n=Date.now(),s=null;for(let D=1;D<=q.attempts;D++){if(e.signal.aborted)return null;try{if(await ge(o,v,y,e.signal,e,z,n,D)==="done")return null}catch(x){let M=await b(x,D,q,e,L=>ve(v,y,L));if(s=M.lastError,!M.shouldContinue)break}}return s}async function he(o,v){let y=r[o];if(!y)return;if(!y.resolveBatch&&!y.resolveBatchWithResults){await fe(o,v);return}let q={...Ve,...y.retry},e={...Ue,...y.batch}.timeoutMs??y.timeout,n=await pe(y,o,v,q,e);n&&me(o,v,n,q.attempts);}let ye=1e4;function $(o){o.timer&&(clearTimeout(o.timer),o.timer=null);}function oe(o){return W.has(o)||W.set(o,{resolverId:o,requirements:[],timer:null}),W.get(o)}function de(o,v){let y=r[o];if(!y)return;let q={...Ue,...y.batch},z=oe(o),e=q.maxSize||ye;if(z.requirements.length>=e&&($(z),Se(o)),z.requirements.push(v),q.maxSize&&z.requirements.length>=q.maxSize){$(z),Se(o);return}$(z),z.timer=setTimeout(()=>{Se(o);},q.windowMs);}function Se(o){let v=W.get(o);if(!v||v.requirements.length===0)return;let y=[...v.requirements];v.requirements=[],v.timer=null,he(o,y).then(()=>{J?.();});}return {resolve(o){if(F.has(o.id))return;let v=f$1(o.requirement);if(!v){f&&console.warn(`[Directive] No resolver found for requirement type "${o.requirement.type}" (id: ${o.id})`);return}let y=r[v];if(!y)return;if(y.batch?.enabled){de(v,o);return}let q=new AbortController,z=Date.now(),e={requirementId:o.id,resolverId:v,controller:q,startedAt:z,attempt:1,status:{state:"pending",requirementId:o.id,startedAt:z},originalRequirement:o};F.set(o.id,e),m?.(v,o),c(v,o,q).finally(()=>{F.delete(o.id)&&J?.();});},cancel(o){let v=F.get(o);if(v){v.controller.abort(),F.delete(o),j.set(o,{state:"canceled",requirementId:o,canceledAt:Date.now()}),G(),w?.(v.resolverId,v.originalRequirement);return}for(let y of W.values()){let q=y.requirements.findIndex(z=>z.id===o);if(q!==-1){let[z]=y.requirements.splice(q,1);j.set(o,{state:"canceled",requirementId:o,canceledAt:Date.now()}),G(),z&&w?.(y.resolverId,z);return}}},cancelAll(){let o=[...F.keys()];for(let v of o)this.cancel(v);for(let v of W.values()){v.timer&&clearTimeout(v.timer);for(let y of v.requirements)j.set(y.id,{state:"canceled",requirementId:y.id,canceledAt:Date.now()}),w?.(v.resolverId,y);}W.clear(),G();},getStatus(o){let v=F.get(o);if(v)return v.status;let y=j.get(o);return y||{state:"idle"}},getInflight(){return [...F.keys()]},getInflightInfo(){return [...F.values()].map(o=>({id:o.requirementId,resolverId:o.resolverId,startedAt:o.startedAt}))},getInflightCount(){return F.size},isResolving(o){return F.has(o)},processBatches(){for(let o of W.keys())Se(o);},hasPendingBatches(){for(let o of W.values())if(o.requirements.length>0)return true;return false},registerDefinitions(o){for(let[v,y]of Object.entries(o))r[v]=y;k.clear();},assignDefinition(o,v){if(!r[o])throw new Error(`[Directive] Cannot assign resolver "${o}" \u2014 it does not exist. Use register() to create it.`);r[o]=v,k.clear();},unregisterDefinition(o){if(!r[o])return;for(let[y,q]of F)q.resolverId===o&&(q.controller.abort(),F.delete(y),j.set(y,{state:"canceled",requirementId:y,canceledAt:Date.now()}),w?.(o,q.originalRequirement));let v=W.get(o);if(v){v.timer&&clearTimeout(v.timer);for(let y of v.requirements)j.set(y.id,{state:"canceled",requirementId:y.id,canceledAt:Date.now()}),w?.(o,y);W.delete(o);}delete r[o],k.clear(),G();},async callOne(o,v){let y=r[o];if(!y)throw new Error(`[Directive] Cannot call resolver "${o}" \u2014 it does not exist.`);let q=new AbortController,z=R(q.signal,[]);if(y.resolve){let e;S.batch(()=>{e=y.resolve(v,z);}),await e;}},destroy(){this.cancelAll(),j.clear(),k.clear();}}}function Xe(d){let{mergedDerive:r,getDerivation:P,definitions:S}=d,O={register:(m,p)=>S.register("derivation",m,p),assign:(m,p)=>S.assign("derivation",m,p),unregister:m=>S.unregister("derivation",m),call:m=>S.call("derivation",m),isDynamic:m=>S.isDynamic("derivation",m),listDynamic:()=>S.listDynamic("derivation")};return new Proxy({},{get(m,p){if(typeof p!="symbol"&&!l.has(p)){if(p in O)return O[p];if(p in r)return P(p)}},has(m,p){return typeof p=="symbol"||l.has(p)?false:p in r||p in O},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(m,p){if(typeof p!="symbol"&&!l.has(p)&&(p in r||p in O))return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}function Ge(d){let{mergedEvents:r,dispatchEvent:P}=d;return new Proxy({},{get(S,O){if(typeof O!="symbol"&&!l.has(O))return m=>{P(O,m);}},has(S,O){return typeof O=="symbol"||l.has(O)?false:O in r},ownKeys(){return Object.keys(r)},getOwnPropertyDescriptor(S,O){if(typeof O!="symbol"&&!l.has(O)&&O in r)return {configurable:true,enumerable:true}},set(){return false},defineProperty(){return false},getPrototypeOf(){return null},setPrototypeOf(){return false}})}var vt=new Set(["register","assign","unregister","call","isDynamic","listDynamic"]);function Ze(d){let{mergedConstraints:r,mergedResolvers:P,mergedDerive:S,mergedEffects:O,constraintsManager:m,resolversManager:p,derivationsManager:_,effectsManager:B,pluginManager:w,getState:J,scheduleReconcile:U,maxDeferredRegistrations:F}=d,j={constraints:new Set,resolvers:new Set,derivations:new Set,effects:new Set},K={constraints:new Map,resolvers:new Map,derivations:new Map,effects:new Map},W=[];function k(f){if(vt.has(f))throw new Error(`[Directive] Derivation ID "${f}" conflicts with a reserved derive method name.`)}let N={constraint:{label:"Constraint",mergedMap:r,manager:m,dynamicSet:j.constraints,originalsMap:K.constraints,reconciles:true},resolver:{label:"Resolver",mergedMap:P,manager:p,dynamicSet:j.resolvers,originalsMap:K.resolvers,reconciles:true},derivation:{label:"Derivation",mergedMap:S,manager:_,dynamicSet:j.derivations,originalsMap:K.derivations,reconciles:false,validateId:k},effect:{label:"Effect",mergedMap:O,manager:B,dynamicSet:j.effects,originalsMap:K.effects,reconciles:false}};function G(f){if(typeof f!="string"||f.length===0)throw new Error(`[Directive] Definition ID must be a non-empty string. Received: ${String(f)}`);if(l.has(f))throw new Error(`[Directive] Security: Definition ID "${f}" is a blocked property.`);if(f.includes("::"))throw new Error(`[Directive] Definition ID "${f}" cannot contain "::". This separator is reserved for namespacing.`)}function ie(f,u,a){let R=N[f];if(R.validateId?.(u),u in R.mergedMap)throw new Error(`[Directive] ${R.label} "${u}" already exists. Use assign() to override.`);if(f!=="derivation"){let I=a;I.meta&&(I.meta=le(I.meta));}R.mergedMap[u]=a,R.manager.registerDefinitions({[u]:a}),R.dynamicSet.add(u),w.emitDefinitionRegister(f,u,a),R.reconciles&&U();}function V(f,u,a){let R=N[f];if(R.validateId?.(u),!(u in R.mergedMap))throw new Error(`[Directive] ${R.label} "${u}" does not exist. Use register() to create it.`);if(f!=="derivation"){let Q=a;Q.meta&&(Q.meta=le(Q.meta));}let I=R.mergedMap[u];R.manager.assignDefinition(u,a),R.originalsMap.set(u,I),R.mergedMap[u]=a,w.emitDefinitionAssign(f,u,a,I),R.reconciles&&U();}function H(f$1,u){let a=N[f$1];if(!a.dynamicSet.has(u)){f&&console.warn(`[Directive] Cannot unregister static ${f$1} "${u}". Only dynamically registered ${f$1}s can be removed.`);return}a.manager.unregisterDefinition(u),delete a.mergedMap[u],a.dynamicSet.delete(u),a.originalsMap.delete(u),w.emitDefinitionUnregister(f$1,u),a.reconciles&&U();}function X(){if(W.length===0)return;let f$1=W.splice(0);for(let u of f$1)try{switch(u.op){case "register":ie(u.type,u.id,u.def);break;case "assign":V(u.type,u.id,u.def);break;case "unregister":H(u.type,u.id);break}}catch(a){f&&console.error(`[Directive] Error in deferred ${u.op} for ${u.type} "${u.id}":`,a);}}function g(f,u,a,R){let{isDestroyed:I,isReconciling:Q}=J();if(I)throw new Error(`[Directive] Cannot ${f} ${u} "${a}" on a destroyed system.`);if(G(a),Q){if(W.length>=F)throw new Error(`[Directive] Too many deferred registrations (max ${F}). Avoid calling register/assign/unregister in resolver or effect callbacks during reconciliation.`);f==="unregister"?W.push({op:f,type:u,id:a}):W.push({op:f,type:u,id:a,def:R});return}switch(f){case "register":ie(u,a,R);break;case "assign":V(u,a,R);break;case "unregister":H(u,a);break}}return {register(f,u,a){g("register",f,u,a);},assign(f,u,a){g("assign",f,u,a);},unregister(f,u){g("unregister",f,u);},call(f,u,a){let{isDestroyed:R}=J();if(R)throw new Error(`[Directive] Cannot call ${f} "${u}" on a destroyed system.`);switch(G(u),w.emitDefinitionCall(f,u,a),f){case "constraint":return m.callOne(u,a);case "resolver":return p.callOne(u,a);case "derivation":return _.callOne(u);case "effect":return B.callOne(u)}},isDynamic(f,u){switch(f){case "constraint":return j.constraints.has(u);case "resolver":return j.resolvers.has(u);case "derivation":return j.derivations.has(u);case "effect":return j.effects.has(u)}},listDynamic(f){switch(f){case "constraint":return [...j.constraints];case "resolver":return [...j.resolvers];case "derivation":return [...j.derivations];case "effect":return [...j.effects]}},flushDeferred:X,getOriginal(f,u){let R={constraint:K.constraints,resolver:K.resolvers,derivation:K.derivations,effect:K.effects}[f];if(R)return R.get(u)},restoreOriginal(f,u){let R={constraint:K.constraints,resolver:K.resolvers,derivation:K.derivations,effect:K.effects}[f];if(!R||!R.has(u))return false;let I=R.get(u);return g("assign",f,u,I),R.delete(u),true},destroy(){W.length=0,j.constraints.clear(),j.resolvers.clear(),j.derivations.clear(),j.effects.clear(),K.constraints.clear(),K.resolvers.clear(),K.derivations.clear(),K.effects.clear();}}}function Ye(d){let{traceConfig:r,pluginManager:P,resolverMetaLookup:S}=d;if(!(r===true||typeof r=="object"&&r!==null))return {enabled:false,recordFactChange(){},startRun(){return 0},currentTrace:null,getEntries(){return null},attributeResolverStart(){},recordResolverComplete(){},recordResolverError(){},decrementInflight(){},finalizeCurrentRun(){},drainPendingChanges(){},destroy(){}};let m=(typeof r=="object"&&r!==null?r.maxRuns:void 0)??100,p=[],_=new Map,B=0,w=null,J=[],U=new Map,F=new Map,j=new Map,K=null,W=0,k=0,N={count:0,totalDuration:0,avgDuration:0,maxDuration:0,avgResolverCount:0,totalResolverCount:0,avgFactChangeCount:0,totalFactChangeCount:0};function G(a){let R=_.get(a);if(R&&R.status==="pending"){R.status="settled";let I=j.get(a);R.duration=I!==void 0?performance.now()-I:Date.now()-R.timestamp,j.delete(a),F.delete(a),R.causalChain=H(R),X(R),k++,P.emitTraceComplete(R);}}function ie(a){let R=U.get(a);if(U.delete(a),R!==void 0){let I=(F.get(R)??1)-1;I<=0?G(R):F.set(R,I);}}function V(){let a=p.shift();if(a&&(_.delete(a.id),j.delete(a.id),a.status==="pending")){F.delete(a.id);for(let[R,I]of U)I===a.id&&U.delete(R);}}function H(a){let R=[];for(let I of a.factChanges)R.push(`${I.key} changed`);for(let I of a.derivationsRecomputed)R.push(`${I.id} recomputed`);for(let I of a.constraintsHit)R.push(`${I.id} constraint hit`);for(let I of a.requirementsAdded)R.push(`${I.type} requirement added`);for(let I of a.resolversCompleted)R.push(`${I.resolver} resolved (${I.duration.toFixed(0)}ms)`);for(let I of a.resolversErrored)R.push(`${I.resolver} errored`);for(let I of a.effectsRun)R.push(`${I.id} effect ran`);return R.join(" \u2192 ")}function X(a){N.count++,N.totalDuration+=a.duration,N.avgDuration=N.totalDuration/N.count,a.duration>N.maxDuration&&(N.maxDuration=a.duration);let R=a.resolversStarted.length;N.totalResolverCount+=R,N.avgResolverCount=N.totalResolverCount/N.count;let I=a.factChanges.length;N.totalFactChangeCount+=I,N.avgFactChangeCount=N.totalFactChangeCount/N.count;let Q=[];N.count>3&&a.duration>N.avgDuration*5&&Q.push(`Duration ${a.duration.toFixed(0)}ms is 5x+ above average (${N.avgDuration.toFixed(0)}ms)`),a.resolversErrored.length>0&&Q.push(`${a.resolversErrored.length} resolver(s) errored`),Q.length>0&&(a.anomalies=Q);}function g(a){p.push(a),_.set(a.id,a),p.length>m&&V(),k++;}function f(a){return a.factChanges.length>0||a.constraintsHit.length>0||a.requirementsAdded.length>0||a.effectsRun.length>0}return {enabled:true,get currentTrace(){return w},set currentTrace(a){w=a;},recordFactChange(a,R,I){J.push({key:a,oldValue:R,newValue:I});},startRun(){let a=performance.now(),R=++B;return j.set(R,a),w={id:R,timestamp:Date.now(),duration:0,status:"pending",factChanges:J.splice(0),derivationsRecomputed:[],constraintsHit:[],requirementsAdded:[],requirementsRemoved:[],resolversStarted:[],resolversCompleted:[],resolversErrored:[],effectsRun:[],effectErrors:[]},a},getEntries(){return (!K||W!==k)&&(K=[...p],W=k),K},attributeResolverStart(a){w&&U.set(a,w.id);},recordResolverComplete(a,R,I){let Q=U.get(a);if(Q!==void 0){let ee=_.get(Q);ee&&ee.resolversCompleted.push({resolver:R,requirementId:a,duration:I,meta:S?.(R)});}},recordResolverError(a,R,I){let Q=U.get(a);if(Q!==void 0){let ee=_.get(Q);ee&&ee.resolversErrored.push({resolver:R,requirementId:a,error:I,meta:S?.(R)});}},decrementInflight(a){ie(a);},finalizeCurrentRun(a){if(!w)return;if(w.duration=performance.now()-a,!f(w)){j.delete(w.id),w=null;return}let R=w.resolversStarted.length;R===0?(w.status="settled",w.causalChain=H(w),X(w),g(w),P.emitTraceComplete(w)):(w.status="pending",g(w),F.set(w.id,R)),w=null;},drainPendingChanges(){J.length=0;},destroy(){p.length=0,_.clear(),U.clear(),F.clear(),j.clear(),J.length=0,w=null,K=null;}}}function bn(d){let r=Object.create(null),P=Object.create(null),S=Object.create(null),O=Object.create(null),m=Object.create(null),p=Object.create(null),_=new Map,B=new Map,w=new Map,J=new Map,U=new Map;for(let e of d.modules){let n=(D,x)=>{if(D)for(let M of Object.keys(D)){if(l.has(M))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${M}" in ${x}. This could indicate a prototype pollution attempt.`);if(x==="schema"&&M.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${M}" starting with "$". Keys starting with $ are reserved for internal accessors ($store, $snapshot).`)}};n(e.schema,"schema"),n(e.events,"events"),n(e.derive,"derive"),n(e.effects,"effects"),n(e.constraints,"constraints"),n(e.resolvers,"resolvers");for(let D of Object.keys(e.schema)){let x=w.get(D);if(x)throw new Error(`[Directive] Schema collision: Fact "${D}" is defined in both module "${x}" and "${e.id}". Use namespacing (e.g., "${e.id}::${D}") or merge into one module.`);w.set(D,e.id);}let s=(D,x)=>{if(D)for(let M of Object.keys(D)){let L=J.get(M);if(L&&L!==e.id)throw new Error(`[Directive] Definition collision: ${x} "${M}" is defined in both module "${L}" and "${e.id}". Use namespacing or rename to avoid conflicts.`);J.set(M,e.id);}};if(s(e.derive,"derivation"),s(e.effects,"effect"),s(e.constraints,"constraint"),s(e.resolvers,"resolver"),s(e.events,"event"),Object.assign(r,e.schema),e.events){for(let[D,x]of Object.entries(e.events))if(typeof x=="object"&&x!==null&&Object.hasOwn(x,"handler")){let M=x;if(e.events[D]=M.handler,M.meta){let L=le(M.meta);L&&B.set(D,L);}}Object.assign(P,e.events);}if(e.derive&&Object.assign(S,e.derive),e.effects&&Object.assign(O,e.effects),e.constraints&&Object.assign(m,e.constraints),e.resolvers){Object.assign(p,e.resolvers);for(let D of Object.keys(e.resolvers))U.set(D,e);}if(e.meta){let D=le(e.meta);D&&_.set(e.id,D);}}for(let e of Object.values(m))e.meta&&(e.meta=le(e.meta));for(let e of Object.values(p))e.meta&&(e.meta=le(e.meta));for(let e of Object.values(O)){let n=e;n.meta&&(n.meta=le(n.meta));}for(let e of Object.values(r)){let n=e;n._meta&&(n._meta=le(n._meta));}let F=null;if(d.modules.some(e=>e.history?.snapshotEvents)){F=new Set;for(let e of d.modules){let n=e;if(n.history?.snapshotEvents)for(let s of n.history.snapshotEvents)F.add(s);else if(n.events)for(let s of Object.keys(n.events))F.add(s);}}let K=0,W=false;if(f){let e=new Set(Object.keys(S));for(let n of Object.keys(r))e.has(n)&&console.warn(`[Directive] "${n}" exists as both a fact and a derivation. This may cause unexpected dependency tracking behavior.`);}let k=Le();for(let e of d.plugins??[])k.register(e);let N=k.getPlugins().length>0,G=k.register.bind(k),ie=k.unregister.bind(k);k.register=e=>{G(e),N=true;},k.unregister=e=>{ie(e),N=k.getPlugins().length>0;};let V=()=>N,H=ze({config:d.errorBoundary,onError:e=>k.emitError(e),onRecovery:(e,n)=>k.emitErrorRecovery(e,n)}),X=null,g=()=>{},f$1=()=>{},u=null,a=Ye({traceConfig:d.trace,pluginManager:k,resolverMetaLookup:e=>p[e]?.meta}),R=a.enabled,{store:I,facts:Q}=He({schema:r,onChange:(e,n,s)=>{k.emitFactSet(e,n,s),g(e),R&&a.recordFactChange(String(e),s,n),!u?.isRestoring&&(K===0&&(W=true),$.changedKeys.add(e),de());},onBatch:e=>{k.emitFactsBatch(e);let n=[];for(let s of e)n.push(s.key);if(R)for(let s of e)a.recordFactChange(s.key,s.prev,s.type==="delete"?void 0:s.value);if(f$1(n),!u?.isRestoring){K===0&&(W=true);for(let s of e)$.changedKeys.add(s.key);de();}}}),ee=_e({definitions:S,facts:Q,onCompute:(e,n,s,D)=>{V()&&k.emitDerivationCompute(e,n,D),a.currentTrace&&a.currentTrace.derivationsRecomputed.push({id:e,deps:D?[...D]:[],oldValue:s,newValue:n,meta:ee.getMeta(e)});},onInvalidate:e=>{V()&&k.emitDerivationInvalidate(e);},onError:(e,n)=>{H.handleError("derivation",e,n)==="retry"&&ee.invalidate(e);}});g=e=>ee.invalidate(e),f$1=e=>ee.invalidateMany(e);let ue=We({definitions:O,facts:Q,store:I,onRun:(e,n)=>{V()&&k.emitEffectRun(e),a.currentTrace&&a.currentTrace.effectsRun.push({id:e,triggeredBy:n,meta:O[e]?.meta});},onError:(e,n)=>{let s=H.handleError("effect",e,n);V()&&k.emitEffectError(e,n),a.currentTrace&&a.currentTrace.effectErrors.push({id:e,error:String(n),meta:O[e]?.meta}),s==="disable"&&ue.disable(e),s==="retry"&&($.changedKeys.add("*"),de());}}),h=Object.create(null);for(let e of Object.values(p))e.key&&typeof e.requirement=="string"&&(h[e.requirement]=e.key);let b=Be({definitions:m,facts:Q,requirementKeys:h,onEvaluate:(e,n)=>{V()&&k.emitConstraintEvaluate(e,n);},onError:(e,n)=>{let s=H.handleError("constraint",e,n);V()&&k.emitConstraintError(e,n),s==="disable"&&b.disable(e);}});function c$1(e){for(let n of Object.values(e))n.key&&typeof n.requirement=="string"&&b.setRequirementKey(n.requirement,n.key);}let E=new Set,A=Je({definitions:p,facts:Q,store:I,getConstraintBinding:e=>{let n=m[e];return n?(n.bind??"none")==="none"?{mode:"none",when:null}:b.getState(e)?.isAsync||n.async?(f&&console.warn(`[Directive] Constraint "${e}" has bind: 'auto' but is async. Binding is disabled \u2014 async predicates cannot be re-evaluated synchronously on every fact write.`),{mode:"none",when:null}):{mode:"auto",when:n.when}:void 0},onStart:(e,n)=>{V()&&k.emitResolverStart(e,n);},onComplete:(e,n,s)=>{H.clearRetryAttempts(e),V()&&(k.emitResolverComplete(e,n,s),k.emitRequirementMet(n,e)),b.markResolved(n.fromConstraint),R&&(a.recordResolverComplete(n.id,e,s),a.decrementInflight(n.id));},onError:(e,n,s)=>{let D=H.handleError("resolver",e,s,n);if(V()&&k.emitResolverError(e,n,s),D==="disable"&&b.disable(n.fromConstraint),D==="retry"&&($.previousRequirements.remove(n.id),de()),D==="retry-later"){let Y=H.getRetryLaterManager().getPendingRetries().find(ne=>ne.sourceId===e);Y&&!Y.callback&&(Y.callback=()=>{de();});}R&&(a.recordResolverError(n.id,e,String(s)),a.decrementInflight(n.id));let x=U.get(e),M=x?.hooks?.onResolverError;if(M){let L=s instanceof Error?s:new Error(String(s));try{M(L,n.requirement,{facts:Q});}catch(Y){console.error(`[Directive] onResolverError hook for module "${x?.id}" threw:`,Y);}}},onRetry:(e,n,s)=>k.emitResolverRetry(e,n,s),onCancel:(e,n)=>{k.emitResolverCancel(e,n),k.emitRequirementCanceled(n),R&&a.decrementInflight(n.id);},onResolutionComplete:()=>{ve(),de();},onRequeue:e=>{E.add(e);}}),te=new Set;function me(){for(let e of te)e();}let fe=d.history?$e({historyOption:d.history,facts:Q,store:I,onSnapshot:e=>{k.emitSnapshot(e),me();},onHistoryChange:(e,n)=>{k.emitHistoryNavigate(e,n),me();}}):Fe();u=fe;let ge=new Set;function ve(){for(let e of ge)e();}let pe=50,he=100,ye=0,$={isRunning:false,isReconciling:false,reconcileScheduled:false,isInitializing:false,isInitialized:false,isReady:false,isDestroyed:false,changedKeys:new Set,previousRequirements:new Re,readyPromise:null,readyResolve:null},oe=Ze({mergedConstraints:m,mergedResolvers:p,mergedDerive:S,mergedEffects:O,constraintsManager:b,resolversManager:A,derivationsManager:ee,effectsManager:ue,pluginManager:k,getState:()=>$,scheduleReconcile:de,maxDeferredRegistrations:he});function de(){!$.isRunning||$.reconcileScheduled||$.isInitializing||($.reconcileScheduled=true,ve(),queueMicrotask(()=>{$.reconcileScheduled=false,$.isRunning&&!$.isInitializing&&Se().catch(e=>{f&&console.error("[Directive] Unexpected error in reconcile:",e);});}));}async function Se(){if($.isReconciling)return;if(ye++,ye>pe){f&&console.warn(`[Directive] Reconcile loop exceeded ${pe} iterations. This usually means resolvers are creating circular requirement chains. Check that resolvers aren't mutating facts that re-trigger their own constraints.`),R&&a.drainPendingChanges(),$.previousRequirements=new Re,ye=0;return}$.isReconciling=true,ve();let e=R?a.startRun():0,n=a.currentTrace;if(n)for(let s of n.factChanges){let D=r[s.key];s.meta=D?._meta;}try{if($.changedKeys.size>0){if(F===null||W){let t=$.changedKeys,i=t.size<=5?`facts-changed:${[...t].join(",")}`:`facts-changed:${[...t].slice(0,5).join(",")}+${t.size-5}more`;fe.takeSnapshot(i);}W=!1;}let s=Q.$snapshot();k.emitReconcileStart(s),await ue.runEffects($.changedKeys);let D=new Set($.changedKeys);$.changedKeys.clear();let x=await b.evaluate(D),M=new Re;for(let t of x)M.add(t),k.emitRequirementCreated(t);if(n){let t=new Set(x.map(i=>i.fromConstraint));for(let i of t){let l=b.getState(i);if(l){let C=b.getDependencies(i);n.constraintsHit.push({id:i,priority:l.priority,deps:C?[...C]:[],meta:m[i]?.meta});}}}let{added:L,removed:Y}=M.diff($.previousRequirements);if(n){for(let t of L)n.requirementsAdded.push({id:t.id,type:t.requirement.type,fromConstraint:t.fromConstraint});for(let t of Y)n.requirementsRemoved.push({id:t.id,type:t.requirement.type,fromConstraint:t.fromConstraint});}for(let t of Y)A.cancel(t.id);for(let t of L)A.resolve(t);if(n){let t=A.getInflightInfo(),i=new Map(t.map(l=>[l.id,l]));for(let l of L){let T=i.get(l.id)?.resolverId??"unknown";n.resolversStarted.push({resolver:T,requirementId:l.id,meta:p[T]?.meta}),a.attributeResolverStart(l.id);}}if($.previousRequirements=M,E.size>0){for(let t of E)$.previousRequirements.remove(t);E.clear(),de();}let ne=A.getInflightInfo();if(d.plugins&&d.plugins.length>0){let t=Y.length>0?new Map(ne.map(l=>[l.id,l.resolverId])):void 0,i={unmet:x.filter(l=>!A.isResolving(l.id)),inflight:ne,completed:[],canceled:Y.map(l=>({id:l.id,resolverId:t?.get(l.id)??"unknown"}))};k.emitReconcileEnd(i);}$.isReady||($.isReady=!0,$.readyResolve&&($.readyResolve(),$.readyResolve=null));}finally{R&&a.finalizeCurrentRun(e),$.isReconciling=false,oe.flushDeferred(),ye=0,$.changedKeys.size>0&&de(),ve();}}function we(e,n){let s=P[e];if(s){K++,(F===null||F.has(e))&&(W=true);try{I.batch(()=>{s(Q,{type:e,...n});});}finally{K--;}}else f&&console.warn(`[Directive] Unknown event type "${e}". No handler is registered for this event. Available events: ${Object.keys(P).join(", ")||"(none)"}`);}let o=Xe({mergedDerive:S,getDerivation:e=>ee.get(e),definitions:oe}),v=Ge({mergedEvents:P,dispatchEvent:we});function y(){let e=[];for(let[n,s]of _)e.push({type:"module",id:n,meta:s});for(let n of Object.keys(r)){let s=r[n]?._meta;s&&e.push({type:"fact",id:n,meta:s});}for(let[n,s]of B)e.push({type:"event",id:n,meta:s});for(let[n,s]of Object.entries(m))s.meta&&e.push({type:"constraint",id:n,meta:s.meta});for(let[n,s]of Object.entries(p))s.meta&&e.push({type:"resolver",id:n,meta:s.meta});for(let[n,s]of Object.entries(O)){let D=s.meta;D&&e.push({type:"effect",id:n,meta:D});}for(let n of Object.keys(S)){let s=ee.getMeta(n);s&&e.push({type:"derivation",id:n,meta:s});}return e}let q={facts:Q,history:fe.isEnabled?fe:null,derive:o,events:v,constraints:{disable:e=>b.disable(e),enable:e=>b.enable(e),isDisabled:e=>b.isDisabled(e),register:(e,n)=>{oe.register("constraint",e,n);},assign:(e,n)=>{oe.assign("constraint",e,n);},unregister:e=>{oe.unregister("constraint",e);},call:(e,n)=>oe.call("constraint",e,n),isDynamic:e=>oe.isDynamic("constraint",e),listDynamic:()=>oe.listDynamic("constraint")},effects:{disable:e=>ue.disable(e),enable:e=>ue.enable(e),isEnabled:e=>ue.isEnabled(e),register:(e,n)=>{oe.register("effect",e,n);},assign:(e,n)=>{oe.assign("effect",e,n);},unregister:e=>{oe.unregister("effect",e);},call:e=>oe.call("effect",e),isDynamic:e=>oe.isDynamic("effect",e),listDynamic:()=>oe.listDynamic("effect")},resolvers:{register:(e,n)=>{oe.register("resolver",e,n),c$1({[e]:n});},assign:(e,n)=>{oe.assign("resolver",e,n),c$1({[e]:n});},unregister:e=>{let n=p[e];n?.key&&typeof n.requirement=="string"&&b.removeRequirementKey(n.requirement),oe.unregister("resolver",e);},call:(e,n)=>oe.call("resolver",e,n),isDynamic:e=>oe.isDynamic("resolver",e),listDynamic:()=>oe.listDynamic("resolver")},get trace(){return a.getEntries()},meta:{module(e){return _.get(e)},fact(e){return r[e]?._meta},event(e){return B.get(e)},constraint(e){return m[e]?.meta},resolver(e){return p[e]?.meta},effect(e){return O[e]?.meta},derivation(e){return ee.getMeta(e)},byCategory(e){return y().filter(n=>n.meta.category===e)},byTag(e){return y().filter(n=>n.meta.tags?.includes(e))}},observe(e){if(k.getPlugins().filter(x=>x.name.startsWith("__observer_")).length>=100)return f&&console.warn("[Directive] Maximum observer limit (100) reached. Call the unsubscribe function returned by observe() to clean up."),()=>{};let s=`__observer_${Date.now()}_${Math.random().toString(36).slice(2)}`,D={name:s,onInit:()=>e({type:"system.init"}),onStart:()=>e({type:"system.start"}),onStop:()=>e({type:"system.stop"}),onDestroy:()=>e({type:"system.destroy"}),onFactSet:(x,M,L)=>e({type:"fact.change",key:x,prev:L,next:M}),onConstraintEvaluate:(x,M)=>e({type:"constraint.evaluate",id:x,active:M}),onConstraintError:(x,M)=>e({type:"constraint.error",id:x,error:M}),onRequirementCreated:x=>e({type:"requirement.created",id:x.id,requirementType:x.requirement.type}),onRequirementMet:(x,M)=>e({type:"requirement.met",id:x.id,byResolver:M}),onRequirementCanceled:x=>e({type:"requirement.canceled",id:x.id}),onResolverStart:(x,M)=>e({type:"resolver.start",resolver:x,requirementId:M.id}),onResolverComplete:(x,M,L)=>e({type:"resolver.complete",resolver:x,requirementId:M.id,duration:L}),onResolverError:(x,M,L)=>e({type:"resolver.error",resolver:x,requirementId:M.id,error:L}),onEffectRun:x=>e({type:"effect.run",id:x}),onEffectError:(x,M)=>e({type:"effect.error",id:x,error:M}),onDerivationCompute:(x,M)=>e({type:"derivation.compute",id:x,value:M}),onReconcileStart:()=>e({type:"reconcile.start"}),onReconcileEnd:x=>{let M=x;e({type:"reconcile.end",resolversCompleted:Array.isArray(M.completed)?M.completed.length:0,resolversCanceled:Array.isArray(M.canceled)?M.canceled.length:0});}};return k.register(D),()=>k.unregister(s)},initialize(){if(!$.isInitialized){$.isInitializing=true;for(let e of d.modules)e.init&&I.batch(()=>{e.init(Q);});d.onAfterModuleInit&&I.batch(()=>{d.onAfterModuleInit();}),$.isInitializing=false,$.isInitialized=true;for(let e of Object.keys(S))ee.get(e);}},start(){if(!$.isRunning){$.isInitialized||this.initialize(),$.isRunning=true;for(let e of d.modules)e.hooks?.onStart?.(q);if(k.emitStart(q),d.errorBoundary?.retryLater&&!X){let e=Math.max(d.errorBoundary.retryLater.delayMs??1e3,250);X=setInterval(()=>{let n=H.processDueRetries();for(let s of n)s.callback?s.callback():de();},Math.min(e,500));}de();}},stop(){if($.isRunning){$.isRunning=false,X!==null&&(clearInterval(X),X=null),H.getRetryLaterManager().clearAll(),A.cancelAll(),ue.cleanupAll();for(let e of d.modules)e.hooks?.onStop?.(q);k.emitStop(q);}},destroy(){$.isDestroyed||(this.stop(),$.isDestroyed=true,I.destroy?.(),A.destroy(),H.clearErrors(),ge.clear(),te.clear(),a.destroy(),oe.destroy(),_.clear(),B.clear(),E.clear(),k.emitDestroy(q));},dispatch(e){l.has(e.type)||we(e.type,e);},read(e){return ee.get(e)},subscribe(e,n){let s=[],D=[];for(let M of e)M in S?s.push(M):M in r?D.push(M):f&&console.warn(`[Directive] subscribe: unknown key "${M}"`);let x=[];return s.length>0&&x.push(ee.subscribe(s,n)),D.length>0&&x.push(I.subscribe(D,n)),()=>{for(let M of x)M();}},watch(e,n,s){let D=s?.equalityFn?(M,L)=>s.equalityFn(M,L):(M,L)=>Object.is(M,L);if(e in S){let M=ee.get(e);return ee.subscribe([e],()=>{let L=ee.get(e);if(!D(L,M)){let Y=M;M=L,n(L,Y);}})}f&&(e in r||console.warn(`[Directive] watch: unknown key "${e}"`));let x=I.get(e);return I.subscribe([e],()=>{let M=I.get(e);if(!D(M,x)){let L=x;x=M,n(M,L);}})},when(e,n){return new Promise((s,D)=>{let x=I.toObject();if(e(x)){s();return}let M,L,Y=()=>{M?.(),L!==void 0&&clearTimeout(L);};M=I.subscribeAll(()=>{let ne=I.toObject();e(ne)&&(Y(),s());}),n?.timeout!==void 0&&n.timeout>0&&(L=setTimeout(()=>{Y(),D(new Error(`[Directive] when: timed out after ${n.timeout}ms`));},n.timeout));})},inspect(){return {unmet:$.previousRequirements.all(),inflight:A.getInflightInfo(),facts:Object.keys(r).map(e=>({key:e,meta:r[e]?._meta})),events:Object.keys(P).map(e=>({name:e,meta:B.get(e)})),constraints:b.getAllStates().map(e=>({id:e.id,active:e.lastResult??false,disabled:b.isDisabled(e.id),priority:e.priority,hitCount:e.hitCount,lastActiveAt:e.lastActiveAt,meta:m[e.id]?.meta})),resolvers:Object.fromEntries(A.getInflight().map(e=>[e,A.getStatus(e)])),resolverDefs:Object.entries(p).map(([e,n])=>({id:e,requirement:typeof n.requirement=="string"?n.requirement:"(predicate)",meta:n.meta})),effects:Object.entries(O).map(([e,n])=>({id:e,meta:n.meta})),derivations:Object.keys(S).map(e=>({id:e,meta:ee.getMeta(e)})),modules:d.modules.map(e=>({id:e.id,meta:_.get(e.id)})),traceEnabled:R,...R?{trace:structuredClone(a.getEntries()??[])}:{}}},explain(e){let s=$.previousRequirements.all().find(C=>C.id===e);if(!s)return null;let D=b.getState(s.fromConstraint),x=A.getStatus(e),M={},L=b.getDependencies(s.fromConstraint);if(L)for(let C of L)M[C]=I.get(C);else for(let[C,T]of Object.entries(I.toObject()))M[C]=T;let Y=m[s.fromConstraint],ne=Y?.meta?.label??s.fromConstraint,t=[`Requirement "${s.requirement.type}" (id: ${s.id})`,`\u251C\u2500 Produced by constraint: ${ne}`,`\u251C\u2500 Constraint priority: ${D?.priority??0}`,`\u251C\u2500 Constraint active: ${D?.lastResult??"unknown"}`,`\u251C\u2500 Resolver status: ${x.state}`];Y?.meta?.description&&t.push(`\u251C\u2500 Description: ${Y.meta.description}`);let i=Object.entries(s.requirement).filter(([C])=>C!=="type").map(([C,T])=>`${C}=${JSON.stringify(T)}`).join(", ");i&&t.push(`\u251C\u2500 Requirement payload: { ${i} }`);let l=Object.entries(M).slice(0,10);return l.length>0&&(t.push("\u2514\u2500 Relevant facts:"),l.forEach(([C,T],Z)=>{let se=Z===l.length-1?" \u2514\u2500":" \u251C\u2500",ae=typeof T=="object"?JSON.stringify(T):String(T);t.push(`${se} ${C} = ${ae.slice(0,50)}${ae.length>50?"...":""}`);})),t.join(`
2
- `)},getOriginal(e,n){return oe.getOriginal(e,n)},restoreOriginal(e,n){return oe.restoreOriginal(e,n)},async settle(e=5e3){let n=()=>A.getInflightCount()===0&&!$.isReconciling&&!$.reconcileScheduled&&!A.hasPendingBatches();if(A.hasPendingBatches()&&A.processBatches(),await new Promise(s=>queueMicrotask(s)),!n())return new Promise((s,D)=>{let x=false,M=()=>{x||(x=true,clearTimeout(L),Y());},L=setTimeout(()=>{M();let ne=[],t=A.getInflightInfo();t.length>0&&ne.push(`${t.length} resolvers inflight: ${t.map(l=>l.resolverId).join(", ")}`),$.isReconciling&&ne.push("reconciliation in progress"),$.reconcileScheduled&&ne.push("reconcile scheduled");let i=$.previousRequirements.all();i.length>0&&ne.push(`${i.length} unmet requirements: ${i.map(l=>l.requirement.type).join(", ")}`),D(new Error(`[Directive] settle() timed out after ${e}ms. ${ne.join("; ")}`));},e),Y=this.onSettledChange(()=>{A.hasPendingBatches()&&A.processBatches(),queueMicrotask(()=>{!x&&n()&&(M(),s());});});})},getSnapshot(){return {facts:I.toObject(),version:1}},getDistributableSnapshot(e$1={}){let{includeDerivations:n,excludeDerivations:s,includeFacts:D,ttlSeconds:x,metadata:M,includeVersion:L}=e$1,Y={},ne=Object.keys(S),t=new Set(ne),i;if(n){if(i=n.filter(T=>t.has(T)),f){let T=n.filter(Z=>!t.has(Z));T.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown derivation keys ignored: ${T.join(", ")}. Available: ${ne.join(", ")||"(none)"}`);}}else i=ne;if(s){let T=new Set(s);i=i.filter(Z=>!T.has(Z));}for(let T of i)try{Y[T]=ee.get(T);}catch(Z){f&&console.warn(`[Directive] getDistributableSnapshot: Skipping derivation "${T}" due to error:`,Z);}if(D&&D.length>0){let T=I.toObject(),Z=Object.keys(T);if(f){let se=D.filter(ae=>!(ae in T));se.length>0&&console.warn(`[Directive] getDistributableSnapshot: Unknown fact keys ignored: ${se.join(", ")}. Available: ${Z.join(", ")||"(none)"}`);}for(let se of D)se in T&&(Y[se]=T[se]);}let l=Date.now(),C={data:Y,createdAt:l};return x!==void 0&&x>0&&(C.expiresAt=l+x*1e3),L&&(C.version=e(Y)),M&&(C.metadata=M),C},watchDistributableSnapshot(e,n){let{includeDerivations:s,excludeDerivations:D}=e,x=Object.keys(S),M;if(s?M=s.filter(ne=>x.includes(ne)):M=x,D){let ne=new Set(D);M=M.filter(t=>!ne.has(t));}if(M.length===0)return f&&console.warn("[Directive] watchDistributableSnapshot: No derivations to watch. Callback will never be called."),()=>{};let Y=this.getDistributableSnapshot({...e,includeVersion:true}).version;return ee.subscribe(M,()=>{let ne=this.getDistributableSnapshot({...e,includeVersion:true});ne.version!==Y&&(Y=ne.version,n(ne));})},restore(e){if(!e||typeof e!="object")throw new Error("[Directive] restore() requires a valid snapshot object");if(!e.facts||typeof e.facts!="object")throw new Error("[Directive] restore() snapshot must have a facts object");if(!c(e))throw new Error("[Directive] restore() rejected: snapshot contains potentially dangerous keys (__proto__, constructor, or prototype). This may indicate a prototype pollution attack.");I.batch(()=>{for(let[n,s]of Object.entries(e.facts))l.has(n)||I.set(n,s);});},onSettledChange(e){return ge.add(e),()=>{ge.delete(e);}},onHistoryChange(e){return te.add(e),()=>{te.delete(e);}},batch(e){I.batch(e);},get isSettled(){return A.getInflightCount()===0&&!A.hasPendingBatches()&&!$.isReconciling&&!$.reconcileScheduled},get isRunning(){return $.isRunning},get isInitialized(){return $.isInitialized},get isReady(){return $.isReady},whenReady(){return $.isReady?Promise.resolve():$.isRunning?($.readyPromise||($.readyPromise=new Promise(e=>{$.readyResolve=e;})),$.readyPromise):Promise.reject(new Error("[Directive] whenReady() called before start(). Call system.start() first, then await system.whenReady()."))}};function z(e){if($.isReconciling)throw new Error(`[Directive] Cannot register module "${e.id}" during reconciliation. Wait for the current reconciliation cycle to complete.`);if($.isDestroyed)throw new Error(`[Directive] Cannot register module "${e.id}" on a destroyed system.`);let n=(s,D)=>{if(s)for(let x of Object.keys(s)){if(l.has(x))throw new Error(`[Directive] Security: Module "${e.id}" has dangerous key "${x}" in ${D}.`);if(D==="schema"&&x.startsWith("$"))throw new Error(`[Directive] Module "${e.id}" has schema key "${x}" starting with "$". Keys starting with $ are reserved for internal accessors ($store, $snapshot).`)}};n(e.schema,"schema"),n(e.events,"events"),n(e.derive,"derive"),n(e.effects,"effects"),n(e.constraints,"constraints"),n(e.resolvers,"resolvers");for(let s of Object.keys(e.schema))if(s in r)throw new Error(`[Directive] Schema collision: Fact "${s}" already exists. Cannot register module "${e.id}".`);if(f&&e.derive){let s=new Set(Object.keys(r));for(let D of Object.keys(e.derive))s.has(D)&&console.warn(`[Directive] "${D}" exists as both a fact and a derivation after registering module "${e.id}".`);}if(e.history?.snapshotEvents){F===null&&(F=new Set(Object.keys(P)));for(let s of e.history.snapshotEvents)F.add(s);}else if(F!==null&&e.events)for(let s of Object.keys(e.events))F.add(s);Object.assign(r,e.schema);for(let s of Object.values(e.schema)){let D=s;D._meta&&(D._meta=le(D._meta));}if(e.events){for(let[s,D]of Object.entries(e.events))if(typeof D=="object"&&D!==null&&Object.hasOwn(D,"handler")){let x=D;if(e.events[s]=x.handler,x.meta){let M=le(x.meta);M&&B.set(s,M);}}Object.assign(P,e.events);}if(e.derive&&(Object.assign(S,e.derive),ee.registerDefinitions(e.derive)),e.effects){for(let s of Object.values(e.effects)){let D=s;D.meta&&(D.meta=le(D.meta));}Object.assign(O,e.effects),ue.registerDefinitions(e.effects);}if(e.constraints){for(let s of Object.values(e.constraints)){let D=s;D.meta&&(D.meta=le(D.meta));}Object.assign(m,e.constraints),b.registerDefinitions(e.constraints);}if(e.resolvers){for(let s of Object.values(e.resolvers)){let D=s;D.meta&&(D.meta=le(D.meta));}Object.assign(p,e.resolvers);for(let s of Object.keys(e.resolvers))U.set(s,e);A.registerDefinitions(e.resolvers),c$1(e.resolvers);}if(I.registerKeys(e.schema),e.meta){let s=le(e.meta);s&&_.set(e.id,s);}d.modules.push(e),e.init&&I.batch(()=>{e.init(Q);}),e.hooks?.onInit?.(q),$.isRunning&&(e.hooks?.onStart?.(q),de());}q.registerModule=z,k.emitInit(q);for(let e of d.modules)e.hooks?.onInit?.(q);return q}export{Ie as a,De as b,Qe as c,et as d,tt as e,nt as f,ht as g,St as h,$e as i,Fe as j,it as k,xt as l,It as m,qt as n,Re as o,Be as p,_e as q,We as r,at as s,ze as t,ut as u,ft as v,He as w,Le as x,Je as y,bn as z};//# sourceMappingURL=chunk-E2WETPLH.js.map
3
- //# sourceMappingURL=chunk-E2WETPLH.js.map