@directive-run/core 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -403,6 +403,129 @@ declare function framesFromSnapshots(snapshots: unknown): ReplayFrame[];
403
403
  */
404
404
  declare function replayUnder<F = Record<string, unknown>>(options: ReplayUnderOptions<F>): PredicateBacktestReport;
405
405
 
406
+ /**
407
+ * Parameter sweep over a predicate template — the grid-search counterpart
408
+ * to `replayUnder`.
409
+ *
410
+ * `replayUnder` diffs ONE proposed predicate against the original.
411
+ * `sweepUnder` takes a **template** with one or more `{ $hole: "name" }`
412
+ * markers and a set of candidate values, then replays the history once
413
+ * per (cartesian-product) combination. The result is a response curve
414
+ * over the parameter space plus the argmax under a user-supplied
415
+ * objective — turning rule-tuning from guess-and-check into a one-call
416
+ * optimization against recorded traffic.
417
+ *
418
+ * Pure module — imports only the predicate runtime and replay engine.
419
+ * No engine / store / tracking dependency.
420
+ */
421
+
422
+ /** A placeholder inside a predicate template — substituted from `sweep` values. */
423
+ interface SweepHole {
424
+ readonly $hole: string;
425
+ }
426
+ interface SweepUnderOptions<F = Record<string, unknown>> {
427
+ /** Recorded fact-state frames, in chronological order. */
428
+ frames: readonly ReplayFrame<F>[];
429
+ /** The constraint's current `when` predicate (baseline). */
430
+ original: FactPredicate<F>;
431
+ /**
432
+ * Predicate template containing one or more `{ $hole: "name" }` markers.
433
+ * Each marker is substituted by the corresponding value from `sweep` on
434
+ * every point in the curve.
435
+ *
436
+ * @example
437
+ * ```ts
438
+ * { cartTotal: { $gte: { $hole: "threshold" } } }
439
+ * ```
440
+ */
441
+ template: unknown;
442
+ /**
443
+ * Map of hole name → candidate values. Multiple holes produce the
444
+ * cartesian product (grid search).
445
+ *
446
+ * @example
447
+ * ```ts
448
+ * { threshold: [25, 50, 100, 200] }
449
+ * { riskScore: [0.5, 0.7, 0.9], minAge: [13, 18, 21] } // 3*3 = 9 points
450
+ * ```
451
+ */
452
+ sweep: Readonly<Record<string, readonly unknown[]>>;
453
+ /**
454
+ * Score function for ranking. Higher is better. Default:
455
+ * `(report) => report.proposed.matched` (maximize matched frames).
456
+ */
457
+ objective?: (report: PredicateBacktestReport) => number;
458
+ /** Optional fact key to additionally report distinct-entity counts. */
459
+ entityKey?: string;
460
+ /**
461
+ * Diff frames sampled per replay (default 0 — count-only for speed).
462
+ * Set higher to inspect specific frames in the report.
463
+ */
464
+ maxSamples?: number;
465
+ }
466
+ /** One point on the sweep curve — one candidate value tuple. */
467
+ interface SweepPoint {
468
+ /** Hole name → value used at this point. */
469
+ values: Readonly<Record<string, unknown>>;
470
+ /** Full backtest report against this candidate. */
471
+ report: PredicateBacktestReport;
472
+ /** Computed objective score (higher is better). */
473
+ score: number;
474
+ }
475
+ interface SweepReport {
476
+ /** All points, in sweep order (cartesian-product traversal of sweep keys). */
477
+ points: readonly SweepPoint[];
478
+ /** Index of the highest-scoring point in `points`. */
479
+ bestIndex: number;
480
+ /** Convenience accessor: `points[bestIndex]`. */
481
+ best: SweepPoint;
482
+ /** The original predicate replayed against itself — score baseline for comparison. */
483
+ baseline: SweepPoint;
484
+ }
485
+ /** Hard cap on points evaluated in a single sweep — protects against runaway grids. */
486
+ declare const MAX_SWEEP_POINTS = 10000;
487
+ /**
488
+ * Sweep a predicate template's hole(s) across candidate values and replay
489
+ * the recorded history through each one. Returns the full response curve
490
+ * plus the argmax under a user-supplied objective.
491
+ *
492
+ * The mechanism is a tight loop over `replayUnder`: walk the cartesian
493
+ * product of sweep values, substitute each combination into the template,
494
+ * and run a backtest. Same caveats as `replayUnder` apply (no cascade
495
+ * modeling, survivorship bias) — see {@link replayUnder} docs.
496
+ *
497
+ * @example
498
+ * ```ts
499
+ * const report = sweepUnder({
500
+ * frames: recordedSessions,
501
+ * original: { cartTotal: { $gte: 100 } },
502
+ * template: { cartTotal: { $gte: { $hole: "threshold" } } },
503
+ * sweep: { threshold: [25, 50, 100, 200] },
504
+ * });
505
+ *
506
+ * report.best.values; // { threshold: 25 } (assuming higher matched is better)
507
+ * report.best.report.proposed.matched; // 9210
508
+ * report.baseline.score; // 4217 — the original spec's matched count
509
+ * report.points.length; // 4
510
+ * ```
511
+ *
512
+ * Multi-hole sweeps grid-search:
513
+ *
514
+ * ```ts
515
+ * sweepUnder({
516
+ * frames,
517
+ * original,
518
+ * template: {
519
+ * risk: { $gte: { $hole: "minRisk" } },
520
+ * age: { $gte: { $hole: "minAge" } },
521
+ * },
522
+ * sweep: { minRisk: [0.5, 0.7, 0.9], minAge: [13, 18, 21] },
523
+ * });
524
+ * // → 9 points (3 × 3)
525
+ * ```
526
+ */
527
+ declare function sweepUnder<F = Record<string, unknown>>(options: SweepUnderOptions<F>): SweepReport;
528
+
406
529
  /** Brand symbol for branded types */
407
530
  declare const Brand: unique symbol;
408
531
  /** Branded type - adds a unique brand to a base type */
@@ -1663,4 +1786,4 @@ declare const Backoff: {
1663
1786
  readonly Exponential: "exponential";
1664
1787
  };
1665
1788
 
1666
- export { Backoff, type Branded, type ChainableSchemaType, ClauseResult, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, ErrorBoundaryConfig, type ExtendedSchemaType, FactPredicate, FactTemplate, Facts, MAX_REPLAY_FRAMES, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, type PredicateBacktestReport, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, SchemaType, type SignalClock, SingleModuleSystem, type TimerFactOpts, type TimerFactState, TraceOption, applyPatch, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, elapsedMs, evaluateKeySelector, evaluatePredicate, evaluatePredicateExplained, evaluateTemplate, extractDeps, extractTemplateKeys, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, t, tickTimer, timerOps, toReplayFrames, validatePredicate, virtualClock };
1789
+ export { Backoff, type Branded, type ChainableSchemaType, ClauseResult, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, ErrorBoundaryConfig, type ExtendedSchemaType, FactPredicate, FactTemplate, Facts, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, type PredicateBacktestReport, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, SchemaType, type SignalClock, SingleModuleSystem, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, applyPatch, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, elapsedMs, evaluateKeySelector, evaluatePredicate, evaluatePredicateExplained, evaluateTemplate, extractDeps, extractTemplateKeys, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, validatePredicate, virtualClock };
package/dist/index.d.ts CHANGED
@@ -403,6 +403,129 @@ declare function framesFromSnapshots(snapshots: unknown): ReplayFrame[];
403
403
  */
404
404
  declare function replayUnder<F = Record<string, unknown>>(options: ReplayUnderOptions<F>): PredicateBacktestReport;
405
405
 
406
+ /**
407
+ * Parameter sweep over a predicate template — the grid-search counterpart
408
+ * to `replayUnder`.
409
+ *
410
+ * `replayUnder` diffs ONE proposed predicate against the original.
411
+ * `sweepUnder` takes a **template** with one or more `{ $hole: "name" }`
412
+ * markers and a set of candidate values, then replays the history once
413
+ * per (cartesian-product) combination. The result is a response curve
414
+ * over the parameter space plus the argmax under a user-supplied
415
+ * objective — turning rule-tuning from guess-and-check into a one-call
416
+ * optimization against recorded traffic.
417
+ *
418
+ * Pure module — imports only the predicate runtime and replay engine.
419
+ * No engine / store / tracking dependency.
420
+ */
421
+
422
+ /** A placeholder inside a predicate template — substituted from `sweep` values. */
423
+ interface SweepHole {
424
+ readonly $hole: string;
425
+ }
426
+ interface SweepUnderOptions<F = Record<string, unknown>> {
427
+ /** Recorded fact-state frames, in chronological order. */
428
+ frames: readonly ReplayFrame<F>[];
429
+ /** The constraint's current `when` predicate (baseline). */
430
+ original: FactPredicate<F>;
431
+ /**
432
+ * Predicate template containing one or more `{ $hole: "name" }` markers.
433
+ * Each marker is substituted by the corresponding value from `sweep` on
434
+ * every point in the curve.
435
+ *
436
+ * @example
437
+ * ```ts
438
+ * { cartTotal: { $gte: { $hole: "threshold" } } }
439
+ * ```
440
+ */
441
+ template: unknown;
442
+ /**
443
+ * Map of hole name → candidate values. Multiple holes produce the
444
+ * cartesian product (grid search).
445
+ *
446
+ * @example
447
+ * ```ts
448
+ * { threshold: [25, 50, 100, 200] }
449
+ * { riskScore: [0.5, 0.7, 0.9], minAge: [13, 18, 21] } // 3*3 = 9 points
450
+ * ```
451
+ */
452
+ sweep: Readonly<Record<string, readonly unknown[]>>;
453
+ /**
454
+ * Score function for ranking. Higher is better. Default:
455
+ * `(report) => report.proposed.matched` (maximize matched frames).
456
+ */
457
+ objective?: (report: PredicateBacktestReport) => number;
458
+ /** Optional fact key to additionally report distinct-entity counts. */
459
+ entityKey?: string;
460
+ /**
461
+ * Diff frames sampled per replay (default 0 — count-only for speed).
462
+ * Set higher to inspect specific frames in the report.
463
+ */
464
+ maxSamples?: number;
465
+ }
466
+ /** One point on the sweep curve — one candidate value tuple. */
467
+ interface SweepPoint {
468
+ /** Hole name → value used at this point. */
469
+ values: Readonly<Record<string, unknown>>;
470
+ /** Full backtest report against this candidate. */
471
+ report: PredicateBacktestReport;
472
+ /** Computed objective score (higher is better). */
473
+ score: number;
474
+ }
475
+ interface SweepReport {
476
+ /** All points, in sweep order (cartesian-product traversal of sweep keys). */
477
+ points: readonly SweepPoint[];
478
+ /** Index of the highest-scoring point in `points`. */
479
+ bestIndex: number;
480
+ /** Convenience accessor: `points[bestIndex]`. */
481
+ best: SweepPoint;
482
+ /** The original predicate replayed against itself — score baseline for comparison. */
483
+ baseline: SweepPoint;
484
+ }
485
+ /** Hard cap on points evaluated in a single sweep — protects against runaway grids. */
486
+ declare const MAX_SWEEP_POINTS = 10000;
487
+ /**
488
+ * Sweep a predicate template's hole(s) across candidate values and replay
489
+ * the recorded history through each one. Returns the full response curve
490
+ * plus the argmax under a user-supplied objective.
491
+ *
492
+ * The mechanism is a tight loop over `replayUnder`: walk the cartesian
493
+ * product of sweep values, substitute each combination into the template,
494
+ * and run a backtest. Same caveats as `replayUnder` apply (no cascade
495
+ * modeling, survivorship bias) — see {@link replayUnder} docs.
496
+ *
497
+ * @example
498
+ * ```ts
499
+ * const report = sweepUnder({
500
+ * frames: recordedSessions,
501
+ * original: { cartTotal: { $gte: 100 } },
502
+ * template: { cartTotal: { $gte: { $hole: "threshold" } } },
503
+ * sweep: { threshold: [25, 50, 100, 200] },
504
+ * });
505
+ *
506
+ * report.best.values; // { threshold: 25 } (assuming higher matched is better)
507
+ * report.best.report.proposed.matched; // 9210
508
+ * report.baseline.score; // 4217 — the original spec's matched count
509
+ * report.points.length; // 4
510
+ * ```
511
+ *
512
+ * Multi-hole sweeps grid-search:
513
+ *
514
+ * ```ts
515
+ * sweepUnder({
516
+ * frames,
517
+ * original,
518
+ * template: {
519
+ * risk: { $gte: { $hole: "minRisk" } },
520
+ * age: { $gte: { $hole: "minAge" } },
521
+ * },
522
+ * sweep: { minRisk: [0.5, 0.7, 0.9], minAge: [13, 18, 21] },
523
+ * });
524
+ * // → 9 points (3 × 3)
525
+ * ```
526
+ */
527
+ declare function sweepUnder<F = Record<string, unknown>>(options: SweepUnderOptions<F>): SweepReport;
528
+
406
529
  /** Brand symbol for branded types */
407
530
  declare const Brand: unique symbol;
408
531
  /** Branded type - adds a unique brand to a base type */
@@ -1663,4 +1786,4 @@ declare const Backoff: {
1663
1786
  readonly Exponential: "exponential";
1664
1787
  };
1665
1788
 
1666
- export { Backoff, type Branded, type ChainableSchemaType, ClauseResult, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, ErrorBoundaryConfig, type ExtendedSchemaType, FactPredicate, FactTemplate, Facts, MAX_REPLAY_FRAMES, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, type PredicateBacktestReport, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, SchemaType, type SignalClock, SingleModuleSystem, type TimerFactOpts, type TimerFactState, TraceOption, applyPatch, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, elapsedMs, evaluateKeySelector, evaluatePredicate, evaluatePredicateExplained, evaluateTemplate, extractDeps, extractTemplateKeys, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, t, tickTimer, timerOps, toReplayFrames, validatePredicate, virtualClock };
1789
+ export { Backoff, type Branded, type ChainableSchemaType, ClauseResult, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, ErrorBoundaryConfig, type ExtendedSchemaType, FactPredicate, FactTemplate, Facts, MAX_REPLAY_FRAMES, MAX_SWEEP_POINTS, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, type PredicateBacktestReport, type ReplayDiffSample, type ReplayFrame, type ReplayUnderOptions, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, SchemaType, type SignalClock, SingleModuleSystem, type SweepHole, type SweepPoint, type SweepReport, type SweepUnderOptions, type TimerFactOpts, type TimerFactState, TraceOption, applyPatch, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, elapsedMs, evaluateKeySelector, evaluatePredicate, evaluatePredicateExplained, evaluateTemplate, extractDeps, extractTemplateKeys, forType, framesFromHistory, framesFromSnapshots, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, realClock, registerRepeat, remainingMs, replayUnder, req, resetTimer, resumeTimer, startTimer, sweepUnder, t, tickTimer, timerOps, toReplayFrames, validatePredicate, virtualClock };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import {a as a$1}from'./chunk-2PLP22ZU.js';export{a as createSystem}from'./chunk-2PLP22ZU.js';import {g,h,f as f$1,c as c$1,d,a as a$2,b}from'./chunk-JFUK5NIO.js';export{p as DirectiveError,C as RequirementSet,n as applyPatch,m as evaluateKeySelector,g as evaluatePredicate,h as evaluatePredicateExplained,k as evaluateTemplate,j as extractDeps,l as extractTemplateKeys,B as forType,y as generateRequirementId,v as isNamespacedSystem,c as isPredicate,A as isRequirementType,u as isSingleModuleSystem,e as isTemplate,i as memoizePredicate,z as req,s as typedConstraint,t as typedResolver,f as validatePredicate}from'./chunk-JFUK5NIO.js';import {a,l}from'./chunk-TZHC4E6S.js';export{j as diffSnapshots,k as isSignedSnapshot,h as isSnapshotExpired,f as shallowEqual,l as signSnapshot,i as validateSnapshot,m as verifySnapshotSignature}from'./chunk-T6IJUWYR.js';var f=1e6;function I(e,t){try{f$1(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(!c$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(d(e,{operator(r,i){n===void 0&&i.startsWith("$")&&!a$2.has(i)&&(n=i);},strayOperatorKey(r){n===void 0&&!a$2.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$2].join(", ")}`)}function N(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return W(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>f)throw new Error(`[Directive] toReplayFrames: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${f}) \u2014 split or down-sample the history`);return t.map((n,r)=>{if(n&&typeof n=="object"&&"facts"in n){let i=n,o={id:i.id??`#${r}`,facts:i.facts??{}};return typeof i.timestamp=="number"&&(o.timestamp=i.timestamp),o}return {id:`#${r}`,facts:n??{}}})}function W(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return O(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 O(n.snapshots)}function O(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>f)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${f}) \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 N(e)}function we(e){let{frames:t,original:n,proposed:r,entityKey:i}=e,o=e.maxSamples??20,a=o>0?o:0;if(t.length>f)throw new Error(`[Directive] replayUnder: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${f}) \u2014 split or down-sample the history`);I(n,"original"),I(r,"proposed");let p=0,s=0,u=0,l=0,d=0,m=[],y=[],h=i?new Set:void 0,x=i?new Set:void 0,g$1;for(let k of t){let T=k.facts,R=g(n,T,g$1),E=g(r,T,g$1);R&&(p++,h?.add(T[i])),E&&(s++,x?.add(T[i])),R===E?d++:!R&&E?(u++,m.length<a&&m.push(U(k,n,r,g$1))):(l++,y.length<a&&y.push(U(k,n,r,g$1))),g$1=T;}let C={framesEvaluated:t.length,original:{matched:p},proposed:{matched:s},delta:s-p,newMatchCount:u,lostMatchCount:l,unchanged:d,newMatches:m,lostMatches:y};return h&&x&&(C.original.matchedEntities=h.size,C.proposed.matchedEntities=x.size),C}function U(e,t,n,r){let i=e.facts,o={frameId:e.id,facts:i,originalExplain:h(t,i,r),proposedExplain:h(n,i,r)};return e.timestamp!==void 0&&(o.timestamp=e.timestamp),o}function D(e=[],t,n,r,i,o,a){return {_type:void 0,_validators:e,_typeName:t,_default:n,_transform:r,_description:i,_refinements:o,_meta:a,validate(p){return D([...e,p],t,n,r,i,o,a)}}}function c(e,t,n,r,i,o,a){return {...D(e,t,n,r,i,o,a),default(s){return c(e,t,s,r,i,o,a)},transform(s){return c([],t,void 0,l=>{let d=r?r(l):l;return s(d)},i,void 0,a)},brand(){return c(e,`Branded<${t}>`,n,r,i,o,a)},describe(s){return c(e,t,n,r,s,o,a)},refine(s,u){let l=[...o??[],{predicate:s,message:u}];return c([...e,s],t,n,r,i,l,a)},nullable(){return c([s=>s===null||e.every(u=>u(s))],`${t} | null`,n,r,i,void 0,a)},optional(){return c([s=>s===void 0||e.every(u=>u(s))],`${t} | undefined`,n,r,i,void 0,a)},meta(s){return c(e,t,n,r,i,o,s)}}}var xe=((...e)=>{if(e.length===0)return c([],"union");let t=e.map(n=>n._typeName??"unknown");return c([n=>e.some(r=>r._validators.every(i=>i(n)))],t.join(" | "))}),Ce={string(){let e=(t,n,r,i,o,a)=>({...c(t,"string",n,r,i,o,a),minLength(s){return e([...t,u=>u.length>=s],n,r,i,o,a)},maxLength(s){return e([...t,u=>u.length<=s],n,r,i,o,a)},pattern(s){return e([...t,u=>s.test(u)],n,r,i,o,a)},default(s){return e(t,s,r,i,o,a)},describe(s){return e(t,n,r,s,o,a)},refine(s,u){let l=[...o??[],{predicate:s,message:u}];return e([...t,s],n,r,i,l,a)},meta(s){return e(t,n,r,i,o,s)}});return e([t=>typeof t=="string"])},number(){let e=(t,n,r,i,o,a)=>({...c(t,"number",n,r,i,o,a),min(s){return e([...t,u=>u>=s],n,r,i,o,a)},max(s){return e([...t,u=>u<=s],n,r,i,o,a)},default(s){return e(t,s,r,i,o,a)},describe(s){return e(t,n,r,s,o,a)},refine(s,u){let l=[...o??[],{predicate:s,message:u}];return e([...t,s],n,r,i,l,a)},meta(s){return e(t,n,r,i,o,s)}});return e([t=>typeof t=="number"])},boolean(){return c([e=>typeof e=="boolean"],"boolean")},array(){let e=(t,n,r,i,o,a)=>{let p=c(t,"array",r,void 0,i,void 0,a),s=o??{value:-1};return {...p,get _lastFailedIndex(){return s.value},set _lastFailedIndex(l){s.value=l;},of(l){let d={value:-1};return e([...t,m=>{for(let y=0;y<m.length;y++)if(!l._validators.every(h=>h(m[y])))return d.value=y,false;return true}],l,r,i,d,a)},nonEmpty(){return e([...t,l=>l.length>0],n,r,i,s,a)},maxLength(l){return e([...t,d=>d.length<=l],n,r,i,s,a)},minLength(l){return e([...t,d=>d.length>=l],n,r,i,s,a)},default(l){return e(t,n,l,i,s,a)},describe(l){return e(t,n,r,l,s,a)},meta(l){return e(t,n,r,i,s,l)}}};return e([t=>Array.isArray(t)])},object(){let e=(t,n,r,i)=>({...c(t,"object",n,void 0,r,void 0,i),shape(a){return e([...t,p=>{for(let[s,u]of Object.entries(a)){let l=p[s],d=u;if(d&&!d._validators.every(m=>m(l)))return false}return true}],n,r,i)},nonNull(){return e([...t,a=>a!=null],n,r,i)},hasKeys(...a){return e([...t,p=>a.every(s=>s in p)],n,r,i)},default(a){return e(t,a,r,i)},describe(a){return e(t,n,a,i)},meta(a){return e(t,n,r,a)}});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 c([n=>typeof n=="string"&&t.has(n)],`enum(${e.join("|")})`)},literal(e){return c([t=>t===e],`literal(${String(e)})`)},nullable(e){let t=e._typeName??"unknown";return D([n=>n===null?true:e._validators.every(r=>r(n))],`${t} | null`)},optional(e){let t=e._typeName??"unknown";return D([n=>n===void 0?true:e._validators.every(r=>r(n))],`${t} | undefined`)},union:xe,record(e){let t=e._typeName??"unknown";return c([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 c([n=>!Array.isArray(n)||n.length!==e.length?false:e.every((r,i)=>r._validators.every(o=>o(n[i])))],`[${t.join(", ")}]`)},date(){return c([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 c([t=>typeof t=="string"&&e.test(t)],"uuid")},email(){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return c([t=>typeof t=="string"&&e.test(t)],"email")},url(){return c([e=>{if(typeof e!="string")return false;try{return new URL(e),!0}catch{return false}}],"url")},bigint(){return c([e=>typeof e=="bigint"],"bigint")},any(){return c([],"any")},unknown(){return c([],"unknown")}};function ke(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 K(e,t,n,r,i){for(let o of e)t.has(o)||console.warn(`[Directive] ${n} "${o}" not declared in ${r}`);for(let o of t)e.has(o)||console.warn(`[Directive] ${r}["${o}"] ${i}`);}function Re(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 Ee(e,t){let n=new Set(Object.keys(t));for(let[r,i]of Object.entries(e)){let o=i;typeof o.requirement=="string"&&!n.has(o.requirement)&&console.warn(`[Directive] Resolver "${r}" references unknown requirement type "${o.requirement}". Available types: ${[...n].join(", ")||"(none)"}`);}}function Ae(e,t){let n=t.schema?.facts??{},r=Object.keys(n);if(r.length===0)return;let i=new Set(["self","prev","current"]),o="crossModuleDeps"in t&&t.crossModuleDeps?Object.keys(t.crossModuleDeps):[];for(let a of o)i.add(a);for(let a of r)if(i.has(a))throw new Error(`[Directive] module '${e}': fact key '${a}' conflicts with a reserved namespace pivot or evaluation alias (self / prev / current / a crossModuleDep namespace). Three fixes:
2
- 1. Rename the fact (e.g. ${a}_)
3
- 2. Remove '${a}' from this module's crossModuleDeps if it's not actually needed
4
- 3. Move the fact under a wrapping namespace (t.object({ inner: ... }))`)}function Fe(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let o=i?.owns;if(o){for(let a of o)if(l.has(a)||a.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': owns key '${a}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function je(e,t){ke(e),t.schema?t.schema.facts||console.warn("[Directive] Module schema.facts is required"):console.warn("[Directive] Module schema is required"),K(new Set(Object.keys(t.derive??{})),new Set(Object.keys(t.schema?.derivations??{})),"Derivation","schema.derivations","has no matching implementation in derive"),K(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&&Re(t.history.snapshotEvents,t.schema?.events??{}),t.resolvers&&t.schema?.requirements&&Ee(t.resolvers,t.schema.requirements);}function L(e,t){Ae(e,t),Fe(e,t),a&&je(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,constraints:t.constraints,resolvers:t.resolvers,hooks:t.hooks,meta:t.meta,history:t.history,crossModuleDeps:n}}function Oe(e){return t=>L(t,e)}function P(){let e={pending:new Map,inflight:new Map,failed:new Map,errors:new Map,listeners:new Set};function t(){for(let s of e.listeners)s();}function n(s,u){let l=s.get(u);return l||(l=new Set,s.set(u,l)),l}function r(s){let u=e.pending.get(s)??new Set,l=e.inflight.get(s)??new Set,d=e.failed.get(s)??new Set,m=e.errors.get(s)??null;return {pending:u.size,inflight:l.size,failed:d.size,isLoading:u.size>0||l.size>0,hasError:d.size>0,lastError:m}}function i(){let s=new Set([...e.pending.keys(),...e.inflight.keys(),...e.failed.keys()]),u=new Map;for(let l of s)u.set(l,r(l));return u}function o(s){return e.listeners.add(s),()=>e.listeners.delete(s)}function a(){e.pending.clear(),e.inflight.clear(),e.failed.clear(),e.errors.clear(),t();}return {plugin:{name:"requirement-status",onRequirementCreated(s){let u=s.requirement.type;n(e.pending,u).add(s.id),e.failed.get(u)?.delete(s.id),t();},onResolverStart(s,u){let l=u.requirement.type;e.pending.get(l)?.delete(u.id),n(e.inflight,l).add(u.id),t();},onResolverComplete(s,u){let l=u.requirement.type;e.inflight.get(l)?.delete(u.id),e.pending.get(l)?.delete(u.id),t();},onResolverError(s,u,l){let d=u.requirement.type;e.inflight.get(d)?.delete(u.id),n(e.failed,d).add(u.id),e.errors.set(d,l instanceof Error?l:new Error(String(l))),t();},onResolverCancel(s,u){let l=u.requirement.type;e.pending.get(l)?.delete(u.id),e.inflight.get(l)?.delete(u.id),t();},onRequirementMet(s){let u=s.requirement.type;e.pending.get(u)?.delete(s.id),e.inflight.get(u)?.delete(s.id),t();}},getStatus:r,getAllStatus:i,subscribe:o,reset:a}}function Pe(e){return t=>e.getStatus(t)}function _e(e){let t=P(),r=[...e.plugins??[],t.plugin];return {system:a$1({module:e.module,plugins:r,trace:e.trace,errorBoundary:e.errorBoundary,tickMs:e.tickMs,zeroConfig:e.zeroConfig,initialFacts:e.initialFacts}),statusPlugin:t}}function z(){return {now:()=>Date.now(),setTimeout:(e,t)=>{let n=globalThis.setTimeout(e,t);return ()=>globalThis.clearTimeout(n)}}}function $e(e=0){let t=e,n=0,r=[];return {now:()=>t,setTimeout:(i,o)=>{let a={id:n++,deadlineMs:t+o,cb:i,canceled:false};return r.push(a),()=>{a.canceled=true;}},advanceBy:i=>{let o=t+i;for(;;){let a=r.filter(s=>!s.canceled&&s.deadlineMs<=o).sort((s,u)=>s.deadlineMs!==u.deadlineMs?s.deadlineMs-u.deadlineMs:s.id-u.id);if(a.length===0)break;let p=a[0];t=Math.max(t,p.deadlineMs),p.canceled=true,p.cb();}t=Math.max(t,o);}}}function Be(){return z()}function _(){return {startedAtMs:null,pausedDurationMs:0,pausedAtMs:null,status:"idle",repeats:0}}function w(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 H(e,t,n){return Math.max(0,n-w(e,t))}function J(e,t){return e.status==="running"||e.status==="paused"?e:{...e,startedAtMs:t,pausedDurationMs:0,pausedAtMs:null,status:"running",repeats:0}}function X(e,t){return e.status!=="running"?e:{...e,pausedAtMs:t,status:"paused"}}function Y(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 G(){return _()}function Q(e){return {...e,status:"completed"}}function Z(e,t){return e.startedAtMs===null||e.status==="paused"?e:{...e,startedAtMs:e.startedAtMs+t,pausedDurationMs:0,pausedAtMs:null,repeats:e.repeats+1}}function V(e,t,n){if(e.status!=="running")return {kind:"no-op"};let r=w(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 qe(e){return {initial:_,start:J,pause:X,resume:Y,reset:G,complete:Q,registerRepeat:t=>Z(t,e.ms),tick:(t,n)=>V(t,n,e),elapsedMs:w,remainingMs:(t,n)=>H(t,n,e.ms)}}var Ve={None:"none",Linear:"linear",Exponential:"exponential"};export{Ve as Backoff,f as MAX_REPLAY_FRAMES,Q as completeTimer,L as createModule,Oe as createModuleFactory,P as createRequirementStatusPlugin,Pe as createStatusHook,_e as createSystemWithStatus,Be as defaultClock,w as elapsedMs,W as framesFromHistory,O as framesFromSnapshots,_ as initialTimerState,X as pauseTimer,z as realClock,Z as registerRepeat,H as remainingMs,we as replayUnder,G as resetTimer,Y as resumeTimer,J as startTimer,Ce as t,V as tickTimer,qe as timerOps,N as toReplayFrames,$e as virtualClock};//# sourceMappingURL=index.js.map
1
+ import {a as a$1}from'./chunk-FCOZCTLY.js';export{a as createSystem}from'./chunk-FCOZCTLY.js';import {h,i,g,d,e,a as a$2,b as b$1,c}from'./chunk-ZE2RY5KP.js';export{q as DirectiveError,D as RequirementSet,o as applyPatch,n as evaluateKeySelector,h as evaluatePredicate,i as evaluatePredicateExplained,l as evaluateTemplate,k as extractDeps,m as extractTemplateKeys,C as forType,z as generateRequirementId,w as isNamespacedSystem,d as isPredicate,B as isRequirementType,v as isSingleModuleSystem,f as isTemplate,j as memoizePredicate,A as req,t as typedConstraint,u as typedResolver,g as validatePredicate}from'./chunk-ZE2RY5KP.js';import {a,l}from'./chunk-TZHC4E6S.js';export{j as diffSnapshots,k as isSignedSnapshot,h as isSnapshotExpired,f as shallowEqual,l as signSnapshot,i as validateSnapshot,m as verifySnapshotSignature}from'./chunk-T6IJUWYR.js';var b=1e6;function K(e$1,t){try{g(e$1);}catch(r){let i=r instanceof Error?r.message:String(r);throw new Error(`[Directive] replayUnder: the ${t} predicate is invalid \u2014 ${i}`)}if(!d(e$1)){let r=e$1===null||typeof e$1!="object"?`${typeof e$1} \u2014 ${JSON.stringify(e$1)}`:JSON.stringify(e$1).slice(0,80);throw new Error(`[Directive] replayUnder: the ${t} predicate is not a valid FactPredicate (got ${r})`)}let n;if(e(e$1,{operator(r,i){n===void 0&&i.startsWith("$")&&!a$2.has(i)&&(n=i);},strayOperatorKey(r){n===void 0&&!a$2.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$2].join(", ")}`)}function z(e){if(e&&typeof e=="object"&&!Array.isArray(e)&&Array.isArray(e.snapshots))return X(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>b)throw new Error(`[Directive] toReplayFrames: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${b}) \u2014 split or down-sample the history`);return t.map((n,r)=>{if(n&&typeof n=="object"&&"facts"in n){let i=n,a={id:i.id??`#${r}`,facts:i.facts??{}};return typeof i.timestamp=="number"&&(a.timestamp=i.timestamp),a}return {id:`#${r}`,facts:n??{}}})}function X(e){let t=typeof e=="string"?JSON.parse(e):e;if(Array.isArray(t))return $(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 $(n.snapshots)}function $(e){if(!Array.isArray(e))throw new Error("[Directive] framesFromSnapshots: expected an array of fact-state snapshots");if(e.length>b)throw new Error(`[Directive] framesFromSnapshots: history has ${e.length} snapshots, exceeds the MAX_REPLAY_FRAMES limit (${b}) \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 z(e)}function C(e){let{frames:t,original:n,proposed:r,entityKey:i}=e,a=e.maxSamples??20,o=a>0?a:0;if(t.length>b)throw new Error(`[Directive] replayUnder: history has ${t.length} frames, exceeds the MAX_REPLAY_FRAMES limit (${b}) \u2014 split or down-sample the history`);K(n,"original"),K(r,"proposed");let d=0,s=0,u=0,l=0,c=0,m=[],y=[],M=i?new Set:void 0,T=i?new Set:void 0,g;for(let v of t){let f=v.facts,h$1=h(n,f,g),S=h(r,f,g);h$1&&(d++,M?.add(f[i])),S&&(s++,T?.add(f[i])),h$1===S?c++:!h$1&&S?(u++,m.length<o&&m.push(L(v,n,r,g))):(l++,y.length<o&&y.push(L(v,n,r,g))),g=f;}let w={framesEvaluated:t.length,original:{matched:d},proposed:{matched:s},delta:s-d,newMatchCount:u,lostMatchCount:l,unchanged:c,newMatches:m,lostMatches:y};return M&&T&&(w.original.matchedEntities=M.size,w.proposed.matchedEntities=T.size),w}function L(e,t,n,r){let i$1=e.facts,a={frameId:e.id,facts:i$1,originalExplain:i(t,i$1,r),proposedExplain:i(n,i$1,r)};return e.timestamp!==void 0&&(a.timestamp=e.timestamp),a}var I=1e4,Y=5e7;function Fe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$hole=="string"}function B(e,t,n=new Set,r=0){if(r>c)throw new Error(`[Directive] sweepUnder: template exceeds MAX_PREDICATE_DEPTH (${c}) \u2014 flatten the template or split the sweep`);if(Fe(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(a=>B(a,t,n,r+1));let i={};for(let[a,o]of Object.entries(e))i[a]=B(o,t,n,r+1);return i}finally{n.delete(e);}}function*J(e,t){if(e.length===0){yield {};return}let n=e[0],r=e.slice(1),i=t[n]??[];for(let a of i)for(let o of J(r,t))yield {[n]:a,...o};}function Pe(e){let t=1;for(let n of Object.values(e))t*=n.length;return t}function je(e){let{frames:t,original:n,template:r,sweep:i,objective:a=f=>f.proposed.matched,entityKey:o,maxSamples:d=0}=e,s=Object.keys(i);if(s.length===0)throw new Error("[Directive] sweepUnder: `sweep` must contain at least one hole name");let u=Pe(i);if(u>I)throw new Error(`[Directive] sweepUnder: grid has ${u} points, exceeds the MAX_SWEEP_POINTS limit (${I}) \u2014 narrow the sweep ranges or split the run`);if(u===0)throw new Error("[Directive] sweepUnder: at least one hole has zero candidate values");let l=u*t.length;if(l>Y)throw new Error(`[Directive] sweepUnder: ${u} points \xD7 ${t.length} frames = ${l} per-frame evaluations, exceeds the MAX_SWEEP_EVALUATIONS limit (${Y}) \u2014 narrow the sweep, down-sample the history, or split the run`);let c=false,m=f=>{let h;try{h=a(f);}catch(S){return c||(c=true,console.warn(`[Directive] sweepUnder: objective threw \u2014 point will not rank (${S.message})`)),Number.NEGATIVE_INFINITY}return typeof h!="number"||!Number.isFinite(h)?(c||(c=true,console.warn(`[Directive] sweepUnder: objective returned a non-finite number (${String(h)}) \u2014 point will not rank`)),Number.NEGATIVE_INFINITY):h},y=C({frames:t,original:n,proposed:n,entityKey:o,maxSamples:d}),M={values:{},report:y,score:m(y)},T=[],g=0,w=Number.NEGATIVE_INFINITY;for(let f of J(s,i)){let h=B(r,f),S=C({frames:t,original:n,proposed:h,entityKey:o,maxSamples:d}),F=m(S);F>w&&(w=F,g=T.length),T.push({values:f,report:S,score:F});}let v=T[g];return {points:T,bestIndex:g,best:v,baseline:M}}function E(e=[],t,n,r,i,a,o){return {_type:void 0,_validators:e,_typeName:t,_default:n,_transform:r,_description:i,_refinements:a,_meta:o,validate(d){return E([...e,d],t,n,r,i,a,o)}}}function p(e,t,n,r,i,a,o){return {...E(e,t,n,r,i,a,o),default(s){return p(e,t,s,r,i,a,o)},transform(s){return p([],t,void 0,l=>{let c=r?r(l):l;return s(c)},i,void 0,o)},brand(){return p(e,`Branded<${t}>`,n,r,i,a,o)},describe(s){return p(e,t,n,r,s,a,o)},refine(s,u){let l=[...a??[],{predicate:s,message:u}];return p([...e,s],t,n,r,i,l,o)},nullable(){return p([s=>s===null||e.every(u=>u(s))],`${t} | null`,n,r,i,void 0,o)},optional(){return p([s=>s===void 0||e.every(u=>u(s))],`${t} | undefined`,n,r,i,void 0,o)},meta(s){return p(e,t,n,r,i,a,s)}}}var Oe=((...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(" | "))}),_e={string(){let e=(t,n,r,i,a,o)=>({...p(t,"string",n,r,i,a,o),minLength(s){return e([...t,u=>u.length>=s],n,r,i,a,o)},maxLength(s){return e([...t,u=>u.length<=s],n,r,i,a,o)},pattern(s){return e([...t,u=>s.test(u)],n,r,i,a,o)},default(s){return e(t,s,r,i,a,o)},describe(s){return e(t,n,r,s,a,o)},refine(s,u){let l=[...a??[],{predicate:s,message:u}];return e([...t,s],n,r,i,l,o)},meta(s){return e(t,n,r,i,a,s)}});return e([t=>typeof t=="string"])},number(){let e=(t,n,r,i,a,o)=>({...p(t,"number",n,r,i,a,o),min(s){return e([...t,u=>u>=s],n,r,i,a,o)},max(s){return e([...t,u=>u<=s],n,r,i,a,o)},default(s){return e(t,s,r,i,a,o)},describe(s){return e(t,n,r,s,a,o)},refine(s,u){let l=[...a??[],{predicate:s,message:u}];return e([...t,s],n,r,i,l,o)},meta(s){return e(t,n,r,i,a,s)}});return e([t=>typeof t=="number"])},boolean(){return p([e=>typeof e=="boolean"],"boolean")},array(){let e=(t,n,r,i,a,o)=>{let d=p(t,"array",r,void 0,i,void 0,o),s=a??{value:-1};return {...d,get _lastFailedIndex(){return s.value},set _lastFailedIndex(l){s.value=l;},of(l){let c={value:-1};return e([...t,m=>{for(let y=0;y<m.length;y++)if(!l._validators.every(M=>M(m[y])))return c.value=y,false;return true}],l,r,i,c,o)},nonEmpty(){return e([...t,l=>l.length>0],n,r,i,s,o)},maxLength(l){return e([...t,c=>c.length<=l],n,r,i,s,o)},minLength(l){return e([...t,c=>c.length>=l],n,r,i,s,o)},default(l){return e(t,n,l,i,s,o)},describe(l){return e(t,n,r,l,s,o)},meta(l){return e(t,n,r,i,s,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,d=>{for(let[s,u]of Object.entries(o)){let l=d[s],c=u;if(c&&!c._validators.every(m=>m(l)))return false}return true}],n,r,i)},nonNull(){return e([...t,o=>o!=null],n,r,i)},hasKeys(...o){return e([...t,d=>o.every(s=>s in d)],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 E([n=>n===null?true:e._validators.every(r=>r(n))],`${t} | null`)},optional(e){let t=e._typeName??"unknown";return E([n=>n===void 0?true:e._validators.every(r=>r(n))],`${t} | undefined`)},union:Oe,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(a=>a(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 $e(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 G(e,t,n,r,i){for(let a of e)t.has(a)||console.warn(`[Directive] ${n} "${a}" not declared in ${r}`);for(let a of t)e.has(a)||console.warn(`[Directive] ${r}["${a}"] ${i}`);}function Ie(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 Be(e,t){let n=new Set(Object.keys(t));for(let[r,i]of Object.entries(e)){let a=i;typeof a.requirement=="string"&&!n.has(a.requirement)&&console.warn(`[Directive] Resolver "${r}" references unknown requirement type "${a.requirement}". Available types: ${[...n].join(", ")||"(none)"}`);}}function Ne(e,t){let n=t.schema?.facts??{},r=Object.keys(n);if(r.length===0)return;let i=new Set(["self","prev","current"]),a="crossModuleDeps"in t&&t.crossModuleDeps?Object.keys(t.crossModuleDeps):[];for(let o of a)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
+ 1. Rename the fact (e.g. ${o}_)
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 Ue(e,t){let n=t.constraints;if(n)for(let[r,i]of Object.entries(n)){let a=i?.owns;if(a){for(let o of a)if(l.has(o)||o.startsWith("$"))throw new Error(`[Directive] module '${e}' constraint '${r}': owns key '${o}' is reserved (BLOCKED_PROPS or $-prefixed)`)}}}function qe(e,t){$e(e),t.schema?t.schema.facts||console.warn("[Directive] Module schema.facts is required"):console.warn("[Directive] Module schema is required"),G(new Set(Object.keys(t.derive??{})),new Set(Object.keys(t.schema?.derivations??{})),"Derivation","schema.derivations","has no matching implementation in derive"),G(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&&Ie(t.history.snapshotEvents,t.schema?.events??{}),t.resolvers&&t.schema?.requirements&&Be(t.resolvers,t.schema.requirements);}function Q(e,t){Ne(e,t),Ue(e,t),a&&qe(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,constraints:t.constraints,resolvers:t.resolvers,hooks:t.hooks,meta:t.meta,history:t.history,crossModuleDeps:n}}function We(e){return t=>Q(t,e)}function N(){let e={pending:new Map,inflight:new Map,failed:new Map,errors:new Map,listeners:new Set};function t(){for(let s of e.listeners)s();}function n(s,u){let l=s.get(u);return l||(l=new Set,s.set(u,l)),l}function r(s){let u=e.pending.get(s)??new Set,l=e.inflight.get(s)??new Set,c=e.failed.get(s)??new Set,m=e.errors.get(s)??null;return {pending:u.size,inflight:l.size,failed:c.size,isLoading:u.size>0||l.size>0,hasError:c.size>0,lastError:m}}function i(){let s=new Set([...e.pending.keys(),...e.inflight.keys(),...e.failed.keys()]),u=new Map;for(let l of s)u.set(l,r(l));return u}function a(s){return e.listeners.add(s),()=>e.listeners.delete(s)}function o(){e.pending.clear(),e.inflight.clear(),e.failed.clear(),e.errors.clear(),t();}return {plugin:{name:"requirement-status",onRequirementCreated(s){let u=s.requirement.type;n(e.pending,u).add(s.id),e.failed.get(u)?.delete(s.id),t();},onResolverStart(s,u){let l=u.requirement.type;e.pending.get(l)?.delete(u.id),n(e.inflight,l).add(u.id),t();},onResolverComplete(s,u){let l=u.requirement.type;e.inflight.get(l)?.delete(u.id),e.pending.get(l)?.delete(u.id),t();},onResolverError(s,u,l){let c=u.requirement.type;e.inflight.get(c)?.delete(u.id),n(e.failed,c).add(u.id),e.errors.set(c,l instanceof Error?l:new Error(String(l))),t();},onResolverCancel(s,u){let l=u.requirement.type;e.pending.get(l)?.delete(u.id),e.inflight.get(l)?.delete(u.id),t();},onRequirementMet(s){let u=s.requirement.type;e.pending.get(u)?.delete(s.id),e.inflight.get(u)?.delete(s.id),t();}},getStatus:r,getAllStatus:i,subscribe:a,reset:o}}function He(e){return t=>e.getStatus(t)}function Ke(e){let t=N(),r=[...e.plugins??[],t.plugin];return {system:a$1({module:e.module,plugins:r,trace:e.trace,errorBoundary:e.errorBoundary,tickMs:e.tickMs,zeroConfig:e.zeroConfig,initialFacts:e.initialFacts}),statusPlugin:t}}function Z(){return {now:()=>Date.now(),setTimeout:(e,t)=>{let n=globalThis.setTimeout(e,t);return ()=>globalThis.clearTimeout(n)}}}function Le(e=0){let t=e,n=0,r=[];return {now:()=>t,setTimeout:(i,a)=>{let o={id:n++,deadlineMs:t+a,cb:i,canceled:false};return r.push(o),()=>{o.canceled=true;}},advanceBy:i=>{let a=t+i;for(;;){let o=r.filter(s=>!s.canceled&&s.deadlineMs<=a).sort((s,u)=>s.deadlineMs!==u.deadlineMs?s.deadlineMs-u.deadlineMs:s.id-u.id);if(o.length===0)break;let d=o[0];t=Math.max(t,d.deadlineMs),d.canceled=true,d.cb();}t=Math.max(t,a);}}}function ze(){return Z()}function U(){return {startedAtMs:null,pausedDurationMs:0,pausedAtMs:null,status:"idle",repeats:0}}function A(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 V(e,t,n){return Math.max(0,n-A(e,t))}function ee(e,t){return e.status==="running"||e.status==="paused"?e:{...e,startedAtMs:t,pausedDurationMs:0,pausedAtMs:null,status:"running",repeats:0}}function te(e,t){return e.status!=="running"?e:{...e,pausedAtMs:t,status:"paused"}}function ne(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 re(){return U()}function se(e){return {...e,status:"completed"}}function ie(e,t){return e.startedAtMs===null||e.status==="paused"?e:{...e,startedAtMs:e.startedAtMs+t,pausedDurationMs:0,pausedAtMs:null,repeats:e.repeats+1}}function oe(e,t,n){if(e.status!=="running")return {kind:"no-op"};let r=A(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 Xe(e){return {initial:U,start:ee,pause:te,resume:ne,reset:re,complete:se,registerRepeat:t=>ie(t,e.ms),tick:(t,n)=>oe(t,n,e),elapsedMs:A,remainingMs:(t,n)=>V(t,n,e.ms)}}var pt={None:"none",Linear:"linear",Exponential:"exponential"};export{pt as Backoff,b as MAX_REPLAY_FRAMES,I as MAX_SWEEP_POINTS,se as completeTimer,Q as createModule,We as createModuleFactory,N as createRequirementStatusPlugin,He as createStatusHook,Ke as createSystemWithStatus,ze as defaultClock,A as elapsedMs,X as framesFromHistory,$ as framesFromSnapshots,U as initialTimerState,te as pauseTimer,Z as realClock,ie as registerRepeat,V as remainingMs,C as replayUnder,re as resetTimer,ne as resumeTimer,ee as startTimer,je as sweepUnder,_e as t,oe as tickTimer,Xe as timerOps,z as toReplayFrames,Le as virtualClock};//# sourceMappingURL=index.js.map
5
5
  //# sourceMappingURL=index.js.map