@directive-run/core 1.5.0 → 1.6.1

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-2PLP22ZU.js +16 -0
  6. package/dist/chunk-2PLP22ZU.js.map +1 -0
  7. package/dist/chunk-BWBPR34Z.cjs +3 -0
  8. package/dist/chunk-BWBPR34Z.cjs.map +1 -0
  9. package/dist/chunk-EOLY64E6.cjs +3 -0
  10. package/dist/chunk-EOLY64E6.cjs.map +1 -0
  11. package/dist/chunk-HJ3CDQGB.cjs +16 -0
  12. package/dist/chunk-HJ3CDQGB.cjs.map +1 -0
  13. package/dist/chunk-JFUK5NIO.js +3 -0
  14. package/dist/chunk-JFUK5NIO.js.map +1 -0
  15. package/dist/chunk-N4KTCKOI.cjs +7 -0
  16. package/dist/chunk-N4KTCKOI.cjs.map +1 -0
  17. package/dist/chunk-T6IJUWYR.js +3 -0
  18. package/dist/chunk-T6IJUWYR.js.map +1 -0
  19. package/dist/chunk-TZHC4E6S.js +7 -0
  20. package/dist/chunk-TZHC4E6S.js.map +1 -0
  21. package/dist/{helpers-h9PR2JSJ.d.ts → helpers-BwAThjnJ.d.ts} +1 -1
  22. package/dist/{helpers-B1MiHave.d.cts → helpers-CG27mEGG.d.cts} +1 -1
  23. package/dist/index.cjs +4 -1
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +236 -6
  26. package/dist/index.d.ts +236 -6
  27. package/dist/index.js +4 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/internals.cjs +1 -1
  30. package/dist/internals.d.cts +41 -5
  31. package/dist/internals.d.ts +41 -5
  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 +1 -1
  36. package/dist/plugins/index.d.ts +1 -1
  37. package/dist/plugins/index.js +1 -1
  38. package/dist/plugins/index.js.map +1 -1
  39. package/dist/{plugins-Bakr7js6.d.ts → plugins-DvrsPhzx.d.cts} +124 -21
  40. package/dist/{plugins-Bakr7js6.d.cts → plugins-DvrsPhzx.d.ts} +124 -21
  41. package/dist/system-K6OITF5B.js +2 -0
  42. package/dist/{system-744ZPPES.js.map → system-K6OITF5B.js.map} +1 -1
  43. package/dist/system-WNO6PRHB.cjs +2 -0
  44. package/dist/{system-CK3SHMXZ.cjs.map → system-WNO6PRHB.cjs.map} +1 -1
  45. package/dist/testing.cjs +1 -1
  46. package/dist/testing.d.cts +1 -1
  47. package/dist/testing.d.ts +1 -1
  48. package/dist/testing.js +1 -1
  49. package/dist/worker.cjs +1 -1
  50. package/dist/worker.d.cts +1 -1
  51. package/dist/worker.d.ts +1 -1
  52. package/dist/worker.js +1 -1
  53. package/package.json +1 -1
  54. package/dist/chunk-EH2Q754B.js +0 -7
  55. package/dist/chunk-EH2Q754B.js.map +0 -1
  56. package/dist/chunk-HAF5JCET.js +0 -16
  57. package/dist/chunk-HAF5JCET.js.map +0 -1
  58. package/dist/chunk-M5KZXNZX.js +0 -3
  59. package/dist/chunk-M5KZXNZX.js.map +0 -1
  60. package/dist/chunk-PGUTGWUI.cjs +0 -3
  61. package/dist/chunk-PGUTGWUI.cjs.map +0 -1
  62. package/dist/chunk-S3CFYDIB.cjs +0 -7
  63. package/dist/chunk-S3CFYDIB.cjs.map +0 -1
  64. package/dist/chunk-SQVKCJHE.cjs +0 -16
  65. package/dist/chunk-SQVKCJHE.cjs.map +0 -1
  66. package/dist/chunk-YCCQ73C6.js +0 -3
  67. package/dist/chunk-YCCQ73C6.js.map +0 -1
  68. package/dist/chunk-ZHS3EW2Z.cjs +0 -3
  69. package/dist/chunk-ZHS3EW2Z.cjs.map +0 -1
  70. package/dist/system-744ZPPES.js +0 -2
  71. package/dist/system-CK3SHMXZ.cjs +0 -2
@@ -230,9 +230,9 @@ interface DefinitionMeta {
230
230
  * Data-configuration predicates and templates.
231
231
  *
232
232
  * A {@link FactPredicate} is a declarative, serializable boolean spec over a
233
- * module's fact + derivation namespace — the data form of a constraint
234
- * `when`, an effect `on`, or a boolean derivation. A {@link FactTemplate} is
235
- * the value-producing counterpart: a fact-interpolating string.
233
+ * module's fact namespace — the data form of a constraint `when`, an effect
234
+ * `on`, or a boolean derivation. A {@link FactTemplate} is the value-producing
235
+ * counterpart: a fact-interpolating string.
236
236
  *
237
237
  * Convention: `$` marks an operator/expression node inside a predicate or
238
238
  * template body (`$eq`, `$gte`, `$all`, `$template`, `$set`, `$ref`).
@@ -260,10 +260,7 @@ type IsOrderable<V> = [V] extends [number | bigint | Date] ? true : [V] extends
260
260
  * One operator per object — for two operators on the same fact, write the
261
261
  * array form or `$all`. This is by design (the type is the source of truth).
262
262
  *
263
- * `$matches` accepts a `RegExp` only string operands cannot express flags
264
- * (case-insensitivity, dotall, etc.), so the type rejects them. Pass a real
265
- * `RegExp` instance for flag control. (The runtime still accepts a string
266
- * operand for one cycle for back-compat, but emits a dev-warn.)
263
+ * `$matches` requires `RegExp`. The runtime throws on string operands.
267
264
  *
268
265
  * @example
269
266
  * ```ts
@@ -313,7 +310,7 @@ type OperatorObject<V> = {
313
310
  */
314
311
  type PredicateField<V> = V | OperatorObject<V> | ([V] extends [readonly unknown[]] ? never : [V] extends [object] ? PredicateObject<V> : never);
315
312
  /**
316
- * Object form — every key is a fact/derivation name, every value a
313
+ * Object form — every key is a fact name, every value a
317
314
  * {@link PredicateField}. Multiple keys are AND-ed. A nested object value
318
315
  * recurses (partial match), which is how cross-module namespaced predicates
319
316
  * (`{ self: { phase: "red" }, auth: { token: { $exists: true } } }`) work.
@@ -379,6 +376,9 @@ interface FactTemplate {
379
376
  readonly $template: string;
380
377
  }
381
378
  /**
379
+ * *Note: despite the "Selector" name, this does not select from facts — it
380
+ * projects fields of the requirement payload for stable-stringification.*
381
+ *
382
382
  * A resolver dedup key written as data: an ordered list of requirement-payload
383
383
  * field names. `key: ["type", "to"]` dedupes requirements by those fields.
384
384
  *
@@ -395,6 +395,10 @@ interface FactTemplate {
395
395
  */
396
396
  type KeySelector<R> = readonly (keyof R & string)[];
397
397
  /**
398
+ * *Note: Directive's `$ref` is **not** a JSON Pointer or JSON Schema `$ref`.
399
+ * It is a payload field copy — equivalent to `event.payload[key]`. Renaming
400
+ * to `$from` is tracked as a possible v1.6+ additive alias.*
401
+ *
398
402
  * A typed single-field copy from an event payload. Lives in the patch-spec
399
403
  * namespace — used inside a {@link PatchSpec} `$set` value.
400
404
  *
@@ -550,12 +554,15 @@ interface ConstraintDef<S extends Schema, R extends Requirement = Requirement> {
550
554
  /** Timeout for async constraints (ms) */
551
555
  timeout?: number;
552
556
  /**
553
- * Names the facts the resolver dispatched by this constraint *owns*:
554
- * a write from that resolver to an
555
- * owned fact is dropped and the resolver aborted — if the fact was
556
- * changed by anything else since the resolver last wrote it. Writes to
557
- * facts not listed always land; `when()` is not consulted. Omit for no
558
- * binding (default). Ignored on async constraints.
557
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
558
+ * these facts land only if they still hold the snapshot value taken at
559
+ * resolver dispatch; otherwise the write is dropped and the resolver
560
+ * aborted.
561
+ *
562
+ * This is value-based per-fact compare-and-swap with one-shot
563
+ * fact-level poisoning — not a lock, not document versioning. Writes
564
+ * to facts not listed always land; `when()` is not consulted. Omit for
565
+ * no binding (default). Ignored on async constraints.
559
566
  *
560
567
  * @example
561
568
  * ```ts
@@ -1690,9 +1697,10 @@ interface TypedConstraintDef<M extends ModuleSchema> {
1690
1697
  /** Timeout for async constraints (ms) */
1691
1698
  timeout?: number;
1692
1699
  /**
1693
- * Names the facts the resolver dispatched by this constraint owns — an
1694
- * external clobber of one of them drops the resolver's write. Omit for no
1695
- * binding (default). Ignored on async constraints.
1700
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
1701
+ * these facts land only if they still hold the snapshot value taken at
1702
+ * resolver dispatch; otherwise the write is dropped and the resolver
1703
+ * aborted. Omit for no binding (default). Ignored on async constraints.
1696
1704
  */
1697
1705
  owns?: readonly string[];
1698
1706
  /**
@@ -1740,9 +1748,10 @@ interface CrossModuleConstraintDef<M extends ModuleSchema, Deps extends CrossMod
1740
1748
  /** Timeout for async constraints (ms) */
1741
1749
  timeout?: number;
1742
1750
  /**
1743
- * Names the facts the resolver dispatched by this constraint owns —
1744
- * an external clobber of one of them drops the resolver's write. Omit
1745
- * for no binding (default). Ignored on async constraints.
1751
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
1752
+ * these facts land only if they still hold the snapshot value taken at
1753
+ * resolver dispatch; otherwise the write is dropped and the resolver
1754
+ * aborted. Omit for no binding (default). Ignored on async constraints.
1746
1755
  */
1747
1756
  owns?: readonly string[];
1748
1757
  /**
@@ -2511,6 +2520,53 @@ type ObservationEvent = {
2511
2520
  resolver: string;
2512
2521
  requirementId: string;
2513
2522
  error: unknown;
2523
+ } | {
2524
+ /**
2525
+ * A real per-write rejection. A bound resolver's owned-fact write was
2526
+ * dropped because the fact was changed by something outside the
2527
+ * resolver between the resolver's baseline and its next write (RFC-0003
2528
+ * optimistic-concurrency check). `reason` keeps the observation protocol
2529
+ * backend-neutral — future write-rejecting backends can report other
2530
+ * reasons without a new event type.
2531
+ *
2532
+ * `kind` discriminates this `"rejection"` arm from the `"summary"` arm:
2533
+ * `fact`/`expected`/`actual` exist only here; `dropped` only on the
2534
+ * summary. TypeScript forces the narrow.
2535
+ *
2536
+ * @example
2537
+ * ```ts
2538
+ * system.observe((e) => {
2539
+ * if (e.type === "resolver.write.rejected") {
2540
+ * if (e.kind === "summary") {
2541
+ * console.warn(`[rejected] ${e.resolver}: ${e.dropped} more writes dropped`);
2542
+ * } else {
2543
+ * console.warn(`[rejected] ${e.resolver} dropped ${e.fact}`);
2544
+ * }
2545
+ * }
2546
+ * });
2547
+ * ```
2548
+ */
2549
+ type: "resolver.write.rejected";
2550
+ kind: "rejection";
2551
+ resolver: string;
2552
+ requirementId: string;
2553
+ reason: "clobbered";
2554
+ fact: string;
2555
+ expected: unknown;
2556
+ actual: unknown;
2557
+ } | {
2558
+ /**
2559
+ * The per-resolver suppression summary: emitted once when a single
2560
+ * resolver instance exceeds the per-instance write-rejection cap (10).
2561
+ * Further per-write `"rejection"` events for that instance are dropped;
2562
+ * `dropped` reports how many were suppressed.
2563
+ */
2564
+ type: "resolver.write.rejected";
2565
+ kind: "summary";
2566
+ resolver: string;
2567
+ requirementId: string;
2568
+ reason: "clobbered";
2569
+ dropped: number;
2514
2570
  } | {
2515
2571
  type: "effect.run";
2516
2572
  id: string;
@@ -2874,6 +2930,53 @@ interface Plugin<M extends ModuleSchema = ModuleSchema> {
2874
2930
  * @param req - The requirement that was canceled
2875
2931
  */
2876
2932
  onResolverCancel?: (resolver: string, req: RequirementWithId) => void;
2933
+ /**
2934
+ * Called when a resolver's write is rejected by the runtime. The only
2935
+ * `reason` today is `"clobbered"`: a bound resolver (RFC-0003) dropped a
2936
+ * write to an owned fact because the fact was changed by something outside
2937
+ * the resolver between the resolver's baseline and its next write — the
2938
+ * resolver's `AbortController` is aborted in the same step. See
2939
+ * {@link createBoundFacts} for the per-fact optimistic-concurrency model.
2940
+ * `reason` keeps the hook backend-neutral.
2941
+ *
2942
+ * The `event` is a discriminated union on `kind`:
2943
+ * - `"rejection"` — a real per-write rejection; carries
2944
+ * `fact`/`expected`/`actual`.
2945
+ * - `"summary"` — the per-resolver suppression summary, emitted once when a
2946
+ * single resolver instance exceeds the per-instance write-rejection cap
2947
+ * (10); carries `dropped` (the count of suppressed `"rejection"` events).
2948
+ *
2949
+ * @param event - The write-rejection event (discriminated on `kind`).
2950
+ *
2951
+ * @example
2952
+ * ```ts
2953
+ * const myPlugin: Plugin = {
2954
+ * name: "write-rejection-logger",
2955
+ * onResolverWriteRejected(event) {
2956
+ * if (event.kind === "summary") {
2957
+ * console.warn(`[${event.resolver}] suppressed ${event.dropped} write rejections`);
2958
+ * return;
2959
+ * }
2960
+ * console.warn(`[clobber] ${event.resolver}: ${event.fact} expected=${JSON.stringify(event.expected)} actual=${JSON.stringify(event.actual)}`);
2961
+ * },
2962
+ * };
2963
+ * ```
2964
+ */
2965
+ onResolverWriteRejected?: (event: {
2966
+ kind: "rejection";
2967
+ resolver: string;
2968
+ req: RequirementWithId;
2969
+ reason: "clobbered";
2970
+ fact: string;
2971
+ expected: unknown;
2972
+ actual: unknown;
2973
+ } | {
2974
+ kind: "summary";
2975
+ resolver: string;
2976
+ req: RequirementWithId;
2977
+ reason: "clobbered";
2978
+ dropped: number;
2979
+ }) => void;
2877
2980
  /**
2878
2981
  * Called when an effect runs.
2879
2982
  * @param id - The effect ID
@@ -2943,4 +3046,4 @@ interface Plugin<M extends ModuleSchema = ModuleSchema> {
2943
3046
  onTraceComplete?: (entry: TraceEntry) => void;
2944
3047
  }
2945
3048
 
2946
- export { type OperatorObject as $, type AnySystem as A, type BatchConfig as B, type ClauseResult as C, type DefinitionMeta as D, type EffectsDef as E, type FactTemplate as F, type FactsSnapshot as G, type HistoryAPI as H, type HistoryOption as I, type HistoryState as J, type InferDerivations as K, type InferEvents as L, type ModuleSchema as M, type NamespacedSystem as N, type InferFacts as O, type PatchSpec as P, type InferRequirementTypes as Q, type RequirementWithId as R, type SchemaType as S, type TypedDerivationsDef as T, type InferRequirements as U, type InferSchemaType as V, type InferSelectorState as W, type KeySelector as X, type MetaAccessor as Y, type MetaMatch as Z, type ObservationEvent as _, type Facts as a, type RequirementsSchema as a$, type PatchValue as a0, type PayloadRef as a1, type PredicateClause as a2, type PredicateCombinator as a3, type PredicateCombinatorKey as a4, type PredicateObject as a5, type PredicateOp as a6, type RetryPolicy as a7, type Schema as a8, type Snapshot as a9, type DerivationReturnType as aA, type DerivationsControl as aB, type DerivationsSchema as aC, type DeriveAccessor as aD, type DispatchEventsFromSchema as aE, type EffectCleanup as aF, type EffectsControl as aG, type EventPayloadSchema as aH, type EventsAccessor as aI, type EventsAccessorFromSchema as aJ, type EventsDef as aK, type EventsSchema as aL, type FactKeys as aM, type FactReturnType as aN, type FlexibleEventHandler as aO, type HistoryConfig as aP, type InferEventPayloadFromSchema as aQ, type InferRequirementPayloadFromSchema as aR, type InferSchema as aS, type MutableNamespacedFacts as aT, type NamespacedDerivations as aU, type NamespacedEventsAccessor as aV, type NamespacedFacts as aW, type ObservableKeys as aX, type RequirementExplanation as aY, type RequirementOutput as aZ, type RequirementPayloadSchema$1 as a_, type System as aa, type SystemConfig as ab, type SystemInspection as ac, type SystemMode as ad, type SystemSnapshot as ae, type TraceEntry as af, isNamespacedSystem as ag, isSingleModuleSystem as ah, type FactsStore as ai, type ConstraintsDef as aj, type ConstraintState as ak, type ResolversDef as al, type ResolverStatus as am, type FactChange as an, type ReconcileResult as ao, type RecoveryStrategy as ap, type ErrorSource as aq, type RetryLaterConfig as ar, type BatchItemResult as as, type BatchResolveResults as at, type ConstraintsControl as au, type CrossModuleConstraintDef as av, type CrossModuleDerivationFn as aw, type CrossModuleEffectDef as ax, type CrossModuleFactsWithSelf as ay, type DerivationKeys as az, type TypedEventsDef as b, type ResolverContext as b0, type ResolversControl as b1, type SnapshotMeta as b2, type SystemEvent as b3, type TraceConfig as b4, type TypedConstraintDef as b5, type TypedResolverContext as b6, type TypedResolverDef as b7, type UnionEvents as b8, type RequirementOutput$1 as b9, type TypedConstraintsDef as c, type TypedResolversDef as d, type ModuleHooks as e, type CrossModuleDeps as f, type CrossModuleDerivationsDef as g, type CrossModuleEffectsDef as h, type CrossModuleConstraintsDef as i, type ModuleDef as j, type CreateSystemOptionsSingle as k, type SingleModuleSystem as l, type ModulesMap as m, type CreateSystemOptionsNamed as n, type Plugin as o, type TraceOption as p, type ErrorBoundaryConfig as q, type Requirement as r, type RequirementKeyFn as s, DirectiveError as t, type DistributableSnapshot as u, type DistributableSnapshotOptions as v, type DynamicConstraintDef as w, type DynamicEffectDef as x, type DynamicResolverDef as y, type FactPredicate as z };
3049
+ export { type OperatorObject as $, type AnySystem as A, type BatchConfig as B, type ClauseResult as C, type DefinitionMeta as D, type EffectsDef as E, type FactTemplate as F, type FactsSnapshot as G, type HistoryAPI as H, type HistoryOption as I, type HistoryState as J, type InferDerivations as K, type InferEvents as L, type ModuleSchema as M, type NamespacedSystem as N, type InferFacts as O, type PatchSpec as P, type InferRequirementTypes as Q, type RequirementWithId as R, type SchemaType as S, type TypedDerivationsDef as T, type InferRequirements as U, type InferSchemaType as V, type InferSelectorState as W, type KeySelector as X, type MetaAccessor as Y, type MetaMatch as Z, type ObservationEvent as _, type FactPredicate as a, type RequirementsSchema as a$, type PatchValue as a0, type PayloadRef as a1, type PredicateClause as a2, type PredicateCombinator as a3, type PredicateCombinatorKey as a4, type PredicateObject as a5, type PredicateOp as a6, type RetryPolicy as a7, type Schema as a8, type Snapshot as a9, type DerivationReturnType as aA, type DerivationsControl as aB, type DerivationsSchema as aC, type DeriveAccessor as aD, type DispatchEventsFromSchema as aE, type EffectCleanup as aF, type EffectsControl as aG, type EventPayloadSchema as aH, type EventsAccessor as aI, type EventsAccessorFromSchema as aJ, type EventsDef as aK, type EventsSchema as aL, type FactKeys as aM, type FactReturnType as aN, type FlexibleEventHandler as aO, type HistoryConfig as aP, type InferEventPayloadFromSchema as aQ, type InferRequirementPayloadFromSchema as aR, type InferSchema as aS, type MutableNamespacedFacts as aT, type NamespacedDerivations as aU, type NamespacedEventsAccessor as aV, type NamespacedFacts as aW, type ObservableKeys as aX, type RequirementExplanation as aY, type RequirementOutput as aZ, type RequirementPayloadSchema$1 as a_, type System as aa, type SystemConfig as ab, type SystemInspection as ac, type SystemMode as ad, type SystemSnapshot as ae, type TraceEntry as af, isNamespacedSystem as ag, isSingleModuleSystem as ah, type FactsStore as ai, type ConstraintsDef as aj, type ConstraintState as ak, type ResolversDef as al, type ResolverStatus as am, type FactChange as an, type ReconcileResult as ao, type RecoveryStrategy as ap, type ErrorSource as aq, type RetryLaterConfig as ar, type BatchItemResult as as, type BatchResolveResults as at, type ConstraintsControl as au, type CrossModuleConstraintDef as av, type CrossModuleDerivationFn as aw, type CrossModuleEffectDef as ax, type CrossModuleFactsWithSelf as ay, type DerivationKeys as az, type Facts as b, type ResolverContext as b0, type ResolversControl as b1, type SnapshotMeta as b2, type SystemEvent as b3, type TraceConfig as b4, type TypedConstraintDef as b5, type TypedResolverContext as b6, type TypedResolverDef as b7, type UnionEvents as b8, type RequirementOutput$1 as b9, type TypedEventsDef as c, type TypedConstraintsDef as d, type TypedResolversDef as e, type ModuleHooks as f, type CrossModuleDeps as g, type CrossModuleDerivationsDef as h, type CrossModuleEffectsDef as i, type CrossModuleConstraintsDef as j, type ModuleDef as k, type CreateSystemOptionsSingle as l, type SingleModuleSystem as m, type ModulesMap as n, type CreateSystemOptionsNamed as o, type Plugin as p, type TraceOption as q, type ErrorBoundaryConfig as r, type Requirement as s, type RequirementKeyFn as t, DirectiveError as u, type DistributableSnapshot as v, type DistributableSnapshotOptions as w, type DynamicConstraintDef as x, type DynamicEffectDef as y, type DynamicResolverDef as z };
@@ -230,9 +230,9 @@ interface DefinitionMeta {
230
230
  * Data-configuration predicates and templates.
231
231
  *
232
232
  * A {@link FactPredicate} is a declarative, serializable boolean spec over a
233
- * module's fact + derivation namespace — the data form of a constraint
234
- * `when`, an effect `on`, or a boolean derivation. A {@link FactTemplate} is
235
- * the value-producing counterpart: a fact-interpolating string.
233
+ * module's fact namespace — the data form of a constraint `when`, an effect
234
+ * `on`, or a boolean derivation. A {@link FactTemplate} is the value-producing
235
+ * counterpart: a fact-interpolating string.
236
236
  *
237
237
  * Convention: `$` marks an operator/expression node inside a predicate or
238
238
  * template body (`$eq`, `$gte`, `$all`, `$template`, `$set`, `$ref`).
@@ -260,10 +260,7 @@ type IsOrderable<V> = [V] extends [number | bigint | Date] ? true : [V] extends
260
260
  * One operator per object — for two operators on the same fact, write the
261
261
  * array form or `$all`. This is by design (the type is the source of truth).
262
262
  *
263
- * `$matches` accepts a `RegExp` only string operands cannot express flags
264
- * (case-insensitivity, dotall, etc.), so the type rejects them. Pass a real
265
- * `RegExp` instance for flag control. (The runtime still accepts a string
266
- * operand for one cycle for back-compat, but emits a dev-warn.)
263
+ * `$matches` requires `RegExp`. The runtime throws on string operands.
267
264
  *
268
265
  * @example
269
266
  * ```ts
@@ -313,7 +310,7 @@ type OperatorObject<V> = {
313
310
  */
314
311
  type PredicateField<V> = V | OperatorObject<V> | ([V] extends [readonly unknown[]] ? never : [V] extends [object] ? PredicateObject<V> : never);
315
312
  /**
316
- * Object form — every key is a fact/derivation name, every value a
313
+ * Object form — every key is a fact name, every value a
317
314
  * {@link PredicateField}. Multiple keys are AND-ed. A nested object value
318
315
  * recurses (partial match), which is how cross-module namespaced predicates
319
316
  * (`{ self: { phase: "red" }, auth: { token: { $exists: true } } }`) work.
@@ -379,6 +376,9 @@ interface FactTemplate {
379
376
  readonly $template: string;
380
377
  }
381
378
  /**
379
+ * *Note: despite the "Selector" name, this does not select from facts — it
380
+ * projects fields of the requirement payload for stable-stringification.*
381
+ *
382
382
  * A resolver dedup key written as data: an ordered list of requirement-payload
383
383
  * field names. `key: ["type", "to"]` dedupes requirements by those fields.
384
384
  *
@@ -395,6 +395,10 @@ interface FactTemplate {
395
395
  */
396
396
  type KeySelector<R> = readonly (keyof R & string)[];
397
397
  /**
398
+ * *Note: Directive's `$ref` is **not** a JSON Pointer or JSON Schema `$ref`.
399
+ * It is a payload field copy — equivalent to `event.payload[key]`. Renaming
400
+ * to `$from` is tracked as a possible v1.6+ additive alias.*
401
+ *
398
402
  * A typed single-field copy from an event payload. Lives in the patch-spec
399
403
  * namespace — used inside a {@link PatchSpec} `$set` value.
400
404
  *
@@ -550,12 +554,15 @@ interface ConstraintDef<S extends Schema, R extends Requirement = Requirement> {
550
554
  /** Timeout for async constraints (ms) */
551
555
  timeout?: number;
552
556
  /**
553
- * Names the facts the resolver dispatched by this constraint *owns*:
554
- * a write from that resolver to an
555
- * owned fact is dropped and the resolver aborted — if the fact was
556
- * changed by anything else since the resolver last wrote it. Writes to
557
- * facts not listed always land; `when()` is not consulted. Omit for no
558
- * binding (default). Ignored on async constraints.
557
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
558
+ * these facts land only if they still hold the snapshot value taken at
559
+ * resolver dispatch; otherwise the write is dropped and the resolver
560
+ * aborted.
561
+ *
562
+ * This is value-based per-fact compare-and-swap with one-shot
563
+ * fact-level poisoning — not a lock, not document versioning. Writes
564
+ * to facts not listed always land; `when()` is not consulted. Omit for
565
+ * no binding (default). Ignored on async constraints.
559
566
  *
560
567
  * @example
561
568
  * ```ts
@@ -1690,9 +1697,10 @@ interface TypedConstraintDef<M extends ModuleSchema> {
1690
1697
  /** Timeout for async constraints (ms) */
1691
1698
  timeout?: number;
1692
1699
  /**
1693
- * Names the facts the resolver dispatched by this constraint owns — an
1694
- * external clobber of one of them drops the resolver's write. Omit for no
1695
- * binding (default). Ignored on async constraints.
1700
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
1701
+ * these facts land only if they still hold the snapshot value taken at
1702
+ * resolver dispatch; otherwise the write is dropped and the resolver
1703
+ * aborted. Omit for no binding (default). Ignored on async constraints.
1696
1704
  */
1697
1705
  owns?: readonly string[];
1698
1706
  /**
@@ -1740,9 +1748,10 @@ interface CrossModuleConstraintDef<M extends ModuleSchema, Deps extends CrossMod
1740
1748
  /** Timeout for async constraints (ms) */
1741
1749
  timeout?: number;
1742
1750
  /**
1743
- * Names the facts the resolver dispatched by this constraint owns —
1744
- * an external clobber of one of them drops the resolver's write. Omit
1745
- * for no binding (default). Ignored on async constraints.
1751
+ * Fact keys whose **value the resolver compare-and-swaps**. Writes to
1752
+ * these facts land only if they still hold the snapshot value taken at
1753
+ * resolver dispatch; otherwise the write is dropped and the resolver
1754
+ * aborted. Omit for no binding (default). Ignored on async constraints.
1746
1755
  */
1747
1756
  owns?: readonly string[];
1748
1757
  /**
@@ -2511,6 +2520,53 @@ type ObservationEvent = {
2511
2520
  resolver: string;
2512
2521
  requirementId: string;
2513
2522
  error: unknown;
2523
+ } | {
2524
+ /**
2525
+ * A real per-write rejection. A bound resolver's owned-fact write was
2526
+ * dropped because the fact was changed by something outside the
2527
+ * resolver between the resolver's baseline and its next write (RFC-0003
2528
+ * optimistic-concurrency check). `reason` keeps the observation protocol
2529
+ * backend-neutral — future write-rejecting backends can report other
2530
+ * reasons without a new event type.
2531
+ *
2532
+ * `kind` discriminates this `"rejection"` arm from the `"summary"` arm:
2533
+ * `fact`/`expected`/`actual` exist only here; `dropped` only on the
2534
+ * summary. TypeScript forces the narrow.
2535
+ *
2536
+ * @example
2537
+ * ```ts
2538
+ * system.observe((e) => {
2539
+ * if (e.type === "resolver.write.rejected") {
2540
+ * if (e.kind === "summary") {
2541
+ * console.warn(`[rejected] ${e.resolver}: ${e.dropped} more writes dropped`);
2542
+ * } else {
2543
+ * console.warn(`[rejected] ${e.resolver} dropped ${e.fact}`);
2544
+ * }
2545
+ * }
2546
+ * });
2547
+ * ```
2548
+ */
2549
+ type: "resolver.write.rejected";
2550
+ kind: "rejection";
2551
+ resolver: string;
2552
+ requirementId: string;
2553
+ reason: "clobbered";
2554
+ fact: string;
2555
+ expected: unknown;
2556
+ actual: unknown;
2557
+ } | {
2558
+ /**
2559
+ * The per-resolver suppression summary: emitted once when a single
2560
+ * resolver instance exceeds the per-instance write-rejection cap (10).
2561
+ * Further per-write `"rejection"` events for that instance are dropped;
2562
+ * `dropped` reports how many were suppressed.
2563
+ */
2564
+ type: "resolver.write.rejected";
2565
+ kind: "summary";
2566
+ resolver: string;
2567
+ requirementId: string;
2568
+ reason: "clobbered";
2569
+ dropped: number;
2514
2570
  } | {
2515
2571
  type: "effect.run";
2516
2572
  id: string;
@@ -2874,6 +2930,53 @@ interface Plugin<M extends ModuleSchema = ModuleSchema> {
2874
2930
  * @param req - The requirement that was canceled
2875
2931
  */
2876
2932
  onResolverCancel?: (resolver: string, req: RequirementWithId) => void;
2933
+ /**
2934
+ * Called when a resolver's write is rejected by the runtime. The only
2935
+ * `reason` today is `"clobbered"`: a bound resolver (RFC-0003) dropped a
2936
+ * write to an owned fact because the fact was changed by something outside
2937
+ * the resolver between the resolver's baseline and its next write — the
2938
+ * resolver's `AbortController` is aborted in the same step. See
2939
+ * {@link createBoundFacts} for the per-fact optimistic-concurrency model.
2940
+ * `reason` keeps the hook backend-neutral.
2941
+ *
2942
+ * The `event` is a discriminated union on `kind`:
2943
+ * - `"rejection"` — a real per-write rejection; carries
2944
+ * `fact`/`expected`/`actual`.
2945
+ * - `"summary"` — the per-resolver suppression summary, emitted once when a
2946
+ * single resolver instance exceeds the per-instance write-rejection cap
2947
+ * (10); carries `dropped` (the count of suppressed `"rejection"` events).
2948
+ *
2949
+ * @param event - The write-rejection event (discriminated on `kind`).
2950
+ *
2951
+ * @example
2952
+ * ```ts
2953
+ * const myPlugin: Plugin = {
2954
+ * name: "write-rejection-logger",
2955
+ * onResolverWriteRejected(event) {
2956
+ * if (event.kind === "summary") {
2957
+ * console.warn(`[${event.resolver}] suppressed ${event.dropped} write rejections`);
2958
+ * return;
2959
+ * }
2960
+ * console.warn(`[clobber] ${event.resolver}: ${event.fact} expected=${JSON.stringify(event.expected)} actual=${JSON.stringify(event.actual)}`);
2961
+ * },
2962
+ * };
2963
+ * ```
2964
+ */
2965
+ onResolverWriteRejected?: (event: {
2966
+ kind: "rejection";
2967
+ resolver: string;
2968
+ req: RequirementWithId;
2969
+ reason: "clobbered";
2970
+ fact: string;
2971
+ expected: unknown;
2972
+ actual: unknown;
2973
+ } | {
2974
+ kind: "summary";
2975
+ resolver: string;
2976
+ req: RequirementWithId;
2977
+ reason: "clobbered";
2978
+ dropped: number;
2979
+ }) => void;
2877
2980
  /**
2878
2981
  * Called when an effect runs.
2879
2982
  * @param id - The effect ID
@@ -2943,4 +3046,4 @@ interface Plugin<M extends ModuleSchema = ModuleSchema> {
2943
3046
  onTraceComplete?: (entry: TraceEntry) => void;
2944
3047
  }
2945
3048
 
2946
- export { type OperatorObject as $, type AnySystem as A, type BatchConfig as B, type ClauseResult as C, type DefinitionMeta as D, type EffectsDef as E, type FactTemplate as F, type FactsSnapshot as G, type HistoryAPI as H, type HistoryOption as I, type HistoryState as J, type InferDerivations as K, type InferEvents as L, type ModuleSchema as M, type NamespacedSystem as N, type InferFacts as O, type PatchSpec as P, type InferRequirementTypes as Q, type RequirementWithId as R, type SchemaType as S, type TypedDerivationsDef as T, type InferRequirements as U, type InferSchemaType as V, type InferSelectorState as W, type KeySelector as X, type MetaAccessor as Y, type MetaMatch as Z, type ObservationEvent as _, type Facts as a, type RequirementsSchema as a$, type PatchValue as a0, type PayloadRef as a1, type PredicateClause as a2, type PredicateCombinator as a3, type PredicateCombinatorKey as a4, type PredicateObject as a5, type PredicateOp as a6, type RetryPolicy as a7, type Schema as a8, type Snapshot as a9, type DerivationReturnType as aA, type DerivationsControl as aB, type DerivationsSchema as aC, type DeriveAccessor as aD, type DispatchEventsFromSchema as aE, type EffectCleanup as aF, type EffectsControl as aG, type EventPayloadSchema as aH, type EventsAccessor as aI, type EventsAccessorFromSchema as aJ, type EventsDef as aK, type EventsSchema as aL, type FactKeys as aM, type FactReturnType as aN, type FlexibleEventHandler as aO, type HistoryConfig as aP, type InferEventPayloadFromSchema as aQ, type InferRequirementPayloadFromSchema as aR, type InferSchema as aS, type MutableNamespacedFacts as aT, type NamespacedDerivations as aU, type NamespacedEventsAccessor as aV, type NamespacedFacts as aW, type ObservableKeys as aX, type RequirementExplanation as aY, type RequirementOutput as aZ, type RequirementPayloadSchema$1 as a_, type System as aa, type SystemConfig as ab, type SystemInspection as ac, type SystemMode as ad, type SystemSnapshot as ae, type TraceEntry as af, isNamespacedSystem as ag, isSingleModuleSystem as ah, type FactsStore as ai, type ConstraintsDef as aj, type ConstraintState as ak, type ResolversDef as al, type ResolverStatus as am, type FactChange as an, type ReconcileResult as ao, type RecoveryStrategy as ap, type ErrorSource as aq, type RetryLaterConfig as ar, type BatchItemResult as as, type BatchResolveResults as at, type ConstraintsControl as au, type CrossModuleConstraintDef as av, type CrossModuleDerivationFn as aw, type CrossModuleEffectDef as ax, type CrossModuleFactsWithSelf as ay, type DerivationKeys as az, type TypedEventsDef as b, type ResolverContext as b0, type ResolversControl as b1, type SnapshotMeta as b2, type SystemEvent as b3, type TraceConfig as b4, type TypedConstraintDef as b5, type TypedResolverContext as b6, type TypedResolverDef as b7, type UnionEvents as b8, type RequirementOutput$1 as b9, type TypedConstraintsDef as c, type TypedResolversDef as d, type ModuleHooks as e, type CrossModuleDeps as f, type CrossModuleDerivationsDef as g, type CrossModuleEffectsDef as h, type CrossModuleConstraintsDef as i, type ModuleDef as j, type CreateSystemOptionsSingle as k, type SingleModuleSystem as l, type ModulesMap as m, type CreateSystemOptionsNamed as n, type Plugin as o, type TraceOption as p, type ErrorBoundaryConfig as q, type Requirement as r, type RequirementKeyFn as s, DirectiveError as t, type DistributableSnapshot as u, type DistributableSnapshotOptions as v, type DynamicConstraintDef as w, type DynamicEffectDef as x, type DynamicResolverDef as y, type FactPredicate as z };
3049
+ export { type OperatorObject as $, type AnySystem as A, type BatchConfig as B, type ClauseResult as C, type DefinitionMeta as D, type EffectsDef as E, type FactTemplate as F, type FactsSnapshot as G, type HistoryAPI as H, type HistoryOption as I, type HistoryState as J, type InferDerivations as K, type InferEvents as L, type ModuleSchema as M, type NamespacedSystem as N, type InferFacts as O, type PatchSpec as P, type InferRequirementTypes as Q, type RequirementWithId as R, type SchemaType as S, type TypedDerivationsDef as T, type InferRequirements as U, type InferSchemaType as V, type InferSelectorState as W, type KeySelector as X, type MetaAccessor as Y, type MetaMatch as Z, type ObservationEvent as _, type FactPredicate as a, type RequirementsSchema as a$, type PatchValue as a0, type PayloadRef as a1, type PredicateClause as a2, type PredicateCombinator as a3, type PredicateCombinatorKey as a4, type PredicateObject as a5, type PredicateOp as a6, type RetryPolicy as a7, type Schema as a8, type Snapshot as a9, type DerivationReturnType as aA, type DerivationsControl as aB, type DerivationsSchema as aC, type DeriveAccessor as aD, type DispatchEventsFromSchema as aE, type EffectCleanup as aF, type EffectsControl as aG, type EventPayloadSchema as aH, type EventsAccessor as aI, type EventsAccessorFromSchema as aJ, type EventsDef as aK, type EventsSchema as aL, type FactKeys as aM, type FactReturnType as aN, type FlexibleEventHandler as aO, type HistoryConfig as aP, type InferEventPayloadFromSchema as aQ, type InferRequirementPayloadFromSchema as aR, type InferSchema as aS, type MutableNamespacedFacts as aT, type NamespacedDerivations as aU, type NamespacedEventsAccessor as aV, type NamespacedFacts as aW, type ObservableKeys as aX, type RequirementExplanation as aY, type RequirementOutput as aZ, type RequirementPayloadSchema$1 as a_, type System as aa, type SystemConfig as ab, type SystemInspection as ac, type SystemMode as ad, type SystemSnapshot as ae, type TraceEntry as af, isNamespacedSystem as ag, isSingleModuleSystem as ah, type FactsStore as ai, type ConstraintsDef as aj, type ConstraintState as ak, type ResolversDef as al, type ResolverStatus as am, type FactChange as an, type ReconcileResult as ao, type RecoveryStrategy as ap, type ErrorSource as aq, type RetryLaterConfig as ar, type BatchItemResult as as, type BatchResolveResults as at, type ConstraintsControl as au, type CrossModuleConstraintDef as av, type CrossModuleDerivationFn as aw, type CrossModuleEffectDef as ax, type CrossModuleFactsWithSelf as ay, type DerivationKeys as az, type Facts as b, type ResolverContext as b0, type ResolversControl as b1, type SnapshotMeta as b2, type SystemEvent as b3, type TraceConfig as b4, type TypedConstraintDef as b5, type TypedResolverContext as b6, type TypedResolverDef as b7, type UnionEvents as b8, type RequirementOutput$1 as b9, type TypedEventsDef as c, type TypedConstraintsDef as d, type TypedResolversDef as e, type ModuleHooks as f, type CrossModuleDeps as g, type CrossModuleDerivationsDef as h, type CrossModuleEffectsDef as i, type CrossModuleConstraintsDef as j, type ModuleDef as k, type CreateSystemOptionsSingle as l, type SingleModuleSystem as m, type ModulesMap as n, type CreateSystemOptionsNamed as o, type Plugin as p, type TraceOption as q, type ErrorBoundaryConfig as r, type Requirement as s, type RequirementKeyFn as t, DirectiveError as u, type DistributableSnapshot as v, type DistributableSnapshotOptions as w, type DynamicConstraintDef as x, type DynamicEffectDef as y, type DynamicResolverDef as z };
@@ -0,0 +1,2 @@
1
+ export{a as createSystem}from'./chunk-2PLP22ZU.js';import'./chunk-JFUK5NIO.js';import'./chunk-TZHC4E6S.js';import'./chunk-T6IJUWYR.js';//# sourceMappingURL=system-K6OITF5B.js.map
2
+ //# sourceMappingURL=system-K6OITF5B.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"system-744ZPPES.js"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"system-K6OITF5B.js"}
@@ -0,0 +1,2 @@
1
+ 'use strict';var chunkHJ3CDQGB_cjs=require('./chunk-HJ3CDQGB.cjs');require('./chunk-BWBPR34Z.cjs'),require('./chunk-N4KTCKOI.cjs'),require('./chunk-EOLY64E6.cjs');Object.defineProperty(exports,"createSystem",{enumerable:true,get:function(){return chunkHJ3CDQGB_cjs.a}});//# sourceMappingURL=system-WNO6PRHB.cjs.map
2
+ //# sourceMappingURL=system-WNO6PRHB.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":"","file":"system-CK3SHMXZ.cjs"}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"system-WNO6PRHB.cjs"}
package/dist/testing.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';var chunkSQVKCJHE_cjs=require('./chunk-SQVKCJHE.cjs');require('./chunk-PGUTGWUI.cjs'),require('./chunk-S3CFYDIB.cjs'),require('./chunk-ZHS3EW2Z.cjs');async function R(){for(let e=0;e<10;e++)await Promise.resolve();}async function T(){for(let e=0;e<10;e++)await Promise.resolve();await new Promise(e=>setTimeout(e,0));for(let e=0;e<10;e++)await Promise.resolve();await new Promise(e=>setTimeout(e,0));for(let e=0;e<10;e++)await Promise.resolve();}async function D(e,s,r={}){let{totalTime:o=5e3,stepSize:c=10,maxIterations:l=1e3}=r,m=0,d=0;for(;m<o&&d<l;){if(await R(),e.inspect().inflight.length===0){await R();return}s(c),m+=c,d++;}let v=e.inspect();if(v.inflight.length>0){let f=v.inflight.map(p=>p.resolverId).join(", ");throw new Error(`[Directive] settleWithFakeTimers did not settle after ${o}ms. ${v.inflight.length} resolvers still inflight: ${f}`)}}function C(){let e=0,s=[];return {async advance(r){let o=e+r;for(;s.length>0&&s[0].time<=o;){let c=s.shift();e=c.time,c.callback(),await Promise.resolve();}e=o;},async next(){if(s.length===0)return;let r=s.shift();e=r.time,r.callback(),await Promise.resolve();},async runAll(){for(;s.length>0;)await this.next();},now(){return e},reset(){e=0,s.length=0;}}}function b(e){let s=typeof e=="string"?{requirement:(o=>o.type===e)}:e,r=s.calls??[];return {requirement:s.requirement??(o=>true),async resolve(o,c){if(r.push(o),s.delay&&await new Promise(l=>setTimeout(l,s.delay)),s.error)throw typeof s.error=="string"?new Error(s.error):s.error;s.resolve&&await s.resolve(o,c);}}}function E(e){let s=[],r=[];return {...{get calls(){return s},get pending(){return r},resolve(l){let m=r.shift();m&&m.resolve(l);},reject(l){let m=r.shift();m&&m.reject(l);},resolveAll(l){for(;r.length>0;)this.resolve(l);},rejectAll(l){for(;r.length>0;)this.reject(l);},reset(){s.length=0,r.length=0;}},handler:(l,m)=>(s.push(l),new Promise((d,v)=>{r.push({requirement:l,resolve:f=>d(f),reject:v});}))}}function P(e){return "module"in e?x(e):M(e)}function x(e){let s=[],r=new Map,o=[],c=[],l={};if(e.mocks?.resolvers)for(let[i,t]of Object.entries(e.mocks.resolvers)){let n=[];r.set(i,n),l[i]=b({...t,calls:n});}let m={...e.module,resolvers:{...e.module.resolvers,...l}},v=chunkSQVKCJHE_cjs.a({...e,module:m,plugins:[{name:"__test-tracking__",onFactSet:(i,t,n)=>{c.push({key:i,fullKey:i,namespace:void 0,previousValue:n,newValue:t,timestamp:Date.now()});},onRequirementCreated:i=>{o.push(i);}},...e.plugins??[]]}),f=v.dispatch.bind(v);return v.dispatch=i=>{s.push(i),f(i);},{...v,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(i=5e3){let t=Date.now(),n=async()=>{await new Promise(u=>setTimeout(u,0));let a=v.inspect();if(a.inflight.length>0){if(Date.now()-t>i){let u=a.inflight.map(g=>g.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${i}ms. ${a.inflight.length} resolvers still inflight: ${u}`)}return await new Promise(u=>setTimeout(u,10)),n()}};return n()},assertRequirement(i){if(!o.some(n=>n.requirement.type===i))throw new Error(`[Directive] Expected requirement of type "${i}" but none found`)},assertResolverCalled(i,t){let n=r.get(i)??[];if(t!==void 0){if(n.length!==t)throw new Error(`[Directive] Expected resolver "${i}" to be called ${t} times but was called ${n.length} times`)}else if(n.length===0)throw new Error(`[Directive] Expected resolver "${i}" to be called but it was not`)},assertFactSet(i,t){let n=c.filter(a=>a.key===i);if(n.length===0)throw new Error(`[Directive] Expected fact "${i}" to be set but it was not`);if(t!==void 0&&!n.some(u=>u.newValue===t)){let u=n.map(g=>JSON.stringify(g.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${i}" to be set to ${JSON.stringify(t)} but got: ${u}`)}},assertFactChanges(i,t){let n=c.filter(a=>a.key===i);if(n.length!==t)throw new Error(`[Directive] Expected fact "${i}" to change ${t} times but it changed ${n.length} times`)}}}function M(e){let s=[],r=new Map,o=[],c=[],l={};if(e.mocks?.resolvers)for(let[t,n]of Object.entries(e.mocks.resolvers)){let a=[];r.set(t,a),l[t]=b({...n,calls:a});}let m={};for(let[t,n]of Object.entries(e.modules))m[t]={...n,resolvers:{...n.resolvers,...l}};let d=new Set(Object.keys(e.modules)),f=chunkSQVKCJHE_cjs.a({...e,modules:m,plugins:[{name:"__test-tracking__",onFactSet:(t,n,a)=>{let g=t.indexOf("::"),y,h;if(g>0){let S=t.substring(0,g);d.has(S)?(y=S,h=t.substring(g+2)):h=t;}else h=t;c.push({key:h,fullKey:t,namespace:y,previousValue:a,newValue:n,timestamp:Date.now()});},onRequirementCreated:t=>{o.push(t);}},...e.plugins??[]]}),p=f.dispatch.bind(f);return f.dispatch=t=>{s.push(t),p(t);},{...f,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(t=5e3){let n=Date.now(),a=async()=>{await new Promise(g=>setTimeout(g,0));let u=f.inspect();if(u.inflight.length>0){if(Date.now()-n>t){let g=u.inflight.map(y=>y.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${t}ms. ${u.inflight.length} resolvers still inflight: ${g}`)}return await new Promise(g=>setTimeout(g,10)),a()}};return a()},assertRequirement(t){if(!o.some(a=>a.requirement.type===t))throw new Error(`[Directive] Expected requirement of type "${t}" but none found`)},assertResolverCalled(t,n){let a=r.get(t)??[];if(n!==void 0){if(a.length!==n)throw new Error(`[Directive] Expected resolver "${t}" to be called ${n} times but was called ${a.length} times`)}else if(a.length===0)throw new Error(`[Directive] Expected resolver "${t}" to be called but it was not`)},assertFactSet(t,n){let a=c.filter(u=>u.key===t);if(a.length===0)throw new Error(`[Directive] Expected fact "${t}" to be set but it was not`);if(n!==void 0&&!a.some(g=>g.newValue===n)){let g=a.map(y=>JSON.stringify(y.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${t}" to be set to ${JSON.stringify(n)} but got: ${g}`)}},assertFactChanges(t,n){let a=c.filter(u=>u.key===t);if(a.length!==n)throw new Error(`[Directive] Expected fact "${t}" to change ${n} times but it changed ${a.length} times`)}}}function O(e,s,r){if(!k(e,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to be dynamic, but it is not.`)}function $(e,s,r){if(k(e,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to NOT be dynamic, but it is.`)}function k(e,s,r){switch(s){case "constraint":return e.constraints.isDynamic(r);case "resolver":return e.resolvers.isDynamic(r);case "derivation":return e.derive.isDynamic(r);case "effect":return e.effects.isDynamic(r)}}function F(e){let s=new Set,r=new Set,o=new Set,c=new Set,l=null;return {async run(m){l=e.observe(d=>{switch(d.type){case "constraint.evaluate":d.active&&s.add(d.id);break;case "resolver.start":r.add(d.resolver);break;case "effect.run":o.add(d.id);break;case "derivation.compute":c.add(d.id);break}});try{await m();}finally{l?.(),l=null;}},report(){let m=e.inspect(),d=new Set(m.constraints.map(i=>i.id)),v=new Set(m.resolverDefs.map(i=>i.id)),f=new Set;for(let i of d)s.has(i)||f.add(i);let p=new Set;for(let i of v)r.has(i)||p.add(i);return {constraintsHit:s,constraintsMissed:f,resolversRun:r,resolversMissed:p,effectsRun:o,derivationsComputed:c,constraintCoverage:d.size===0?1:s.size/d.size,resolverCoverage:v.size===0?1:r.size/v.size,effectCoverage:m.effects.length===0?1:o.size/m.effects.length,derivationCoverage:m.derivations.length===0?1:c.size/m.derivations.length}}}}function I(e){let s=[],r=e.observe(o=>s.push(o));return {events:s,ofType(o){return s.filter(c=>c.type===o)},clear(){s.length=0;},dispose(){r();}}}exports.assertDynamic=O;exports.assertNotDynamic=$;exports.createCoverageTracker=F;exports.createFakeTimers=C;exports.createMockResolver=b;exports.createTestObserver=I;exports.createTestSystem=P;exports.flushAsync=T;exports.flushMicrotasks=R;exports.mockResolver=E;exports.settleWithFakeTimers=D;//# sourceMappingURL=testing.cjs.map
1
+ 'use strict';var chunkHJ3CDQGB_cjs=require('./chunk-HJ3CDQGB.cjs');require('./chunk-BWBPR34Z.cjs'),require('./chunk-N4KTCKOI.cjs'),require('./chunk-EOLY64E6.cjs');async function R(){for(let e=0;e<10;e++)await Promise.resolve();}async function T(){for(let e=0;e<10;e++)await Promise.resolve();await new Promise(e=>setTimeout(e,0));for(let e=0;e<10;e++)await Promise.resolve();await new Promise(e=>setTimeout(e,0));for(let e=0;e<10;e++)await Promise.resolve();}async function D(e,s,r={}){let{totalTime:o=5e3,stepSize:c=10,maxIterations:l=1e3}=r,m=0,d=0;for(;m<o&&d<l;){if(await R(),e.inspect().inflight.length===0){await R();return}s(c),m+=c,d++;}let v=e.inspect();if(v.inflight.length>0){let f=v.inflight.map(p=>p.resolverId).join(", ");throw new Error(`[Directive] settleWithFakeTimers did not settle after ${o}ms. ${v.inflight.length} resolvers still inflight: ${f}`)}}function C(){let e=0,s=[];return {async advance(r){let o=e+r;for(;s.length>0&&s[0].time<=o;){let c=s.shift();e=c.time,c.callback(),await Promise.resolve();}e=o;},async next(){if(s.length===0)return;let r=s.shift();e=r.time,r.callback(),await Promise.resolve();},async runAll(){for(;s.length>0;)await this.next();},now(){return e},reset(){e=0,s.length=0;}}}function b(e){let s=typeof e=="string"?{requirement:(o=>o.type===e)}:e,r=s.calls??[];return {requirement:s.requirement??(o=>true),async resolve(o,c){if(r.push(o),s.delay&&await new Promise(l=>setTimeout(l,s.delay)),s.error)throw typeof s.error=="string"?new Error(s.error):s.error;s.resolve&&await s.resolve(o,c);}}}function E(e){let s=[],r=[];return {...{get calls(){return s},get pending(){return r},resolve(l){let m=r.shift();m&&m.resolve(l);},reject(l){let m=r.shift();m&&m.reject(l);},resolveAll(l){for(;r.length>0;)this.resolve(l);},rejectAll(l){for(;r.length>0;)this.reject(l);},reset(){s.length=0,r.length=0;}},handler:(l,m)=>(s.push(l),new Promise((d,v)=>{r.push({requirement:l,resolve:f=>d(f),reject:v});}))}}function P(e){return "module"in e?x(e):M(e)}function x(e){let s=[],r=new Map,o=[],c=[],l={};if(e.mocks?.resolvers)for(let[i,t]of Object.entries(e.mocks.resolvers)){let n=[];r.set(i,n),l[i]=b({...t,calls:n});}let m={...e.module,resolvers:{...e.module.resolvers,...l}},v=chunkHJ3CDQGB_cjs.a({...e,module:m,plugins:[{name:"__test-tracking__",onFactSet:(i,t,n)=>{c.push({key:i,fullKey:i,namespace:void 0,previousValue:n,newValue:t,timestamp:Date.now()});},onRequirementCreated:i=>{o.push(i);}},...e.plugins??[]]}),f=v.dispatch.bind(v);return v.dispatch=i=>{s.push(i),f(i);},{...v,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(i=5e3){let t=Date.now(),n=async()=>{await new Promise(u=>setTimeout(u,0));let a=v.inspect();if(a.inflight.length>0){if(Date.now()-t>i){let u=a.inflight.map(g=>g.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${i}ms. ${a.inflight.length} resolvers still inflight: ${u}`)}return await new Promise(u=>setTimeout(u,10)),n()}};return n()},assertRequirement(i){if(!o.some(n=>n.requirement.type===i))throw new Error(`[Directive] Expected requirement of type "${i}" but none found`)},assertResolverCalled(i,t){let n=r.get(i)??[];if(t!==void 0){if(n.length!==t)throw new Error(`[Directive] Expected resolver "${i}" to be called ${t} times but was called ${n.length} times`)}else if(n.length===0)throw new Error(`[Directive] Expected resolver "${i}" to be called but it was not`)},assertFactSet(i,t){let n=c.filter(a=>a.key===i);if(n.length===0)throw new Error(`[Directive] Expected fact "${i}" to be set but it was not`);if(t!==void 0&&!n.some(u=>u.newValue===t)){let u=n.map(g=>JSON.stringify(g.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${i}" to be set to ${JSON.stringify(t)} but got: ${u}`)}},assertFactChanges(i,t){let n=c.filter(a=>a.key===i);if(n.length!==t)throw new Error(`[Directive] Expected fact "${i}" to change ${t} times but it changed ${n.length} times`)}}}function M(e){let s=[],r=new Map,o=[],c=[],l={};if(e.mocks?.resolvers)for(let[t,n]of Object.entries(e.mocks.resolvers)){let a=[];r.set(t,a),l[t]=b({...n,calls:a});}let m={};for(let[t,n]of Object.entries(e.modules))m[t]={...n,resolvers:{...n.resolvers,...l}};let d=new Set(Object.keys(e.modules)),f=chunkHJ3CDQGB_cjs.a({...e,modules:m,plugins:[{name:"__test-tracking__",onFactSet:(t,n,a)=>{let g=t.indexOf("::"),y,h;if(g>0){let S=t.substring(0,g);d.has(S)?(y=S,h=t.substring(g+2)):h=t;}else h=t;c.push({key:h,fullKey:t,namespace:y,previousValue:a,newValue:n,timestamp:Date.now()});},onRequirementCreated:t=>{o.push(t);}},...e.plugins??[]]}),p=f.dispatch.bind(f);return f.dispatch=t=>{s.push(t),p(t);},{...f,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(t=5e3){let n=Date.now(),a=async()=>{await new Promise(g=>setTimeout(g,0));let u=f.inspect();if(u.inflight.length>0){if(Date.now()-n>t){let g=u.inflight.map(y=>y.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${t}ms. ${u.inflight.length} resolvers still inflight: ${g}`)}return await new Promise(g=>setTimeout(g,10)),a()}};return a()},assertRequirement(t){if(!o.some(a=>a.requirement.type===t))throw new Error(`[Directive] Expected requirement of type "${t}" but none found`)},assertResolverCalled(t,n){let a=r.get(t)??[];if(n!==void 0){if(a.length!==n)throw new Error(`[Directive] Expected resolver "${t}" to be called ${n} times but was called ${a.length} times`)}else if(a.length===0)throw new Error(`[Directive] Expected resolver "${t}" to be called but it was not`)},assertFactSet(t,n){let a=c.filter(u=>u.key===t);if(a.length===0)throw new Error(`[Directive] Expected fact "${t}" to be set but it was not`);if(n!==void 0&&!a.some(g=>g.newValue===n)){let g=a.map(y=>JSON.stringify(y.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${t}" to be set to ${JSON.stringify(n)} but got: ${g}`)}},assertFactChanges(t,n){let a=c.filter(u=>u.key===t);if(a.length!==n)throw new Error(`[Directive] Expected fact "${t}" to change ${n} times but it changed ${a.length} times`)}}}function O(e,s,r){if(!k(e,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to be dynamic, but it is not.`)}function $(e,s,r){if(k(e,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to NOT be dynamic, but it is.`)}function k(e,s,r){switch(s){case "constraint":return e.constraints.isDynamic(r);case "resolver":return e.resolvers.isDynamic(r);case "derivation":return e.derive.isDynamic(r);case "effect":return e.effects.isDynamic(r)}}function F(e){let s=new Set,r=new Set,o=new Set,c=new Set,l=null;return {async run(m){l=e.observe(d=>{switch(d.type){case "constraint.evaluate":d.active&&s.add(d.id);break;case "resolver.start":r.add(d.resolver);break;case "effect.run":o.add(d.id);break;case "derivation.compute":c.add(d.id);break}});try{await m();}finally{l?.(),l=null;}},report(){let m=e.inspect(),d=new Set(m.constraints.map(i=>i.id)),v=new Set(m.resolverDefs.map(i=>i.id)),f=new Set;for(let i of d)s.has(i)||f.add(i);let p=new Set;for(let i of v)r.has(i)||p.add(i);return {constraintsHit:s,constraintsMissed:f,resolversRun:r,resolversMissed:p,effectsRun:o,derivationsComputed:c,constraintCoverage:d.size===0?1:s.size/d.size,resolverCoverage:v.size===0?1:r.size/v.size,effectCoverage:m.effects.length===0?1:o.size/m.effects.length,derivationCoverage:m.derivations.length===0?1:c.size/m.derivations.length}}}}function I(e){let s=[],r=e.observe(o=>s.push(o));return {events:s,ofType(o){return s.filter(c=>c.type===o)},clear(){s.length=0;},dispose(){r();}}}exports.assertDynamic=O;exports.assertNotDynamic=$;exports.createCoverageTracker=F;exports.createFakeTimers=C;exports.createMockResolver=b;exports.createTestObserver=I;exports.createTestSystem=P;exports.flushAsync=T;exports.flushMicrotasks=R;exports.mockResolver=E;exports.settleWithFakeTimers=D;//# sourceMappingURL=testing.cjs.map
2
2
  //# sourceMappingURL=testing.cjs.map
@@ -1,4 +1,4 @@
1
- import { m as ModulesMap, n as CreateSystemOptionsNamed, r as Requirement, M as ModuleSchema, k as CreateSystemOptionsSingle, N as NamespacedSystem, R as RequirementWithId, l as SingleModuleSystem, _ as ObservationEvent, ac as SystemInspection } from './plugins-Bakr7js6.cjs';
1
+ import { n as ModulesMap, o as CreateSystemOptionsNamed, s as Requirement, M as ModuleSchema, l as CreateSystemOptionsSingle, N as NamespacedSystem, R as RequirementWithId, m as SingleModuleSystem, _ as ObservationEvent, ac as SystemInspection } from './plugins-DvrsPhzx.cjs';
2
2
 
3
3
  /**
4
4
  * Flush all pending microtasks by awaiting multiple rounds of `Promise.resolve()`.
package/dist/testing.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { m as ModulesMap, n as CreateSystemOptionsNamed, r as Requirement, M as ModuleSchema, k as CreateSystemOptionsSingle, N as NamespacedSystem, R as RequirementWithId, l as SingleModuleSystem, _ as ObservationEvent, ac as SystemInspection } from './plugins-Bakr7js6.js';
1
+ import { n as ModulesMap, o as CreateSystemOptionsNamed, s as Requirement, M as ModuleSchema, l as CreateSystemOptionsSingle, N as NamespacedSystem, R as RequirementWithId, m as SingleModuleSystem, _ as ObservationEvent, ac as SystemInspection } from './plugins-DvrsPhzx.js';
2
2
 
3
3
  /**
4
4
  * Flush all pending microtasks by awaiting multiple rounds of `Promise.resolve()`.
package/dist/testing.js CHANGED
@@ -1,2 +1,2 @@
1
- import {a}from'./chunk-HAF5JCET.js';import'./chunk-YCCQ73C6.js';import'./chunk-EH2Q754B.js';import'./chunk-M5KZXNZX.js';async function R(){for(let e=0;e<10;e++)await Promise.resolve();}async function T(){for(let e=0;e<10;e++)await Promise.resolve();await new Promise(e=>setTimeout(e,0));for(let e=0;e<10;e++)await Promise.resolve();await new Promise(e=>setTimeout(e,0));for(let e=0;e<10;e++)await Promise.resolve();}async function D(e,s,r={}){let{totalTime:o=5e3,stepSize:c=10,maxIterations:l=1e3}=r,m=0,d=0;for(;m<o&&d<l;){if(await R(),e.inspect().inflight.length===0){await R();return}s(c),m+=c,d++;}let v=e.inspect();if(v.inflight.length>0){let f=v.inflight.map(p=>p.resolverId).join(", ");throw new Error(`[Directive] settleWithFakeTimers did not settle after ${o}ms. ${v.inflight.length} resolvers still inflight: ${f}`)}}function C(){let e=0,s=[];return {async advance(r){let o=e+r;for(;s.length>0&&s[0].time<=o;){let c=s.shift();e=c.time,c.callback(),await Promise.resolve();}e=o;},async next(){if(s.length===0)return;let r=s.shift();e=r.time,r.callback(),await Promise.resolve();},async runAll(){for(;s.length>0;)await this.next();},now(){return e},reset(){e=0,s.length=0;}}}function b(e){let s=typeof e=="string"?{requirement:(o=>o.type===e)}:e,r=s.calls??[];return {requirement:s.requirement??(o=>true),async resolve(o,c){if(r.push(o),s.delay&&await new Promise(l=>setTimeout(l,s.delay)),s.error)throw typeof s.error=="string"?new Error(s.error):s.error;s.resolve&&await s.resolve(o,c);}}}function E(e){let s=[],r=[];return {...{get calls(){return s},get pending(){return r},resolve(l){let m=r.shift();m&&m.resolve(l);},reject(l){let m=r.shift();m&&m.reject(l);},resolveAll(l){for(;r.length>0;)this.resolve(l);},rejectAll(l){for(;r.length>0;)this.reject(l);},reset(){s.length=0,r.length=0;}},handler:(l,m)=>(s.push(l),new Promise((d,v)=>{r.push({requirement:l,resolve:f=>d(f),reject:v});}))}}function P(e){return "module"in e?x(e):M(e)}function x(e){let s=[],r=new Map,o=[],c=[],l={};if(e.mocks?.resolvers)for(let[i,t]of Object.entries(e.mocks.resolvers)){let n=[];r.set(i,n),l[i]=b({...t,calls:n});}let m={...e.module,resolvers:{...e.module.resolvers,...l}},v=a({...e,module:m,plugins:[{name:"__test-tracking__",onFactSet:(i,t,n)=>{c.push({key:i,fullKey:i,namespace:void 0,previousValue:n,newValue:t,timestamp:Date.now()});},onRequirementCreated:i=>{o.push(i);}},...e.plugins??[]]}),f=v.dispatch.bind(v);return v.dispatch=i=>{s.push(i),f(i);},{...v,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(i=5e3){let t=Date.now(),n=async()=>{await new Promise(u=>setTimeout(u,0));let a=v.inspect();if(a.inflight.length>0){if(Date.now()-t>i){let u=a.inflight.map(g=>g.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${i}ms. ${a.inflight.length} resolvers still inflight: ${u}`)}return await new Promise(u=>setTimeout(u,10)),n()}};return n()},assertRequirement(i){if(!o.some(n=>n.requirement.type===i))throw new Error(`[Directive] Expected requirement of type "${i}" but none found`)},assertResolverCalled(i,t){let n=r.get(i)??[];if(t!==void 0){if(n.length!==t)throw new Error(`[Directive] Expected resolver "${i}" to be called ${t} times but was called ${n.length} times`)}else if(n.length===0)throw new Error(`[Directive] Expected resolver "${i}" to be called but it was not`)},assertFactSet(i,t){let n=c.filter(a=>a.key===i);if(n.length===0)throw new Error(`[Directive] Expected fact "${i}" to be set but it was not`);if(t!==void 0&&!n.some(u=>u.newValue===t)){let u=n.map(g=>JSON.stringify(g.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${i}" to be set to ${JSON.stringify(t)} but got: ${u}`)}},assertFactChanges(i,t){let n=c.filter(a=>a.key===i);if(n.length!==t)throw new Error(`[Directive] Expected fact "${i}" to change ${t} times but it changed ${n.length} times`)}}}function M(e){let s=[],r=new Map,o=[],c=[],l={};if(e.mocks?.resolvers)for(let[t,n]of Object.entries(e.mocks.resolvers)){let a=[];r.set(t,a),l[t]=b({...n,calls:a});}let m={};for(let[t,n]of Object.entries(e.modules))m[t]={...n,resolvers:{...n.resolvers,...l}};let d=new Set(Object.keys(e.modules)),f=a({...e,modules:m,plugins:[{name:"__test-tracking__",onFactSet:(t,n,a)=>{let g=t.indexOf("::"),y,h;if(g>0){let S=t.substring(0,g);d.has(S)?(y=S,h=t.substring(g+2)):h=t;}else h=t;c.push({key:h,fullKey:t,namespace:y,previousValue:a,newValue:n,timestamp:Date.now()});},onRequirementCreated:t=>{o.push(t);}},...e.plugins??[]]}),p=f.dispatch.bind(f);return f.dispatch=t=>{s.push(t),p(t);},{...f,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(t=5e3){let n=Date.now(),a=async()=>{await new Promise(g=>setTimeout(g,0));let u=f.inspect();if(u.inflight.length>0){if(Date.now()-n>t){let g=u.inflight.map(y=>y.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${t}ms. ${u.inflight.length} resolvers still inflight: ${g}`)}return await new Promise(g=>setTimeout(g,10)),a()}};return a()},assertRequirement(t){if(!o.some(a=>a.requirement.type===t))throw new Error(`[Directive] Expected requirement of type "${t}" but none found`)},assertResolverCalled(t,n){let a=r.get(t)??[];if(n!==void 0){if(a.length!==n)throw new Error(`[Directive] Expected resolver "${t}" to be called ${n} times but was called ${a.length} times`)}else if(a.length===0)throw new Error(`[Directive] Expected resolver "${t}" to be called but it was not`)},assertFactSet(t,n){let a=c.filter(u=>u.key===t);if(a.length===0)throw new Error(`[Directive] Expected fact "${t}" to be set but it was not`);if(n!==void 0&&!a.some(g=>g.newValue===n)){let g=a.map(y=>JSON.stringify(y.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${t}" to be set to ${JSON.stringify(n)} but got: ${g}`)}},assertFactChanges(t,n){let a=c.filter(u=>u.key===t);if(a.length!==n)throw new Error(`[Directive] Expected fact "${t}" to change ${n} times but it changed ${a.length} times`)}}}function O(e,s,r){if(!k(e,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to be dynamic, but it is not.`)}function $(e,s,r){if(k(e,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to NOT be dynamic, but it is.`)}function k(e,s,r){switch(s){case "constraint":return e.constraints.isDynamic(r);case "resolver":return e.resolvers.isDynamic(r);case "derivation":return e.derive.isDynamic(r);case "effect":return e.effects.isDynamic(r)}}function F(e){let s=new Set,r=new Set,o=new Set,c=new Set,l=null;return {async run(m){l=e.observe(d=>{switch(d.type){case "constraint.evaluate":d.active&&s.add(d.id);break;case "resolver.start":r.add(d.resolver);break;case "effect.run":o.add(d.id);break;case "derivation.compute":c.add(d.id);break}});try{await m();}finally{l?.(),l=null;}},report(){let m=e.inspect(),d=new Set(m.constraints.map(i=>i.id)),v=new Set(m.resolverDefs.map(i=>i.id)),f=new Set;for(let i of d)s.has(i)||f.add(i);let p=new Set;for(let i of v)r.has(i)||p.add(i);return {constraintsHit:s,constraintsMissed:f,resolversRun:r,resolversMissed:p,effectsRun:o,derivationsComputed:c,constraintCoverage:d.size===0?1:s.size/d.size,resolverCoverage:v.size===0?1:r.size/v.size,effectCoverage:m.effects.length===0?1:o.size/m.effects.length,derivationCoverage:m.derivations.length===0?1:c.size/m.derivations.length}}}}function I(e){let s=[],r=e.observe(o=>s.push(o));return {events:s,ofType(o){return s.filter(c=>c.type===o)},clear(){s.length=0;},dispose(){r();}}}export{O as assertDynamic,$ as assertNotDynamic,F as createCoverageTracker,C as createFakeTimers,b as createMockResolver,I as createTestObserver,P as createTestSystem,T as flushAsync,R as flushMicrotasks,E as mockResolver,D as settleWithFakeTimers};//# sourceMappingURL=testing.js.map
1
+ import {a}from'./chunk-2PLP22ZU.js';import'./chunk-JFUK5NIO.js';import'./chunk-TZHC4E6S.js';import'./chunk-T6IJUWYR.js';async function R(){for(let e=0;e<10;e++)await Promise.resolve();}async function T(){for(let e=0;e<10;e++)await Promise.resolve();await new Promise(e=>setTimeout(e,0));for(let e=0;e<10;e++)await Promise.resolve();await new Promise(e=>setTimeout(e,0));for(let e=0;e<10;e++)await Promise.resolve();}async function D(e,s,r={}){let{totalTime:o=5e3,stepSize:c=10,maxIterations:l=1e3}=r,m=0,d=0;for(;m<o&&d<l;){if(await R(),e.inspect().inflight.length===0){await R();return}s(c),m+=c,d++;}let v=e.inspect();if(v.inflight.length>0){let f=v.inflight.map(p=>p.resolverId).join(", ");throw new Error(`[Directive] settleWithFakeTimers did not settle after ${o}ms. ${v.inflight.length} resolvers still inflight: ${f}`)}}function C(){let e=0,s=[];return {async advance(r){let o=e+r;for(;s.length>0&&s[0].time<=o;){let c=s.shift();e=c.time,c.callback(),await Promise.resolve();}e=o;},async next(){if(s.length===0)return;let r=s.shift();e=r.time,r.callback(),await Promise.resolve();},async runAll(){for(;s.length>0;)await this.next();},now(){return e},reset(){e=0,s.length=0;}}}function b(e){let s=typeof e=="string"?{requirement:(o=>o.type===e)}:e,r=s.calls??[];return {requirement:s.requirement??(o=>true),async resolve(o,c){if(r.push(o),s.delay&&await new Promise(l=>setTimeout(l,s.delay)),s.error)throw typeof s.error=="string"?new Error(s.error):s.error;s.resolve&&await s.resolve(o,c);}}}function E(e){let s=[],r=[];return {...{get calls(){return s},get pending(){return r},resolve(l){let m=r.shift();m&&m.resolve(l);},reject(l){let m=r.shift();m&&m.reject(l);},resolveAll(l){for(;r.length>0;)this.resolve(l);},rejectAll(l){for(;r.length>0;)this.reject(l);},reset(){s.length=0,r.length=0;}},handler:(l,m)=>(s.push(l),new Promise((d,v)=>{r.push({requirement:l,resolve:f=>d(f),reject:v});}))}}function P(e){return "module"in e?x(e):M(e)}function x(e){let s=[],r=new Map,o=[],c=[],l={};if(e.mocks?.resolvers)for(let[i,t]of Object.entries(e.mocks.resolvers)){let n=[];r.set(i,n),l[i]=b({...t,calls:n});}let m={...e.module,resolvers:{...e.module.resolvers,...l}},v=a({...e,module:m,plugins:[{name:"__test-tracking__",onFactSet:(i,t,n)=>{c.push({key:i,fullKey:i,namespace:void 0,previousValue:n,newValue:t,timestamp:Date.now()});},onRequirementCreated:i=>{o.push(i);}},...e.plugins??[]]}),f=v.dispatch.bind(v);return v.dispatch=i=>{s.push(i),f(i);},{...v,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(i=5e3){let t=Date.now(),n=async()=>{await new Promise(u=>setTimeout(u,0));let a=v.inspect();if(a.inflight.length>0){if(Date.now()-t>i){let u=a.inflight.map(g=>g.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${i}ms. ${a.inflight.length} resolvers still inflight: ${u}`)}return await new Promise(u=>setTimeout(u,10)),n()}};return n()},assertRequirement(i){if(!o.some(n=>n.requirement.type===i))throw new Error(`[Directive] Expected requirement of type "${i}" but none found`)},assertResolverCalled(i,t){let n=r.get(i)??[];if(t!==void 0){if(n.length!==t)throw new Error(`[Directive] Expected resolver "${i}" to be called ${t} times but was called ${n.length} times`)}else if(n.length===0)throw new Error(`[Directive] Expected resolver "${i}" to be called but it was not`)},assertFactSet(i,t){let n=c.filter(a=>a.key===i);if(n.length===0)throw new Error(`[Directive] Expected fact "${i}" to be set but it was not`);if(t!==void 0&&!n.some(u=>u.newValue===t)){let u=n.map(g=>JSON.stringify(g.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${i}" to be set to ${JSON.stringify(t)} but got: ${u}`)}},assertFactChanges(i,t){let n=c.filter(a=>a.key===i);if(n.length!==t)throw new Error(`[Directive] Expected fact "${i}" to change ${t} times but it changed ${n.length} times`)}}}function M(e){let s=[],r=new Map,o=[],c=[],l={};if(e.mocks?.resolvers)for(let[t,n]of Object.entries(e.mocks.resolvers)){let a=[];r.set(t,a),l[t]=b({...n,calls:a});}let m={};for(let[t,n]of Object.entries(e.modules))m[t]={...n,resolvers:{...n.resolvers,...l}};let d=new Set(Object.keys(e.modules)),f=a({...e,modules:m,plugins:[{name:"__test-tracking__",onFactSet:(t,n,a)=>{let g=t.indexOf("::"),y,h;if(g>0){let S=t.substring(0,g);d.has(S)?(y=S,h=t.substring(g+2)):h=t;}else h=t;c.push({key:h,fullKey:t,namespace:y,previousValue:a,newValue:n,timestamp:Date.now()});},onRequirementCreated:t=>{o.push(t);}},...e.plugins??[]]}),p=f.dispatch.bind(f);return f.dispatch=t=>{s.push(t),p(t);},{...f,eventHistory:s,resolverCalls:r,get allRequirements(){return o},getFactsHistory(){return [...c]},resetFactsHistory(){c.length=0;},async waitForIdle(t=5e3){let n=Date.now(),a=async()=>{await new Promise(g=>setTimeout(g,0));let u=f.inspect();if(u.inflight.length>0){if(Date.now()-n>t){let g=u.inflight.map(y=>y.id).join(", ");throw new Error(`[Directive] waitForIdle timed out after ${t}ms. ${u.inflight.length} resolvers still inflight: ${g}`)}return await new Promise(g=>setTimeout(g,10)),a()}};return a()},assertRequirement(t){if(!o.some(a=>a.requirement.type===t))throw new Error(`[Directive] Expected requirement of type "${t}" but none found`)},assertResolverCalled(t,n){let a=r.get(t)??[];if(n!==void 0){if(a.length!==n)throw new Error(`[Directive] Expected resolver "${t}" to be called ${n} times but was called ${a.length} times`)}else if(a.length===0)throw new Error(`[Directive] Expected resolver "${t}" to be called but it was not`)},assertFactSet(t,n){let a=c.filter(u=>u.key===t);if(a.length===0)throw new Error(`[Directive] Expected fact "${t}" to be set but it was not`);if(n!==void 0&&!a.some(g=>g.newValue===n)){let g=a.map(y=>JSON.stringify(y.newValue)).join(", ");throw new Error(`[Directive] Expected fact "${t}" to be set to ${JSON.stringify(n)} but got: ${g}`)}},assertFactChanges(t,n){let a=c.filter(u=>u.key===t);if(a.length!==n)throw new Error(`[Directive] Expected fact "${t}" to change ${n} times but it changed ${a.length} times`)}}}function O(e,s,r){if(!k(e,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to be dynamic, but it is not.`)}function $(e,s,r){if(k(e,s,r))throw new Error(`[Directive] Expected ${s} "${r}" to NOT be dynamic, but it is.`)}function k(e,s,r){switch(s){case "constraint":return e.constraints.isDynamic(r);case "resolver":return e.resolvers.isDynamic(r);case "derivation":return e.derive.isDynamic(r);case "effect":return e.effects.isDynamic(r)}}function F(e){let s=new Set,r=new Set,o=new Set,c=new Set,l=null;return {async run(m){l=e.observe(d=>{switch(d.type){case "constraint.evaluate":d.active&&s.add(d.id);break;case "resolver.start":r.add(d.resolver);break;case "effect.run":o.add(d.id);break;case "derivation.compute":c.add(d.id);break}});try{await m();}finally{l?.(),l=null;}},report(){let m=e.inspect(),d=new Set(m.constraints.map(i=>i.id)),v=new Set(m.resolverDefs.map(i=>i.id)),f=new Set;for(let i of d)s.has(i)||f.add(i);let p=new Set;for(let i of v)r.has(i)||p.add(i);return {constraintsHit:s,constraintsMissed:f,resolversRun:r,resolversMissed:p,effectsRun:o,derivationsComputed:c,constraintCoverage:d.size===0?1:s.size/d.size,resolverCoverage:v.size===0?1:r.size/v.size,effectCoverage:m.effects.length===0?1:o.size/m.effects.length,derivationCoverage:m.derivations.length===0?1:c.size/m.derivations.length}}}}function I(e){let s=[],r=e.observe(o=>s.push(o));return {events:s,ofType(o){return s.filter(c=>c.type===o)},clear(){s.length=0;},dispose(){r();}}}export{O as assertDynamic,$ as assertNotDynamic,F as createCoverageTracker,C as createFakeTimers,b as createMockResolver,I as createTestObserver,P as createTestSystem,T as flushAsync,R as flushMicrotasks,E as mockResolver,D as settleWithFakeTimers};//# sourceMappingURL=testing.js.map
2
2
  //# sourceMappingURL=testing.js.map
package/dist/worker.cjs CHANGED
@@ -1,2 +1,2 @@
1
- 'use strict';function _(o){let{worker:c,onFactChange:l,onDerivationChange:y,onRequirementCreated:E,onRequirementMet:a,onError:r}=o,s=new Map,u=0,t=null,i=null,d=null,T=null;function g(e){return e?.(),null}function R(e,n){let S=s.get(e);S&&(S.resolve(n),s.delete(e));}function M(){t=g(t);}function m(){i=g(i);}function I(){d=g(d);}function b(){T=g(T);}function h(e){l?.(e.key,e.value,e.prev);}function O(e){y?.(e.key,e.value);}function W(e){E?.(e.requirement);}function C(e){a?.(e.requirementId,e.resolverId);}function P(e){r?.(e.error,e.source);}function D(e){R(e.requestId,e.snapshot);}function w(e){R(e.requestId,e.inspection);}function q(e){let n=s.get(e.requestId);n&&(e.success?n.resolve(void 0):n.reject(new Error(e.error||"Settle failed")),s.delete(e.requestId));}c.onmessage=e=>{let n=e.data;switch(n.type){case "READY":return M();case "STARTED":return m();case "STOPPED":return I();case "DESTROYED":return b();case "FACT_CHANGED":return h(n);case "DERIVATION_CHANGED":return O(n);case "REQUIREMENT_CREATED":return W(n);case "REQUIREMENT_MET":return C(n);case "ERROR":return P(n);case "SNAPSHOT_RESULT":return D(n);case "INSPECT_RESULT":return w(n);case "SETTLE_RESULT":return q(n)}},c.onerror=e=>{r?.(e.message,"worker");};function p(e){c.postMessage(e);}function k(e){return new Promise((n,S)=>{s.set(e.requestId,{resolve:n,reject:S}),p(e);})}return {init(e){return new Promise(n=>{t=n,p({type:"INIT",config:e});})},start(){return new Promise(e=>{i=e,p({type:"START"});})},stop(){return new Promise(e=>{d=e,p({type:"STOP"});})},destroy(){return new Promise(e=>{T=e,p({type:"DESTROY"});})},setFact(e,n){p({type:"SET_FACT",key:e,value:n});},setFacts(e){p({type:"SET_FACTS",facts:e});},dispatch(e){p({type:"DISPATCH",event:e});},getSnapshot(e){let n=`snapshot-${++u}`;return k({type:"GET_SNAPSHOT",options:e,requestId:n})},inspect(){let e=`inspect-${++u}`;return k({type:"INSPECT",requestId:e})},settle(e){let n=`settle-${++u}`;return k({type:"SETTLE",timeout:e,requestId:n})},terminate(){c.terminate();}}}var v=null;function f(){return v||(v=new Map),v}function N(o,c){f().set(o,c);}function x(){let o=null;async function c(t){let i=await A(t.config);return postMessage({type:"READY"}),i}function l(t){t.start(),postMessage({type:"STARTED"});}function y(t){t.stop(),postMessage({type:"STOPPED"});}function E(t){t.destroy(),postMessage({type:"DESTROYED"});}function a(t,i){let d=t.getSnapshot(i.options);postMessage({type:"SNAPSHOT_RESULT",requestId:i.requestId,snapshot:d});}function r(t,i){let d=t.inspect();postMessage({type:"INSPECT_RESULT",requestId:i.requestId,inspection:d});}async function s(t,i){try{await t.settle(i.timeout),postMessage({type:"SETTLE_RESULT",requestId:i.requestId,success:!0});}catch(d){postMessage({type:"SETTLE_RESULT",requestId:i.requestId,success:false,error:d instanceof Error?d.message:String(d)});}}async function u(t){if(t.type==="INIT"){o=await c(t);return}if(o)switch(t.type){case "START":l(o);break;case "STOP":y(o);break;case "DESTROY":E(o),o=null;break;case "SET_FACT":o.setFact(t.key,t.value);break;case "SET_FACTS":o.setFacts(t.facts);break;case "DISPATCH":o.dispatch(t.event);break;case "GET_SNAPSHOT":a(o,t);break;case "INSPECT":r(o,t);break;case "SETTLE":await s(o,t);break}}self.onmessage=async t=>{try{await u(t.data);}catch(i){postMessage({type:"ERROR",error:i instanceof Error?i.message:String(i),source:t.data.type});}};}async function A(o){let{createSystem:c}=await import('./system-CK3SHMXZ.cjs'),l=f(),y={};for(let r of o.moduleNames){let s=l.get(r);if(!s)throw new Error(`[Directive Worker] Module "${r}" not registered. Call registerWorkerModule('${r}', module) before handling messages.`);y[r]=s;}let a=c({modules:y,plugins:[{name:"__worker-tracking__",onFactSet:(r,s,u)=>{postMessage({type:"FACT_CHANGED",key:r,value:s,prev:u});},onDerivationCompute:(r,s)=>{postMessage({type:"DERIVATION_CHANGED",key:r,value:s});},onRequirementCreated:r=>{postMessage({type:"REQUIREMENT_CREATED",requirement:{...r.requirement,id:r.id}});},onRequirementMet:(r,s)=>{postMessage({type:"REQUIREMENT_MET",requirementId:r.id,resolverId:s});}}],history:o.history});return {start:()=>a.start(),stop:()=>a.stop(),destroy:()=>a.destroy(),setFact:(r,s)=>{a.facts[r]=s;},setFacts:r=>{let s=a.facts;if(s.$store?.batch)s.$store.batch(()=>{for(let[u,t]of Object.entries(r))s[u]=t;});else for(let[u,t]of Object.entries(r))s[u]=t;},dispatch:r=>{a.dispatch(r);},getSnapshot:r=>a.getDistributableSnapshot(r),inspect:()=>a.inspect(),settle:r=>a.settle(r)}}exports.createWorkerClient=_;exports.getWorkerModuleRegistry=f;exports.handleWorkerMessages=x;exports.registerWorkerModule=N;//# sourceMappingURL=worker.cjs.map
1
+ 'use strict';function _(o){let{worker:c,onFactChange:l,onDerivationChange:y,onRequirementCreated:E,onRequirementMet:a,onError:r}=o,s=new Map,u=0,t=null,i=null,d=null,T=null;function g(e){return e?.(),null}function R(e,n){let S=s.get(e);S&&(S.resolve(n),s.delete(e));}function M(){t=g(t);}function m(){i=g(i);}function I(){d=g(d);}function b(){T=g(T);}function h(e){l?.(e.key,e.value,e.prev);}function O(e){y?.(e.key,e.value);}function W(e){E?.(e.requirement);}function C(e){a?.(e.requirementId,e.resolverId);}function P(e){r?.(e.error,e.source);}function D(e){R(e.requestId,e.snapshot);}function w(e){R(e.requestId,e.inspection);}function q(e){let n=s.get(e.requestId);n&&(e.success?n.resolve(void 0):n.reject(new Error(e.error||"Settle failed")),s.delete(e.requestId));}c.onmessage=e=>{let n=e.data;switch(n.type){case "READY":return M();case "STARTED":return m();case "STOPPED":return I();case "DESTROYED":return b();case "FACT_CHANGED":return h(n);case "DERIVATION_CHANGED":return O(n);case "REQUIREMENT_CREATED":return W(n);case "REQUIREMENT_MET":return C(n);case "ERROR":return P(n);case "SNAPSHOT_RESULT":return D(n);case "INSPECT_RESULT":return w(n);case "SETTLE_RESULT":return q(n)}},c.onerror=e=>{r?.(e.message,"worker");};function p(e){c.postMessage(e);}function k(e){return new Promise((n,S)=>{s.set(e.requestId,{resolve:n,reject:S}),p(e);})}return {init(e){return new Promise(n=>{t=n,p({type:"INIT",config:e});})},start(){return new Promise(e=>{i=e,p({type:"START"});})},stop(){return new Promise(e=>{d=e,p({type:"STOP"});})},destroy(){return new Promise(e=>{T=e,p({type:"DESTROY"});})},setFact(e,n){p({type:"SET_FACT",key:e,value:n});},setFacts(e){p({type:"SET_FACTS",facts:e});},dispatch(e){p({type:"DISPATCH",event:e});},getSnapshot(e){let n=`snapshot-${++u}`;return k({type:"GET_SNAPSHOT",options:e,requestId:n})},inspect(){let e=`inspect-${++u}`;return k({type:"INSPECT",requestId:e})},settle(e){let n=`settle-${++u}`;return k({type:"SETTLE",timeout:e,requestId:n})},terminate(){c.terminate();}}}var v=null;function f(){return v||(v=new Map),v}function N(o,c){f().set(o,c);}function x(){let o=null;async function c(t){let i=await A(t.config);return postMessage({type:"READY"}),i}function l(t){t.start(),postMessage({type:"STARTED"});}function y(t){t.stop(),postMessage({type:"STOPPED"});}function E(t){t.destroy(),postMessage({type:"DESTROYED"});}function a(t,i){let d=t.getSnapshot(i.options);postMessage({type:"SNAPSHOT_RESULT",requestId:i.requestId,snapshot:d});}function r(t,i){let d=t.inspect();postMessage({type:"INSPECT_RESULT",requestId:i.requestId,inspection:d});}async function s(t,i){try{await t.settle(i.timeout),postMessage({type:"SETTLE_RESULT",requestId:i.requestId,success:!0});}catch(d){postMessage({type:"SETTLE_RESULT",requestId:i.requestId,success:false,error:d instanceof Error?d.message:String(d)});}}async function u(t){if(t.type==="INIT"){o=await c(t);return}if(o)switch(t.type){case "START":l(o);break;case "STOP":y(o);break;case "DESTROY":E(o),o=null;break;case "SET_FACT":o.setFact(t.key,t.value);break;case "SET_FACTS":o.setFacts(t.facts);break;case "DISPATCH":o.dispatch(t.event);break;case "GET_SNAPSHOT":a(o,t);break;case "INSPECT":r(o,t);break;case "SETTLE":await s(o,t);break}}self.onmessage=async t=>{try{await u(t.data);}catch(i){postMessage({type:"ERROR",error:i instanceof Error?i.message:String(i),source:t.data.type});}};}async function A(o){let{createSystem:c}=await import('./system-WNO6PRHB.cjs'),l=f(),y={};for(let r of o.moduleNames){let s=l.get(r);if(!s)throw new Error(`[Directive Worker] Module "${r}" not registered. Call registerWorkerModule('${r}', module) before handling messages.`);y[r]=s;}let a=c({modules:y,plugins:[{name:"__worker-tracking__",onFactSet:(r,s,u)=>{postMessage({type:"FACT_CHANGED",key:r,value:s,prev:u});},onDerivationCompute:(r,s)=>{postMessage({type:"DERIVATION_CHANGED",key:r,value:s});},onRequirementCreated:r=>{postMessage({type:"REQUIREMENT_CREATED",requirement:{...r.requirement,id:r.id}});},onRequirementMet:(r,s)=>{postMessage({type:"REQUIREMENT_MET",requirementId:r.id,resolverId:s});}}],history:o.history});return {start:()=>a.start(),stop:()=>a.stop(),destroy:()=>a.destroy(),setFact:(r,s)=>{a.facts[r]=s;},setFacts:r=>{let s=a.facts;if(s.$store?.batch)s.$store.batch(()=>{for(let[u,t]of Object.entries(r))s[u]=t;});else for(let[u,t]of Object.entries(r))s[u]=t;},dispatch:r=>{a.dispatch(r);},getSnapshot:r=>a.getDistributableSnapshot(r),inspect:()=>a.inspect(),settle:r=>a.settle(r)}}exports.createWorkerClient=_;exports.getWorkerModuleRegistry=f;exports.handleWorkerMessages=x;exports.registerWorkerModule=N;//# sourceMappingURL=worker.cjs.map
2
2
  //# sourceMappingURL=worker.cjs.map
package/dist/worker.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { M as ModuleSchema, v as DistributableSnapshotOptions, u as DistributableSnapshot, ac as SystemInspection, r as Requirement } from './plugins-Bakr7js6.cjs';
1
+ import { M as ModuleSchema, w as DistributableSnapshotOptions, v as DistributableSnapshot, ac as SystemInspection, s as Requirement } from './plugins-DvrsPhzx.cjs';
2
2
 
3
3
  /**
4
4
  * Web Worker Adapter - Run Directive engine off the main thread
package/dist/worker.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { M as ModuleSchema, v as DistributableSnapshotOptions, u as DistributableSnapshot, ac as SystemInspection, r as Requirement } from './plugins-Bakr7js6.js';
1
+ import { M as ModuleSchema, w as DistributableSnapshotOptions, v as DistributableSnapshot, ac as SystemInspection, s as Requirement } from './plugins-DvrsPhzx.js';
2
2
 
3
3
  /**
4
4
  * Web Worker Adapter - Run Directive engine off the main thread