@directive-run/core 1.22.0 → 1.23.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 (84) 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-YJEDX2JX.js → chunk-AFPLATPV.js} +3 -3
  6. package/dist/chunk-AFPLATPV.js.map +1 -0
  7. package/dist/{chunk-OAPD3HIG.cjs → chunk-FCCJUQB2.cjs} +3 -3
  8. package/dist/chunk-FCCJUQB2.cjs.map +1 -0
  9. package/dist/chunk-IZNOPHPL.js +3 -0
  10. package/dist/chunk-IZNOPHPL.js.map +1 -0
  11. package/dist/chunk-LN5H74CU.js +2 -0
  12. package/dist/{chunk-RBF653NR.js.map → chunk-LN5H74CU.js.map} +1 -1
  13. package/dist/chunk-PJIIBQTK.js +2 -0
  14. package/dist/chunk-PJIIBQTK.js.map +1 -0
  15. package/dist/chunk-PTT4MWNL.cjs +3 -0
  16. package/dist/chunk-PTT4MWNL.cjs.map +1 -0
  17. package/dist/{chunk-GKMJ7NMP.cjs → chunk-RD2HO5NZ.cjs} +2 -2
  18. package/dist/{chunk-GKMJ7NMP.cjs.map → chunk-RD2HO5NZ.cjs.map} +1 -1
  19. package/dist/{chunk-GACC2DMS.cjs → chunk-S6W6Y44G.cjs} +2 -2
  20. package/dist/{chunk-GACC2DMS.cjs.map → chunk-S6W6Y44G.cjs.map} +1 -1
  21. package/dist/{chunk-6PF2FRBG.js → chunk-WD47DB52.js} +2 -2
  22. package/dist/{chunk-6PF2FRBG.js.map → chunk-WD47DB52.js.map} +1 -1
  23. package/dist/chunk-WKGNK4QK.cjs +2 -0
  24. package/dist/chunk-WKGNK4QK.cjs.map +1 -0
  25. package/dist/chunk-WVP3GOY2.js +3 -0
  26. package/dist/chunk-WVP3GOY2.js.map +1 -0
  27. package/dist/chunk-XKXTRVJF.cjs +3 -0
  28. package/dist/chunk-XKXTRVJF.cjs.map +1 -0
  29. package/dist/{index-BgKC_ZT_.d.ts → index-DpvgHVHR.d.cts} +29 -2
  30. package/dist/{index-DRPkZ8HE.d.cts → index-n8oQmdOZ.d.ts} +29 -2
  31. package/dist/index.cjs +2 -2
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.d.cts +6 -128
  34. package/dist/index.d.ts +6 -128
  35. package/dist/index.js +2 -2
  36. package/dist/index.js.map +1 -1
  37. package/dist/internals.cjs +1 -1
  38. package/dist/internals.d.cts +10 -4
  39. package/dist/internals.d.ts +10 -4
  40. package/dist/internals.js +1 -1
  41. package/dist/plugins/index.cjs +2 -2
  42. package/dist/plugins/index.cjs.map +1 -1
  43. package/dist/plugins/index.d.cts +202 -3
  44. package/dist/plugins/index.d.ts +202 -3
  45. package/dist/plugins/index.js +2 -2
  46. package/dist/plugins/index.js.map +1 -1
  47. package/dist/{plugins-5Supk7it.d.cts → plugins-CaPMTICa.d.cts} +323 -2
  48. package/dist/{plugins-5Supk7it.d.ts → plugins-CaPMTICa.d.ts} +323 -2
  49. package/dist/{predicate-DYb-3Mvl.d.cts → predicate-CU0YC1i6.d.cts} +1 -1
  50. package/dist/{predicate-C9oMO_ny.d.ts → predicate-CgpwJqf4.d.ts} +1 -1
  51. package/dist/system-HOP37Z4V.js +2 -0
  52. package/dist/{system-6YWCXQOQ.js.map → system-HOP37Z4V.js.map} +1 -1
  53. package/dist/system-VZUHL56W.cjs +2 -0
  54. package/dist/{system-5FKUBLLV.cjs.map → system-VZUHL56W.cjs.map} +1 -1
  55. package/dist/testing.cjs +1 -1
  56. package/dist/testing.cjs.map +1 -1
  57. package/dist/testing.d.cts +1 -1
  58. package/dist/testing.d.ts +1 -1
  59. package/dist/testing.js +1 -1
  60. package/dist/testing.js.map +1 -1
  61. package/dist/worker.cjs +1 -1
  62. package/dist/worker.cjs.map +1 -1
  63. package/dist/worker.d.cts +1 -1
  64. package/dist/worker.d.ts +1 -1
  65. package/dist/worker.js +1 -1
  66. package/dist/worker.js.map +1 -1
  67. package/package.json +1 -1
  68. package/dist/chunk-6NCC6RBC.js +0 -3
  69. package/dist/chunk-6NCC6RBC.js.map +0 -1
  70. package/dist/chunk-GBCWXTXW.cjs +0 -3
  71. package/dist/chunk-GBCWXTXW.cjs.map +0 -1
  72. package/dist/chunk-KGTBTGOY.js +0 -2
  73. package/dist/chunk-KGTBTGOY.js.map +0 -1
  74. package/dist/chunk-MARZI3EY.cjs +0 -2
  75. package/dist/chunk-MARZI3EY.cjs.map +0 -1
  76. package/dist/chunk-OAPD3HIG.cjs.map +0 -1
  77. package/dist/chunk-QTY2FXZY.cjs +0 -3
  78. package/dist/chunk-QTY2FXZY.cjs.map +0 -1
  79. package/dist/chunk-RBF653NR.js +0 -2
  80. package/dist/chunk-SFUVPP4L.js +0 -3
  81. package/dist/chunk-SFUVPP4L.js.map +0 -1
  82. package/dist/chunk-YJEDX2JX.js.map +0 -1
  83. package/dist/system-5FKUBLLV.cjs +0 -2
  84. package/dist/system-6YWCXQOQ.js +0 -2
package/dist/index.d.cts CHANGED
@@ -1,8 +1,8 @@
1
- import { C as ClauseResult, F as FactPredicate, S as SchemaType, D as DefinitionMeta, M as ModuleSchema, a as Facts, T as TypedDerivationsDef, b as TypedEventsDef, E as EffectsDef, c as SourcesDef, d as TypedConstraintsDef, e as TypedResolversDef, f as ModuleHooks, g as CrossModuleDeps, h as CrossModuleDerivationsDef, i as CrossModuleEffectsDef, j as CrossModuleConstraintsDef, k as ModuleDef, l as CreateSystemOptionsSingle, m as SingleModuleSystem, n as ModulesMap, o as CreateSystemOptionsNamed, N as NamespacedSystem, P as Plugin, p as TraceOption, q as ErrorBoundaryConfig, R as RequirementWithId, r as Requirement, s as RequirementKeyFn } from './plugins-5Supk7it.cjs';
2
- export { A as AnySystem, B as BatchConfig, t as ConstraintDefinition, u as ConstraintsDefinition, v as CrossModuleConstraintDefinition, w as CrossModuleEffectDefinition, x as DirectiveError, y as DistributableSnapshot, z as DistributableSnapshotOptions, G as DynamicConstraintDef, G as DynamicConstraintDefinition, H as DynamicEffectDef, I as DynamicResolverDef, I as DynamicResolverDefinition, J as EffectDefinition, K as EventsDefinition, L as FactTemplate, O as FactsSnapshot, Q as HistoryAPI, U as HistoryOption, V as HistoryState, W as InferDerivations, X as InferEvents, Y as InferFacts, Z as InferRequirementTypes, _ as InferRequirements, $ as InferSchemaType, a0 as InferSelectorState, a1 as KeySelector, a2 as MetaAccessor, a3 as MetaMatch, a4 as ObservationEvent, a5 as OperatorObject, a6 as PatchSpec, a7 as PatchValue, a8 as PayloadRef, a9 as PredicateClause, aa as PredicateCombinator, ab as PredicateCombinatorKey, ac as PredicateObject, ad as PredicateOp, ae as ResolverDefinition, af as ResolversDefinition, ag as RetryPolicy, ah as Schema, ai as SchemaTypedResolversDefinition, aj as Snapshot, ak as SourceDef, ak as SourceDefinition, al as SourceDropReason, am as SourcePublish, am as SourcePublishFn, an as SourceReportError, ao as SourceUnsubscribe, ao as SourceUnsubscribeFn, ap as System, aq as SystemConfig, ar as SystemDerived, as as SystemFacts, at as SystemInspection, au as SystemMode, av as SystemSnapshot, aw as TraceEntry, ax as TypedConstraintDefinition, ay as TypedResolverDefinition, az as isNamespacedSystem, aA as isSingleModuleSystem } from './plugins-5Supk7it.cjs';
3
- import { S as SchemaKindNode } from './predicate-DYb-3Mvl.cjs';
4
- export { D as DerivationDefWithMeta, a as DerivationDefinition, D as DerivationDefinitionWithMeta, b as DerivationsDefinition, c as SchemaKind, d as SchemaValidationError, e as SchemaValidationOptions, f as SchemaValidationResult, g as applyPatch, h as evaluateKeySelector, i as evaluatePredicate, j as evaluatePredicateExplained, k as evaluateTemplate, l as extractDeps, m as extractTemplateKeys, n as getKind, o as getOperatorsForKind, p as getSchemaFieldKinds, q as isPredicate, r as isTemplate, s as listAllPredicateOperators, t as memoizePredicate, u as typedConstraint, v as typedResolver, w as validatePredicate, x as validatePredicateAgainstSchema } from './predicate-DYb-3Mvl.cjs';
5
- export { A as AuditEntry, a as AuditEntryKind, b as AuditLedger, c as AuditLedgerOptions, d as AuditLedgerSink, Q as QueryFilter, V as VerifyResult, e as createAuditLedger, m as memorySink } from './index-DRPkZ8HE.cjs';
1
+ import { C as ClauseResult, F as FactPredicate, S as SchemaType, D as DefinitionMeta, M as ModuleSchema, a as Facts, T as TypedDerivationsDef, b as TypedEventsDef, E as EffectsDef, c as SourcesDef, d as TypedConstraintsDef, e as TypedResolversDef, f as ModuleHooks, g as CrossModuleDeps, h as CrossModuleDerivationsDef, i as CrossModuleEffectsDef, j as CrossModuleConstraintsDef, k as ModuleDef, l as CreateSystemOptionsSingle, m as SingleModuleSystem, n as ModulesMap, o as CreateSystemOptionsNamed, N as NamespacedSystem, P as Plugin, p as TraceOption, q as ErrorBoundaryConfig, R as RequirementWithId, r as Requirement, s as RequirementKeyFn } from './plugins-CaPMTICa.cjs';
2
+ export { A as AnySystem, B as BatchConfig, t as Change, u as ChangeKind, v as ConstraintDefinition, w as ConstraintDiff, x as ConstraintStatus, y as ConstraintsDefinition, z as CrossModuleConstraintDefinition, G as CrossModuleEffectDefinition, H as DiffRulesOptions, I as DirectiveError, J as DistributableSnapshot, K as DistributableSnapshotOptions, L as DynamicConstraintDef, L as DynamicConstraintDefinition, O as DynamicEffectDef, Q as DynamicResolverDef, Q as DynamicResolverDefinition, U as EffectDefinition, V as EventsDefinition, W as FactTemplate, X as FactsSnapshot, Y as HistoryAPI, Z as HistoryOption, _ as HistoryState, $ as InferDerivations, a0 as InferEvents, a1 as InferFacts, a2 as InferRequirementTypes, a3 as InferRequirements, a4 as InferSchemaType, a5 as InferSelectorState, a6 as KeySelector, a7 as LeafClause, a8 as MetaAccessor, a9 as MetaMatch, aa as ObservationEvent, ab as OperatorObject, ac as PatchSpec, ad as PatchValue, ae as PayloadRef, af as PredicateClause, ag as PredicateCombinator, ah as PredicateCombinatorKey, ai as PredicateObject, aj as PredicateOp, ak as PredicateOverlapProof, al as ResolverAbortReason, am as ResolverDefinition, an as ResolversDefinition, ao as RetryPolicy, ap as RulesDiffReport, aq as RulesMapInput, ar as Schema, as as SchemaTypedResolversDefinition, at as ShouldRetryContext, au as Snapshot, av as SourceDef, av as SourceDefinition, aw as SourceDropReason, ax as SourcePublish, ax as SourcePublishFn, ay as SourceReportError, az as SourceUnsubscribe, az as SourceUnsubscribeFn, aA as System, aB as SystemConfig, aC as SystemDerived, aD as SystemFacts, aE as SystemInspection, aF as SystemMode, aG as SystemSnapshot, aH as TraceEntry, aI as TypedConstraintDefinition, aJ as TypedResolverDefinition, aK as diffClauses, aL as diffRules, aM as flattenPredicate, aN as isNamespacedSystem, aO as isSingleModuleSystem, aP as toRulesMap } from './plugins-CaPMTICa.cjs';
3
+ import { S as SchemaKindNode } from './predicate-CU0YC1i6.cjs';
4
+ export { D as DerivationDefWithMeta, a as DerivationDefinition, D as DerivationDefinitionWithMeta, b as DerivationsDefinition, c as SchemaKind, d as SchemaValidationError, e as SchemaValidationOptions, f as SchemaValidationResult, g as applyPatch, h as evaluateKeySelector, i as evaluatePredicate, j as evaluatePredicateExplained, k as evaluateTemplate, l as extractDeps, m as extractTemplateKeys, n as getKind, o as getOperatorsForKind, p as getSchemaFieldKinds, q as isPredicate, r as isTemplate, s as listAllPredicateOperators, t as memoizePredicate, u as typedConstraint, v as typedResolver, w as validatePredicate, x as validatePredicateAgainstSchema } from './predicate-CU0YC1i6.cjs';
5
+ export { A as AuditEntry, a as AuditEntryKind, b as AuditLedger, c as AuditLedgerOptions, d as AuditLedgerSink, Q as QueryFilter, V as VerifyResult, e as createAuditLedger, m as memorySink } from './index-DpvgHVHR.cjs';
6
6
  export { D as DistributableSnapshotLike, S as SignedSnapshot, a as SnapshotDiff, b as SnapshotDiffEntry, d as diffSnapshots, i as isSignedSnapshot, c as isSnapshotExpired, s as shallowEqual, e as signSnapshot, v as validateSnapshot, f as verifySnapshotSignature } from './utils-DY8KTiD6.cjs';
7
7
 
8
8
  /**
@@ -325,128 +325,6 @@ declare const MAX_SWEEP_POINTS = 10000;
325
325
  */
326
326
  declare function sweepUnder<F = Record<string, unknown>>(options: SweepUnderOptions<F>): SweepReport;
327
327
 
328
- /**
329
- * Structural diff between two snapshots of a system's constraint `whenSpec`
330
- * map. The "git diff for business rules" — operates on the predicate AST
331
- * instead of source-text lines.
332
- *
333
- * A predicate is a tree of leaf clauses (`{ fact: operator(value) }`) and
334
- * combinators (`$all` / `$any` / `$not`). `diffRules` flattens both trees
335
- * into path-keyed leaf lists and compares: missing path → added/removed,
336
- * same path with different operand → changed (with relaxed/tightened
337
- * classification for numeric thresholds).
338
- *
339
- * Pure module — imports only utils. No engine / store / predicate-runtime
340
- * dependency: predicates are walked as plain JSON.
341
- */
342
- /** A leaf clause extracted from a predicate tree, keyed by its dotted path. */
343
- interface LeafClause {
344
- /** Dotted path through the predicate. E.g. `phase`, `$all[0].elapsed`, `$not.paused`. */
345
- path: string;
346
- /** Operator name. `$eq` is implied for bare-value equality. */
347
- op: string;
348
- /** Operand. */
349
- value: unknown;
350
- }
351
- /** Kind of change observed for a single clause. */
352
- type ChangeKind = "added" | "removed" | "changed" | "relaxed" | "tightened";
353
- /** A single change between two predicates at a specific path. */
354
- interface Change {
355
- path: string;
356
- kind: ChangeKind;
357
- before?: {
358
- op: string;
359
- value: unknown;
360
- };
361
- after?: {
362
- op: string;
363
- value: unknown;
364
- };
365
- }
366
- /** Status of a single constraint across the two snapshots. */
367
- type ConstraintStatus = "added" | "removed" | "changed" | "unchanged";
368
- interface ConstraintDiff {
369
- id: string;
370
- status: ConstraintStatus;
371
- /** Empty for `unchanged`. For `added` / `removed`, every leaf is listed once. */
372
- changes: Change[];
373
- }
374
- interface RulesDiffReport {
375
- constraints: ConstraintDiff[];
376
- summary: {
377
- added: number;
378
- removed: number;
379
- changed: number;
380
- unchanged: number;
381
- totalClauseChanges: number;
382
- };
383
- }
384
- interface DiffRulesOptions {
385
- before: RulesMapInput;
386
- after: RulesMapInput;
387
- }
388
- /**
389
- * Accepted shapes for the `before` / `after` predicate maps:
390
- * - A plain map `{ [constraintId]: whenSpec }`
391
- * - The `system.inspect().constraints` array form `Array<{ id, whenSpec? }>`
392
- * - Either wrapped as `{ constraints: <one-of-the-above> }`
393
- *
394
- * Anything else throws at `toRulesMap` so a bad input fails loud.
395
- */
396
- type RulesMapInput = unknown;
397
- /**
398
- * Coerce supported input shapes into a flat `Record<constraintId, whenSpec>`.
399
- * Constraints without a `whenSpec` (function-form `when`) are dropped with
400
- * an undefined entry so callers can distinguish them from absent constraints
401
- * if they care; the diff treats `undefined` as "no data" and skips clause
402
- * walking.
403
- */
404
- declare function toRulesMap(raw: RulesMapInput): Record<string, unknown>;
405
- /**
406
- * Walk a predicate tree and emit every leaf clause with its dotted path.
407
- * Combinators (`$all` / `$any` / `$not`) become indexed path segments.
408
- * Bare-value equality (`{ phase: "red" }`) emits as `op: "$eq"`.
409
- *
410
- * Array-form predicates (`[{ fact, op, value }, ...]`) are also accepted —
411
- * each clause's `fact` becomes the path, the operator is `op`, and the
412
- * value is `value`.
413
- *
414
- * **What gets dropped:** non-object combinator children (e.g. `$not: "red"`
415
- * with a string operand instead of a predicate object), function-form
416
- * predicates (the engine accepts a function for `when`; this walker only
417
- * sees data), and bare primitive predicates (a top-level `true` or `"x"`).
418
- * The walker is a tree visitor — anything not shaped like a predicate node
419
- * is silently skipped, never thrown on.
420
- */
421
- declare function flattenPredicate(spec: unknown, pathPrefix?: string, out?: LeafClause[]): LeafClause[];
422
- /**
423
- * Diff two snapshots of a system's constraint whenSpec map.
424
- *
425
- * @example
426
- * ```ts
427
- * const report = diffRules({
428
- * before: { blockCheckout: { cartTotal: { $gte: 100 } } },
429
- * after: { blockCheckout: { cartTotal: { $gte: 50 } } },
430
- * });
431
- *
432
- * report.constraints[0].status; // "changed"
433
- * report.constraints[0].changes[0].kind; // "relaxed"
434
- * report.summary.totalClauseChanges; // 1
435
- * ```
436
- *
437
- * The input shape is forgiving — either a flat `{ id: whenSpec }` map, the
438
- * `system.inspect().constraints` array form, or either wrapped as
439
- * `{ constraints: ... }`. Constraints whose `when` is a function (no
440
- * `whenSpec`) are tracked as added/removed but cannot be clause-diffed
441
- * (the function form is opaque).
442
- */
443
- declare function diffRules(options: DiffRulesOptions): RulesDiffReport;
444
- /**
445
- * Diff two predicate trees and return the list of leaf-level changes.
446
- * Exported for reuse beyond the full per-constraint report.
447
- */
448
- declare function diffClauses(before: unknown, after: unknown): Change[];
449
-
450
328
  /**
451
329
  * `predicateHash` — content-addressed fingerprint for a {@link FactPredicate}.
452
330
  *
@@ -2257,4 +2135,4 @@ declare const Backoff: {
2257
2135
  readonly Exponential: "exponential";
2258
2136
  };
2259
2137
 
2260
- export { Backoff, type Branded, type ChainableSchemaType, type Change, type ChangeKind, type CheckAbortOnFinding, type CheckAbortOnResult, type CheckAgainstResult, ClauseResult, type ConstraintDiff, type ConstraintStatus, type Contradiction, type ContradictionType, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleConstraintsDef as CrossModuleConstraintsDefinition, CrossModuleDeps, CrossModuleDerivationsDef as CrossModuleDerivationsDefinition, CrossModuleEffectsDef as CrossModuleEffectsDefinition, DefinitionMeta, type DescribeOptions, type DiffRulesOptions, EffectsDef as EffectsDefinition, ErrorBoundaryConfig, type ExistingConstraint, type ExtendedSchemaType, FactPredicate, Facts, type LeafClause, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleDef as ModuleDefinition, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, Plugin, type PredicateBacktestReport, type PredicateToMongoOptions, type PredicateToPostgrestOptions, type PredicateToSqlOptions, type PredicateToSqlResult, type PredictMissingChange, type PredictResult, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, type RulesDiffReport, type RulesMapInput, SchemaKindNode, SchemaType, type SignalClock, SingleModuleSystem, SourcesDef, SourcesDef as SourcesDefinition, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, TypedConstraintsDef as TypedConstraintsDefinition, TypedDerivationsDef as TypedDerivationsDefinition, TypedEventsDef as TypedEventsDefinition, TypedResolversDef as TypedResolversDefinition, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, describePredicate, diffClauses, diffRules, doctor, elapsedMs, flattenPredicate, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isRequirementType, pauseTimer, predicateHash, predicateToMongo, predicateToPostgrest, predicateToSQL, predicateToWhere, predict, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, toRulesMap, virtualClock };
2138
+ export { Backoff, type Branded, type ChainableSchemaType, type CheckAbortOnFinding, type CheckAbortOnResult, type CheckAgainstResult, ClauseResult, type Contradiction, type ContradictionType, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleConstraintsDef as CrossModuleConstraintsDefinition, CrossModuleDeps, CrossModuleDerivationsDef as CrossModuleDerivationsDefinition, CrossModuleEffectsDef as CrossModuleEffectsDefinition, DefinitionMeta, type DescribeOptions, EffectsDef as EffectsDefinition, ErrorBoundaryConfig, type ExistingConstraint, type ExtendedSchemaType, FactPredicate, Facts, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleDef as ModuleDefinition, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, Plugin, type PredicateBacktestReport, type PredicateToMongoOptions, type PredicateToPostgrestOptions, type PredicateToSqlOptions, type PredicateToSqlResult, type PredictMissingChange, type PredictResult, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, SchemaKindNode, SchemaType, type SignalClock, SingleModuleSystem, SourcesDef, SourcesDef as SourcesDefinition, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, TypedConstraintsDef as TypedConstraintsDefinition, TypedDerivationsDef as TypedDerivationsDefinition, TypedEventsDef as TypedEventsDefinition, TypedResolversDef as TypedResolversDefinition, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, describePredicate, doctor, elapsedMs, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isRequirementType, pauseTimer, predicateHash, predicateToMongo, predicateToPostgrest, predicateToSQL, predicateToWhere, predict, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, virtualClock };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import { C as ClauseResult, F as FactPredicate, S as SchemaType, D as DefinitionMeta, M as ModuleSchema, a as Facts, T as TypedDerivationsDef, b as TypedEventsDef, E as EffectsDef, c as SourcesDef, d as TypedConstraintsDef, e as TypedResolversDef, f as ModuleHooks, g as CrossModuleDeps, h as CrossModuleDerivationsDef, i as CrossModuleEffectsDef, j as CrossModuleConstraintsDef, k as ModuleDef, l as CreateSystemOptionsSingle, m as SingleModuleSystem, n as ModulesMap, o as CreateSystemOptionsNamed, N as NamespacedSystem, P as Plugin, p as TraceOption, q as ErrorBoundaryConfig, R as RequirementWithId, r as Requirement, s as RequirementKeyFn } from './plugins-5Supk7it.js';
2
- export { A as AnySystem, B as BatchConfig, t as ConstraintDefinition, u as ConstraintsDefinition, v as CrossModuleConstraintDefinition, w as CrossModuleEffectDefinition, x as DirectiveError, y as DistributableSnapshot, z as DistributableSnapshotOptions, G as DynamicConstraintDef, G as DynamicConstraintDefinition, H as DynamicEffectDef, I as DynamicResolverDef, I as DynamicResolverDefinition, J as EffectDefinition, K as EventsDefinition, L as FactTemplate, O as FactsSnapshot, Q as HistoryAPI, U as HistoryOption, V as HistoryState, W as InferDerivations, X as InferEvents, Y as InferFacts, Z as InferRequirementTypes, _ as InferRequirements, $ as InferSchemaType, a0 as InferSelectorState, a1 as KeySelector, a2 as MetaAccessor, a3 as MetaMatch, a4 as ObservationEvent, a5 as OperatorObject, a6 as PatchSpec, a7 as PatchValue, a8 as PayloadRef, a9 as PredicateClause, aa as PredicateCombinator, ab as PredicateCombinatorKey, ac as PredicateObject, ad as PredicateOp, ae as ResolverDefinition, af as ResolversDefinition, ag as RetryPolicy, ah as Schema, ai as SchemaTypedResolversDefinition, aj as Snapshot, ak as SourceDef, ak as SourceDefinition, al as SourceDropReason, am as SourcePublish, am as SourcePublishFn, an as SourceReportError, ao as SourceUnsubscribe, ao as SourceUnsubscribeFn, ap as System, aq as SystemConfig, ar as SystemDerived, as as SystemFacts, at as SystemInspection, au as SystemMode, av as SystemSnapshot, aw as TraceEntry, ax as TypedConstraintDefinition, ay as TypedResolverDefinition, az as isNamespacedSystem, aA as isSingleModuleSystem } from './plugins-5Supk7it.js';
3
- import { S as SchemaKindNode } from './predicate-C9oMO_ny.js';
4
- export { D as DerivationDefWithMeta, a as DerivationDefinition, D as DerivationDefinitionWithMeta, b as DerivationsDefinition, c as SchemaKind, d as SchemaValidationError, e as SchemaValidationOptions, f as SchemaValidationResult, g as applyPatch, h as evaluateKeySelector, i as evaluatePredicate, j as evaluatePredicateExplained, k as evaluateTemplate, l as extractDeps, m as extractTemplateKeys, n as getKind, o as getOperatorsForKind, p as getSchemaFieldKinds, q as isPredicate, r as isTemplate, s as listAllPredicateOperators, t as memoizePredicate, u as typedConstraint, v as typedResolver, w as validatePredicate, x as validatePredicateAgainstSchema } from './predicate-C9oMO_ny.js';
5
- export { A as AuditEntry, a as AuditEntryKind, b as AuditLedger, c as AuditLedgerOptions, d as AuditLedgerSink, Q as QueryFilter, V as VerifyResult, e as createAuditLedger, m as memorySink } from './index-BgKC_ZT_.js';
1
+ import { C as ClauseResult, F as FactPredicate, S as SchemaType, D as DefinitionMeta, M as ModuleSchema, a as Facts, T as TypedDerivationsDef, b as TypedEventsDef, E as EffectsDef, c as SourcesDef, d as TypedConstraintsDef, e as TypedResolversDef, f as ModuleHooks, g as CrossModuleDeps, h as CrossModuleDerivationsDef, i as CrossModuleEffectsDef, j as CrossModuleConstraintsDef, k as ModuleDef, l as CreateSystemOptionsSingle, m as SingleModuleSystem, n as ModulesMap, o as CreateSystemOptionsNamed, N as NamespacedSystem, P as Plugin, p as TraceOption, q as ErrorBoundaryConfig, R as RequirementWithId, r as Requirement, s as RequirementKeyFn } from './plugins-CaPMTICa.js';
2
+ export { A as AnySystem, B as BatchConfig, t as Change, u as ChangeKind, v as ConstraintDefinition, w as ConstraintDiff, x as ConstraintStatus, y as ConstraintsDefinition, z as CrossModuleConstraintDefinition, G as CrossModuleEffectDefinition, H as DiffRulesOptions, I as DirectiveError, J as DistributableSnapshot, K as DistributableSnapshotOptions, L as DynamicConstraintDef, L as DynamicConstraintDefinition, O as DynamicEffectDef, Q as DynamicResolverDef, Q as DynamicResolverDefinition, U as EffectDefinition, V as EventsDefinition, W as FactTemplate, X as FactsSnapshot, Y as HistoryAPI, Z as HistoryOption, _ as HistoryState, $ as InferDerivations, a0 as InferEvents, a1 as InferFacts, a2 as InferRequirementTypes, a3 as InferRequirements, a4 as InferSchemaType, a5 as InferSelectorState, a6 as KeySelector, a7 as LeafClause, a8 as MetaAccessor, a9 as MetaMatch, aa as ObservationEvent, ab as OperatorObject, ac as PatchSpec, ad as PatchValue, ae as PayloadRef, af as PredicateClause, ag as PredicateCombinator, ah as PredicateCombinatorKey, ai as PredicateObject, aj as PredicateOp, ak as PredicateOverlapProof, al as ResolverAbortReason, am as ResolverDefinition, an as ResolversDefinition, ao as RetryPolicy, ap as RulesDiffReport, aq as RulesMapInput, ar as Schema, as as SchemaTypedResolversDefinition, at as ShouldRetryContext, au as Snapshot, av as SourceDef, av as SourceDefinition, aw as SourceDropReason, ax as SourcePublish, ax as SourcePublishFn, ay as SourceReportError, az as SourceUnsubscribe, az as SourceUnsubscribeFn, aA as System, aB as SystemConfig, aC as SystemDerived, aD as SystemFacts, aE as SystemInspection, aF as SystemMode, aG as SystemSnapshot, aH as TraceEntry, aI as TypedConstraintDefinition, aJ as TypedResolverDefinition, aK as diffClauses, aL as diffRules, aM as flattenPredicate, aN as isNamespacedSystem, aO as isSingleModuleSystem, aP as toRulesMap } from './plugins-CaPMTICa.js';
3
+ import { S as SchemaKindNode } from './predicate-CgpwJqf4.js';
4
+ export { D as DerivationDefWithMeta, a as DerivationDefinition, D as DerivationDefinitionWithMeta, b as DerivationsDefinition, c as SchemaKind, d as SchemaValidationError, e as SchemaValidationOptions, f as SchemaValidationResult, g as applyPatch, h as evaluateKeySelector, i as evaluatePredicate, j as evaluatePredicateExplained, k as evaluateTemplate, l as extractDeps, m as extractTemplateKeys, n as getKind, o as getOperatorsForKind, p as getSchemaFieldKinds, q as isPredicate, r as isTemplate, s as listAllPredicateOperators, t as memoizePredicate, u as typedConstraint, v as typedResolver, w as validatePredicate, x as validatePredicateAgainstSchema } from './predicate-CgpwJqf4.js';
5
+ export { A as AuditEntry, a as AuditEntryKind, b as AuditLedger, c as AuditLedgerOptions, d as AuditLedgerSink, Q as QueryFilter, V as VerifyResult, e as createAuditLedger, m as memorySink } from './index-n8oQmdOZ.js';
6
6
  export { D as DistributableSnapshotLike, S as SignedSnapshot, a as SnapshotDiff, b as SnapshotDiffEntry, d as diffSnapshots, i as isSignedSnapshot, c as isSnapshotExpired, s as shallowEqual, e as signSnapshot, v as validateSnapshot, f as verifySnapshotSignature } from './utils-DY8KTiD6.js';
7
7
 
8
8
  /**
@@ -325,128 +325,6 @@ declare const MAX_SWEEP_POINTS = 10000;
325
325
  */
326
326
  declare function sweepUnder<F = Record<string, unknown>>(options: SweepUnderOptions<F>): SweepReport;
327
327
 
328
- /**
329
- * Structural diff between two snapshots of a system's constraint `whenSpec`
330
- * map. The "git diff for business rules" — operates on the predicate AST
331
- * instead of source-text lines.
332
- *
333
- * A predicate is a tree of leaf clauses (`{ fact: operator(value) }`) and
334
- * combinators (`$all` / `$any` / `$not`). `diffRules` flattens both trees
335
- * into path-keyed leaf lists and compares: missing path → added/removed,
336
- * same path with different operand → changed (with relaxed/tightened
337
- * classification for numeric thresholds).
338
- *
339
- * Pure module — imports only utils. No engine / store / predicate-runtime
340
- * dependency: predicates are walked as plain JSON.
341
- */
342
- /** A leaf clause extracted from a predicate tree, keyed by its dotted path. */
343
- interface LeafClause {
344
- /** Dotted path through the predicate. E.g. `phase`, `$all[0].elapsed`, `$not.paused`. */
345
- path: string;
346
- /** Operator name. `$eq` is implied for bare-value equality. */
347
- op: string;
348
- /** Operand. */
349
- value: unknown;
350
- }
351
- /** Kind of change observed for a single clause. */
352
- type ChangeKind = "added" | "removed" | "changed" | "relaxed" | "tightened";
353
- /** A single change between two predicates at a specific path. */
354
- interface Change {
355
- path: string;
356
- kind: ChangeKind;
357
- before?: {
358
- op: string;
359
- value: unknown;
360
- };
361
- after?: {
362
- op: string;
363
- value: unknown;
364
- };
365
- }
366
- /** Status of a single constraint across the two snapshots. */
367
- type ConstraintStatus = "added" | "removed" | "changed" | "unchanged";
368
- interface ConstraintDiff {
369
- id: string;
370
- status: ConstraintStatus;
371
- /** Empty for `unchanged`. For `added` / `removed`, every leaf is listed once. */
372
- changes: Change[];
373
- }
374
- interface RulesDiffReport {
375
- constraints: ConstraintDiff[];
376
- summary: {
377
- added: number;
378
- removed: number;
379
- changed: number;
380
- unchanged: number;
381
- totalClauseChanges: number;
382
- };
383
- }
384
- interface DiffRulesOptions {
385
- before: RulesMapInput;
386
- after: RulesMapInput;
387
- }
388
- /**
389
- * Accepted shapes for the `before` / `after` predicate maps:
390
- * - A plain map `{ [constraintId]: whenSpec }`
391
- * - The `system.inspect().constraints` array form `Array<{ id, whenSpec? }>`
392
- * - Either wrapped as `{ constraints: <one-of-the-above> }`
393
- *
394
- * Anything else throws at `toRulesMap` so a bad input fails loud.
395
- */
396
- type RulesMapInput = unknown;
397
- /**
398
- * Coerce supported input shapes into a flat `Record<constraintId, whenSpec>`.
399
- * Constraints without a `whenSpec` (function-form `when`) are dropped with
400
- * an undefined entry so callers can distinguish them from absent constraints
401
- * if they care; the diff treats `undefined` as "no data" and skips clause
402
- * walking.
403
- */
404
- declare function toRulesMap(raw: RulesMapInput): Record<string, unknown>;
405
- /**
406
- * Walk a predicate tree and emit every leaf clause with its dotted path.
407
- * Combinators (`$all` / `$any` / `$not`) become indexed path segments.
408
- * Bare-value equality (`{ phase: "red" }`) emits as `op: "$eq"`.
409
- *
410
- * Array-form predicates (`[{ fact, op, value }, ...]`) are also accepted —
411
- * each clause's `fact` becomes the path, the operator is `op`, and the
412
- * value is `value`.
413
- *
414
- * **What gets dropped:** non-object combinator children (e.g. `$not: "red"`
415
- * with a string operand instead of a predicate object), function-form
416
- * predicates (the engine accepts a function for `when`; this walker only
417
- * sees data), and bare primitive predicates (a top-level `true` or `"x"`).
418
- * The walker is a tree visitor — anything not shaped like a predicate node
419
- * is silently skipped, never thrown on.
420
- */
421
- declare function flattenPredicate(spec: unknown, pathPrefix?: string, out?: LeafClause[]): LeafClause[];
422
- /**
423
- * Diff two snapshots of a system's constraint whenSpec map.
424
- *
425
- * @example
426
- * ```ts
427
- * const report = diffRules({
428
- * before: { blockCheckout: { cartTotal: { $gte: 100 } } },
429
- * after: { blockCheckout: { cartTotal: { $gte: 50 } } },
430
- * });
431
- *
432
- * report.constraints[0].status; // "changed"
433
- * report.constraints[0].changes[0].kind; // "relaxed"
434
- * report.summary.totalClauseChanges; // 1
435
- * ```
436
- *
437
- * The input shape is forgiving — either a flat `{ id: whenSpec }` map, the
438
- * `system.inspect().constraints` array form, or either wrapped as
439
- * `{ constraints: ... }`. Constraints whose `when` is a function (no
440
- * `whenSpec`) are tracked as added/removed but cannot be clause-diffed
441
- * (the function form is opaque).
442
- */
443
- declare function diffRules(options: DiffRulesOptions): RulesDiffReport;
444
- /**
445
- * Diff two predicate trees and return the list of leaf-level changes.
446
- * Exported for reuse beyond the full per-constraint report.
447
- */
448
- declare function diffClauses(before: unknown, after: unknown): Change[];
449
-
450
328
  /**
451
329
  * `predicateHash` — content-addressed fingerprint for a {@link FactPredicate}.
452
330
  *
@@ -2257,4 +2135,4 @@ declare const Backoff: {
2257
2135
  readonly Exponential: "exponential";
2258
2136
  };
2259
2137
 
2260
- export { Backoff, type Branded, type ChainableSchemaType, type Change, type ChangeKind, type CheckAbortOnFinding, type CheckAbortOnResult, type CheckAgainstResult, ClauseResult, type ConstraintDiff, type ConstraintStatus, type Contradiction, type ContradictionType, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleConstraintsDef as CrossModuleConstraintsDefinition, CrossModuleDeps, CrossModuleDerivationsDef as CrossModuleDerivationsDefinition, CrossModuleEffectsDef as CrossModuleEffectsDefinition, DefinitionMeta, type DescribeOptions, type DiffRulesOptions, EffectsDef as EffectsDefinition, ErrorBoundaryConfig, type ExistingConstraint, type ExtendedSchemaType, FactPredicate, Facts, type LeafClause, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleDef as ModuleDefinition, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, Plugin, type PredicateBacktestReport, type PredicateToMongoOptions, type PredicateToPostgrestOptions, type PredicateToSqlOptions, type PredicateToSqlResult, type PredictMissingChange, type PredictResult, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, type RulesDiffReport, type RulesMapInput, SchemaKindNode, SchemaType, type SignalClock, SingleModuleSystem, SourcesDef, SourcesDef as SourcesDefinition, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, TypedConstraintsDef as TypedConstraintsDefinition, TypedDerivationsDef as TypedDerivationsDefinition, TypedEventsDef as TypedEventsDefinition, TypedResolversDef as TypedResolversDefinition, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, describePredicate, diffClauses, diffRules, doctor, elapsedMs, flattenPredicate, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isRequirementType, pauseTimer, predicateHash, predicateToMongo, predicateToPostgrest, predicateToSQL, predicateToWhere, predict, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, toRulesMap, virtualClock };
2138
+ export { Backoff, type Branded, type ChainableSchemaType, type CheckAbortOnFinding, type CheckAbortOnResult, type CheckAgainstResult, ClauseResult, type Contradiction, type ContradictionType, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleConstraintsDef as CrossModuleConstraintsDefinition, CrossModuleDeps, CrossModuleDerivationsDef as CrossModuleDerivationsDefinition, CrossModuleEffectsDef as CrossModuleEffectsDefinition, DefinitionMeta, type DescribeOptions, EffectsDef as EffectsDefinition, ErrorBoundaryConfig, type ExistingConstraint, type ExtendedSchemaType, FactPredicate, Facts, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleDef as ModuleDefinition, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, Plugin, type PredicateBacktestReport, type PredicateToMongoOptions, type PredicateToPostgrestOptions, type PredicateToSqlOptions, type PredicateToSqlResult, type PredictMissingChange, type PredictResult, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, SchemaKindNode, SchemaType, type SignalClock, SingleModuleSystem, SourcesDef, SourcesDef as SourcesDefinition, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, TypedConstraintsDef as TypedConstraintsDefinition, TypedDerivationsDef as TypedDerivationsDefinition, TypedEventsDef as TypedEventsDefinition, TypedResolversDef as TypedResolversDefinition, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, describePredicate, doctor, elapsedMs, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isRequirementType, pauseTimer, predicateHash, predicateToMongo, predicateToPostgrest, predicateToSQL, predicateToWhere, predict, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, virtualClock };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- export{b as createAuditLedger,a as memorySink}from'./chunk-KGTBTGOY.js';import {a as a$2}from'./chunk-YJEDX2JX.js';export{a as createSystem}from'./chunk-YJEDX2JX.js';export{b as DirectiveError,o as RequirementSet,n as forType,k as generateRequirementId,h as isNamespacedSystem,m as isRequirementType,g as isSingleModuleSystem,l as req,e as typedConstraint,f as typedResolver}from'./chunk-6NCC6RBC.js';import {o,p as p$1,i,g,a as a$1,l,h as h$1,b as b$1}from'./chunk-RBF653NR.js';export{v as applyPatch,u as evaluateKeySelector,o as evaluatePredicate,p as evaluatePredicateExplained,s as evaluateTemplate,r as extractDeps,t as extractTemplateKeys,c as getKind,e as getOperatorsForKind,d as getSchemaFieldKinds,h as isPredicate,k as isTemplate,f as listAllPredicateOperators,q as memoizePredicate,l as validatePredicate,n as validatePredicateAgainstSchema}from'./chunk-RBF653NR.js';import {k as k$1}from'./chunk-6PF2FRBG.js';import {e,h,a}from'./chunk-SFUVPP4L.js';export{k as diffSnapshots,l as isSignedSnapshot,i as isSnapshotExpired,g as shallowEqual,m as signSnapshot,j as validateSnapshot,n as verifySnapshotSignature}from'./chunk-SFUVPP4L.js';var A=1e6;function Me(e,t){try{l(e);}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`[Directive] replayUnder: the ${t} predicate is invalid \u2014 ${i}`)}if(!h$1(e)){let r=e===null||typeof e!="object"?`${typeof e} \u2014 ${JSON.stringify(e)}`:JSON.stringify(e).slice(0,80);throw new Error(`[Directive] replayUnder: the ${t} predicate is not a valid FactPredicate (got ${r})`)}let n;if(i(e,{operator(r,i){n===void 0&&i.startsWith("$")&&!a$1.has(i)&&(n=i);},strayOperatorKey(r){n===void 0&&!a$1.has(r)&&!b$1.has(r)&&(n=r);}}),n!==void 0)throw new Error(`[Directive] replayUnder: the ${t} predicate uses an unknown operator "${n}" \u2014 known operators: ${[...a$1].join(", ")}`)}function Re(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return Ce(e);let t=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.frames)?e.frames:null;if(!t)throw new Error("[Directive] toReplayFrames: history must be a JSON array of frames, an object with a `frames` array, or a history export with a `snapshots` array");if(t.length>A)throw new Error(`[Directive] toReplayFrames: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${A}) \u2014 split or down-sample the history`);return t.map((n,r)=>{if(n&&typeof n=="object"&&"facts"in n){let i=n,s={id:i.id??`#${r}`,facts:i.facts??{}};return typeof i.timestamp=="number"&&(s.timestamp=i.timestamp),s}return {id:`#${r}`,facts:n??{}}})}function Ce(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return ae(t);if(!t||typeof t!="object")throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");let n=t;if(n.version!==void 0&&n.version!==1)throw new Error(`[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(n.version)} \u2014 expected 1`);if(!Array.isArray(n.snapshots))throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");return ae(n.snapshots)}function ae(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>A)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${A}) \u2014 split or down-sample the history`);for(let t=0;t<e.length;t++){let n=e[t];if(!n||typeof n!="object"||!("facts"in n))throw new Error(`[Directive] framesFromSnapshots: snapshot at index ${t} is not a { facts, ... } object`)}return Re(e)}function H(e){let{frames:t,original:n,proposed:r,entityKey:i}=e,s=e.maxSamples??20,o$1=s>0?s:0;if(t.length>A)throw new Error(`[Directive] replayUnder: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${A}) \u2014 split or down-sample the history`);Me(n,"original"),Me(r,"proposed");let u=0,a=0,c=0,l=0,d=0,g=[],y=[],$=i?new Set:void 0,m=i?new Set:void 0,M;for(let F of t){let T=F.facts,v=o(n,T,M),R=o(r,T,M);v&&(u++,$?.add(T[i])),R&&(a++,m?.add(T[i])),v===R?d++:!v&&R?(c++,g.length<o$1&&g.push(De(F,n,r,M))):(l++,y.length<o$1&&y.push(De(F,n,r,M))),M=T;}let E={framesEvaluated:t.length,original:{matched:u},proposed:{matched:a},delta:a-u,newMatchCount:c,lostMatchCount:l,unchanged:d,newMatches:g,lostMatches:y};return $&&m&&(E.original.matchedEntities=$.size,E.proposed.matchedEntities=m.size),E}function De(e,t,n,r){let i=e.facts,s={frameId:e.id,facts:i,originalExplain:p$1(t,i,r),proposedExplain:p$1(n,i,r)};return e.timestamp!==void 0&&(s.timestamp=e.timestamp),s}var ue=1e4,Ae=5e7;function It(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function ce(e,t,n=new Set,r=0){if(r>g)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${g}) \u2014 flatten the template or split the sweep`);if(It(e)){let i=e.$hole;if(!(i in t))throw new Error(`[Directive] sweepUnder: template references hole "${i}" but sweep has no values for it`);return t[i]}if(e===null||typeof e!="object")return e;if(n.has(e))throw new Error("[Directive] sweepUnder: template contains a cycle \u2014 predicate templates must be a tree");n.add(e);try{if(Array.isArray(e))return e.map(s=>ce(s,t,n,r+1));let i={};for(let[s,o]of Object.entries(e))i[s]=ce(o,t,n,r+1);return i}finally{n.delete(e);}}function*Ee(e,t){if(e.length===0){yield {};return}let n=e[0],r=e.slice(1),i=t[n]??[];for(let s of i)for(let o of Ee(r,t))yield {[n]:s,...o};}function Lt(e){let t=1;for(let n of Object.values(e))t*=n.length;return t}function qt(e){let{frames:t,original:n,template:r,sweep:i,objective:s=T=>T.proposed.matched,entityKey:o,maxSamples:u=0}=e,a=Object.keys(i);if(a.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let c=Lt(i);if(c>ue)throw new Error(`[Directive] sweepUnder: grid has ${c} points, exceeds the MAX_SWEEP_POINTS limit (${ue}) \u2014 narrow the sweep ranges or split the run`);if(c===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let l=c*t.length;if(l>Ae)throw new Error(`[Directive] sweepUnder: ${c} points \xD7 ${t.length} frames = ${l} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${Ae}) \u2014 narrow the sweep, down-sample the history, or split the run`);let d=false,g=T=>{let v;try{v=s(T);}catch(R){return d||(d=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${R.message})`)),Number.NEGATIVE_INFINITY}return typeof v!="number"||!Number.isFinite(v)?(d||(d=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(v)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):v},y=H({frames:t,original:n,proposed:n,entityKey:o,maxSamples:u}),$={values:{},report:y,score:g(y)},m=[],M=0,E=Number.NEGATIVE_INFINITY;for(let T of Ee(a,i)){let v=ce(r,T),R=H({frames:t,original:n,proposed:v,entityKey:o,maxSamples:u}),te=g(R);te>E&&(E=te,M=m.length),m.push({values:T,report:R,score:te});}let F=m[M];return {points:m,bestIndex:M,best:F,baseline:$}}function le(e){let t=e&&typeof e=="object"&&!Array.isArray(e)&&"constraints"in e?e.constraints:e;if(Array.isArray(t)){let n={};for(let r of t){if(!r||typeof r!="object"||!("id"in r))throw new Error("[Directive] diffRules: array entries must be `{ id, whenSpec }` objects");let i=r;if(typeof i.id!="string")throw new Error("[Directive] diffRules: constraint `id` must be a string");n[i.id]=i.whenSpec;}return n}if(t&&typeof t=="object")return t;throw new Error("[Directive] diffRules: expected a `{ id: whenSpec }` map, an array of `{ id, whenSpec }`, or `{ constraints: ... }`")}var Wt=new Set(["$eq","$ne","$in","$nin","$exists","$gt","$gte","$lt","$lte","$between","$matches","$startsWith","$endsWith","$contains","$changed"]),Bt=new Set(["$all","$any","$not"]);function Oe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ut(e){if(!Oe(e))return false;let t=Object.keys(e);if(t.length===0)return false;let n=false;for(let r of t){if(!r.startsWith("$"))return false;Wt.has(r)&&(n=true);}return n}function S(e,t="",n=[]){if(e===null||typeof e!="object")return n;if(Array.isArray(e)){for(let r of e)if(r&&typeof r=="object"&&"fact"in r&&"op"in r){let i=r;n.push({path:t?`${t}.${String(i.fact)}`:String(i.fact),op:String(i.op),value:i.value});}return n}if("$all"in e&&Array.isArray(e.$all))return e.$all.forEach((i,s)=>{S(i,`${t}$all[${s}]`,n);}),n;if("$any"in e&&Array.isArray(e.$any))return e.$any.forEach((i,s)=>{S(i,`${t}$any[${s}]`,n);}),n;if("$not"in e)return S(e.$not,`${t}$not`,n),n;for(let[r,i]of Object.entries(e)){let s=t?`${t}.${r}`:r;if(Ut(i))for(let[o,u]of Object.entries(i))n.push({path:s,op:o,value:u});else Oe(i)&&!Bt.has(r)?S(i,s,n):n.push({path:s,op:"$eq",value:i});}return n}function C(e){return typeof e=="number"&&Number.isFinite(e)}function Kt(e,t,n){switch(e){case "$gte":case "$gt":if(C(t)&&C(n)){if(n<t)return "relaxed";if(n>t)return "tightened"}return null;case "$lte":case "$lt":if(C(t)&&C(n)){if(n>t)return "relaxed";if(n<t)return "tightened"}return null;case "$between":{if(Array.isArray(t)&&Array.isArray(n)&&t.length===2&&n.length===2&&C(t[0])&&C(t[1])&&C(n[0])&&C(n[1])){let r=t[1]-t[0],i=n[1]-n[0];if(i>r)return "relaxed";if(i<r)return "tightened"}return null}case "$in":case "$nin":{if(Array.isArray(t)&&Array.isArray(n))if(e==="$in"){if(n.length>t.length)return "relaxed";if(n.length<t.length)return "tightened"}else {if(n.length>t.length)return "tightened";if(n.length<t.length)return "relaxed"}return null}case "$contains":{if(Array.isArray(t)&&Array.isArray(n)){if(n.length>t.length)return "relaxed";if(n.length<t.length)return "tightened"}return null}default:return null}}function zt(e){let t=le(e.before),n=le(e.after),i=[...new Set([...Object.keys(t),...Object.keys(n)])].sort(),s=[],o={added:0,removed:0,changed:0,unchanged:0,totalClauseChanges:0};for(let u of i){let a=t[u],c=n[u],l=u in t,d=u in n;if(l&&!d){let y=S(a),$=y.length===0?[{path:"(function-form predicate)",kind:"removed"}]:y.map(m=>({path:m.path,kind:"removed",before:{op:m.op,value:m.value}}));de($),s.push({id:u,status:"removed",changes:$}),o.removed++,o.totalClauseChanges+=$.length;continue}if(!l&&d){let y=S(c),$=y.length===0?[{path:"(function-form predicate)",kind:"added"}]:y.map(m=>({path:m.path,kind:"added",after:{op:m.op,value:m.value}}));de($),s.push({id:u,status:"added",changes:$}),o.added++,o.totalClauseChanges+=$.length;continue}let g=xe(a,c);g.length===0?(s.push({id:u,status:"unchanged",changes:[]}),o.unchanged++):(s.push({id:u,status:"changed",changes:g}),o.changed++,o.totalClauseChanges+=g.length);}return {constraints:s,summary:o}}function xe(e$1,t){if(e$1!==void 0&&t!==void 0&&(e$1===null||t===null||typeof e$1!="object"||typeof t!="object"))return e(e$1)===e(t)?[]:[{path:"",kind:"changed",before:{op:"$eq",value:e$1},after:{op:"$eq",value:t}}];let n=e$1===void 0?[]:S(e$1),r=t===void 0?[]:S(t),i=c=>`${c.path}::${c.op}`,s=new Map(n.map(c=>[i(c),c])),o=new Map(r.map(c=>[i(c),c])),u=new Set([...s.keys(),...o.keys()]),a=[];for(let c of u){let l=s.get(c),d=o.get(c);if(l&&!d){a.push({path:l.path,kind:"removed",before:{op:l.op,value:l.value}});continue}if(!l&&d){a.push({path:d.path,kind:"added",after:{op:d.op,value:d.value}});continue}if(l&&d){if(e(l.value)===e(d.value))continue;let g=Kt(l.op,l.value,d.value);a.push({path:l.path,kind:g??"changed",before:{op:l.op,value:l.value},after:{op:d.op,value:d.value}});}}return de(a),a}function de(e){e.sort((t,n)=>{let r=t.path.localeCompare(n.path);if(r!==0)return r;let i=t.before?.op??t.after?.op??"",s=n.before?.op??n.after?.op??"";return i.localeCompare(s)});}function Ht(e){return h(e)}function J(e){return e===null?"null":e===void 0?"undefined":e instanceof Date?e.toISOString():typeof e=="string"||typeof e=="object"?JSON.stringify(e):String(e)}function Jt(e){let t=e.path,n=J(e.expected),r=J(e.actual);switch(e.op){case "$eq":return `set ${t} to ${n} (currently ${r})`;case "$ne":return `change ${t} to anything other than ${n} (currently ${r})`;case "$gt":return `set ${t} above ${n} (currently ${r})`;case "$gte":return `set ${t} to at least ${n} (currently ${r})`;case "$lt":return `set ${t} below ${n} (currently ${r})`;case "$lte":return `set ${t} to at most ${n} (currently ${r})`;case "$in":return `set ${t} to one of ${n} (currently ${r})`;case "$nin":return `set ${t} to something other than ${n} (currently ${r})`;case "$exists":return e.expected===true?`set ${t} to a non-null value (currently null/missing)`:`unset ${t} (currently ${r})`;case "$between":return Array.isArray(e.expected)&&e.expected.length===2?`set ${t} between ${J(e.expected[0])} and ${J(e.expected[1])} (currently ${r})`:`set ${t} within range ${n} (currently ${r})`;case "$startsWith":return `set ${t} to start with ${n} (currently ${r})`;case "$endsWith":return `set ${t} to end with ${n} (currently ${r})`;case "$contains":return `set ${t} to contain ${n} (currently ${r})`;case "$matches":return `set ${t} to match the pattern ${n} (currently ${r})`;case "$changed":return `the previous-vs-current change of ${t} is required to differ (currently they match: ${r})`;case "$all":case "$any":case "$not":return `the ${e.op} group at "${t}" did not pass \u2014 see its child clauses`;default:return `clause at ${t} (${e.op}) failed: expected ${n}, got ${r}`}}function je(e,t){for(let n of e)if(!n.pass){if((n.op==="$all"||n.op==="$any"||n.op==="$not")&&n.children){je(n.children,t);continue}t.push({path:n.path,op:n.op,expected:n.expected,actual:n.actual,suggestion:Jt(n)});}}function Qt(e,t,n){let r=p$1(e,t,n),i$1=r.every(o=>o.pass),s=[];if(i$1||je(r,s),!i$1&&n===void 0){let o=[];i(e,{operator(u,a){a==="$changed"&&o.push(u);}});for(let u of o)s.push({path:u,op:"$changed",expected:true,actual:void 0,suggestion:`$changed clause at "${u}" cannot be evaluated without a \`prev\` snapshot \u2014 pass predict(predicate, facts, prev).`});}return {wouldFire:i$1,whenExplain:r,missingChanges:s}}var Pe=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$nin"]);function Q(e,t){if(e===t)return 0;if(typeof e=="number"&&typeof t=="number"||typeof e=="bigint"&&typeof t=="bigint")return e<t?-1:e>t?1:0;if(e instanceof Date&&t instanceof Date){let n=e.getTime(),r=t.getTime();return n<r?-1:n>r?1:0}return typeof e=="string"&&typeof t=="string"?e<t?-1:e>t?1:0:Number.NaN}function _(e,t){if(e===t)return true;if(typeof e!=typeof t||e===null||t===null||typeof e!="object"||Array.isArray(e)!==Array.isArray(t))return false;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return false;for(let i=0;i<e.length;i++)if(!_(e[i],t[i]))return false;return true}let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return false;for(let i of n)if(!_(e[i],t[i]))return false;return true}function Xt(e,t){if(!Pe.has(e.op)||!Pe.has(t.op))return {type:"overlap",reason:`Both rules touch "${e.path}".`};if(e.op==="$eq"&&t.op==="$eq")return _(e.value,t.value)?{type:"subset",reason:`Both rules require ${e.path} = ${JSON.stringify(e.value)} \u2014 candidate is redundant.`}:{type:"direct",reason:`Candidate requires ${e.path} = ${JSON.stringify(e.value)} but an existing rule requires ${e.path} = ${JSON.stringify(t.value)} \u2014 they cannot both fire.`};if(e.op==="$eq"&&t.op==="$ne")return _(e.value,t.value)?{type:"direct",reason:`Candidate requires ${e.path} = ${JSON.stringify(e.value)} but an existing rule excludes that value.`}:null;if(e.op==="$ne"&&t.op==="$eq")return _(e.value,t.value)?{type:"direct",reason:`Candidate excludes ${e.path} = ${JSON.stringify(e.value)} but an existing rule requires that exact value.`}:null;if(e.op==="$in"&&t.op==="$in"){let o=new Set(Array.isArray(e.value)?e.value:[]),u=new Set(Array.isArray(t.value)?t.value:[]),a=[...o].filter(c=>u.has(c));return a.length===0?{type:"direct",reason:`Candidate $in set for ${e.path} (${JSON.stringify([...o])}) and existing $in set (${JSON.stringify([...u])}) have no values in common \u2014 the candidate can never fire while the existing rule holds.`}:a.length===o.size&&a.length<u.size?{type:"subset",reason:`Candidate $in set for ${e.path} is a strict subset of the existing rule's $in set.`}:null}let n=e.op==="$gt"||e.op==="$gte"?e.value:void 0,r=e.op==="$lt"||e.op==="$lte"?e.value:void 0,i=t.op==="$gt"||t.op==="$gte"?t.value:void 0,s=t.op==="$lt"||t.op==="$lte"?t.value:void 0;if(n!==void 0&&s!==void 0){let o=Q(n,s);if(!Number.isNaN(o)&&(o>0||o===0&&(e.op==="$gt"||t.op==="$lt")))return {type:"direct",reason:`Candidate requires ${e.path} ${e.op==="$gt"?">":"\u2265"} ${JSON.stringify(n)} but an existing rule caps it at ${t.op==="$lt"?"<":"\u2264"} ${JSON.stringify(s)}.`}}if(i!==void 0&&r!==void 0){let o=Q(i,r);if(!Number.isNaN(o)&&(o>0||o===0&&(t.op==="$gt"||e.op==="$lt")))return {type:"direct",reason:`Candidate caps ${e.path} at ${e.op==="$lt"?"<":"\u2264"} ${JSON.stringify(r)} but an existing rule requires it ${t.op==="$gt"?">":"\u2265"} ${JSON.stringify(i)}.`}}if(n!==void 0&&i!==void 0){let o=Q(n,i);if(!Number.isNaN(o)&&o>0)return {type:"subset",reason:`Candidate's lower bound on ${e.path} (${JSON.stringify(n)}) is stricter than the existing rule's lower bound (${JSON.stringify(i)}) \u2014 candidate is a subset.`}}if(r!==void 0&&s!==void 0){let o=Q(r,s);if(!Number.isNaN(o)&&o<0)return {type:"subset",reason:`Candidate's upper bound on ${e.path} (${JSON.stringify(r)}) is stricter than the existing rule's upper bound (${JSON.stringify(s)}) \u2014 candidate is a subset.`}}return {type:"overlap",reason:`Both rules constrain "${e.path}".`}}function Fe(e){return typeof e=="object"&&e!==null&&typeof e.id=="string"}var Zt={checkAgainst(e,t){let n=Array.isArray(t)?t:"constraints"in t&&Array.isArray(t.constraints)?t.constraints:[],r=S(e);if(r.length===0)return {contradictions:[],warnings:[]};let i=new Map;for(let u of r){let a=i.get(u.path)??[];a.push(u),i.set(u.path,a);}let s=[],o=[];for(let u of n){if(!Fe(u)||u.whenSpec===void 0)continue;let a=S(u.whenSpec);for(let c of a){let l=i.get(c.path);if(l)for(let d of l){let g=Xt(d,c);if(!g)continue;let y={constraintId:u.id,type:g.type,reason:g.reason,candidatePath:d.path,candidate:{op:d.op,value:d.value},existing:{op:c.op,value:c.value}};g.type==="overlap"||g.type==="subset"?o.push(y):s.push(y);}}}return {contradictions:s,warnings:o}},checkAbortOn(e,t){let n=Array.isArray(t)?t:"constraints"in t&&Array.isArray(t.constraints)?t.constraints:[],r=S(e);if(r.length===0)return {warnings:[]};let i=new Set(r.map(o=>o.path)),s=[];for(let o of n){if(!Fe(o))continue;let u=Array.isArray(o.abortOn)?o.abortOn:[],a=Array.isArray(o.bind)?o.bind:[];for(let c of u)i.has(c)&&s.push({constraintId:o.id,candidatePath:c,source:"abortOn",reason:`Constraint "${o.id}" aborts on "${c}" \u2014 candidate would race or shadow its writes.`,severity:"warning"});for(let c of a)i.has(c)&&s.push({constraintId:o.id,candidatePath:c,source:"bind",reason:`Constraint "${o.id}" binds "${c}" \u2014 candidate would write to a bound field.`,severity:"warning"});}return {warnings:s}}};var I=new Map,Yt=50;function Gt(e){let t=I.get(e);if(!t){try{t=new Intl.NumberFormat(e);}catch{t=new Intl.NumberFormat("en-US");}if(I.size>=Yt){let n=I.keys().next().value;n!==void 0&&I.delete(n);}I.set(e,t);}return t}function Vt(e,t={}){let n=t.style??"natural",r=t.parenthesize??true,i=t.locale??"en-US",s=t.factName??(a=>a);if(e===null||typeof e!="object")return "<invalid predicate>";let o={style:n,parenthesize:r,locale:i,factName:s,seen:new WeakSet,cycle:false},u=X(e,o,0);return o.cycle?"<invalid predicate: cycle>":u}var Ie=" AND ",en=" OR ",tn="NOT",Le=" \u2227 ",nn=" \u2228 ",rn="\xAC";function q(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function on(e){if(!q(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function X(e,t,n){if(n>g)return a&&console.warn(`[Directive] describePredicate: depth limit (${g}) exceeded \u2014 bailing.`),t.style==="formal"?"\u22A5":"always true";if(Array.isArray(e))return sn(e,t);if(!q(e))return f(e,t);if(t.seen.has(e))return t.cycle=true,"<invalid predicate: cycle>";t.seen.add(e);let r=e,i=Object.keys(r);for(let o of ["$all","$any","$not"])if(o in r)return an(o,r[o],t,n);let s=[];for(let o of i)o.startsWith("$")||s.push(qe(o,r[o],t,n));return Z(s,t)}function sn(e,t,n){let r=[];for(let i of e){if(!q(i))continue;let s=i;typeof s.fact!="string"||typeof s.op!="string"||r.push(L(s.fact,s.op,s.value,t));}return r.length===0?t.style==="formal"?"\u22A4":"always true":Z(r,t)}function an(e,t,n,r){if(e==="$not"){if(q(t)&&Object.keys(t).length===0)return n.style==="formal"?"\u22A5":"never";let o=X(t,n,r+1);return o==="always true"?"never":o==="\u22A4"?"\u22A5":`${n.style==="formal"?rn:`${tn} `}(${o})`}if(!Array.isArray(t))return n.style==="formal"?"\u22A5":"<invalid predicate>";if(t.length===0)return e==="$all"?n.style==="formal"?"\u22A4":"always true":n.style==="formal"?"\u22A5":"never";let i=[];for(let o of t){let u=X(o,n,r+1);i.push(u);}if(i.length===1)return i[0];let s=n.parenthesize?i.map(o=>`(${o})`):i;return e==="$all"?s.join(n.style==="formal"?Le:Ie):s.join(n.style==="formal"?nn:en)}function qe(e,t,n,r){if(on(t)){let i=t,s=Object.keys(i);if(s.length===1)return L(e,s[0],i[s[0]],n);let o=s.map(u=>L(e,u,i[u],n));return Z(o,n)}if(q(t)){let i=t;if("$all"in i||"$any"in i||"$not"in i)return X(t,n,r+1);let o=[];for(let u of Object.keys(i))u.startsWith("$")||o.push(qe(`${e}.${u}`,i[u],n,r+1));return o.length===0?L(e,"$eq",t,n):Z(o,n)}return L(e,"$eq",t,n)}function L(e,t,n,r){let i=r.style==="formal"?e:r.factName(e);return r.style==="formal"?cn(i,t,n,r):un(i,t,n,r)}function un(e,t,n,r){switch(t){case "$eq":return n===null?`${e} is null`:`${e} is ${f(n,r)}`;case "$ne":return n===null?`${e} is not null`:`${e} is not ${f(n,r)}`;case "$gt":return `${e} is more than ${f(n,r)}`;case "$gte":return `${e} is at least ${f(n,r)}`;case "$lt":return `${e} is less than ${f(n,r)}`;case "$lte":return `${e} is at most ${f(n,r)}`;case "$in":return `${e} is one of ${Ne(n,r)}`;case "$nin":return `${e} is not one of ${Ne(n,r)}`;case "$exists":return n===true?`${e} is set`:`${e} is not set`;case "$between":return Array.isArray(n)&&n.length===2?`${e} is between ${f(n[0],r)} and ${f(n[1],r)}`:`${e} is between ${f(n,r)}`;case "$startsWith":return `${e} starts with ${x(n,r,true)}`;case "$endsWith":return `${e} ends with ${x(n,r,true)}`;case "$contains":return `${e} contains ${x(n,r,true)}`;case "$matches":return n instanceof RegExp?`${e} matches ${n.toString()}`:`${e} matches ${f(n,r)}`;case "$changed":return `${e} changed`;default:return a&&!a$1.has(t)&&console.warn(`[Directive] describePredicate: unknown operator "${t}" \u2014 falling through to generic rendering.`),`${e} ${t} ${f(n,r)}`}}function cn(e,t,n,r){switch(t){case "$eq":return `${e} = ${f(n,r)}`;case "$ne":return `${e} \u2260 ${f(n,r)}`;case "$gt":return `${e} > ${f(n,r)}`;case "$gte":return `${e} \u2265 ${f(n,r)}`;case "$lt":return `${e} < ${f(n,r)}`;case "$lte":return `${e} \u2264 ${f(n,r)}`;case "$in":return `${e} \u2208 {${_e(n,r)}}`;case "$nin":return `${e} \u2209 {${_e(n,r)}}`;case "$exists":return n===true?`\u2203 ${e}`:`\u2204 ${e}`;case "$between":return Array.isArray(n)&&n.length===2?`${f(n[0],r)} \u2264 ${e} \u2264 ${f(n[1],r)}`:`${e} \u2208 [${f(n,r)}]`;case "$startsWith":return `${e} ^= ${x(n,r,true)}`;case "$endsWith":return `${e} $= ${x(n,r,true)}`;case "$contains":return `${e} \u2287 ${x(n,r,true)}`;case "$matches":return n instanceof RegExp?`${e} ~ ${n.toString()}`:`${e} ~ ${f(n,r)}`;case "$changed":return `\u0394${e}`;default:return a&&!a$1.has(t)&&console.warn(`[Directive] describePredicate: unknown operator "${t}" \u2014 falling through to generic rendering.`),`${e} ${t} ${f(n,r)}`}}function Y(e){return e.length===0?true:/[\s,"']/.test(e)}function x(e,t,n){return typeof e!="string"||n||Y(e)?JSON.stringify(e):e}function f(e,t){if(e===null)return "null";if(e===void 0)return "undefined";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))return String(e);try{return Gt(t.locale).format(e)}catch{return String(e)}}if(typeof e=="bigint")return t.style==="formal"?`${e.toString()}n`:e.toString();if(typeof e=="string")return t.style==="formal"||Y(e)?JSON.stringify(e):e;if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return `[${e.map(n=>f(n,t)).join(", ")}]`;if(typeof e=="object")try{return JSON.stringify(e)}catch{return "[object]"}return String(e)}function Ne(e,t){return Array.isArray(e)?e.map(n=>typeof n=="string"?Y(n)?JSON.stringify(n):n:f(n,t)).join(", "):f(e,t)}function _e(e,t){return Array.isArray(e)?e.map(n=>typeof n=="string"?Y(n)?JSON.stringify(n):n:f(n,t)).join(", "):f(e,t)}function Z(e,t){if(e.length===0)return t.style==="formal"?"\u22A4":"always true";if(e.length===1)return e[0];let n=t.style==="formal"?Le:Ie;return t.parenthesize,e.join(n)}var ln=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/;function B(e,t){if(typeof e!="string"||!ln.test(e))throw new Error(`[Directive] predicateToSQL: invalid ${t} identifier "${e}" \u2014 must match /^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)?$/`)}function We(e,t){if(t&&!t.includes(e))throw new Error(`[Directive] predicateToSQL: column "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function dn(e){if(Array.isArray(e)){if(e.length===0)throw new Error("[Directive] predicateToSQL: select must not be empty");for(let n of e)B(n,"column");return e.join(", ")}let t=e;return t==="*"?"*":(B(t,"column"),t)}function b(e,t){return e.params.push(t),e.placeholder(e.params.length)}function fe(e,t,n,r){switch(t){case "$eq":return `${e} = ${b(r,n)}`;case "$ne":return `${e} <> ${b(r,n)}`;case "$gt":return `${e} > ${b(r,n)}`;case "$gte":return `${e} >= ${b(r,n)}`;case "$lt":return `${e} < ${b(r,n)}`;case "$lte":return `${e} <= ${b(r,n)}`;case "$in":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $in operand must be an array");return `${e} = ANY(${b(r,n)})`;case "$nin":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $nin operand must be an array");return `NOT (${e} = ANY(${b(r,n)}))`;case "$exists":return n===true?`${e} IS NOT NULL`:`${e} IS NULL`;case "$between":{if(!Array.isArray(n)||n.length!==2)throw new Error("[Directive] predicateToSQL: $between operand must be a [low, high] tuple");return `${e} BETWEEN ${b(r,n[0])} AND ${b(r,n[1])}`}case "$startsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $startsWith operand must be a string");return `${e} LIKE ${b(r,pe(n))} || '%' ESCAPE '\\'`;case "$endsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $endsWith operand must be a string");return `${e} LIKE '%' || ${b(r,pe(n))} ESCAPE '\\'`;case "$contains":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $contains only supports string operands \u2014 array containment requires a JOIN, not a predicate");return `${e} LIKE '%' || ${b(r,pe(n))} || '%' ESCAPE '\\'`;case "$matches":{if(!(n instanceof RegExp))throw new Error("[Directive] predicateToSQL: $matches operand must be a RegExp");let i=n.flags.includes("i")?"~*":"~";return `${e} ${i} ${b(r,n.source)}`}case "$changed":throw new Error('[Directive] predicateToSQL: $changed is an effects-only operator \u2014 no server-side translation (a database row has no "prev" snapshot)');default:throw new Error(`[Directive] predicateToSQL: unknown operator "${t}" \u2014 known: ${[...a$1].join(", ")}`)}}function pe(e){return e.replace(/[\\%_]/g,"\\$&")}function Be(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fn(e){if(!Be(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function ge(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToSQL: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function W(e,t,n){if(n>g)throw new Error(`[Directive] predicateToSQL: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error(`[Directive] predicateToSQL: predicate must be an object or array, got ${typeof e}`);if(Array.isArray(e)){if(e.length===0)return "TRUE";let i=e.map(s=>{if(!s||typeof s!="object"||!("fact"in s)||!("op"in s))throw new Error("[Directive] predicateToSQL: array-form clause must be { fact, op, value }");let o=s;return B(o.fact,"column"),We(o.fact,t.allowed),fe(o.fact,o.op,o.value,t)});return i.length===1?i[0]:`(${i.join(" AND ")})`}if("$all"in e){ge(e,"$all");let i=e.$all;if(!Array.isArray(i))throw new Error("[Directive] predicateToSQL: $all must be an array");if(i.length===0)return "TRUE";let s=i.map(o=>W(o,t,n+1));return s.length===1?s[0]:`(${s.join(" AND ")})`}if("$any"in e){ge(e,"$any");let i=e.$any;if(!Array.isArray(i))throw new Error("[Directive] predicateToSQL: $any must be an array");if(i.length===0)return "FALSE";let s=i.map(o=>W(o,t,n+1));return s.length===1?s[0]:`(${s.join(" OR ")})`}if("$not"in e){ge(e,"$not");let i=e.$not;return `NOT (${W(i,t,n+1)})`}let r=[];for(let[i,s]of Object.entries(e))if(B(i,"column"),We(i,t.allowed),fn(s))for(let[o,u]of Object.entries(s)){if(!a$1.has(o))throw new Error(`[Directive] predicateToSQL: unknown operator "${o}" on column "${i}" \u2014 known: ${[...a$1].join(", ")}`);r.push(fe(i,o,u,t));}else {if(Be(s))throw new Error(`[Directive] predicateToSQL: nested predicate at "${i}" \u2014 cross-module / partial-match predicates have no SQL equivalent (single-table queries only in v1; pass a flat predicate or build JOIN by hand with predicateToWhere)`);r.push(fe(i,"$eq",s,t));}return r.length===0?"TRUE":r.length===1?r[0]:`(${r.join(" AND ")})`}var Ue=e=>`$${e}`;function pn(e,t){let{table:n,allowedKeys:r}=t,i=t.placeholder??Ue,s=t.select??"*";B(n,"table");let o=dn(s),u={params:[],placeholder:i,allowed:r},a=W(e,u,0);return {sql:`SELECT ${o} FROM ${n} WHERE ${a}`,where:a,params:u.params}}function gn(e,t={}){let n=t.placeholder??Ue,r={params:[],placeholder:n,allowed:t.allowedKeys};return {where:W(e,r,0),params:r.params}}function ye(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function me(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yn(e){if(!me(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}var hn=/^[A-Za-z_][A-Za-z0-9_]*$/,mn=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;function Ke(e,t){if(typeof e!="string"||e.length===0)throw new Error(`[Directive] predicateToMongo: field name must be a non-empty string, got ${typeof e}`);if(e.startsWith("$"))throw new Error(`[Directive] predicateToMongo: field name "${e}" starts with "$" \u2014 reserved for Mongo operators (a top-level $where would be an injection vector)`);if(!(t.allowDottedPaths?mn:hn).test(e))throw new Error(`[Directive] predicateToMongo: invalid field name "${e}"${t.allowDottedPaths?"":' \u2014 pass options.allowDottedPaths=true to permit sub-document paths like "user.role"'}`)}function ze(e,t){if(t&&!t.includes(e))throw new Error(`[Directive] predicateToMongo: field "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function he(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToMongo: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function He(e,t){switch(e){case "$eq":case "$ne":case "$gt":case "$gte":case "$lt":case "$lte":case "$in":case "$nin":case "$exists":return {[e]:t};case "$between":{if(!Array.isArray(t)||t.length!==2)throw new Error("[Directive] predicateToMongo: $between operand must be a [low, high] tuple");return {$gte:t[0],$lte:t[1]}}case "$startsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $startsWith operand must be a string");return {$regex:`^${ye(t)}`};case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $endsWith operand must be a string");return {$regex:`${ye(t)}$`};case "$contains":if(typeof t=="string")return {$regex:ye(t)};throw new Error("[Directive] predicateToMongo: $contains in Mongo expects a string operand \u2014 for array element membership use $elemMatch or $in directly");case "$matches":{if(t instanceof RegExp)return t.flags?{$regex:t.source,$options:t.flags}:{$regex:t.source};if(typeof t=="string")return {$regex:t};throw new Error("[Directive] predicateToMongo: $matches operand must be a RegExp or string")}case "$changed":throw new Error("[Directive] predicateToMongo: $changed is an effects-only operator \u2014 no MongoDB query equivalent");default:throw new Error(`[Directive] predicateToMongo: unknown operator "${e}" \u2014 known: ${[...a$1].join(", ")}`)}}function j(e,t,n){if(n>g)throw new Error(`[Directive] predicateToMongo: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error(`[Directive] predicateToMongo: predicate must be an object or array, got ${typeof e}`);if(Array.isArray(e)){if(e.length===0)return {};let i={},s=[];for(let o of e){if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToMongo: array-form clause must be { fact, op, value }");let u=o;Ke(u.fact,t),ze(u.fact,t.allowedKeys);let a=He(u.op,u.value);if(u.fact in i&&me(i[u.fact])){let c=i[u.fact];Object.keys(a).some(d=>d in c)?s.push({[u.fact]:a}):i[u.fact]={...c,...a};}else u.fact in i?s.push({[u.fact]:a}):i[u.fact]=a;}if(s.length>0){let o=[];for(let[u,a]of Object.entries(i))o.push({[u]:a});return o.push(...s),{$and:o}}return i}if("$all"in e){he(e,"$all");let i=e.$all;if(!Array.isArray(i))throw new Error("[Directive] predicateToMongo: $all must be an array");return i.length===0?{}:i.length===1?j(i[0],t,n+1):{$and:i.map(s=>j(s,t,n+1))}}if("$any"in e){he(e,"$any");let i=e.$any;if(!Array.isArray(i))throw new Error("[Directive] predicateToMongo: $any must be an array");return i.length===0?{$expr:{$eq:[1,0]}}:i.length===1?j(i[0],t,n+1):{$or:i.map(s=>j(s,t,n+1))}}if("$not"in e){he(e,"$not");let i=e.$not;return {$nor:[j(i,t,n+1)]}}let r={};for(let[i,s]of Object.entries(e))if(Ke(i,t),ze(i,t.allowedKeys),yn(s)){let o={};for(let[u,a]of Object.entries(s)){if(!a$1.has(u))throw new Error(`[Directive] predicateToMongo: unknown operator "${u}" on field "${i}" \u2014 known: ${[...a$1].join(", ")}`);Object.assign(o,He(u,a));}r[i]=o;}else r[i]=s;return r}function $n(e,t={}){return j(e,t,0)}var wn=/^[A-Za-z_][A-Za-z0-9_]*$/;function Je(e,t){if(typeof e!="string"||!wn.test(e))throw new Error(`[Directive] predicateToPostgrest: invalid column identifier "${e}"`);if(t&&!t.includes(e))throw new Error(`[Directive] predicateToPostgrest: column "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function $e(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToPostgrest: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function k(e){if(e==null)return "null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"||typeof e=="bigint")return String(e);if(e instanceof Date)return e.toISOString();if(typeof e=="string")return /[,.():"\\\s]/.test(e)?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e;throw new Error(`[Directive] predicateToPostgrest: cannot encode value of type ${typeof e}`)}function Qe(e){return `(${e.map(k).join(",")})`}function we(e){return e.replace(/[\\%_*]/g,"\\$&")}function P(e,t){switch(e){case "$eq":return `eq.${k(t)}`;case "$ne":return `neq.${k(t)}`;case "$gt":return `gt.${k(t)}`;case "$gte":return `gte.${k(t)}`;case "$lt":return `lt.${k(t)}`;case "$lte":return `lte.${k(t)}`;case "$in":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $in operand must be an array");return `in.${Qe(t)}`;case "$nin":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $nin operand must be an array");return `not.in.${Qe(t)}`;case "$exists":return t===true?"not.is.null":"is.null";case "$startsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $startsWith operand must be a string");return `like.${k(`${we(t)}*`)}`;case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $endsWith operand must be a string");return `like.${k(`*${we(t)}`)}`;case "$contains":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $contains expects a string operand (array containment is the cs operator with a different shape \u2014 out of scope for v1)");return `like.${k(`*${we(t)}*`)}`;case "$matches":if(t instanceof RegExp)return `${t.flags.includes("i")?"imatch":"match"}.${k(t.source)}`;if(typeof t=="string")return `match.${k(t)}`;throw new Error("[Directive] predicateToPostgrest: $matches operand must be a RegExp or string");case "$changed":throw new Error("[Directive] predicateToPostgrest: $changed is an effects-only operator \u2014 no server query equivalent");default:throw new Error(`[Directive] predicateToPostgrest: unknown operator "${e}" \u2014 known: ${[...a$1].join(", ")}`)}}function Xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function bn(e){if(!Xe(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function be(e,t){return `${e}=${t}`}function G(e,t){return `${e}=(${t.join(",")})`}function Se(e,t,n,r){if(t==="$between"){if(!Array.isArray(n)||n.length!==2)throw new Error("[Directive] predicateToPostgrest: $between operand must be a [low, high] tuple");let i=r?be(e,P("$gte",n[0])):`${e}.${P("$gte",n[0])}`,s=r?be(e,P("$lte",n[1])):`${e}.${P("$lte",n[1])}`;return [i,s]}return [r?be(e,P(t,n)):`${e}.${P(t,n)}`]}function U(e,t,n,r){if(r>g)throw new Error(`[Directive] predicateToPostgrest: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error("[Directive] predicateToPostgrest: predicate must be an object or array");if(Array.isArray(e)){let s=[];for(let o of e){if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToPostgrest: array-form clause must be { fact, op, value }");let u=o;Je(u.fact,t),s.push(...Se(u.fact,u.op,u.value,n));}return s}if("$all"in e){$e(e,"$all");let s=e.$all;if(!Array.isArray(s))throw new Error("[Directive] predicateToPostgrest: $all must be an array");if(n){let u=[];for(let a of s)u.push(...U(a,t,true,r+1));return u}let o=[];for(let u of s)o.push(...U(u,t,false,r+1));return [G("and",o)]}if("$any"in e){$e(e,"$any");let s=e.$any;if(!Array.isArray(s))throw new Error("[Directive] predicateToPostgrest: $any must be an array");if(s.length===0)return n?["id=is.null","id=not.is.null"]:[G("and",["id.is.null","id.not.is.null"])];let o=[];for(let u of s)o.push(...U(u,t,false,r+1));return [G("or",o)]}if("$not"in e){$e(e,"$not");let s=e.$not,o=U(s,t,false,r+1);return [G("not.and",o)]}let i=[];for(let[s,o]of Object.entries(e))if(Je(s,t),bn(o))for(let[u,a]of Object.entries(o)){if(!a$1.has(u))throw new Error(`[Directive] predicateToPostgrest: unknown operator "${u}" on column "${s}" \u2014 known: ${[...a$1].join(", ")}`);i.push(...Se(s,u,a,n));}else {if(Xe(o))throw new Error(`[Directive] predicateToPostgrest: nested predicate at "${s}" \u2014 single-table queries only`);i.push(...Se(s,"$eq",o,n));}return i}function Sn(e){let t=e.indexOf("=");if(t<0)return encodeURIComponent(e);let n=e.slice(0,t),r=e.slice(t+1);return `${n}=${encodeURIComponent(r)}`}function Tn(e,t={}){let n=t.mode??"querystring",r=U(e,t.allowedKeys,true,0);return r.length===0?"":n==="raw"?r.join("&"):r.map(Sn).join("&")}function V(e=[],t,n,r,i,s,o){return {_type:void 0,_validators:e,_typeName:t,_default:n,_transform:r,_description:i,_refinements:s,_meta:o,validate(u){return V([...e,u],t,n,r,i,s,o)}}}function p(e,t,n,r,i,s,o){return {...V(e,t,n,r,i,s,o),default(a){return p(e,t,a,r,i,s,o)},transform(a){return p([],t,void 0,l=>{let d=r?r(l):l;return a(d)},i,void 0,o)},brand(){return p(e,`Branded<${t}>`,n,r,i,s,o)},describe(a){return p(e,t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return p([...e,a],t,n,r,i,l,o)},nullable(){return p([a=>a===null||e.every(c=>c(a))],`${t} | null`,n,r,i,void 0,o)},optional(){return p([a=>a===void 0||e.every(c=>c(a))],`${t} | undefined`,n,r,i,void 0,o)},meta(a){return p(e,t,n,r,i,s,a)}}}var kn=((...e)=>{if(e.length===0)return p([],"union");let t=e.map(n=>n._typeName??"unknown");return p([n=>e.some(r=>r._validators.every(i=>i(n)))],t.join(" | "))}),vn={string(){let e=(t,n,r,i,s,o)=>({...p(t,"string",n,r,i,s,o),minLength(a){return e([...t,c=>c.length>=a],n,r,i,s,o)},maxLength(a){return e([...t,c=>c.length<=a],n,r,i,s,o)},pattern(a){return e([...t,c=>a.test(c)],n,r,i,s,o)},default(a){return e(t,a,r,i,s,o)},describe(a){return e(t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return e([...t,a],n,r,i,l,o)},meta(a){return e(t,n,r,i,s,a)}});return e([t=>typeof t=="string"])},number(){let e=(t,n,r,i,s,o)=>({...p(t,"number",n,r,i,s,o),min(a){return e([...t,c=>c>=a],n,r,i,s,o)},max(a){return e([...t,c=>c<=a],n,r,i,s,o)},default(a){return e(t,a,r,i,s,o)},describe(a){return e(t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return e([...t,a],n,r,i,l,o)},meta(a){return e(t,n,r,i,s,a)}});return e([t=>typeof t=="number"])},boolean(){return p([e=>typeof e=="boolean"],"boolean")},array(){let e=(t,n,r,i,s,o)=>{let u=p(t,"array",r,void 0,i,void 0,o),a=s??{value:-1};return {...u,get _lastFailedIndex(){return a.value},set _lastFailedIndex(l){a.value=l;},of(l){let d={value:-1};return e([...t,g=>{for(let y=0;y<g.length;y++)if(!l._validators.every($=>$(g[y])))return d.value=y,false;return true}],l,r,i,d,o)},nonEmpty(){return e([...t,l=>l.length>0],n,r,i,a,o)},maxLength(l){return e([...t,d=>d.length<=l],n,r,i,a,o)},minLength(l){return e([...t,d=>d.length>=l],n,r,i,a,o)},default(l){return e(t,n,l,i,a,o)},describe(l){return e(t,n,r,l,a,o)},meta(l){return e(t,n,r,i,a,l)}}};return e([t=>Array.isArray(t)])},object(){let e=(t,n,r,i)=>({...p(t,"object",n,void 0,r,void 0,i),shape(o){return e([...t,u=>{for(let[a,c]of Object.entries(o)){let l=u[a],d=c;if(d&&!d._validators.every(g=>g(l)))return false}return true}],n,r,i)},nonNull(){return e([...t,o=>o!=null],n,r,i)},hasKeys(...o){return e([...t,u=>o.every(a=>a in u)],n,r,i)},default(o){return e(t,o,r,i)},describe(o){return e(t,n,o,i)},meta(o){return e(t,n,r,o)}});return e([t=>typeof t=="object"&&t!==null&&!Array.isArray(t)])},enum(...e){a&&e.length===0&&console.warn("[Directive] t.enum() called with no values - this will reject all strings");let t=new Set(e);return p([n=>typeof n=="string"&&t.has(n)],`enum(${e.join("|")})`)},literal(e){return p([t=>t===e],`literal(${String(e)})`)},nullable(e){let t=e._typeName??"unknown";return V([n=>n===null?true:e._validators.every(r=>r(n))],`${t} | null`)},optional(e){let t=e._typeName??"unknown";return V([n=>n===void 0?true:e._validators.every(r=>r(n))],`${t} | undefined`)},union:kn,record(e){let t=e._typeName??"unknown";return p([n=>typeof n!="object"||n===null||Array.isArray(n)?false:Object.values(n).every(r=>e._validators.every(i=>i(r)))],`Record<string, ${t}>`)},tuple(...e){a&&e.length===0&&console.warn("[Directive] t.tuple() called with no types - this will only accept empty arrays");let t=e.map(n=>n._typeName??"unknown");return p([n=>!Array.isArray(n)||n.length!==e.length?false:e.every((r,i)=>r._validators.every(s=>s(n[i])))],`[${t.join(", ")}]`)},date(){return p([e=>e instanceof Date&&!Number.isNaN(e.getTime())],"Date")},uuid(){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;return p([t=>typeof t=="string"&&e.test(t)],"uuid")},email(){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return p([t=>typeof t=="string"&&e.test(t)],"email")},url(){return p([e=>{if(typeof e!="string")return false;try{return new URL(e),!0}catch{return false}}],"url")},bigint(){return p([e=>typeof e=="bigint"],"bigint")},any(){return p([],"any")},unknown(){return p([],"unknown")}};function Mn(e){if(!e||typeof e!="string"){console.warn("[Directive] Module ID must be a non-empty string");return}/^(__[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$/i.test(e)||console.warn(`[Directive] Module ID "${e}" should follow kebab-case convention (e.g., "my-module")`);}function Ze(e,t,n,r,i){for(let s of e)t.has(s)||console.warn(`[Directive] ${n} "${s}" not declared in ${r}`);for(let s of t)e.has(s)||console.warn(`[Directive] ${r}["${s}"] ${i}`);}function Dn(e,t){e.length===0&&console.warn("[Directive] history.snapshotEvents is an empty array \u2014 no events will create history snapshots. Omit history.snapshotEvents entirely to snapshot all events, or list specific events.");let n=new Set(Object.keys(t));for(let r of e)n.has(r)||console.warn(`[Directive] history.snapshotEvents entry "${r}" not declared in schema.events. Available events: ${[...n].join(", ")||"(none)"}`);}function Rn(e,t){let n=new Set(Object.keys(t));for(let[r,i]of Object.entries(e)){let s=i;typeof s.requirement=="string"&&!n.has(s.requirement)&&console.warn(`[Directive] Resolver "${r}" references unknown requirement type "${s.requirement}". Available types: ${[...n].join(", ")||"(none)"}`);}}function Cn(e,t){let n=t.schema?.facts??{},r=Object.keys(n);if(r.length===0)return;let i=new Set(["self","prev","current"]),s="crossModuleDeps"in t&&t.crossModuleDeps?Object.keys(t.crossModuleDeps):[];for(let o of s)i.add(o);for(let o of r)if(i.has(o))throw new Error(`[Directive] module '${e}': fact key '${o}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:
1
+ export{i as createAuditLedger,d as diffClauses,c as diffRules,f as doctor,b as flattenPredicate,h as memorySink,a as toRulesMap}from'./chunk-PJIIBQTK.js';import {a as a$2}from'./chunk-AFPLATPV.js';export{a as createSystem}from'./chunk-AFPLATPV.js';export{b as DirectiveError,o as RequirementSet,n as forType,k as generateRequirementId,h as isNamespacedSystem,m as isRequirementType,g as isSingleModuleSystem,l as req,e as typedConstraint,f as typedResolver}from'./chunk-WVP3GOY2.js';import {o,p as p$1,i as i$1,g,a as a$1,l,h,b}from'./chunk-LN5H74CU.js';export{v as applyPatch,u as evaluateKeySelector,o as evaluatePredicate,p as evaluatePredicateExplained,s as evaluateTemplate,r as extractDeps,t as extractTemplateKeys,c as getKind,e as getOperatorsForKind,d as getSchemaFieldKinds,h as isPredicate,k as isTemplate,f as listAllPredicateOperators,q as memoizePredicate,l as validatePredicate,n as validatePredicateAgainstSchema}from'./chunk-LN5H74CU.js';import {k}from'./chunk-WD47DB52.js';import {i,a}from'./chunk-IZNOPHPL.js';export{l as diffSnapshots,m as isSignedSnapshot,j as isSnapshotExpired,h as shallowEqual,n as signSnapshot,k as validateSnapshot,o as verifySnapshotSignature}from'./chunk-IZNOPHPL.js';var R=1e6;function $e(e,t){try{l(e);}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`[Directive] replayUnder: the ${t} predicate is invalid \u2014 ${i}`)}if(!h(e)){let r=e===null||typeof e!="object"?`${typeof e} \u2014 ${JSON.stringify(e)}`:JSON.stringify(e).slice(0,80);throw new Error(`[Directive] replayUnder: the ${t} predicate is not a valid FactPredicate (got ${r})`)}let n;if(i$1(e,{operator(r,i){n===void 0&&i.startsWith("$")&&!a$1.has(i)&&(n=i);},strayOperatorKey(r){n===void 0&&!a$1.has(r)&&!b.has(r)&&(n=r);}}),n!==void 0)throw new Error(`[Directive] replayUnder: the ${t} predicate uses an unknown operator "${n}" \u2014 known operators: ${[...a$1].join(", ")}`)}function be(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return Te(e);let t=Array.isArray(e)?e:e&&typeof e=="object"&&Array.isArray(e.frames)?e.frames:null;if(!t)throw new Error("[Directive] toReplayFrames: history must be a JSON array of frames, an object with a `frames` array, or a history export with a `snapshots` array");if(t.length>R)throw new Error(`[Directive] toReplayFrames: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);return t.map((n,r)=>{if(n&&typeof n=="object"&&"facts"in n){let i=n,s={id:i.id??`#${r}`,facts:i.facts??{}};return typeof i.timestamp=="number"&&(s.timestamp=i.timestamp),s}return {id:`#${r}`,facts:n??{}}})}function Te(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return ne(t);if(!t||typeof t!="object")throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");let n=t;if(n.version!==void 0&&n.version!==1)throw new Error(`[Directive] framesFromHistory: unsupported history export version ${JSON.stringify(n.version)} \u2014 expected 1`);if(!Array.isArray(n.snapshots))throw new Error("[Directive] framesFromHistory: expected a history export object with a `snapshots` array (from system.history.export())");return ne(n.snapshots)}function ne(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>R)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);for(let t=0;t<e.length;t++){let n=e[t];if(!n||typeof n!="object"||!("facts"in n))throw new Error(`[Directive] framesFromSnapshots: snapshot at index ${t} is not a { facts, ... } object`)}return be(e)}function U(e){let{frames:t,original:n,proposed:r,entityKey:i}=e,s=e.maxSamples??20,o$1=s>0?s:0;if(t.length>R)throw new Error(`[Directive] replayUnder: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${R}) \u2014 split or down-sample the history`);$e(n,"original"),$e(r,"proposed");let u=0,a=0,c=0,l=0,f=0,h=[],b=[],v=i?new Set:void 0,D=i?new Set:void 0,S;for(let O of t){let $=O.facts,T=o(n,$,S),k=o(r,$,S);T&&(u++,v?.add($[i])),k&&(a++,D?.add($[i])),T===k?f++:!T&&k?(c++,h.length<o$1&&h.push(we(O,n,r,S))):(l++,b.length<o$1&&b.push(we(O,n,r,S))),S=$;}let E={framesEvaluated:t.length,original:{matched:u},proposed:{matched:a},delta:a-u,newMatchCount:c,lostMatchCount:l,unchanged:f,newMatches:h,lostMatches:b};return v&&D&&(E.original.matchedEntities=v.size,E.proposed.matchedEntities=D.size),E}function we(e,t,n,r){let i=e.facts,s={frameId:e.id,facts:i,originalExplain:p$1(t,i,r),proposedExplain:p$1(n,i,r)};return e.timestamp!==void 0&&(s.timestamp=e.timestamp),s}var re=1e4,Se=5e7;function Pt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function ie(e,t,n=new Set,r=0){if(r>g)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${g}) \u2014 flatten the template or split the sweep`);if(Pt(e)){let i=e.$hole;if(!(i in t))throw new Error(`[Directive] sweepUnder: template references hole "${i}" but sweep has no values for it`);return t[i]}if(e===null||typeof e!="object")return e;if(n.has(e))throw new Error("[Directive] sweepUnder: template contains a cycle \u2014 predicate templates must be a tree");n.add(e);try{if(Array.isArray(e))return e.map(s=>ie(s,t,n,r+1));let i={};for(let[s,o]of Object.entries(e))i[s]=ie(o,t,n,r+1);return i}finally{n.delete(e);}}function*Me(e,t){if(e.length===0){yield {};return}let n=e[0],r=e.slice(1),i=t[n]??[];for(let s of i)for(let o of Me(r,t))yield {[n]:s,...o};}function Ot(e){let t=1;for(let n of Object.values(e))t*=n.length;return t}function jt(e){let{frames:t,original:n,template:r,sweep:i,objective:s=$=>$.proposed.matched,entityKey:o,maxSamples:u=0}=e,a=Object.keys(i);if(a.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let c=Ot(i);if(c>re)throw new Error(`[Directive] sweepUnder: grid has ${c} points, exceeds the MAX_SWEEP_POINTS limit (${re}) \u2014 narrow the sweep ranges or split the run`);if(c===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let l=c*t.length;if(l>Se)throw new Error(`[Directive] sweepUnder: ${c} points \xD7 ${t.length} frames = ${l} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${Se}) \u2014 narrow the sweep, down-sample the history, or split the run`);let f=false,h=$=>{let T;try{T=s($);}catch(k){return f||(f=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${k.message})`)),Number.NEGATIVE_INFINITY}return typeof T!="number"||!Number.isFinite(T)?(f||(f=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(T)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):T},b=U({frames:t,original:n,proposed:n,entityKey:o,maxSamples:u}),v={values:{},report:b,score:h(b)},D=[],S=0,E=Number.NEGATIVE_INFINITY;for(let $ of Me(a,i)){let T=ie(r,$),k=U({frames:t,original:n,proposed:T,entityKey:o,maxSamples:u}),Z=h(k);Z>E&&(E=Z,S=D.length),D.push({values:$,report:k,score:Z});}let O=D[S];return {points:D,bestIndex:S,best:O,baseline:v}}function Ft(e){return i(e)}function B(e){return e===null?"null":e===void 0?"undefined":e instanceof Date?e.toISOString():typeof e=="string"||typeof e=="object"?JSON.stringify(e):String(e)}function _t(e){let t=e.path,n=B(e.expected),r=B(e.actual);switch(e.op){case "$eq":return `set ${t} to ${n} (currently ${r})`;case "$ne":return `change ${t} to anything other than ${n} (currently ${r})`;case "$gt":return `set ${t} above ${n} (currently ${r})`;case "$gte":return `set ${t} to at least ${n} (currently ${r})`;case "$lt":return `set ${t} below ${n} (currently ${r})`;case "$lte":return `set ${t} to at most ${n} (currently ${r})`;case "$in":return `set ${t} to one of ${n} (currently ${r})`;case "$nin":return `set ${t} to something other than ${n} (currently ${r})`;case "$exists":return e.expected===true?`set ${t} to a non-null value (currently null/missing)`:`unset ${t} (currently ${r})`;case "$between":return Array.isArray(e.expected)&&e.expected.length===2?`set ${t} between ${B(e.expected[0])} and ${B(e.expected[1])} (currently ${r})`:`set ${t} within range ${n} (currently ${r})`;case "$startsWith":return `set ${t} to start with ${n} (currently ${r})`;case "$endsWith":return `set ${t} to end with ${n} (currently ${r})`;case "$contains":return `set ${t} to contain ${n} (currently ${r})`;case "$matches":return `set ${t} to match the pattern ${n} (currently ${r})`;case "$changed":return `the previous-vs-current change of ${t} is required to differ (currently they match: ${r})`;case "$all":case "$any":case "$not":return `the ${e.op} group at "${t}" did not pass \u2014 see its child clauses`;default:return `clause at ${t} (${e.op}) failed: expected ${n}, got ${r}`}}function De(e,t){for(let n of e)if(!n.pass){if((n.op==="$all"||n.op==="$any"||n.op==="$not")&&n.children){De(n.children,t);continue}t.push({path:n.path,op:n.op,expected:n.expected,actual:n.actual,suggestion:_t(n)});}}function Nt(e,t,n){let r=p$1(e,t,n),i=r.every(o=>o.pass),s=[];if(i||De(r,s),!i&&n===void 0){let o=[];i$1(e,{operator(u,a){a==="$changed"&&o.push(u);}});for(let u of o)s.push({path:u,op:"$changed",expected:true,actual:void 0,suggestion:`$changed clause at "${u}" cannot be evaluated without a \`prev\` snapshot \u2014 pass predict(predicate, facts, prev).`});}return {wouldFire:i,whenExplain:r,missingChanges:s}}var j=new Map,It=50;function Lt(e){let t=j.get(e);if(!t){try{t=new Intl.NumberFormat(e);}catch{t=new Intl.NumberFormat("en-US");}if(j.size>=It){let n=j.keys().next().value;n!==void 0&&j.delete(n);}j.set(e,t);}return t}function qt(e,t={}){let n=t.style??"natural",r=t.parenthesize??true,i=t.locale??"en-US",s=t.factName??(a=>a);if(e===null||typeof e!="object")return "<invalid predicate>";let o={style:n,parenthesize:r,locale:i,factName:s,seen:new WeakSet,cycle:false},u=K(e,o,0);return o.cycle?"<invalid predicate: cycle>":u}var Re=" AND ",Wt=" OR ",Ut="NOT",Ee=" \u2227 ",Bt=" \u2228 ",Kt="\xAC";function _(e){return typeof e!="object"||e===null||Array.isArray(e)?false:!(e instanceof Date)&&!(e instanceof RegExp)}function zt(e){if(!_(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function K(e,t,n){if(n>g)return a&&console.warn(`[Directive] describePredicate: depth limit (${g}) exceeded \u2014 bailing.`),t.style==="formal"?"\u22A5":"always true";if(Array.isArray(e))return Ht(e,t);if(!_(e))return d(e,t);if(t.seen.has(e))return t.cycle=true,"<invalid predicate: cycle>";t.seen.add(e);let r=e,i=Object.keys(r);for(let o of ["$all","$any","$not"])if(o in r)return Qt(o,r[o],t,n);let s=[];for(let o of i)o.startsWith("$")||s.push(Ae(o,r[o],t,n));return z(s,t)}function Ht(e,t,n){let r=[];for(let i of e){if(!_(i))continue;let s=i;typeof s.fact!="string"||typeof s.op!="string"||r.push(F(s.fact,s.op,s.value,t));}return r.length===0?t.style==="formal"?"\u22A4":"always true":z(r,t)}function Qt(e,t,n,r){if(e==="$not"){if(_(t)&&Object.keys(t).length===0)return n.style==="formal"?"\u22A5":"never";let o=K(t,n,r+1);return o==="always true"?"never":o==="\u22A4"?"\u22A5":`${n.style==="formal"?Kt:`${Ut} `}(${o})`}if(!Array.isArray(t))return n.style==="formal"?"\u22A5":"<invalid predicate>";if(t.length===0)return e==="$all"?n.style==="formal"?"\u22A4":"always true":n.style==="formal"?"\u22A5":"never";let i=[];for(let o of t){let u=K(o,n,r+1);i.push(u);}if(i.length===1)return i[0];let s=n.parenthesize?i.map(o=>`(${o})`):i;return e==="$all"?s.join(n.style==="formal"?Ee:Re):s.join(n.style==="formal"?Bt:Wt)}function Ae(e,t,n,r){if(zt(t)){let i=t,s=Object.keys(i);if(s.length===1)return F(e,s[0],i[s[0]],n);let o=s.map(u=>F(e,u,i[u],n));return z(o,n)}if(_(t)){let i=t;if("$all"in i||"$any"in i||"$not"in i)return K(t,n,r+1);let o=[];for(let u of Object.keys(i))u.startsWith("$")||o.push(Ae(`${e}.${u}`,i[u],n,r+1));return o.length===0?F(e,"$eq",t,n):z(o,n)}return F(e,"$eq",t,n)}function F(e,t,n,r){let i=r.style==="formal"?e:r.factName(e);return r.style==="formal"?Xt(i,t,n,r):Jt(i,t,n,r)}function Jt(e,t,n,r){switch(t){case "$eq":return n===null?`${e} is null`:`${e} is ${d(n,r)}`;case "$ne":return n===null?`${e} is not null`:`${e} is not ${d(n,r)}`;case "$gt":return `${e} is more than ${d(n,r)}`;case "$gte":return `${e} is at least ${d(n,r)}`;case "$lt":return `${e} is less than ${d(n,r)}`;case "$lte":return `${e} is at most ${d(n,r)}`;case "$in":return `${e} is one of ${ke(n,r)}`;case "$nin":return `${e} is not one of ${ke(n,r)}`;case "$exists":return n===true?`${e} is set`:`${e} is not set`;case "$between":return Array.isArray(n)&&n.length===2?`${e} is between ${d(n[0],r)} and ${d(n[1],r)}`:`${e} is between ${d(n,r)}`;case "$startsWith":return `${e} starts with ${C(n,r,true)}`;case "$endsWith":return `${e} ends with ${C(n,r,true)}`;case "$contains":return `${e} contains ${C(n,r,true)}`;case "$matches":return n instanceof RegExp?`${e} matches ${n.toString()}`:`${e} matches ${d(n,r)}`;case "$changed":return `${e} changed`;default:return a&&!a$1.has(t)&&console.warn(`[Directive] describePredicate: unknown operator "${t}" \u2014 falling through to generic rendering.`),`${e} ${t} ${d(n,r)}`}}function Xt(e,t,n,r){switch(t){case "$eq":return `${e} = ${d(n,r)}`;case "$ne":return `${e} \u2260 ${d(n,r)}`;case "$gt":return `${e} > ${d(n,r)}`;case "$gte":return `${e} \u2265 ${d(n,r)}`;case "$lt":return `${e} < ${d(n,r)}`;case "$lte":return `${e} \u2264 ${d(n,r)}`;case "$in":return `${e} \u2208 {${ve(n,r)}}`;case "$nin":return `${e} \u2209 {${ve(n,r)}}`;case "$exists":return n===true?`\u2203 ${e}`:`\u2204 ${e}`;case "$between":return Array.isArray(n)&&n.length===2?`${d(n[0],r)} \u2264 ${e} \u2264 ${d(n[1],r)}`:`${e} \u2208 [${d(n,r)}]`;case "$startsWith":return `${e} ^= ${C(n,r,true)}`;case "$endsWith":return `${e} $= ${C(n,r,true)}`;case "$contains":return `${e} \u2287 ${C(n,r,true)}`;case "$matches":return n instanceof RegExp?`${e} ~ ${n.toString()}`:`${e} ~ ${d(n,r)}`;case "$changed":return `\u0394${e}`;default:return a&&!a$1.has(t)&&console.warn(`[Directive] describePredicate: unknown operator "${t}" \u2014 falling through to generic rendering.`),`${e} ${t} ${d(n,r)}`}}function H(e){return e.length===0?true:/[\s,"']/.test(e)}function C(e,t,n){return typeof e!="string"||n||H(e)?JSON.stringify(e):e}function d(e,t){if(e===null)return "null";if(e===void 0)return "undefined";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"){if(!Number.isFinite(e))return String(e);try{return Lt(t.locale).format(e)}catch{return String(e)}}if(typeof e=="bigint")return t.style==="formal"?`${e.toString()}n`:e.toString();if(typeof e=="string")return t.style==="formal"||H(e)?JSON.stringify(e):e;if(e instanceof Date)return e.toISOString();if(e instanceof RegExp)return e.toString();if(Array.isArray(e))return `[${e.map(n=>d(n,t)).join(", ")}]`;if(typeof e=="object")try{return JSON.stringify(e)}catch{return "[object]"}return String(e)}function ke(e,t){return Array.isArray(e)?e.map(n=>typeof n=="string"?H(n)?JSON.stringify(n):n:d(n,t)).join(", "):d(e,t)}function ve(e,t){return Array.isArray(e)?e.map(n=>typeof n=="string"?H(n)?JSON.stringify(n):n:d(n,t)).join(", "):d(e,t)}function z(e,t){if(e.length===0)return t.style==="formal"?"\u22A4":"always true";if(e.length===1)return e[0];let n=t.style==="formal"?Ee:Re;return t.parenthesize,e.join(n)}var Zt=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)?$/;function I(e,t){if(typeof e!="string"||!Zt.test(e))throw new Error(`[Directive] predicateToSQL: invalid ${t} identifier "${e}" \u2014 must match /^[A-Za-z_][A-Za-z0-9_]*(\\.[A-Za-z_][A-Za-z0-9_]*)?$/`)}function Ce(e,t){if(t&&!t.includes(e))throw new Error(`[Directive] predicateToSQL: column "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function Yt(e){if(Array.isArray(e)){if(e.length===0)throw new Error("[Directive] predicateToSQL: select must not be empty");for(let n of e)I(n,"column");return e.join(", ")}let t=e;return t==="*"?"*":(I(t,"column"),t)}function m(e,t){return e.params.push(t),e.placeholder(e.params.length)}function oe(e,t,n,r){switch(t){case "$eq":return `${e} = ${m(r,n)}`;case "$ne":return `${e} <> ${m(r,n)}`;case "$gt":return `${e} > ${m(r,n)}`;case "$gte":return `${e} >= ${m(r,n)}`;case "$lt":return `${e} < ${m(r,n)}`;case "$lte":return `${e} <= ${m(r,n)}`;case "$in":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $in operand must be an array");return `${e} = ANY(${m(r,n)})`;case "$nin":if(!Array.isArray(n))throw new Error("[Directive] predicateToSQL: $nin operand must be an array");return `NOT (${e} = ANY(${m(r,n)}))`;case "$exists":return n===true?`${e} IS NOT NULL`:`${e} IS NULL`;case "$between":{if(!Array.isArray(n)||n.length!==2)throw new Error("[Directive] predicateToSQL: $between operand must be a [low, high] tuple");return `${e} BETWEEN ${m(r,n[0])} AND ${m(r,n[1])}`}case "$startsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $startsWith operand must be a string");return `${e} LIKE ${m(r,se(n))} || '%' ESCAPE '\\'`;case "$endsWith":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $endsWith operand must be a string");return `${e} LIKE '%' || ${m(r,se(n))} ESCAPE '\\'`;case "$contains":if(typeof n!="string")throw new Error("[Directive] predicateToSQL: $contains only supports string operands \u2014 array containment requires a JOIN, not a predicate");return `${e} LIKE '%' || ${m(r,se(n))} || '%' ESCAPE '\\'`;case "$matches":{if(!(n instanceof RegExp))throw new Error("[Directive] predicateToSQL: $matches operand must be a RegExp");let i=n.flags.includes("i")?"~*":"~";return `${e} ${i} ${m(r,n.source)}`}case "$changed":throw new Error('[Directive] predicateToSQL: $changed is an effects-only operator \u2014 no server-side translation (a database row has no "prev" snapshot)');default:throw new Error(`[Directive] predicateToSQL: unknown operator "${t}" \u2014 known: ${[...a$1].join(", ")}`)}}function se(e){return e.replace(/[\\%_]/g,"\\$&")}function xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Gt(e){if(!xe(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function ae(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToSQL: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function N(e,t,n){if(n>g)throw new Error(`[Directive] predicateToSQL: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error(`[Directive] predicateToSQL: predicate must be an object or array, got ${typeof e}`);if(Array.isArray(e)){if(e.length===0)return "TRUE";let i=e.map(s=>{if(!s||typeof s!="object"||!("fact"in s)||!("op"in s))throw new Error("[Directive] predicateToSQL: array-form clause must be { fact, op, value }");let o=s;return I(o.fact,"column"),Ce(o.fact,t.allowed),oe(o.fact,o.op,o.value,t)});return i.length===1?i[0]:`(${i.join(" AND ")})`}if("$all"in e){ae(e,"$all");let i=e.$all;if(!Array.isArray(i))throw new Error("[Directive] predicateToSQL: $all must be an array");if(i.length===0)return "TRUE";let s=i.map(o=>N(o,t,n+1));return s.length===1?s[0]:`(${s.join(" AND ")})`}if("$any"in e){ae(e,"$any");let i=e.$any;if(!Array.isArray(i))throw new Error("[Directive] predicateToSQL: $any must be an array");if(i.length===0)return "FALSE";let s=i.map(o=>N(o,t,n+1));return s.length===1?s[0]:`(${s.join(" OR ")})`}if("$not"in e){ae(e,"$not");let i=e.$not;return `NOT (${N(i,t,n+1)})`}let r=[];for(let[i,s]of Object.entries(e))if(I(i,"column"),Ce(i,t.allowed),Gt(s))for(let[o,u]of Object.entries(s)){if(!a$1.has(o))throw new Error(`[Directive] predicateToSQL: unknown operator "${o}" on column "${i}" \u2014 known: ${[...a$1].join(", ")}`);r.push(oe(i,o,u,t));}else {if(xe(s))throw new Error(`[Directive] predicateToSQL: nested predicate at "${i}" \u2014 cross-module / partial-match predicates have no SQL equivalent (single-table queries only in v1; pass a flat predicate or build JOIN by hand with predicateToWhere)`);r.push(oe(i,"$eq",s,t));}return r.length===0?"TRUE":r.length===1?r[0]:`(${r.join(" AND ")})`}var Pe=e=>`$${e}`;function Vt(e,t){let{table:n,allowedKeys:r}=t,i=t.placeholder??Pe,s=t.select??"*";I(n,"table");let o=Yt(s),u={params:[],placeholder:i,allowed:r},a=N(e,u,0);return {sql:`SELECT ${o} FROM ${n} WHERE ${a}`,where:a,params:u.params}}function en(e,t={}){let n=t.placeholder??Pe,r={params:[],placeholder:n,allowed:t.allowedKeys};return {where:N(e,r,0),params:r.params}}function ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function le(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tn(e){if(!le(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}var nn=/^[A-Za-z_][A-Za-z0-9_]*$/,rn=/^[A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*$/;function Oe(e,t){if(typeof e!="string"||e.length===0)throw new Error(`[Directive] predicateToMongo: field name must be a non-empty string, got ${typeof e}`);if(e.startsWith("$"))throw new Error(`[Directive] predicateToMongo: field name "${e}" starts with "$" \u2014 reserved for Mongo operators (a top-level $where would be an injection vector)`);if(!(t.allowDottedPaths?rn:nn).test(e))throw new Error(`[Directive] predicateToMongo: invalid field name "${e}"${t.allowDottedPaths?"":' \u2014 pass options.allowDottedPaths=true to permit sub-document paths like "user.role"'}`)}function je(e,t){if(t&&!t.includes(e))throw new Error(`[Directive] predicateToMongo: field "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function ce(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToMongo: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function Fe(e,t){switch(e){case "$eq":case "$ne":case "$gt":case "$gte":case "$lt":case "$lte":case "$in":case "$nin":case "$exists":return {[e]:t};case "$between":{if(!Array.isArray(t)||t.length!==2)throw new Error("[Directive] predicateToMongo: $between operand must be a [low, high] tuple");return {$gte:t[0],$lte:t[1]}}case "$startsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $startsWith operand must be a string");return {$regex:`^${ue(t)}`};case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToMongo: $endsWith operand must be a string");return {$regex:`${ue(t)}$`};case "$contains":if(typeof t=="string")return {$regex:ue(t)};throw new Error("[Directive] predicateToMongo: $contains in Mongo expects a string operand \u2014 for array element membership use $elemMatch or $in directly");case "$matches":{if(t instanceof RegExp)return t.flags?{$regex:t.source,$options:t.flags}:{$regex:t.source};if(typeof t=="string")return {$regex:t};throw new Error("[Directive] predicateToMongo: $matches operand must be a RegExp or string")}case "$changed":throw new Error("[Directive] predicateToMongo: $changed is an effects-only operator \u2014 no MongoDB query equivalent");default:throw new Error(`[Directive] predicateToMongo: unknown operator "${e}" \u2014 known: ${[...a$1].join(", ")}`)}}function x(e,t,n){if(n>g)throw new Error(`[Directive] predicateToMongo: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error(`[Directive] predicateToMongo: predicate must be an object or array, got ${typeof e}`);if(Array.isArray(e)){if(e.length===0)return {};let i={},s=[];for(let o of e){if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToMongo: array-form clause must be { fact, op, value }");let u=o;Oe(u.fact,t),je(u.fact,t.allowedKeys);let a=Fe(u.op,u.value);if(u.fact in i&&le(i[u.fact])){let c=i[u.fact];Object.keys(a).some(f=>f in c)?s.push({[u.fact]:a}):i[u.fact]={...c,...a};}else u.fact in i?s.push({[u.fact]:a}):i[u.fact]=a;}if(s.length>0){let o=[];for(let[u,a]of Object.entries(i))o.push({[u]:a});return o.push(...s),{$and:o}}return i}if("$all"in e){ce(e,"$all");let i=e.$all;if(!Array.isArray(i))throw new Error("[Directive] predicateToMongo: $all must be an array");return i.length===0?{}:i.length===1?x(i[0],t,n+1):{$and:i.map(s=>x(s,t,n+1))}}if("$any"in e){ce(e,"$any");let i=e.$any;if(!Array.isArray(i))throw new Error("[Directive] predicateToMongo: $any must be an array");return i.length===0?{$expr:{$eq:[1,0]}}:i.length===1?x(i[0],t,n+1):{$or:i.map(s=>x(s,t,n+1))}}if("$not"in e){ce(e,"$not");let i=e.$not;return {$nor:[x(i,t,n+1)]}}let r={};for(let[i,s]of Object.entries(e))if(Oe(i,t),je(i,t.allowedKeys),tn(s)){let o={};for(let[u,a]of Object.entries(s)){if(!a$1.has(u))throw new Error(`[Directive] predicateToMongo: unknown operator "${u}" on field "${i}" \u2014 known: ${[...a$1].join(", ")}`);Object.assign(o,Fe(u,a));}r[i]=o;}else r[i]=s;return r}function on(e,t={}){return x(e,t,0)}var sn=/^[A-Za-z_][A-Za-z0-9_]*$/;function _e(e,t){if(typeof e!="string"||!sn.test(e))throw new Error(`[Directive] predicateToPostgrest: invalid column identifier "${e}"`);if(t&&!t.includes(e))throw new Error(`[Directive] predicateToPostgrest: column "${e}" is not in the allowedKeys list \u2014 add it to options.allowedKeys or remove it from the predicate`)}function fe(e,t){let n=Object.keys(e).filter(r=>r!==t);if(n.length>0)throw new Error(`[Directive] predicateToPostgrest: ${t} cannot coexist with sibling keys (${n.join(", ")}) \u2014 wrap them in $all together, or move them inside the ${t} children`)}function w(e){if(e==null)return "null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="number"||typeof e=="bigint")return String(e);if(e instanceof Date)return e.toISOString();if(typeof e=="string")return /[,.():"\\\s]/.test(e)?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:e;throw new Error(`[Directive] predicateToPostgrest: cannot encode value of type ${typeof e}`)}function Ne(e){return `(${e.map(w).join(",")})`}function de(e){return e.replace(/[\\%_*]/g,"\\$&")}function P(e,t){switch(e){case "$eq":return `eq.${w(t)}`;case "$ne":return `neq.${w(t)}`;case "$gt":return `gt.${w(t)}`;case "$gte":return `gte.${w(t)}`;case "$lt":return `lt.${w(t)}`;case "$lte":return `lte.${w(t)}`;case "$in":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $in operand must be an array");return `in.${Ne(t)}`;case "$nin":if(!Array.isArray(t))throw new Error("[Directive] predicateToPostgrest: $nin operand must be an array");return `not.in.${Ne(t)}`;case "$exists":return t===true?"not.is.null":"is.null";case "$startsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $startsWith operand must be a string");return `like.${w(`${de(t)}*`)}`;case "$endsWith":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $endsWith operand must be a string");return `like.${w(`*${de(t)}`)}`;case "$contains":if(typeof t!="string")throw new Error("[Directive] predicateToPostgrest: $contains expects a string operand (array containment is the cs operator with a different shape \u2014 out of scope for v1)");return `like.${w(`*${de(t)}*`)}`;case "$matches":if(t instanceof RegExp)return `${t.flags.includes("i")?"imatch":"match"}.${w(t.source)}`;if(typeof t=="string")return `match.${w(t)}`;throw new Error("[Directive] predicateToPostgrest: $matches operand must be a RegExp or string");case "$changed":throw new Error("[Directive] predicateToPostgrest: $changed is an effects-only operator \u2014 no server query equivalent");default:throw new Error(`[Directive] predicateToPostgrest: unknown operator "${e}" \u2014 known: ${[...a$1].join(", ")}`)}}function Ie(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function an(e){if(!Ie(e))return false;let t=Object.keys(e);if(t.length===0)return false;for(let n of t)if(!n.startsWith("$"))return false;return true}function pe(e,t){return `${e}=${t}`}function Q(e,t){return `${e}=(${t.join(",")})`}function ge(e,t,n,r){if(t==="$between"){if(!Array.isArray(n)||n.length!==2)throw new Error("[Directive] predicateToPostgrest: $between operand must be a [low, high] tuple");let i=r?pe(e,P("$gte",n[0])):`${e}.${P("$gte",n[0])}`,s=r?pe(e,P("$lte",n[1])):`${e}.${P("$lte",n[1])}`;return [i,s]}return [r?pe(e,P(t,n)):`${e}.${P(t,n)}`]}function L(e,t,n,r){if(r>g)throw new Error(`[Directive] predicateToPostgrest: predicate depth limit (${g}) exceeded \u2014 flatten the predicate or check for a cyclic spec object`);if(e===null||typeof e!="object")throw new Error("[Directive] predicateToPostgrest: predicate must be an object or array");if(Array.isArray(e)){let s=[];for(let o of e){if(!o||typeof o!="object"||!("fact"in o)||!("op"in o))throw new Error("[Directive] predicateToPostgrest: array-form clause must be { fact, op, value }");let u=o;_e(u.fact,t),s.push(...ge(u.fact,u.op,u.value,n));}return s}if("$all"in e){fe(e,"$all");let s=e.$all;if(!Array.isArray(s))throw new Error("[Directive] predicateToPostgrest: $all must be an array");if(n){let u=[];for(let a of s)u.push(...L(a,t,true,r+1));return u}let o=[];for(let u of s)o.push(...L(u,t,false,r+1));return [Q("and",o)]}if("$any"in e){fe(e,"$any");let s=e.$any;if(!Array.isArray(s))throw new Error("[Directive] predicateToPostgrest: $any must be an array");if(s.length===0)return n?["id=is.null","id=not.is.null"]:[Q("and",["id.is.null","id.not.is.null"])];let o=[];for(let u of s)o.push(...L(u,t,false,r+1));return [Q("or",o)]}if("$not"in e){fe(e,"$not");let s=e.$not,o=L(s,t,false,r+1);return [Q("not.and",o)]}let i=[];for(let[s,o]of Object.entries(e))if(_e(s,t),an(o))for(let[u,a]of Object.entries(o)){if(!a$1.has(u))throw new Error(`[Directive] predicateToPostgrest: unknown operator "${u}" on column "${s}" \u2014 known: ${[...a$1].join(", ")}`);i.push(...ge(s,u,a,n));}else {if(Ie(o))throw new Error(`[Directive] predicateToPostgrest: nested predicate at "${s}" \u2014 single-table queries only`);i.push(...ge(s,"$eq",o,n));}return i}function un(e){let t=e.indexOf("=");if(t<0)return encodeURIComponent(e);let n=e.slice(0,t),r=e.slice(t+1);return `${n}=${encodeURIComponent(r)}`}function cn(e,t={}){let n=t.mode??"querystring",r=L(e,t.allowedKeys,true,0);return r.length===0?"":n==="raw"?r.join("&"):r.map(un).join("&")}function J(e=[],t,n,r,i,s,o){return {_type:void 0,_validators:e,_typeName:t,_default:n,_transform:r,_description:i,_refinements:s,_meta:o,validate(u){return J([...e,u],t,n,r,i,s,o)}}}function p(e,t,n,r,i,s,o){return {...J(e,t,n,r,i,s,o),default(a){return p(e,t,a,r,i,s,o)},transform(a){return p([],t,void 0,l=>{let f=r?r(l):l;return a(f)},i,void 0,o)},brand(){return p(e,`Branded<${t}>`,n,r,i,s,o)},describe(a){return p(e,t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return p([...e,a],t,n,r,i,l,o)},nullable(){return p([a=>a===null||e.every(c=>c(a))],`${t} | null`,n,r,i,void 0,o)},optional(){return p([a=>a===void 0||e.every(c=>c(a))],`${t} | undefined`,n,r,i,void 0,o)},meta(a){return p(e,t,n,r,i,s,a)}}}var ln=((...e)=>{if(e.length===0)return p([],"union");let t=e.map(n=>n._typeName??"unknown");return p([n=>e.some(r=>r._validators.every(i=>i(n)))],t.join(" | "))}),fn={string(){let e=(t,n,r,i,s,o)=>({...p(t,"string",n,r,i,s,o),minLength(a){return e([...t,c=>c.length>=a],n,r,i,s,o)},maxLength(a){return e([...t,c=>c.length<=a],n,r,i,s,o)},pattern(a){return e([...t,c=>a.test(c)],n,r,i,s,o)},default(a){return e(t,a,r,i,s,o)},describe(a){return e(t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return e([...t,a],n,r,i,l,o)},meta(a){return e(t,n,r,i,s,a)}});return e([t=>typeof t=="string"])},number(){let e=(t,n,r,i,s,o)=>({...p(t,"number",n,r,i,s,o),min(a){return e([...t,c=>c>=a],n,r,i,s,o)},max(a){return e([...t,c=>c<=a],n,r,i,s,o)},default(a){return e(t,a,r,i,s,o)},describe(a){return e(t,n,r,a,s,o)},refine(a,c){let l=[...s??[],{predicate:a,message:c}];return e([...t,a],n,r,i,l,o)},meta(a){return e(t,n,r,i,s,a)}});return e([t=>typeof t=="number"])},boolean(){return p([e=>typeof e=="boolean"],"boolean")},array(){let e=(t,n,r,i,s,o)=>{let u=p(t,"array",r,void 0,i,void 0,o),a=s??{value:-1};return {...u,get _lastFailedIndex(){return a.value},set _lastFailedIndex(l){a.value=l;},of(l){let f={value:-1};return e([...t,h=>{for(let b=0;b<h.length;b++)if(!l._validators.every(v=>v(h[b])))return f.value=b,false;return true}],l,r,i,f,o)},nonEmpty(){return e([...t,l=>l.length>0],n,r,i,a,o)},maxLength(l){return e([...t,f=>f.length<=l],n,r,i,a,o)},minLength(l){return e([...t,f=>f.length>=l],n,r,i,a,o)},default(l){return e(t,n,l,i,a,o)},describe(l){return e(t,n,r,l,a,o)},meta(l){return e(t,n,r,i,a,l)}}};return e([t=>Array.isArray(t)])},object(){let e=(t,n,r,i)=>({...p(t,"object",n,void 0,r,void 0,i),shape(o){return e([...t,u=>{for(let[a,c]of Object.entries(o)){let l=u[a],f=c;if(f&&!f._validators.every(h=>h(l)))return false}return true}],n,r,i)},nonNull(){return e([...t,o=>o!=null],n,r,i)},hasKeys(...o){return e([...t,u=>o.every(a=>a in u)],n,r,i)},default(o){return e(t,o,r,i)},describe(o){return e(t,n,o,i)},meta(o){return e(t,n,r,o)}});return e([t=>typeof t=="object"&&t!==null&&!Array.isArray(t)])},enum(...e){a&&e.length===0&&console.warn("[Directive] t.enum() called with no values - this will reject all strings");let t=new Set(e);return p([n=>typeof n=="string"&&t.has(n)],`enum(${e.join("|")})`)},literal(e){return p([t=>t===e],`literal(${String(e)})`)},nullable(e){let t=e._typeName??"unknown";return J([n=>n===null?true:e._validators.every(r=>r(n))],`${t} | null`)},optional(e){let t=e._typeName??"unknown";return J([n=>n===void 0?true:e._validators.every(r=>r(n))],`${t} | undefined`)},union:ln,record(e){let t=e._typeName??"unknown";return p([n=>typeof n!="object"||n===null||Array.isArray(n)?false:Object.values(n).every(r=>e._validators.every(i=>i(r)))],`Record<string, ${t}>`)},tuple(...e){a&&e.length===0&&console.warn("[Directive] t.tuple() called with no types - this will only accept empty arrays");let t=e.map(n=>n._typeName??"unknown");return p([n=>!Array.isArray(n)||n.length!==e.length?false:e.every((r,i)=>r._validators.every(s=>s(n[i])))],`[${t.join(", ")}]`)},date(){return p([e=>e instanceof Date&&!Number.isNaN(e.getTime())],"Date")},uuid(){let e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;return p([t=>typeof t=="string"&&e.test(t)],"uuid")},email(){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return p([t=>typeof t=="string"&&e.test(t)],"email")},url(){return p([e=>{if(typeof e!="string")return false;try{return new URL(e),!0}catch{return false}}],"url")},bigint(){return p([e=>typeof e=="bigint"],"bigint")},any(){return p([],"any")},unknown(){return p([],"unknown")}};function dn(e){if(!e||typeof e!="string"){console.warn("[Directive] Module ID must be a non-empty string");return}/^(__[a-z][a-z0-9_-]*|[a-z][a-z0-9-]*)$/i.test(e)||console.warn(`[Directive] Module ID "${e}" should follow kebab-case convention (e.g., "my-module")`);}function Le(e,t,n,r,i){for(let s of e)t.has(s)||console.warn(`[Directive] ${n} "${s}" not declared in ${r}`);for(let s of t)e.has(s)||console.warn(`[Directive] ${r}["${s}"] ${i}`);}function pn(e,t){e.length===0&&console.warn("[Directive] history.snapshotEvents is an empty array \u2014 no events will create history snapshots. Omit history.snapshotEvents entirely to snapshot all events, or list specific events.");let n=new Set(Object.keys(t));for(let r of e)n.has(r)||console.warn(`[Directive] history.snapshotEvents entry "${r}" not declared in schema.events. Available events: ${[...n].join(", ")||"(none)"}`);}function gn(e,t){let n=new Set(Object.keys(t));for(let[r,i]of Object.entries(e)){let s=i;typeof s.requirement=="string"&&!n.has(s.requirement)&&console.warn(`[Directive] Resolver "${r}" references unknown requirement type "${s.requirement}". Available types: ${[...n].join(", ")||"(none)"}`);}}function yn(e,t){let n=t.schema?.facts??{},r=Object.keys(n);if(r.length===0)return;let i=new Set(["self","prev","current"]),s="crossModuleDeps"in t&&t.crossModuleDeps?Object.keys(t.crossModuleDeps):[];for(let o of s)i.add(o);for(let o of r)if(i.has(o))throw new Error(`[Directive] module '${e}': fact key '${o}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:
2
2
  1. Rename the fact (e.g. ${o}_)
3
3
  2. Remove '${o}' from this module's crossModuleDeps if it's not actually needed
4
- 3. Move the fact under a wrapping namespace (t.object({ inner: ... }))`)}function An(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let s=i?.abortOn;if(s){for(let o of s)if(k$1.has(o)||o.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': abortOn key '${o}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function En(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let s=i?.bind;if(s){for(let o of s)if(k$1.has(o)||o.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': bind key '${o}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function On(e,t){Mn(e),t.schema?t.schema.facts||(Object.values(t.schema).some(r=>r!=null&&typeof r=="object"&&"_typeName"in r)&&console.warn(`[Directive] Module "${e}" schema appears to contain fact declarations directly. Did you mean \`schema: { facts: { ... } }\` instead of \`schema: { ... }\`?`),console.warn("[Directive] Module schema.facts is required")):console.warn("[Directive] Module schema is required"),Ze(new Set(Object.keys(t.derive??{})),new Set(Object.keys(t.schema?.derivations??{})),"Derivation","schema.derivations","has no matching implementation in derive"),Ze(new Set(Object.keys(t.events??{})),new Set(Object.keys(t.schema?.events??{})),"Event","schema.events","has no matching handler in events"),t.history?.snapshotEvents&&Dn(t.history.snapshotEvents,t.schema?.events??{}),t.resolvers&&t.schema?.requirements&&Rn(t.resolvers,t.schema.requirements);}function Ye(e,t){Cn(e,t),An(e,t),En(e,t),a&&On(e,t);let n="crossModuleDeps"in t?t.crossModuleDeps:void 0;return {id:e,schema:t.schema,init:t.init,derive:t.derive??{},events:t.events??{},effects:t.effects,sources:t.sources,constraints:t.constraints,resolvers:t.resolvers,hooks:t.hooks,meta:t.meta,history:t.history,crossModuleDeps:n}}function xn(e){return t=>Ye(t,e)}function Te(){let e={pending:new Map,inflight:new Map,failed:new Map,errors:new Map,listeners:new Set};function t(){for(let a of e.listeners)a();}function n(a,c){let l=a.get(c);return l||(l=new Set,a.set(c,l)),l}function r(a){let c=e.pending.get(a)??new Set,l=e.inflight.get(a)??new Set,d=e.failed.get(a)??new Set,g=e.errors.get(a)??null;return {pending:c.size,inflight:l.size,failed:d.size,isLoading:c.size>0||l.size>0,hasError:d.size>0,lastError:g}}function i(){let a=new Set([...e.pending.keys(),...e.inflight.keys(),...e.failed.keys()]),c=new Map;for(let l of a)c.set(l,r(l));return c}function s(a){return e.listeners.add(a),()=>e.listeners.delete(a)}function o(){e.pending.clear(),e.inflight.clear(),e.failed.clear(),e.errors.clear(),t();}return {plugin:{name:"requirement-status",onRequirementCreated(a){let c=a.requirement.type;n(e.pending,c).add(a.id),e.failed.get(c)?.delete(a.id),t();},onResolverStart(a,c){let l=c.requirement.type;e.pending.get(l)?.delete(c.id),n(e.inflight,l).add(c.id),t();},onResolverComplete(a,c){let l=c.requirement.type;e.inflight.get(l)?.delete(c.id),e.pending.get(l)?.delete(c.id),t();},onResolverError(a,c,l){let d=c.requirement.type;e.inflight.get(d)?.delete(c.id),n(e.failed,d).add(c.id),e.errors.set(d,l instanceof Error?l:new Error(String(l))),t();},onResolverCancel(a,c){let l=c.requirement.type;e.pending.get(l)?.delete(c.id),e.inflight.get(l)?.delete(c.id),t();},onRequirementMet(a){let c=a.requirement.type;e.pending.get(c)?.delete(a.id),e.inflight.get(c)?.delete(a.id),t();}},getStatus:r,getAllStatus:i,subscribe:s,reset:o}}function jn(e){return t=>e.getStatus(t)}function Pn(e){let t=Te(),r=[...e.plugins??[],t.plugin];return {system:a$2({module:e.module,plugins:r,trace:e.trace,errorBoundary:e.errorBoundary,tickMs:e.tickMs,zeroConfig:e.zeroConfig,initialFacts:e.initialFacts}),statusPlugin:t}}function Ge(){return {now:()=>Date.now(),setTimeout:(e,t)=>{let n=globalThis.setTimeout(e,t);return ()=>globalThis.clearTimeout(n)}}}function Fn(e=0){let t=e,n=0,r=[];return {now:()=>t,setTimeout:(i,s)=>{let o={id:n++,deadlineMs:t+s,cb:i,canceled:false};return r.push(o),()=>{o.canceled=true;}},advanceBy:i=>{let s=t+i;for(;;){let o=r.filter(a=>!a.canceled&&a.deadlineMs<=s).sort((a,c)=>a.deadlineMs!==c.deadlineMs?a.deadlineMs-c.deadlineMs:a.id-c.id);if(o.length===0)break;let u=o[0];t=Math.max(t,u.deadlineMs),u.canceled=true,u.cb();}t=Math.max(t,s);}}}function Nn(){return Ge()}function ke(){return {startedAtMs:null,pausedDurationMs:0,pausedAtMs:null,status:"idle",repeats:0}}function ee(e,t){return e.startedAtMs===null?0:e.status==="paused"&&e.pausedAtMs!==null?Math.max(0,e.pausedAtMs-e.startedAtMs-e.pausedDurationMs):Math.max(0,t-e.startedAtMs-e.pausedDurationMs)}function Ve(e,t,n){return Math.max(0,n-ee(e,t))}function et(e,t){return e.status==="running"||e.status==="paused"?e:{...e,startedAtMs:t,pausedDurationMs:0,pausedAtMs:null,status:"running",repeats:0}}function tt(e,t){return e.status!=="running"?e:{...e,pausedAtMs:t,status:"paused"}}function nt(e,t){if(e.status!=="paused"||e.pausedAtMs===null)return e;let n=Math.max(0,t-e.pausedAtMs);return {...e,pausedDurationMs:e.pausedDurationMs+n,pausedAtMs:null,status:"running"}}function rt(){return ke()}function it(e){return {...e,status:"completed"}}function ot(e,t){return e.startedAtMs===null||e.status==="paused"?e:{...e,startedAtMs:e.startedAtMs+t,pausedDurationMs:0,pausedAtMs:null,repeats:e.repeats+1}}function st(e,t,n){if(e.status!=="running")return {kind:"no-op"};let r=ee(e,t);return n.mode==="up"?{kind:"no-op"}:n.mode==="repeat"?r>=n.ms?{kind:"repeat"}:{kind:"no-op"}:r>=n.ms?{kind:"complete"}:{kind:"no-op"}}function _n(e){return {initial:ke,start:et,pause:tt,resume:nt,reset:rt,complete:it,registerRepeat:t=>ot(t,e.ms),tick:(t,n)=>st(t,n,e),elapsedMs:ee,remainingMs:(t,n)=>Ve(t,n,e.ms)}}var Tr={None:"none",Linear:"linear",Exponential:"exponential"};export{Tr as Backoff,A as MAX_REPLAY_FRAMES,ue as MAX_SWEEP_POINTS,it as completeTimer,Ye as createModule,xn as createModuleFactory,Te as createRequirementStatusPlugin,jn as createStatusHook,Pn as createSystemWithStatus,Nn as defaultClock,Vt as describePredicate,xe as diffClauses,zt as diffRules,Zt as doctor,ee as elapsedMs,S as flattenPredicate,Ce as framesFromHistory,ae as framesFromSnapshots,ke as initialTimerState,tt as pauseTimer,Ht as predicateHash,$n as predicateToMongo,Tn as predicateToPostgrest,pn as predicateToSQL,gn as predicateToWhere,Qt as predict,Ge as realClock,ot as registerRepeat,Ve as remainingMs,H as replayUnder,rt as resetTimer,nt as resumeTimer,et as startTimer,qt as sweepUnder,vn as t,st as tickTimer,_n as timerOps,Re as toReplayFrames,le as toRulesMap,Fn as virtualClock};//# sourceMappingURL=index.js.map
4
+ 3. Move the fact under a wrapping namespace (t.object({ inner: ... }))`)}function mn(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let s=i?.abortOn;if(s){for(let o of s)if(k.has(o)||o.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': abortOn key '${o}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function hn(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let s=i?.bind;if(s){for(let o of s)if(k.has(o)||o.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': bind key '${o}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function $n(e,t){dn(e),t.schema?t.schema.facts||(Object.values(t.schema).some(r=>r!=null&&typeof r=="object"&&"_typeName"in r)&&console.warn(`[Directive] Module "${e}" schema appears to contain fact declarations directly. Did you mean \`schema: { facts: { ... } }\` instead of \`schema: { ... }\`?`),console.warn("[Directive] Module schema.facts is required")):console.warn("[Directive] Module schema is required"),Le(new Set(Object.keys(t.derive??{})),new Set(Object.keys(t.schema?.derivations??{})),"Derivation","schema.derivations","has no matching implementation in derive"),Le(new Set(Object.keys(t.events??{})),new Set(Object.keys(t.schema?.events??{})),"Event","schema.events","has no matching handler in events"),t.history?.snapshotEvents&&pn(t.history.snapshotEvents,t.schema?.events??{}),t.resolvers&&t.schema?.requirements&&gn(t.resolvers,t.schema.requirements);}function qe(e,t){yn(e,t),mn(e,t),hn(e,t),a&&$n(e,t);let n="crossModuleDeps"in t?t.crossModuleDeps:void 0;return {id:e,schema:t.schema,init:t.init,derive:t.derive??{},events:t.events??{},effects:t.effects,sources:t.sources,constraints:t.constraints,resolvers:t.resolvers,hooks:t.hooks,meta:t.meta,history:t.history,crossModuleDeps:n}}function wn(e){return t=>qe(t,e)}function ye(){let e={pending:new Map,inflight:new Map,failed:new Map,errors:new Map,listeners:new Set};function t(){for(let a of e.listeners)a();}function n(a,c){let l=a.get(c);return l||(l=new Set,a.set(c,l)),l}function r(a){let c=e.pending.get(a)??new Set,l=e.inflight.get(a)??new Set,f=e.failed.get(a)??new Set,h=e.errors.get(a)??null;return {pending:c.size,inflight:l.size,failed:f.size,isLoading:c.size>0||l.size>0,hasError:f.size>0,lastError:h}}function i(){let a=new Set([...e.pending.keys(),...e.inflight.keys(),...e.failed.keys()]),c=new Map;for(let l of a)c.set(l,r(l));return c}function s(a){return e.listeners.add(a),()=>e.listeners.delete(a)}function o(){e.pending.clear(),e.inflight.clear(),e.failed.clear(),e.errors.clear(),t();}return {plugin:{name:"requirement-status",onRequirementCreated(a){let c=a.requirement.type;n(e.pending,c).add(a.id),e.failed.get(c)?.delete(a.id),t();},onResolverStart(a,c){let l=c.requirement.type;e.pending.get(l)?.delete(c.id),n(e.inflight,l).add(c.id),t();},onResolverComplete(a,c){let l=c.requirement.type;e.inflight.get(l)?.delete(c.id),e.pending.get(l)?.delete(c.id),t();},onResolverError(a,c,l){let f=c.requirement.type;e.inflight.get(f)?.delete(c.id),n(e.failed,f).add(c.id),e.errors.set(f,l instanceof Error?l:new Error(String(l))),t();},onResolverCancel(a,c){let l=c.requirement.type;e.pending.get(l)?.delete(c.id),e.inflight.get(l)?.delete(c.id),t();},onRequirementMet(a){let c=a.requirement.type;e.pending.get(c)?.delete(a.id),e.inflight.get(c)?.delete(a.id),t();}},getStatus:r,getAllStatus:i,subscribe:s,reset:o}}function bn(e){return t=>e.getStatus(t)}function Tn(e){let t=ye(),r=[...e.plugins??[],t.plugin];return {system:a$2({module:e.module,plugins:r,trace:e.trace,errorBoundary:e.errorBoundary,tickMs:e.tickMs,zeroConfig:e.zeroConfig,initialFacts:e.initialFacts}),statusPlugin:t}}function We(){return {now:()=>Date.now(),setTimeout:(e,t)=>{let n=globalThis.setTimeout(e,t);return ()=>globalThis.clearTimeout(n)}}}function Sn(e=0){let t=e,n=0,r=[];return {now:()=>t,setTimeout:(i,s)=>{let o={id:n++,deadlineMs:t+s,cb:i,canceled:false};return r.push(o),()=>{o.canceled=true;}},advanceBy:i=>{let s=t+i;for(;;){let o=r.filter(a=>!a.canceled&&a.deadlineMs<=s).sort((a,c)=>a.deadlineMs!==c.deadlineMs?a.deadlineMs-c.deadlineMs:a.id-c.id);if(o.length===0)break;let u=o[0];t=Math.max(t,u.deadlineMs),u.canceled=true,u.cb();}t=Math.max(t,s);}}}function Mn(){return We()}function me(){return {startedAtMs:null,pausedDurationMs:0,pausedAtMs:null,status:"idle",repeats:0}}function X(e,t){return e.startedAtMs===null?0:e.status==="paused"&&e.pausedAtMs!==null?Math.max(0,e.pausedAtMs-e.startedAtMs-e.pausedDurationMs):Math.max(0,t-e.startedAtMs-e.pausedDurationMs)}function Ue(e,t,n){return Math.max(0,n-X(e,t))}function Be(e,t){return e.status==="running"||e.status==="paused"?e:{...e,startedAtMs:t,pausedDurationMs:0,pausedAtMs:null,status:"running",repeats:0}}function Ke(e,t){return e.status!=="running"?e:{...e,pausedAtMs:t,status:"paused"}}function ze(e,t){if(e.status!=="paused"||e.pausedAtMs===null)return e;let n=Math.max(0,t-e.pausedAtMs);return {...e,pausedDurationMs:e.pausedDurationMs+n,pausedAtMs:null,status:"running"}}function He(){return me()}function Qe(e){return {...e,status:"completed"}}function Je(e,t){return e.startedAtMs===null||e.status==="paused"?e:{...e,startedAtMs:e.startedAtMs+t,pausedDurationMs:0,pausedAtMs:null,repeats:e.repeats+1}}function Xe(e,t,n){if(e.status!=="running")return {kind:"no-op"};let r=X(e,t);return n.mode==="up"?{kind:"no-op"}:n.mode==="repeat"?r>=n.ms?{kind:"repeat"}:{kind:"no-op"}:r>=n.ms?{kind:"complete"}:{kind:"no-op"}}function Dn(e){return {initial:me,start:Be,pause:Ke,resume:ze,reset:He,complete:Qe,registerRepeat:t=>Je(t,e.ms),tick:(t,n)=>Xe(t,n,e),elapsedMs:X,remainingMs:(t,n)=>Ue(t,n,e.ms)}}var or={None:"none",Linear:"linear",Exponential:"exponential"};export{or as Backoff,R as MAX_REPLAY_FRAMES,re as MAX_SWEEP_POINTS,Qe as completeTimer,qe as createModule,wn as createModuleFactory,ye as createRequirementStatusPlugin,bn as createStatusHook,Tn as createSystemWithStatus,Mn as defaultClock,qt as describePredicate,X as elapsedMs,Te as framesFromHistory,ne as framesFromSnapshots,me as initialTimerState,Ke as pauseTimer,Ft as predicateHash,on as predicateToMongo,cn as predicateToPostgrest,Vt as predicateToSQL,en as predicateToWhere,Nt as predict,We as realClock,Je as registerRepeat,Ue as remainingMs,U as replayUnder,He as resetTimer,ze as resumeTimer,Be as startTimer,jt as sweepUnder,fn as t,Xe as tickTimer,Dn as timerOps,be as toReplayFrames,Sn as virtualClock};//# sourceMappingURL=index.js.map
5
5
  //# sourceMappingURL=index.js.map