@directive-run/core 1.3.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/adapter-utils.cjs +1 -1
- package/dist/adapter-utils.d.cts +1 -1
- package/dist/adapter-utils.d.ts +1 -1
- package/dist/adapter-utils.js +1 -1
- package/dist/{chunk-FK7BD7XT.js → chunk-EH2Q754B.js} +3 -3
- package/dist/chunk-EH2Q754B.js.map +1 -0
- package/dist/chunk-HAF5JCET.js +16 -0
- package/dist/chunk-HAF5JCET.js.map +1 -0
- package/dist/{chunk-4CMO5OVZ.js → chunk-M5KZXNZX.js} +2 -2
- package/dist/chunk-M5KZXNZX.js.map +1 -0
- package/dist/chunk-PGUTGWUI.cjs +3 -0
- package/dist/chunk-PGUTGWUI.cjs.map +1 -0
- package/dist/{chunk-DDUARSUH.cjs → chunk-S3CFYDIB.cjs} +3 -3
- package/dist/chunk-S3CFYDIB.cjs.map +1 -0
- package/dist/chunk-SQVKCJHE.cjs +16 -0
- package/dist/chunk-SQVKCJHE.cjs.map +1 -0
- package/dist/chunk-YCCQ73C6.js +3 -0
- package/dist/chunk-YCCQ73C6.js.map +1 -0
- package/dist/{chunk-BEJ6ICA7.cjs → chunk-ZHS3EW2Z.cjs} +2 -2
- package/dist/chunk-ZHS3EW2Z.cjs.map +1 -0
- package/dist/{helpers-CfZCxxkR.d.ts → helpers-B1MiHave.d.cts} +12 -2
- package/dist/{helpers-CCljEIsG.d.cts → helpers-h9PR2JSJ.d.ts} +12 -2
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +183 -5
- package/dist/index.d.ts +183 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internals.cjs +1 -1
- package/dist/internals.d.cts +63 -22
- package/dist/internals.d.ts +63 -22
- package/dist/internals.js +1 -1
- package/dist/plugins/index.cjs +1 -1
- package/dist/plugins/index.cjs.map +1 -1
- package/dist/plugins/index.d.cts +11 -8
- package/dist/plugins/index.d.ts +11 -8
- package/dist/plugins/index.js +1 -1
- package/dist/plugins/index.js.map +1 -1
- package/dist/{plugins-CLZ3xci0.d.ts → plugins-Bakr7js6.d.cts} +376 -17
- package/dist/{plugins-CLZ3xci0.d.cts → plugins-Bakr7js6.d.ts} +376 -17
- package/dist/system-744ZPPES.js +2 -0
- package/dist/{system-F2QGHEG7.js.map → system-744ZPPES.js.map} +1 -1
- package/dist/system-CK3SHMXZ.cjs +2 -0
- package/dist/{system-LZMEZBOA.cjs.map → system-CK3SHMXZ.cjs.map} +1 -1
- package/dist/testing.cjs +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +1 -1
- package/dist/testing.js.map +1 -1
- package/dist/worker.cjs +1 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +1 -1
- package/dist/worker.d.ts +1 -1
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-4CMO5OVZ.js.map +0 -1
- package/dist/chunk-BEJ6ICA7.cjs.map +0 -1
- package/dist/chunk-DDUARSUH.cjs.map +0 -1
- package/dist/chunk-FK7BD7XT.js.map +0 -1
- package/dist/chunk-GVVNFVEX.js +0 -3
- package/dist/chunk-GVVNFVEX.js.map +0 -1
- package/dist/chunk-JYGG4RIL.js +0 -16
- package/dist/chunk-JYGG4RIL.js.map +0 -1
- package/dist/chunk-RCCTZCZZ.cjs +0 -3
- package/dist/chunk-RCCTZCZZ.cjs.map +0 -1
- package/dist/chunk-U3DN2WML.cjs +0 -16
- package/dist/chunk-U3DN2WML.cjs.map +0 -1
- package/dist/system-F2QGHEG7.js +0 -2
- package/dist/system-LZMEZBOA.cjs +0 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,8 +1,178 @@
|
|
|
1
|
-
import { S as SchemaType, D as DefinitionMeta, M as ModuleSchema,
|
|
2
|
-
export { A as AnySystem, B as BatchConfig,
|
|
3
|
-
export { D as DerivationDefWithMeta, t as typedConstraint, a as typedResolver } from './helpers-
|
|
1
|
+
import { P as PatchSpec, C as ClauseResult, F as FactTemplate, S as SchemaType, D as DefinitionMeta, M as ModuleSchema, a as Facts, T as TypedDerivationsDef, b as TypedEventsDef, E as EffectsDef, c as TypedConstraintsDef, d as TypedResolversDef, e as ModuleHooks, f as CrossModuleDeps, g as CrossModuleDerivationsDef, h as CrossModuleEffectsDef, i as CrossModuleConstraintsDef, j as ModuleDef, k as CreateSystemOptionsSingle, l as SingleModuleSystem, m as ModulesMap, n as CreateSystemOptionsNamed, N as NamespacedSystem, o as Plugin, p as TraceOption, q as ErrorBoundaryConfig, R as RequirementWithId, r as Requirement, s as RequirementKeyFn } from './plugins-Bakr7js6.cjs';
|
|
2
|
+
export { A as AnySystem, B as BatchConfig, t as DirectiveError, u as DistributableSnapshot, v as DistributableSnapshotOptions, w as DynamicConstraintDef, x as DynamicEffectDef, y as DynamicResolverDef, z as FactPredicate, G as FactsSnapshot, H as HistoryAPI, I as HistoryOption, J as HistoryState, K as InferDerivations, L as InferEvents, O as InferFacts, Q as InferRequirementTypes, U as InferRequirements, V as InferSchemaType, W as InferSelectorState, X as KeySelector, Y as MetaAccessor, Z as MetaMatch, _ as ObservationEvent, $ as OperatorObject, a0 as PatchValue, a1 as PayloadRef, a2 as PredicateClause, a3 as PredicateCombinator, a4 as PredicateCombinatorKey, a5 as PredicateObject, a6 as PredicateOp, a7 as RetryPolicy, a8 as Schema, a9 as Snapshot, aa as System, ab as SystemConfig, ac as SystemInspection, ad as SystemMode, ae as SystemSnapshot, af as TraceEntry, ag as isNamespacedSystem, ah as isSingleModuleSystem } from './plugins-Bakr7js6.cjs';
|
|
3
|
+
export { D as DerivationDefWithMeta, t as typedConstraint, a as typedResolver } from './helpers-B1MiHave.cjs';
|
|
4
4
|
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-BnQajqPu.cjs';
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Runtime for data-configuration predicates and templates.
|
|
8
|
+
*
|
|
9
|
+
* Pure module — imports only its own types. Reads facts through whatever
|
|
10
|
+
* object it is handed (the reactive `Facts` proxy in production, a plain
|
|
11
|
+
* snapshot in tests), so it never depends on the engine, store, or tracking.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** A readable scope — the `Facts` proxy and a plain snapshot both satisfy it. */
|
|
15
|
+
type Scope = Record<string, unknown>;
|
|
16
|
+
/**
|
|
17
|
+
* True when `v` is a data-form spec (predicate object/array) rather than a
|
|
18
|
+
* function. Excludes class instances (Date, RegExp, Map, Set, Promise, etc.)
|
|
19
|
+
* — only plain `{}` literals and arrays of plain clause shapes qualify.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* isPredicate({ phase: "red" }); // true
|
|
24
|
+
* isPredicate((f) => f.phase === "red"); // false
|
|
25
|
+
* isPredicate([{ fact: "phase", op: "$eq", value: "red" }]); // true
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
declare function isPredicate(v: unknown): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* True when `v` is a {@link FactTemplate} (`{ $template: string }`).
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* isTemplate({ $template: "Hi ${name}" }); // true
|
|
35
|
+
* isTemplate({ $set: { name: "x" } }); // false
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
declare function isTemplate(v: unknown): v is FactTemplate;
|
|
39
|
+
/**
|
|
40
|
+
* Evaluate a {@link FactPredicate} against a fact scope. `prev` (a previous
|
|
41
|
+
* snapshot) is consulted only by the `$changed` operator.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* evaluatePredicate({ phase: "red", elapsed: { $gte: 30 } }, { phase: "red", elapsed: 45 });
|
|
46
|
+
* // → true
|
|
47
|
+
* evaluatePredicate({ $any: [{ phase: "red" }, { phase: "yellow" }] }, { phase: "green" });
|
|
48
|
+
* // → false
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
declare function evaluatePredicate(spec: unknown, facts: Scope, prev?: Scope): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Evaluate a predicate and return a per-clause breakdown — the data feed for
|
|
54
|
+
* devtools, `system.explain()`, and `directive explain`.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* evaluatePredicateExplained(
|
|
59
|
+
* { phase: "red", elapsed: { $gte: 30 } },
|
|
60
|
+
* { phase: "red", elapsed: 20 },
|
|
61
|
+
* );
|
|
62
|
+
* // → [
|
|
63
|
+
* // { path: "phase", op: "$eq", expected: "red", actual: "red", pass: true },
|
|
64
|
+
* // { path: "elapsed", op: "$gte", expected: 30, actual: 20, pass: false },
|
|
65
|
+
* // ]
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
declare function evaluatePredicateExplained(spec: unknown, facts: Scope, prev?: Scope, pathPrefix?: string): ClauseResult[];
|
|
69
|
+
/**
|
|
70
|
+
* Memoize a predicate as a reusable evaluation closure.
|
|
71
|
+
*
|
|
72
|
+
* The returned function accepts any `facts` scope (the reactive proxy in
|
|
73
|
+
* production, a plain object in tests) plus an optional `prev` snapshot for
|
|
74
|
+
* `$changed`. The closure is cached **by predicate identity** in a
|
|
75
|
+
* `WeakMap`, so passing the same `predicate` reference repeatedly is
|
|
76
|
+
* allocation-free; cleanup is automatic once the predicate is no longer
|
|
77
|
+
* reachable.
|
|
78
|
+
*
|
|
79
|
+
* Note: no actual compilation happens — the returned closure re-walks the
|
|
80
|
+
* spec on every call via `evaluatePredicate`. The name reflects what the
|
|
81
|
+
* function does (closure memoization keyed by predicate identity), not a
|
|
82
|
+
* bytecode/AST compile step.
|
|
83
|
+
*
|
|
84
|
+
* Intended for advanced users who want a stable function reference per
|
|
85
|
+
* predicate (custom devtools, batched analyses). Regular module code does
|
|
86
|
+
* not need to call this — the engine wraps data-form `when` / `on` specs
|
|
87
|
+
* automatically at registration.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```ts
|
|
91
|
+
* const predicate = { phase: "red", elapsed: { $gte: 30 } };
|
|
92
|
+
* const check = memoizePredicate(predicate);
|
|
93
|
+
* check({ phase: "red", elapsed: 45 }); // → true
|
|
94
|
+
* check({ phase: "red", elapsed: 5 }); // → false
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
declare function memoizePredicate(predicate: object): (facts: Scope, prev?: Scope) => boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Collect the fact keys a predicate references. Used for static analysis,
|
|
100
|
+
* devtools, and effect `on` dependency wiring. Nested predicates contribute
|
|
101
|
+
* dotted keys (`auth.token`).
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```ts
|
|
105
|
+
* extractDeps({ phase: "red", elapsed: { $gte: 30 } });
|
|
106
|
+
* // → Set { "phase", "elapsed" }
|
|
107
|
+
* extractDeps({ self: { phase: "red" }, auth: { token: { $exists: true } } });
|
|
108
|
+
* // → Set { "self.phase", "auth.token" }
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
declare function extractDeps(spec: unknown, prefix?: string, into?: Set<string>): Set<string>;
|
|
112
|
+
/**
|
|
113
|
+
* Interpolate a {@link FactTemplate} against a scope. Single-pass character
|
|
114
|
+
* scanner: `${ident}` interpolates `scope[ident]`; `$${` emits a literal
|
|
115
|
+
* `${`; unknown keys dev-warn and yield an empty string.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* evaluateTemplate({ $template: "Hi ${name}!" }, { name: "Ada" });
|
|
120
|
+
* // → "Hi Ada!"
|
|
121
|
+
* evaluateTemplate({ $template: "$${price}" }, {});
|
|
122
|
+
* // → "${price}"
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
declare function evaluateTemplate(spec: FactTemplate, scope: Scope): string;
|
|
126
|
+
/**
|
|
127
|
+
* Collect the placeholder keys referenced by a template. The static-analysis
|
|
128
|
+
* counterpart to {@link extractDeps} — useful for devtools, codegen, and
|
|
129
|
+
* "which facts does this template read" inspections. Only valid identifier
|
|
130
|
+
* placeholders are collected; malformed ones are ignored.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* ```ts
|
|
134
|
+
* extractTemplateKeys({ $template: "${firstName} ${lastName}" });
|
|
135
|
+
* // → Set { "firstName", "lastName" }
|
|
136
|
+
* extractTemplateKeys({ $template: "$${literal}" });
|
|
137
|
+
* // → Set {} (escaped — not a placeholder)
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
declare function extractTemplateKeys(spec: FactTemplate): Set<string>;
|
|
141
|
+
/**
|
|
142
|
+
* Build a stable dedup key by selecting fields from a requirement payload.
|
|
143
|
+
* Order-as-declared; values are stable-stringified (keys sorted recursively)
|
|
144
|
+
* so two payloads with the same fields in different orders dedupe to the
|
|
145
|
+
* same key.
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* evaluateKeySelector(["url", "method"], { url: "/a", method: "GET" });
|
|
150
|
+
* // → '"/a"|"GET"'
|
|
151
|
+
* evaluateKeySelector(["id"], { id: 42 });
|
|
152
|
+
* // → '42'
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
declare function evaluateKeySelector(selector: readonly string[], source: Record<string, unknown>): string;
|
|
156
|
+
/**
|
|
157
|
+
* Apply a {@link PatchSpec} — assign facts from literals, payload copies
|
|
158
|
+
* (`$ref`), or interpolated strings (`$template`). Mutates through the passed
|
|
159
|
+
* `facts` proxy so change-tracking and downstream invalidation fire.
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```ts
|
|
163
|
+
* const spec = {
|
|
164
|
+
* $set: {
|
|
165
|
+
* active: true,
|
|
166
|
+
* userId: { $ref: "id" },
|
|
167
|
+
* label: { $template: "user ${name}" },
|
|
168
|
+
* },
|
|
169
|
+
* };
|
|
170
|
+
* applyPatch(spec, facts, { id: "u_1", name: "Ada" });
|
|
171
|
+
* // facts.active = true; facts.userId = "u_1"; facts.label = "user Ada"
|
|
172
|
+
* ```
|
|
173
|
+
*/
|
|
174
|
+
declare function applyPatch(spec: PatchSpec<Record<string, unknown>, Record<string, unknown>>, facts: Record<string, unknown>, payload: Record<string, unknown>): void;
|
|
175
|
+
|
|
6
176
|
/** Brand symbol for branded types */
|
|
7
177
|
declare const Brand: unique symbol;
|
|
8
178
|
/** Branded type - adds a unique brand to a base type */
|
|
@@ -793,6 +963,14 @@ declare function createSystemWithStatus<M extends ModuleSchema>(options: CreateS
|
|
|
793
963
|
* - Requirement comparison and hashing
|
|
794
964
|
*/
|
|
795
965
|
|
|
966
|
+
/**
|
|
967
|
+
* Computes a stable identifier for a requirement, used for coalescing
|
|
968
|
+
* duplicate fetches across the constraint graph.
|
|
969
|
+
*
|
|
970
|
+
* @param req - the requirement to identify
|
|
971
|
+
* @param keyFn - optional custom key function; if omitted, a stableStringify-based default is used (memoized via WeakMap)
|
|
972
|
+
* @returns the requirement's stable string ID
|
|
973
|
+
*/
|
|
796
974
|
declare function generateRequirementId(req: Requirement, keyFn?: RequirementKeyFn): string;
|
|
797
975
|
/**
|
|
798
976
|
* Create a typed requirement factory for a given requirement type string.
|
|
@@ -1141,7 +1319,7 @@ declare function resumeTimer(state: TimerFactState, nowMs: number): TimerFactSta
|
|
|
1141
1319
|
declare function resetTimer(): TimerFactState;
|
|
1142
1320
|
/**
|
|
1143
1321
|
* Transition: mark the timer completed. For countdown mode when
|
|
1144
|
-
* elapsed
|
|
1322
|
+
* elapsed reaches `ms`; for repeat mode when consumer wants to halt.
|
|
1145
1323
|
*/
|
|
1146
1324
|
declare function completeTimer(state: TimerFactState): TimerFactState;
|
|
1147
1325
|
/**
|
|
@@ -1255,4 +1433,4 @@ declare const Backoff: {
|
|
|
1255
1433
|
readonly Exponential: "exponential";
|
|
1256
1434
|
};
|
|
1257
1435
|
|
|
1258
|
-
export { Backoff, type Branded, type ChainableSchemaType, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, ErrorBoundaryConfig, type ExtendedSchemaType, Facts, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, Plugin, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, SchemaType, type SignalClock, SingleModuleSystem, type TimerFactOpts, type TimerFactState, TraceOption, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, elapsedMs, forType, generateRequirementId, initialTimerState, isRequirementType, pauseTimer, realClock, registerRepeat, remainingMs, req, resetTimer, resumeTimer, startTimer, t, tickTimer, timerOps, virtualClock };
|
|
1436
|
+
export { Backoff, type Branded, type ChainableSchemaType, ClauseResult, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, ErrorBoundaryConfig, type ExtendedSchemaType, FactTemplate, Facts, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, 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, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, realClock, registerRepeat, remainingMs, req, resetTimer, resumeTimer, startTimer, t, tickTimer, timerOps, virtualClock };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,178 @@
|
|
|
1
|
-
import { S as SchemaType, D as DefinitionMeta, M as ModuleSchema,
|
|
2
|
-
export { A as AnySystem, B as BatchConfig,
|
|
3
|
-
export { D as DerivationDefWithMeta, t as typedConstraint, a as typedResolver } from './helpers-
|
|
1
|
+
import { P as PatchSpec, C as ClauseResult, F as FactTemplate, S as SchemaType, D as DefinitionMeta, M as ModuleSchema, a as Facts, T as TypedDerivationsDef, b as TypedEventsDef, E as EffectsDef, c as TypedConstraintsDef, d as TypedResolversDef, e as ModuleHooks, f as CrossModuleDeps, g as CrossModuleDerivationsDef, h as CrossModuleEffectsDef, i as CrossModuleConstraintsDef, j as ModuleDef, k as CreateSystemOptionsSingle, l as SingleModuleSystem, m as ModulesMap, n as CreateSystemOptionsNamed, N as NamespacedSystem, o as Plugin, p as TraceOption, q as ErrorBoundaryConfig, R as RequirementWithId, r as Requirement, s as RequirementKeyFn } from './plugins-Bakr7js6.js';
|
|
2
|
+
export { A as AnySystem, B as BatchConfig, t as DirectiveError, u as DistributableSnapshot, v as DistributableSnapshotOptions, w as DynamicConstraintDef, x as DynamicEffectDef, y as DynamicResolverDef, z as FactPredicate, G as FactsSnapshot, H as HistoryAPI, I as HistoryOption, J as HistoryState, K as InferDerivations, L as InferEvents, O as InferFacts, Q as InferRequirementTypes, U as InferRequirements, V as InferSchemaType, W as InferSelectorState, X as KeySelector, Y as MetaAccessor, Z as MetaMatch, _ as ObservationEvent, $ as OperatorObject, a0 as PatchValue, a1 as PayloadRef, a2 as PredicateClause, a3 as PredicateCombinator, a4 as PredicateCombinatorKey, a5 as PredicateObject, a6 as PredicateOp, a7 as RetryPolicy, a8 as Schema, a9 as Snapshot, aa as System, ab as SystemConfig, ac as SystemInspection, ad as SystemMode, ae as SystemSnapshot, af as TraceEntry, ag as isNamespacedSystem, ah as isSingleModuleSystem } from './plugins-Bakr7js6.js';
|
|
3
|
+
export { D as DerivationDefWithMeta, t as typedConstraint, a as typedResolver } from './helpers-h9PR2JSJ.js';
|
|
4
4
|
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-BnQajqPu.js';
|
|
5
5
|
|
|
6
|
+
/**
|
|
7
|
+
* Runtime for data-configuration predicates and templates.
|
|
8
|
+
*
|
|
9
|
+
* Pure module — imports only its own types. Reads facts through whatever
|
|
10
|
+
* object it is handed (the reactive `Facts` proxy in production, a plain
|
|
11
|
+
* snapshot in tests), so it never depends on the engine, store, or tracking.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/** A readable scope — the `Facts` proxy and a plain snapshot both satisfy it. */
|
|
15
|
+
type Scope = Record<string, unknown>;
|
|
16
|
+
/**
|
|
17
|
+
* True when `v` is a data-form spec (predicate object/array) rather than a
|
|
18
|
+
* function. Excludes class instances (Date, RegExp, Map, Set, Promise, etc.)
|
|
19
|
+
* — only plain `{}` literals and arrays of plain clause shapes qualify.
|
|
20
|
+
*
|
|
21
|
+
* @example
|
|
22
|
+
* ```ts
|
|
23
|
+
* isPredicate({ phase: "red" }); // true
|
|
24
|
+
* isPredicate((f) => f.phase === "red"); // false
|
|
25
|
+
* isPredicate([{ fact: "phase", op: "$eq", value: "red" }]); // true
|
|
26
|
+
* ```
|
|
27
|
+
*/
|
|
28
|
+
declare function isPredicate(v: unknown): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* True when `v` is a {@link FactTemplate} (`{ $template: string }`).
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* ```ts
|
|
34
|
+
* isTemplate({ $template: "Hi ${name}" }); // true
|
|
35
|
+
* isTemplate({ $set: { name: "x" } }); // false
|
|
36
|
+
* ```
|
|
37
|
+
*/
|
|
38
|
+
declare function isTemplate(v: unknown): v is FactTemplate;
|
|
39
|
+
/**
|
|
40
|
+
* Evaluate a {@link FactPredicate} against a fact scope. `prev` (a previous
|
|
41
|
+
* snapshot) is consulted only by the `$changed` operator.
|
|
42
|
+
*
|
|
43
|
+
* @example
|
|
44
|
+
* ```ts
|
|
45
|
+
* evaluatePredicate({ phase: "red", elapsed: { $gte: 30 } }, { phase: "red", elapsed: 45 });
|
|
46
|
+
* // → true
|
|
47
|
+
* evaluatePredicate({ $any: [{ phase: "red" }, { phase: "yellow" }] }, { phase: "green" });
|
|
48
|
+
* // → false
|
|
49
|
+
* ```
|
|
50
|
+
*/
|
|
51
|
+
declare function evaluatePredicate(spec: unknown, facts: Scope, prev?: Scope): boolean;
|
|
52
|
+
/**
|
|
53
|
+
* Evaluate a predicate and return a per-clause breakdown — the data feed for
|
|
54
|
+
* devtools, `system.explain()`, and `directive explain`.
|
|
55
|
+
*
|
|
56
|
+
* @example
|
|
57
|
+
* ```ts
|
|
58
|
+
* evaluatePredicateExplained(
|
|
59
|
+
* { phase: "red", elapsed: { $gte: 30 } },
|
|
60
|
+
* { phase: "red", elapsed: 20 },
|
|
61
|
+
* );
|
|
62
|
+
* // → [
|
|
63
|
+
* // { path: "phase", op: "$eq", expected: "red", actual: "red", pass: true },
|
|
64
|
+
* // { path: "elapsed", op: "$gte", expected: 30, actual: 20, pass: false },
|
|
65
|
+
* // ]
|
|
66
|
+
* ```
|
|
67
|
+
*/
|
|
68
|
+
declare function evaluatePredicateExplained(spec: unknown, facts: Scope, prev?: Scope, pathPrefix?: string): ClauseResult[];
|
|
69
|
+
/**
|
|
70
|
+
* Memoize a predicate as a reusable evaluation closure.
|
|
71
|
+
*
|
|
72
|
+
* The returned function accepts any `facts` scope (the reactive proxy in
|
|
73
|
+
* production, a plain object in tests) plus an optional `prev` snapshot for
|
|
74
|
+
* `$changed`. The closure is cached **by predicate identity** in a
|
|
75
|
+
* `WeakMap`, so passing the same `predicate` reference repeatedly is
|
|
76
|
+
* allocation-free; cleanup is automatic once the predicate is no longer
|
|
77
|
+
* reachable.
|
|
78
|
+
*
|
|
79
|
+
* Note: no actual compilation happens — the returned closure re-walks the
|
|
80
|
+
* spec on every call via `evaluatePredicate`. The name reflects what the
|
|
81
|
+
* function does (closure memoization keyed by predicate identity), not a
|
|
82
|
+
* bytecode/AST compile step.
|
|
83
|
+
*
|
|
84
|
+
* Intended for advanced users who want a stable function reference per
|
|
85
|
+
* predicate (custom devtools, batched analyses). Regular module code does
|
|
86
|
+
* not need to call this — the engine wraps data-form `when` / `on` specs
|
|
87
|
+
* automatically at registration.
|
|
88
|
+
*
|
|
89
|
+
* @example
|
|
90
|
+
* ```ts
|
|
91
|
+
* const predicate = { phase: "red", elapsed: { $gte: 30 } };
|
|
92
|
+
* const check = memoizePredicate(predicate);
|
|
93
|
+
* check({ phase: "red", elapsed: 45 }); // → true
|
|
94
|
+
* check({ phase: "red", elapsed: 5 }); // → false
|
|
95
|
+
* ```
|
|
96
|
+
*/
|
|
97
|
+
declare function memoizePredicate(predicate: object): (facts: Scope, prev?: Scope) => boolean;
|
|
98
|
+
/**
|
|
99
|
+
* Collect the fact keys a predicate references. Used for static analysis,
|
|
100
|
+
* devtools, and effect `on` dependency wiring. Nested predicates contribute
|
|
101
|
+
* dotted keys (`auth.token`).
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```ts
|
|
105
|
+
* extractDeps({ phase: "red", elapsed: { $gte: 30 } });
|
|
106
|
+
* // → Set { "phase", "elapsed" }
|
|
107
|
+
* extractDeps({ self: { phase: "red" }, auth: { token: { $exists: true } } });
|
|
108
|
+
* // → Set { "self.phase", "auth.token" }
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
111
|
+
declare function extractDeps(spec: unknown, prefix?: string, into?: Set<string>): Set<string>;
|
|
112
|
+
/**
|
|
113
|
+
* Interpolate a {@link FactTemplate} against a scope. Single-pass character
|
|
114
|
+
* scanner: `${ident}` interpolates `scope[ident]`; `$${` emits a literal
|
|
115
|
+
* `${`; unknown keys dev-warn and yield an empty string.
|
|
116
|
+
*
|
|
117
|
+
* @example
|
|
118
|
+
* ```ts
|
|
119
|
+
* evaluateTemplate({ $template: "Hi ${name}!" }, { name: "Ada" });
|
|
120
|
+
* // → "Hi Ada!"
|
|
121
|
+
* evaluateTemplate({ $template: "$${price}" }, {});
|
|
122
|
+
* // → "${price}"
|
|
123
|
+
* ```
|
|
124
|
+
*/
|
|
125
|
+
declare function evaluateTemplate(spec: FactTemplate, scope: Scope): string;
|
|
126
|
+
/**
|
|
127
|
+
* Collect the placeholder keys referenced by a template. The static-analysis
|
|
128
|
+
* counterpart to {@link extractDeps} — useful for devtools, codegen, and
|
|
129
|
+
* "which facts does this template read" inspections. Only valid identifier
|
|
130
|
+
* placeholders are collected; malformed ones are ignored.
|
|
131
|
+
*
|
|
132
|
+
* @example
|
|
133
|
+
* ```ts
|
|
134
|
+
* extractTemplateKeys({ $template: "${firstName} ${lastName}" });
|
|
135
|
+
* // → Set { "firstName", "lastName" }
|
|
136
|
+
* extractTemplateKeys({ $template: "$${literal}" });
|
|
137
|
+
* // → Set {} (escaped — not a placeholder)
|
|
138
|
+
* ```
|
|
139
|
+
*/
|
|
140
|
+
declare function extractTemplateKeys(spec: FactTemplate): Set<string>;
|
|
141
|
+
/**
|
|
142
|
+
* Build a stable dedup key by selecting fields from a requirement payload.
|
|
143
|
+
* Order-as-declared; values are stable-stringified (keys sorted recursively)
|
|
144
|
+
* so two payloads with the same fields in different orders dedupe to the
|
|
145
|
+
* same key.
|
|
146
|
+
*
|
|
147
|
+
* @example
|
|
148
|
+
* ```ts
|
|
149
|
+
* evaluateKeySelector(["url", "method"], { url: "/a", method: "GET" });
|
|
150
|
+
* // → '"/a"|"GET"'
|
|
151
|
+
* evaluateKeySelector(["id"], { id: 42 });
|
|
152
|
+
* // → '42'
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
declare function evaluateKeySelector(selector: readonly string[], source: Record<string, unknown>): string;
|
|
156
|
+
/**
|
|
157
|
+
* Apply a {@link PatchSpec} — assign facts from literals, payload copies
|
|
158
|
+
* (`$ref`), or interpolated strings (`$template`). Mutates through the passed
|
|
159
|
+
* `facts` proxy so change-tracking and downstream invalidation fire.
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* ```ts
|
|
163
|
+
* const spec = {
|
|
164
|
+
* $set: {
|
|
165
|
+
* active: true,
|
|
166
|
+
* userId: { $ref: "id" },
|
|
167
|
+
* label: { $template: "user ${name}" },
|
|
168
|
+
* },
|
|
169
|
+
* };
|
|
170
|
+
* applyPatch(spec, facts, { id: "u_1", name: "Ada" });
|
|
171
|
+
* // facts.active = true; facts.userId = "u_1"; facts.label = "user Ada"
|
|
172
|
+
* ```
|
|
173
|
+
*/
|
|
174
|
+
declare function applyPatch(spec: PatchSpec<Record<string, unknown>, Record<string, unknown>>, facts: Record<string, unknown>, payload: Record<string, unknown>): void;
|
|
175
|
+
|
|
6
176
|
/** Brand symbol for branded types */
|
|
7
177
|
declare const Brand: unique symbol;
|
|
8
178
|
/** Branded type - adds a unique brand to a base type */
|
|
@@ -793,6 +963,14 @@ declare function createSystemWithStatus<M extends ModuleSchema>(options: CreateS
|
|
|
793
963
|
* - Requirement comparison and hashing
|
|
794
964
|
*/
|
|
795
965
|
|
|
966
|
+
/**
|
|
967
|
+
* Computes a stable identifier for a requirement, used for coalescing
|
|
968
|
+
* duplicate fetches across the constraint graph.
|
|
969
|
+
*
|
|
970
|
+
* @param req - the requirement to identify
|
|
971
|
+
* @param keyFn - optional custom key function; if omitted, a stableStringify-based default is used (memoized via WeakMap)
|
|
972
|
+
* @returns the requirement's stable string ID
|
|
973
|
+
*/
|
|
796
974
|
declare function generateRequirementId(req: Requirement, keyFn?: RequirementKeyFn): string;
|
|
797
975
|
/**
|
|
798
976
|
* Create a typed requirement factory for a given requirement type string.
|
|
@@ -1141,7 +1319,7 @@ declare function resumeTimer(state: TimerFactState, nowMs: number): TimerFactSta
|
|
|
1141
1319
|
declare function resetTimer(): TimerFactState;
|
|
1142
1320
|
/**
|
|
1143
1321
|
* Transition: mark the timer completed. For countdown mode when
|
|
1144
|
-
* elapsed
|
|
1322
|
+
* elapsed reaches `ms`; for repeat mode when consumer wants to halt.
|
|
1145
1323
|
*/
|
|
1146
1324
|
declare function completeTimer(state: TimerFactState): TimerFactState;
|
|
1147
1325
|
/**
|
|
@@ -1255,4 +1433,4 @@ declare const Backoff: {
|
|
|
1255
1433
|
readonly Exponential: "exponential";
|
|
1256
1434
|
};
|
|
1257
1435
|
|
|
1258
|
-
export { Backoff, type Branded, type ChainableSchemaType, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, ErrorBoundaryConfig, type ExtendedSchemaType, Facts, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, Plugin, Requirement, RequirementSet, type RequirementTypeStatus, RequirementWithId, SchemaType, type SignalClock, SingleModuleSystem, type TimerFactOpts, type TimerFactState, TraceOption, completeTimer, createModule, createModuleFactory, createRequirementStatusPlugin, createStatusHook, createSystem, createSystemWithStatus, defaultClock, elapsedMs, forType, generateRequirementId, initialTimerState, isRequirementType, pauseTimer, realClock, registerRepeat, remainingMs, req, resetTimer, resumeTimer, startTimer, t, tickTimer, timerOps, virtualClock };
|
|
1436
|
+
export { Backoff, type Branded, type ChainableSchemaType, ClauseResult, CreateSystemOptionsNamed, CreateSystemOptionsSingle, CrossModuleDeps, DefinitionMeta, ErrorBoundaryConfig, type ExtendedSchemaType, FactTemplate, Facts, type ModuleConfig, type ModuleConfigWithDeps, ModuleDef, ModuleHooks, ModuleSchema, ModulesMap, NamespacedSystem, PatchSpec, Plugin, 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, generateRequirementId, initialTimerState, isPredicate, isRequirementType, isTemplate, memoizePredicate, pauseTimer, realClock, registerRepeat, remainingMs, req, resetTimer, resumeTimer, startTimer, t, tickTimer, timerOps, virtualClock };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'./chunk-JYGG4RIL.js';export{a as createSystem}from'./chunk-JYGG4RIL.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-GVVNFVEX.js';import {f}from'./chunk-FK7BD7XT.js';export{h as diffSnapshots,i as isSignedSnapshot,f as isSnapshotExpired,d as shallowEqual,j as signSnapshot,g as validateSnapshot,k as verifySnapshotSignature}from'./chunk-4CMO5OVZ.js';function h(e=[],n,t,s,i,l,o){return {_type:void 0,_validators:e,_typeName:n,_default:t,_transform:s,_description:i,_refinements:l,_meta:o,validate(p){return h([...e,p],n,t,s,i,l,o)}}}function c(e,n,t,s,i,l,o){return {...h(e,n,t,s,i,l,o),default(r){return c(e,n,r,s,i,l,o)},transform(r){return c([],n,void 0,u=>{let d=s?s(u):u;return r(d)},i,void 0,o)},brand(){return c(e,`Branded<${n}>`,t,s,i,l,o)},describe(r){return c(e,n,t,s,r,l,o)},refine(r,a){let u=[...l??[],{predicate:r,message:a}];return c([...e,r],n,t,s,i,u,o)},nullable(){return c([r=>r===null||e.every(a=>a(r))],`${n} | null`,t,s,i,void 0,o)},optional(){return c([r=>r===void 0||e.every(a=>a(r))],`${n} | undefined`,t,s,i,void 0,o)},meta(r){return c(e,n,t,s,i,l,r)}}}var X=((...e)=>{if(e.length===0)return c([],"union");let n=e.map(t=>t._typeName??"unknown");return c([t=>e.some(s=>s._validators.every(i=>i(t)))],n.join(" | "))}),Y={string(){let e=(n,t,s,i,l,o)=>({...c(n,"string",t,s,i,l,o),minLength(r){return e([...n,a=>a.length>=r],t,s,i,l,o)},maxLength(r){return e([...n,a=>a.length<=r],t,s,i,l,o)},pattern(r){return e([...n,a=>r.test(a)],t,s,i,l,o)},default(r){return e(n,r,s,i,l,o)},describe(r){return e(n,t,s,r,l,o)},refine(r,a){let u=[...l??[],{predicate:r,message:a}];return e([...n,r],t,s,i,u,o)},meta(r){return e(n,t,s,i,l,r)}});return e([n=>typeof n=="string"])},number(){let e=(n,t,s,i,l,o)=>({...c(n,"number",t,s,i,l,o),min(r){return e([...n,a=>a>=r],t,s,i,l,o)},max(r){return e([...n,a=>a<=r],t,s,i,l,o)},default(r){return e(n,r,s,i,l,o)},describe(r){return e(n,t,s,r,l,o)},refine(r,a){let u=[...l??[],{predicate:r,message:a}];return e([...n,r],t,s,i,u,o)},meta(r){return e(n,t,s,i,l,r)}});return e([n=>typeof n=="number"])},boolean(){return c([e=>typeof e=="boolean"],"boolean")},array(){let e=(n,t,s,i,l,o)=>{let p=c(n,"array",s,void 0,i,void 0,o),r=l??{value:-1};return {...p,get _lastFailedIndex(){return r.value},set _lastFailedIndex(u){r.value=u;},of(u){let d={value:-1};return e([...n,m=>{for(let g=0;g<m.length;g++)if(!u._validators.every(F=>F(m[g])))return d.value=g,false;return true}],u,s,i,d,o)},nonEmpty(){return e([...n,u=>u.length>0],t,s,i,r,o)},maxLength(u){return e([...n,d=>d.length<=u],t,s,i,r,o)},minLength(u){return e([...n,d=>d.length>=u],t,s,i,r,o)},default(u){return e(n,t,u,i,r,o)},describe(u){return e(n,t,s,u,r,o)},meta(u){return e(n,t,s,i,r,u)}}};return e([n=>Array.isArray(n)])},object(){let e=(n,t,s,i)=>({...c(n,"object",t,void 0,s,void 0,i),shape(o){return e([...n,p=>{for(let[r,a]of Object.entries(o)){let u=p[r],d=a;if(d&&!d._validators.every(m=>m(u)))return false}return true}],t,s,i)},nonNull(){return e([...n,o=>o!=null],t,s,i)},hasKeys(...o){return e([...n,p=>o.every(r=>r in p)],t,s,i)},default(o){return e(n,o,s,i)},describe(o){return e(n,t,o,i)},meta(o){return e(n,t,s,o)}});return e([n=>typeof n=="object"&&n!==null&&!Array.isArray(n)])},enum(...e){f&&e.length===0&&console.warn("[Directive] t.enum() called with no values - this will reject all strings");let n=new Set(e);return c([t=>typeof t=="string"&&n.has(t)],`enum(${e.join("|")})`)},literal(e){return c([n=>n===e],`literal(${String(e)})`)},nullable(e){let n=e._typeName??"unknown";return h([t=>t===null?true:e._validators.every(s=>s(t))],`${n} | null`)},optional(e){let n=e._typeName??"unknown";return h([t=>t===void 0?true:e._validators.every(s=>s(t))],`${n} | undefined`)},union:X,record(e){let n=e._typeName??"unknown";return c([t=>typeof t!="object"||t===null||Array.isArray(t)?false:Object.values(t).every(s=>e._validators.every(i=>i(s)))],`Record<string, ${n}>`)},tuple(...e){f&&e.length===0&&console.warn("[Directive] t.tuple() called with no types - this will only accept empty arrays");let n=e.map(t=>t._typeName??"unknown");return c([t=>!Array.isArray(t)||t.length!==e.length?false:e.every((s,i)=>s._validators.every(l=>l(t[i])))],`[${n.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([n=>typeof n=="string"&&e.test(n)],"uuid")},email(){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return c([n=>typeof n=="string"&&e.test(n)],"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 Z(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 b(e,n,t,s,i){for(let l of e)n.has(l)||console.warn(`[Directive] ${t} "${l}" not declared in ${s}`);for(let l of n)e.has(l)||console.warn(`[Directive] ${s}["${l}"] ${i}`);}function V(e,n){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 t=new Set(Object.keys(n));for(let s of e)t.has(s)||console.warn(`[Directive] history.snapshotEvents entry "${s}" not declared in schema.events. Available events: ${[...t].join(", ")||"(none)"}`);}function ee(e,n){let t=new Set(Object.keys(n));for(let[s,i]of Object.entries(e)){let l=i;typeof l.requirement=="string"&&!t.has(l.requirement)&&console.warn(`[Directive] Resolver "${s}" references unknown requirement type "${l.requirement}". Available types: ${[...t].join(", ")||"(none)"}`);}}function ne(e,n){Z(e),n.schema?n.schema.facts||console.warn("[Directive] Module schema.facts is required"):console.warn("[Directive] Module schema is required"),b(new Set(Object.keys(n.derive??{})),new Set(Object.keys(n.schema?.derivations??{})),"Derivation","schema.derivations","has no matching implementation in derive"),b(new Set(Object.keys(n.events??{})),new Set(Object.keys(n.schema?.events??{})),"Event","schema.events","has no matching handler in events"),n.history?.snapshotEvents&&V(n.history.snapshotEvents,n.schema?.events??{}),n.resolvers&&n.schema?.requirements&&ee(n.resolvers,n.schema.requirements);}function v(e,n){f&&ne(e,n);let t="crossModuleDeps"in n?n.crossModuleDeps:void 0;return {id:e,schema:n.schema,init:n.init,derive:n.derive??{},events:n.events??{},effects:n.effects,constraints:n.constraints,resolvers:n.resolvers,hooks:n.hooks,meta:n.meta,history:n.history,crossModuleDeps:t}}function te(e){return n=>v(n,e)}function M(){let e={pending:new Map,inflight:new Map,failed:new Map,errors:new Map,listeners:new Set};function n(){for(let r of e.listeners)r();}function t(r,a){let u=r.get(a);return u||(u=new Set,r.set(a,u)),u}function s(r){let a=e.pending.get(r)??new Set,u=e.inflight.get(r)??new Set,d=e.failed.get(r)??new Set,m=e.errors.get(r)??null;return {pending:a.size,inflight:u.size,failed:d.size,isLoading:a.size>0||u.size>0,hasError:d.size>0,lastError:m}}function i(){let r=new Set([...e.pending.keys(),...e.inflight.keys(),...e.failed.keys()]),a=new Map;for(let u of r)a.set(u,s(u));return a}function l(r){return e.listeners.add(r),()=>e.listeners.delete(r)}function o(){e.pending.clear(),e.inflight.clear(),e.failed.clear(),e.errors.clear(),n();}return {plugin:{name:"requirement-status",onRequirementCreated(r){let a=r.requirement.type;t(e.pending,a).add(r.id),e.failed.get(a)?.delete(r.id),n();},onResolverStart(r,a){let u=a.requirement.type;e.pending.get(u)?.delete(a.id),t(e.inflight,u).add(a.id),n();},onResolverComplete(r,a){let u=a.requirement.type;e.inflight.get(u)?.delete(a.id),e.pending.get(u)?.delete(a.id),n();},onResolverError(r,a,u){let d=a.requirement.type;e.inflight.get(d)?.delete(a.id),t(e.failed,d).add(a.id),e.errors.set(d,u instanceof Error?u:new Error(String(u))),n();},onResolverCancel(r,a){let u=a.requirement.type;e.pending.get(u)?.delete(a.id),e.inflight.get(u)?.delete(a.id),n();},onRequirementMet(r){let a=r.requirement.type;e.pending.get(a)?.delete(r.id),e.inflight.get(a)?.delete(r.id),n();}},getStatus:s,getAllStatus:i,subscribe:l,reset:o}}function re(e){return n=>e.getStatus(n)}function se(e){let n=M(),s=[...e.plugins??[],n.plugin];return {system:a({module:e.module,plugins:s,trace:e.trace,errorBoundary:e.errorBoundary,tickMs:e.tickMs,zeroConfig:e.zeroConfig,initialFacts:e.initialFacts}),statusPlugin:n}}function D(){return {now:()=>Date.now(),setTimeout:(e,n)=>{let t=globalThis.setTimeout(e,n);return ()=>globalThis.clearTimeout(t)}}}function ie(e=0){let n=e,t=0,s=[];return {now:()=>n,setTimeout:(i,l)=>{let o={id:t++,deadlineMs:n+l,cb:i,canceled:false};return s.push(o),()=>{o.canceled=true;}},advanceBy:i=>{let l=n+i;for(;;){let o=s.filter(r=>!r.canceled&&r.deadlineMs<=l).sort((r,a)=>r.deadlineMs!==a.deadlineMs?r.deadlineMs-a.deadlineMs:r.id-a.id);if(o.length===0)break;let p=o[0];n=Math.max(n,p.deadlineMs),p.canceled=true,p.cb();}n=Math.max(n,l);}}}function ae(){return D()}function S(){return {startedAtMs:null,pausedDurationMs:0,pausedAtMs:null,status:"idle",repeats:0}}function T(e,n){return e.startedAtMs===null?0:e.status==="paused"&&e.pausedAtMs!==null?Math.max(0,e.pausedAtMs-e.startedAtMs-e.pausedDurationMs):Math.max(0,n-e.startedAtMs-e.pausedDurationMs)}function x(e,n,t){return Math.max(0,t-T(e,n))}function C(e,n){return e.status==="running"||e.status==="paused"?e:{...e,startedAtMs:n,pausedDurationMs:0,pausedAtMs:null,status:"running",repeats:0}}function k(e,n){return e.status!=="running"?e:{...e,pausedAtMs:n,status:"paused"}}function w(e,n){if(e.status!=="paused"||e.pausedAtMs===null)return e;let t=Math.max(0,n-e.pausedAtMs);return {...e,pausedDurationMs:e.pausedDurationMs+t,pausedAtMs:null,status:"running"}}function R(){return S()}function A(e){return {...e,status:"completed"}}function E(e,n){return e.startedAtMs===null||e.status==="paused"?e:{...e,startedAtMs:e.startedAtMs+n,pausedDurationMs:0,pausedAtMs:null,repeats:e.repeats+1}}function j(e,n,t){if(e.status!=="running")return {kind:"no-op"};let s=T(e,n);return t.mode==="up"?{kind:"no-op"}:t.mode==="repeat"?s>=t.ms?{kind:"repeat"}:{kind:"no-op"}:s>=t.ms?{kind:"complete"}:{kind:"no-op"}}function oe(e){return {initial:S,start:C,pause:k,resume:w,reset:R,complete:A,registerRepeat:n=>E(n,e.ms),tick:(n,t)=>j(n,t,e),elapsedMs:T,remainingMs:(n,t)=>x(n,t,e.ms)}}var fe={None:"none",Linear:"linear",Exponential:"exponential"};export{fe as Backoff,A as completeTimer,v as createModule,te as createModuleFactory,M as createRequirementStatusPlugin,re as createStatusHook,se as createSystemWithStatus,ae as defaultClock,T as elapsedMs,S as initialTimerState,k as pauseTimer,D as realClock,E as registerRepeat,x as remainingMs,R as resetTimer,w as resumeTimer,C as startTimer,Y as t,j as tickTimer,oe as timerOps,ie as virtualClock};//# sourceMappingURL=index.js.map
|
|
1
|
+
import {a as a$1}from'./chunk-HAF5JCET.js';export{a as createSystem}from'./chunk-HAF5JCET.js';export{l as DirectiveError,y as RequirementSet,j as applyPatch,i as evaluateKeySelector,c as evaluatePredicate,d as evaluatePredicateExplained,g as evaluateTemplate,f as extractDeps,h as extractTemplateKeys,x as forType,u as generateRequirementId,r as isNamespacedSystem,a as isPredicate,w as isRequirementType,q as isSingleModuleSystem,b as isTemplate,e as memoizePredicate,v as req,o as typedConstraint,p as typedResolver}from'./chunk-YCCQ73C6.js';import {a}from'./chunk-EH2Q754B.js';export{h as diffSnapshots,i as isSignedSnapshot,f as isSnapshotExpired,d as shallowEqual,j as signSnapshot,g as validateSnapshot,k as verifySnapshotSignature}from'./chunk-M5KZXNZX.js';function h(e=[],n,t,i,s,l,o){return {_type:void 0,_validators:e,_typeName:n,_default:t,_transform:i,_description:s,_refinements:l,_meta:o,validate(p){return h([...e,p],n,t,i,s,l,o)}}}function c(e,n,t,i,s,l,o){return {...h(e,n,t,i,s,l,o),default(r){return c(e,n,r,i,s,l,o)},transform(r){return c([],n,void 0,u=>{let d=i?i(u):u;return r(d)},s,void 0,o)},brand(){return c(e,`Branded<${n}>`,t,i,s,l,o)},describe(r){return c(e,n,t,i,r,l,o)},refine(r,a){let u=[...l??[],{predicate:r,message:a}];return c([...e,r],n,t,i,s,u,o)},nullable(){return c([r=>r===null||e.every(a=>a(r))],`${n} | null`,t,i,s,void 0,o)},optional(){return c([r=>r===void 0||e.every(a=>a(r))],`${n} | undefined`,t,i,s,void 0,o)},meta(r){return c(e,n,t,i,s,l,r)}}}var ae=((...e)=>{if(e.length===0)return c([],"union");let n=e.map(t=>t._typeName??"unknown");return c([t=>e.some(i=>i._validators.every(s=>s(t)))],n.join(" | "))}),oe={string(){let e=(n,t,i,s,l,o)=>({...c(n,"string",t,i,s,l,o),minLength(r){return e([...n,a=>a.length>=r],t,i,s,l,o)},maxLength(r){return e([...n,a=>a.length<=r],t,i,s,l,o)},pattern(r){return e([...n,a=>r.test(a)],t,i,s,l,o)},default(r){return e(n,r,i,s,l,o)},describe(r){return e(n,t,i,r,l,o)},refine(r,a){let u=[...l??[],{predicate:r,message:a}];return e([...n,r],t,i,s,u,o)},meta(r){return e(n,t,i,s,l,r)}});return e([n=>typeof n=="string"])},number(){let e=(n,t,i,s,l,o)=>({...c(n,"number",t,i,s,l,o),min(r){return e([...n,a=>a>=r],t,i,s,l,o)},max(r){return e([...n,a=>a<=r],t,i,s,l,o)},default(r){return e(n,r,i,s,l,o)},describe(r){return e(n,t,i,r,l,o)},refine(r,a){let u=[...l??[],{predicate:r,message:a}];return e([...n,r],t,i,s,u,o)},meta(r){return e(n,t,i,s,l,r)}});return e([n=>typeof n=="number"])},boolean(){return c([e=>typeof e=="boolean"],"boolean")},array(){let e=(n,t,i,s,l,o)=>{let p=c(n,"array",i,void 0,s,void 0,o),r=l??{value:-1};return {...p,get _lastFailedIndex(){return r.value},set _lastFailedIndex(u){r.value=u;},of(u){let d={value:-1};return e([...n,m=>{for(let g=0;g<m.length;g++)if(!u._validators.every(F=>F(m[g])))return d.value=g,false;return true}],u,i,s,d,o)},nonEmpty(){return e([...n,u=>u.length>0],t,i,s,r,o)},maxLength(u){return e([...n,d=>d.length<=u],t,i,s,r,o)},minLength(u){return e([...n,d=>d.length>=u],t,i,s,r,o)},default(u){return e(n,t,u,s,r,o)},describe(u){return e(n,t,i,u,r,o)},meta(u){return e(n,t,i,s,r,u)}}};return e([n=>Array.isArray(n)])},object(){let e=(n,t,i,s)=>({...c(n,"object",t,void 0,i,void 0,s),shape(o){return e([...n,p=>{for(let[r,a]of Object.entries(o)){let u=p[r],d=a;if(d&&!d._validators.every(m=>m(u)))return false}return true}],t,i,s)},nonNull(){return e([...n,o=>o!=null],t,i,s)},hasKeys(...o){return e([...n,p=>o.every(r=>r in p)],t,i,s)},default(o){return e(n,o,i,s)},describe(o){return e(n,t,o,s)},meta(o){return e(n,t,i,o)}});return e([n=>typeof n=="object"&&n!==null&&!Array.isArray(n)])},enum(...e){a&&e.length===0&&console.warn("[Directive] t.enum() called with no values - this will reject all strings");let n=new Set(e);return c([t=>typeof t=="string"&&n.has(t)],`enum(${e.join("|")})`)},literal(e){return c([n=>n===e],`literal(${String(e)})`)},nullable(e){let n=e._typeName??"unknown";return h([t=>t===null?true:e._validators.every(i=>i(t))],`${n} | null`)},optional(e){let n=e._typeName??"unknown";return h([t=>t===void 0?true:e._validators.every(i=>i(t))],`${n} | undefined`)},union:ae,record(e){let n=e._typeName??"unknown";return c([t=>typeof t!="object"||t===null||Array.isArray(t)?false:Object.values(t).every(i=>e._validators.every(s=>s(i)))],`Record<string, ${n}>`)},tuple(...e){a&&e.length===0&&console.warn("[Directive] t.tuple() called with no types - this will only accept empty arrays");let n=e.map(t=>t._typeName??"unknown");return c([t=>!Array.isArray(t)||t.length!==e.length?false:e.every((i,s)=>i._validators.every(l=>l(t[s])))],`[${n.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([n=>typeof n=="string"&&e.test(n)],"uuid")},email(){let e=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return c([n=>typeof n=="string"&&e.test(n)],"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 ue(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 b(e,n,t,i,s){for(let l of e)n.has(l)||console.warn(`[Directive] ${t} "${l}" not declared in ${i}`);for(let l of n)e.has(l)||console.warn(`[Directive] ${i}["${l}"] ${s}`);}function le(e,n){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 t=new Set(Object.keys(n));for(let i of e)t.has(i)||console.warn(`[Directive] history.snapshotEvents entry "${i}" not declared in schema.events. Available events: ${[...t].join(", ")||"(none)"}`);}function ce(e,n){let t=new Set(Object.keys(n));for(let[i,s]of Object.entries(e)){let l=s;typeof l.requirement=="string"&&!t.has(l.requirement)&&console.warn(`[Directive] Resolver "${i}" references unknown requirement type "${l.requirement}". Available types: ${[...t].join(", ")||"(none)"}`);}}function de(e,n){ue(e),n.schema?n.schema.facts||console.warn("[Directive] Module schema.facts is required"):console.warn("[Directive] Module schema is required"),b(new Set(Object.keys(n.derive??{})),new Set(Object.keys(n.schema?.derivations??{})),"Derivation","schema.derivations","has no matching implementation in derive"),b(new Set(Object.keys(n.events??{})),new Set(Object.keys(n.schema?.events??{})),"Event","schema.events","has no matching handler in events"),n.history?.snapshotEvents&&le(n.history.snapshotEvents,n.schema?.events??{}),n.resolvers&&n.schema?.requirements&&ce(n.resolvers,n.schema.requirements);}function v(e,n){a&&de(e,n);let t="crossModuleDeps"in n?n.crossModuleDeps:void 0;return {id:e,schema:n.schema,init:n.init,derive:n.derive??{},events:n.events??{},effects:n.effects,constraints:n.constraints,resolvers:n.resolvers,hooks:n.hooks,meta:n.meta,history:n.history,crossModuleDeps:t}}function pe(e){return n=>v(n,e)}function M(){let e={pending:new Map,inflight:new Map,failed:new Map,errors:new Map,listeners:new Set};function n(){for(let r of e.listeners)r();}function t(r,a){let u=r.get(a);return u||(u=new Set,r.set(a,u)),u}function i(r){let a=e.pending.get(r)??new Set,u=e.inflight.get(r)??new Set,d=e.failed.get(r)??new Set,m=e.errors.get(r)??null;return {pending:a.size,inflight:u.size,failed:d.size,isLoading:a.size>0||u.size>0,hasError:d.size>0,lastError:m}}function s(){let r=new Set([...e.pending.keys(),...e.inflight.keys(),...e.failed.keys()]),a=new Map;for(let u of r)a.set(u,i(u));return a}function l(r){return e.listeners.add(r),()=>e.listeners.delete(r)}function o(){e.pending.clear(),e.inflight.clear(),e.failed.clear(),e.errors.clear(),n();}return {plugin:{name:"requirement-status",onRequirementCreated(r){let a=r.requirement.type;t(e.pending,a).add(r.id),e.failed.get(a)?.delete(r.id),n();},onResolverStart(r,a){let u=a.requirement.type;e.pending.get(u)?.delete(a.id),t(e.inflight,u).add(a.id),n();},onResolverComplete(r,a){let u=a.requirement.type;e.inflight.get(u)?.delete(a.id),e.pending.get(u)?.delete(a.id),n();},onResolverError(r,a,u){let d=a.requirement.type;e.inflight.get(d)?.delete(a.id),t(e.failed,d).add(a.id),e.errors.set(d,u instanceof Error?u:new Error(String(u))),n();},onResolverCancel(r,a){let u=a.requirement.type;e.pending.get(u)?.delete(a.id),e.inflight.get(u)?.delete(a.id),n();},onRequirementMet(r){let a=r.requirement.type;e.pending.get(a)?.delete(r.id),e.inflight.get(a)?.delete(r.id),n();}},getStatus:i,getAllStatus:s,subscribe:l,reset:o}}function me(e){return n=>e.getStatus(n)}function ye(e){let n=M(),i=[...e.plugins??[],n.plugin];return {system:a$1({module:e.module,plugins:i,trace:e.trace,errorBoundary:e.errorBoundary,tickMs:e.tickMs,zeroConfig:e.zeroConfig,initialFacts:e.initialFacts}),statusPlugin:n}}function D(){return {now:()=>Date.now(),setTimeout:(e,n)=>{let t=globalThis.setTimeout(e,n);return ()=>globalThis.clearTimeout(t)}}}function ge(e=0){let n=e,t=0,i=[];return {now:()=>n,setTimeout:(s,l)=>{let o={id:t++,deadlineMs:n+l,cb:s,canceled:false};return i.push(o),()=>{o.canceled=true;}},advanceBy:s=>{let l=n+s;for(;;){let o=i.filter(r=>!r.canceled&&r.deadlineMs<=l).sort((r,a)=>r.deadlineMs!==a.deadlineMs?r.deadlineMs-a.deadlineMs:r.id-a.id);if(o.length===0)break;let p=o[0];n=Math.max(n,p.deadlineMs),p.canceled=true,p.cb();}n=Math.max(n,l);}}}function he(){return D()}function S(){return {startedAtMs:null,pausedDurationMs:0,pausedAtMs:null,status:"idle",repeats:0}}function T(e,n){return e.startedAtMs===null?0:e.status==="paused"&&e.pausedAtMs!==null?Math.max(0,e.pausedAtMs-e.startedAtMs-e.pausedDurationMs):Math.max(0,n-e.startedAtMs-e.pausedDurationMs)}function x(e,n,t){return Math.max(0,t-T(e,n))}function C(e,n){return e.status==="running"||e.status==="paused"?e:{...e,startedAtMs:n,pausedDurationMs:0,pausedAtMs:null,status:"running",repeats:0}}function k(e,n){return e.status!=="running"?e:{...e,pausedAtMs:n,status:"paused"}}function w(e,n){if(e.status!=="paused"||e.pausedAtMs===null)return e;let t=Math.max(0,n-e.pausedAtMs);return {...e,pausedDurationMs:e.pausedDurationMs+t,pausedAtMs:null,status:"running"}}function R(){return S()}function A(e){return {...e,status:"completed"}}function E(e,n){return e.startedAtMs===null||e.status==="paused"?e:{...e,startedAtMs:e.startedAtMs+n,pausedDurationMs:0,pausedAtMs:null,repeats:e.repeats+1}}function j(e,n,t){if(e.status!=="running")return {kind:"no-op"};let i=T(e,n);return t.mode==="up"?{kind:"no-op"}:t.mode==="repeat"?i>=t.ms?{kind:"repeat"}:{kind:"no-op"}:i>=t.ms?{kind:"complete"}:{kind:"no-op"}}function Te(e){return {initial:S,start:C,pause:k,resume:w,reset:R,complete:A,registerRepeat:n=>E(n,e.ms),tick:(n,t)=>j(n,t,e),elapsedMs:T,remainingMs:(n,t)=>x(n,t,e.ms)}}var Re={None:"none",Linear:"linear",Exponential:"exponential"};export{Re as Backoff,A as completeTimer,v as createModule,pe as createModuleFactory,M as createRequirementStatusPlugin,me as createStatusHook,ye as createSystemWithStatus,he as defaultClock,T as elapsedMs,S as initialTimerState,k as pauseTimer,D as realClock,E as registerRepeat,x as remainingMs,R as resetTimer,w as resumeTimer,C as startTimer,oe as t,j as tickTimer,Te as timerOps,ge as virtualClock};//# sourceMappingURL=index.js.map
|
|
2
2
|
//# sourceMappingURL=index.js.map
|