@coldsmirk/abacus-core 0.2.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.
@@ -0,0 +1,495 @@
1
+ import { InitInput } from "@gorules/zen-engine-wasm";
2
+
3
+ //#region src/engine/intellisense.d.ts
4
+ /**
5
+ * Whether an expression is a standard value expression or a unary (test) expression.
6
+ */
7
+ type ExpressionMode = "standard" | "unary";
8
+ /**
9
+ * A ZEN type descriptor — the shape the engine understands for type-aware
10
+ * completion and validation: a primitive kind name or one of the structural
11
+ * variants `{ Const }`, `{ Enum }`, `{ Array }`, `{ Object }`.
12
+ *
13
+ * Defined here rather than aliasing the wasm `VariableTypeJson` because the
14
+ * engine also emits and accepts `"Date"` — its sole method-receiver kind — which
15
+ * that type omits. Aliasing it would make a Date-typed variable unrepresentable
16
+ * and break `kind === "Date"` narrowing; the structural variants mirror the wasm
17
+ * shape exactly so a value crosses the boundary unchanged.
18
+ */
19
+ type ExpressionType = "Any" | "Null" | "Bool" | "String" | "Number" | "Date" | {
20
+ Const: string;
21
+ } | {
22
+ Enum: [string | undefined, string[]];
23
+ } | {
24
+ Array: ExpressionType;
25
+ } | {
26
+ Object: Record<string, ExpressionType>;
27
+ };
28
+ /**
29
+ * A single syntax / type diagnostic, positioned by character offset.
30
+ */
31
+ interface ExpressionDiagnostic {
32
+ /**
33
+ * Start offset in the source.
34
+ */
35
+ from: number;
36
+ /**
37
+ * End offset in the source.
38
+ */
39
+ to: number;
40
+ /**
41
+ * Human-readable error message.
42
+ */
43
+ message: string;
44
+ /**
45
+ * Diagnostic origin label (e.g. `"Parser error"`).
46
+ */
47
+ source: string;
48
+ }
49
+ /**
50
+ * An autocomplete suggestion for a ZEN built-in (function / method / variable).
51
+ */
52
+ interface ExpressionCompletion {
53
+ type: "function" | "method" | "variable";
54
+ label: string;
55
+ detail: string;
56
+ info: string;
57
+ boost: number | null;
58
+ /**
59
+ * For methods, the type-kind they attach to (e.g. `"Date"`); otherwise `null`.
60
+ */
61
+ methodFor: string | null;
62
+ }
63
+ /**
64
+ * The inferred type of one span of the source, produced by type-checking.
65
+ */
66
+ interface ExpressionTypeSpan {
67
+ error: string | null;
68
+ kind: ExpressionType;
69
+ nodeKind: string;
70
+ span: [number, number];
71
+ }
72
+ /**
73
+ * The result of type-checking an expression against a variable context.
74
+ */
75
+ interface ExpressionAnalysis {
76
+ /**
77
+ * The root context type (the variables object).
78
+ */
79
+ rootKind: ExpressionType;
80
+ /**
81
+ * Per-span inferred types; `spans[0]` is the whole-expression result type.
82
+ */
83
+ spans: ExpressionTypeSpan[];
84
+ }
85
+ /**
86
+ * Validate an expression, loading the engine on first use. Resolves to `null`
87
+ * when the expression is valid, or a positioned diagnostic otherwise.
88
+ */
89
+ declare function getDiagnostics(expression: string, mode: ExpressionMode): Promise<ExpressionDiagnostic | null>;
90
+ /**
91
+ * Synchronous {@link getDiagnostics}. Throws `ExpressionNotReadyError` if the
92
+ * engine has not loaded yet — use only behind a readiness gate.
93
+ */
94
+ declare function getDiagnosticsSync(expression: string, mode: ExpressionMode): ExpressionDiagnostic | null;
95
+ /**
96
+ * Return the ZEN built-in completion list, loading the engine on first use.
97
+ */
98
+ declare function getCompletionItems(): Promise<ExpressionCompletion[]>;
99
+ /**
100
+ * Synchronous {@link getCompletionItems}. Throws `ExpressionNotReadyError` if the
101
+ * engine has not loaded yet.
102
+ */
103
+ declare function getCompletionItemsSync(): ExpressionCompletion[];
104
+ /**
105
+ * Type-check an expression against a `variables` context, loading the engine on
106
+ * first use. See {@link ExpressionAnalysis}.
107
+ */
108
+ declare function analyzeTypes(variables: ExpressionType, source: string, mode: ExpressionMode): Promise<ExpressionAnalysis>;
109
+ /**
110
+ * Synchronous {@link analyzeTypes}. Throws `ExpressionNotReadyError` if the
111
+ * engine has not loaded yet.
112
+ */
113
+ declare function analyzeTypesSync(variables: ExpressionType, source: string, mode: ExpressionMode): ExpressionAnalysis;
114
+ /**
115
+ * Whether `actual` satisfies (is assignable to) `expected`, loading the engine on
116
+ * first use. Used for expected-return-type validation.
117
+ */
118
+ declare function satisfiesType(actual: ExpressionType, expected: ExpressionType): Promise<boolean>;
119
+ /**
120
+ * Synchronous {@link satisfiesType}. Throws `ExpressionNotReadyError` if the
121
+ * engine has not loaded yet.
122
+ */
123
+ declare function satisfiesTypeSync(actual: ExpressionType, expected: ExpressionType): boolean;
124
+ //#endregion
125
+ //#region src/engine/errors.d.ts
126
+ /**
127
+ * Error raised when the ZEN engine fails to load or an expression cannot be
128
+ * evaluated. The original failure is preserved on {@link cause} and the
129
+ * offending expression (if any) on {@link expression}.
130
+ */
131
+ declare class ExpressionError extends Error {
132
+ readonly expression?: string;
133
+ constructor(message: string, expression?: string, cause?: unknown);
134
+ }
135
+ /**
136
+ * Raised by the synchronous evaluation helpers when the engine has not finished
137
+ * initializing yet. Await {@link loadEngine} (or render under
138
+ * `<ExpressionEngineProvider>`) before evaluating synchronously.
139
+ */
140
+ declare class ExpressionNotReadyError extends ExpressionError {
141
+ constructor(message?: string);
142
+ }
143
+ //#endregion
144
+ //#region src/engine/loader.d.ts
145
+ /**
146
+ * The data an expression reads from. Property paths in the expression (e.g.
147
+ * `customer.name`) resolve against this object.
148
+ */
149
+ type ExpressionContext = Record<string, unknown>;
150
+ interface LoadEngineOptions {
151
+ /**
152
+ * Override how the wasm binary is located. By default the engine resolves the
153
+ * co-located `.wasm` through the GoRules package's own `import.meta.url`,
154
+ * which the host bundler (Vite / webpack) rewrites to a served asset URL — no
155
+ * option is needed in normal browser app setups. Supply a URL / Response /
156
+ * bytes for exotic hosting (CDN, embedded buffer) or for a non-browser host
157
+ * (Node / SSR), where `import.meta.url` asset resolution does not work and the
158
+ * input must be provided explicitly. Aliased to the wasm initializer's own
159
+ * `InitInput` so it never drifts from the dependency.
160
+ */
161
+ wasmInput?: InitInput;
162
+ }
163
+ /**
164
+ * The initialized ZEN expression engine. Every method is synchronous — obtain
165
+ * an instance via {@link loadEngine} (async, loads the wasm) before calling.
166
+ */
167
+ interface ExpressionEngine {
168
+ /**
169
+ * Evaluate a standard ZEN expression, returning its computed value.
170
+ */
171
+ evaluate: <T = unknown>(expression: string, context?: ExpressionContext) => T;
172
+ /**
173
+ * Evaluate a ZEN unary (test) expression, returning a boolean.
174
+ */
175
+ evaluateUnary: (expression: string, context?: ExpressionContext) => boolean;
176
+ /**
177
+ * Validate a standard expression; returns ZEN's diagnostic payload (`null`
178
+ * when the expression parses, an error object otherwise).
179
+ */
180
+ validate: (expression: string) => unknown;
181
+ /**
182
+ * Validate a unary expression; returns ZEN's diagnostic payload.
183
+ */
184
+ validateUnary: (expression: string) => unknown;
185
+ /**
186
+ * Return ZEN's completion metadata, for building an expression editor.
187
+ */
188
+ getCompletions: () => unknown;
189
+ /**
190
+ * Type-check `source` against a `variables` context, returning the root context
191
+ * type and the inferred type of every span (`unary` selects test-expression
192
+ * checking). Powers an editor's type-aware completion / hover / diagnostics.
193
+ */
194
+ analyze: (variables: ExpressionType, source: string, unary: boolean) => ExpressionAnalysis;
195
+ /**
196
+ * Whether `actual` satisfies (is assignable to) `expected`. Powers
197
+ * expected-return-type validation in an editor.
198
+ */
199
+ satisfies: (actual: ExpressionType, expected: ExpressionType) => boolean;
200
+ /**
201
+ * Whether the underlying wasm module reports itself ready.
202
+ */
203
+ isReady: () => boolean;
204
+ }
205
+ /**
206
+ * Configure how the wasm binary is located, before the engine loads. Must be
207
+ * called before the first {@link loadEngine} (or any evaluation), so that the
208
+ * configured input is the one actually used — calling it after the engine has
209
+ * started loading throws, rather than silently taking no effect.
210
+ */
211
+ declare function configureEngine(options: LoadEngineOptions): void;
212
+ /**
213
+ * Load and initialize the ZEN expression engine exactly once. Concurrent and
214
+ * subsequent calls share the same in-flight promise / resolved instance. Set a
215
+ * custom wasm source up front with {@link configureEngine}.
216
+ *
217
+ * The GoRules wasm dependency is reached via a dynamic `import()` on purpose: it
218
+ * keeps this module usable from the package's CommonJS build (the dep is
219
+ * ESM-only, so a static `require` would throw) and defers the multi-megabyte
220
+ * wasm download until the engine is actually needed. Do NOT convert this to a
221
+ * static import.
222
+ *
223
+ * A failed load is not cached: the rejected promise is dropped (the error is
224
+ * latched on {@link getEngineError} for inspection), so calling `loadEngine()`
225
+ * again retries from scratch. This is the clear-and-reload retry primitive after
226
+ * a transient failure — an error boundary should call it before resetting.
227
+ */
228
+ declare function loadEngine(): Promise<ExpressionEngine>;
229
+ /**
230
+ * Whether the engine has finished initializing and is ready for sync use.
231
+ */
232
+ declare function isEngineReady(): boolean;
233
+ /**
234
+ * The error from the last failed {@link loadEngine} attempt, or `null`. Used by
235
+ * the React provider to surface a wasm-load failure to an error boundary rather
236
+ * than suspending forever, and by imperative pollers to tell "failed" apart from
237
+ * "still loading". Cleared when a new load starts or {@link resetEngine}.
238
+ */
239
+ declare function getEngineError(): ExpressionError | null;
240
+ /**
241
+ * Return the already-initialized engine synchronously, or throw
242
+ * {@link ExpressionNotReadyError} if {@link loadEngine} has not resolved yet.
243
+ */
244
+ declare function getEngineSync(): ExpressionEngine;
245
+ /**
246
+ * Reset the engine singleton — drops the loaded engine, the cached type context,
247
+ * the latched error, and the configured wasm input. Mainly for tests, but also the
248
+ * way to re-run {@link configureEngine} after a load (configure throws once the
249
+ * engine has started loading).
250
+ */
251
+ declare function resetEngine(): void;
252
+ //#endregion
253
+ //#region src/condition/types.d.ts
254
+ /**
255
+ * Structural shapes for the visual condition model compiled to ZEN. They mirror
256
+ * the condition types used in the form and flow editors so a host can map those
257
+ * definitions to {@link compileCondition} / {@link selectBranch} without this
258
+ * package depending on either editor. The editors keep a flat working model for
259
+ * form ergonomics (a row can hold both a half-typed field triple and an
260
+ * expression while the author toggles between them); this discriminated input is
261
+ * the narrowed, compiler-facing shape where each kind carries only what it uses.
262
+ */
263
+ /**
264
+ * The closed operator vocabulary understood by {@link compileCondition}, as a
265
+ * runtime constant so validators can build allow-lists from it instead of
266
+ * re-declaring the set. The {@link ConditionOperator} type derives from this
267
+ * array — one definition site for both the type and the runtime list.
268
+ */
269
+ declare const CONDITION_OPERATORS: readonly ["eq", "ne", "gt", "gte", "lt", "lte", "contains", "not_contains", "starts_with", "ends_with", "in", "not_in", "is_empty", "is_not_empty"];
270
+ /**
271
+ * Operators understood by {@link compileCondition}. The compiler maps each to a
272
+ * ZEN expression; this closed set is the single source of truth for the operator
273
+ * vocabulary (the flow editor shares it instead of re-declaring its own).
274
+ */
275
+ type ConditionOperator = typeof CONDITION_OPERATORS[number];
276
+ /**
277
+ * A field/operator/value condition.
278
+ */
279
+ interface FieldConditionInput {
280
+ kind: "field";
281
+ /**
282
+ * The field path the operator tests. Emitted **verbatim** into the compiled
283
+ * ZEN source as a path expression (guarded by an identifier-path pattern that
284
+ * also rejects ZEN reserved words such as `true` or `not` as segments), unlike
285
+ * `value`, which is serialized to a ZEN literal — so callers must supply a
286
+ * valid identifier path, not arbitrary user text.
287
+ */
288
+ subject: string;
289
+ operator: ConditionOperator;
290
+ value: unknown;
291
+ }
292
+ /**
293
+ * A raw ZEN expression condition, passed through to the engine verbatim.
294
+ */
295
+ interface ExpressionConditionInput {
296
+ kind: "expression";
297
+ expression: string;
298
+ }
299
+ /**
300
+ * A single condition: either a field/operator/value triple or a raw expression.
301
+ */
302
+ type ConditionInput = FieldConditionInput | ExpressionConditionInput;
303
+ /**
304
+ * A group of conditions, combined with AND.
305
+ */
306
+ interface ConditionGroupInput {
307
+ conditions: readonly ConditionInput[];
308
+ }
309
+ /**
310
+ * A branch guarded by one or more condition groups (combined with OR).
311
+ */
312
+ interface ConditionBranchInput {
313
+ id: string;
314
+ priority: number;
315
+ isDefault?: boolean;
316
+ conditionGroups?: readonly ConditionGroupInput[];
317
+ }
318
+ /**
319
+ * The branch chosen by {@link selectBranch}. `matched` is true only when a
320
+ * non-default branch's expression evaluated true (then `branchId` is that
321
+ * branch's id). On the default-branch fallback `matched` is false while
322
+ * `branchId` is the default's id; `branchId` is null only when nothing matched
323
+ * and there is no default branch.
324
+ */
325
+ type BranchSelection = {
326
+ matched: true;
327
+ branchId: string;
328
+ } | {
329
+ matched: false;
330
+ branchId: string | null;
331
+ };
332
+ //#endregion
333
+ //#region src/condition/compile.d.ts
334
+ /**
335
+ * Serialize a JavaScript value into a ZEN literal. Nullish becomes `null`;
336
+ * numbers / booleans / bigints are emitted verbatim; strings are quoted via
337
+ * {@link encodeZenString}; arrays become `[a, b, ...]`.
338
+ *
339
+ * Throws {@link ExpressionError} for a value with no faithful ZEN
340
+ * representation — an object, symbol, or function, or a string containing both
341
+ * quote styles. Callers that need a sentinel instead of a throw go through
342
+ * {@link compileCondition}, which degrades such a value to a non-compiling
343
+ * (null) condition.
344
+ */
345
+ declare function toZenLiteral(value: unknown): string;
346
+ /**
347
+ * Compile a single condition into a ZEN boolean expression. Field conditions map
348
+ * their operator to ZEN; expression conditions are wrapped in parentheses to
349
+ * preserve their grouping. Returns `null` when the condition is empty, its
350
+ * subject is not an identifier path, or its value has no ZEN representation.
351
+ */
352
+ declare function compileCondition(condition: ConditionInput): string | null;
353
+ /**
354
+ * Compile a condition group (its conditions joined with AND). Returns `null`
355
+ * when the group has no compilable conditions.
356
+ */
357
+ declare function compileGroup(group: ConditionGroupInput): string | null;
358
+ /**
359
+ * Compile a branch's condition groups into a single ZEN expression (groups
360
+ * joined with OR). Returns `null` when the branch has no compilable groups
361
+ * (e.g. a default branch).
362
+ */
363
+ declare function compileBranch(branch: ConditionBranchInput): string | null;
364
+ /**
365
+ * Pick the matching branch for the given context using a pre-loaded engine.
366
+ * Non-default branches are tested in ascending `priority` order; the first whose
367
+ * compiled expression evaluates to `true` wins. Falls back to the default
368
+ * branch, or a `null` id when neither matches.
369
+ *
370
+ * A branch whose expression throws for the given context (e.g. ZEN's `>`
371
+ * throws when the subject is missing or non-numeric) is treated as not matching
372
+ * rather than propagating — so a missing field degrades to the default branch
373
+ * instead of crashing the caller.
374
+ */
375
+ declare function selectBranchWith(branches: readonly ConditionBranchInput[], context: ExpressionContext, engine: Pick<ExpressionEngine, "evaluate" | "validate">): BranchSelection;
376
+ /**
377
+ * Pick the matching branch for the given context, loading the ZEN engine on
378
+ * first use. See {@link selectBranchWith} for the selection semantics.
379
+ */
380
+ declare function selectBranch(branches: readonly ConditionBranchInput[], context: ExpressionContext): Promise<BranchSelection>;
381
+ //#endregion
382
+ //#region src/engine/evaluate.d.ts
383
+ /**
384
+ * Evaluate a standard ZEN expression, loading the engine on first use.
385
+ *
386
+ * `T` is an **unchecked** assertion — the value is returned as `T` with no
387
+ * runtime validation, and ZEN's result type depends on the expression and
388
+ * context. Prefer the `unknown` default and narrow at the call site.
389
+ */
390
+ declare function evaluate<T = unknown>(expression: string, context?: ExpressionContext): Promise<T>;
391
+ /**
392
+ * Evaluate a ZEN unary (test) expression, loading the engine on first use.
393
+ */
394
+ declare function evaluateUnary(expression: string, context?: ExpressionContext): Promise<boolean>;
395
+ /**
396
+ * Evaluate a standard ZEN expression synchronously. Throws
397
+ * {@link ExpressionNotReadyError} when the engine has not loaded yet — use this
398
+ * only behind a readiness gate (e.g. under `<ExpressionEngineProvider>`).
399
+ */
400
+ declare function evaluateSync<T = unknown>(expression: string, context?: ExpressionContext): T;
401
+ /**
402
+ * Evaluate a ZEN unary (test) expression synchronously. Throws
403
+ * {@link ExpressionNotReadyError} when the engine has not loaded yet.
404
+ */
405
+ declare function evaluateUnarySync(expression: string, context?: ExpressionContext): boolean;
406
+ //#endregion
407
+ //#region src/engine/messages.d.ts
408
+ /**
409
+ * The locales the library ships with out of the box.
410
+ */
411
+ type BuiltInExpressionLocale = "en-US" | "zh-CN";
412
+ /**
413
+ * A locale key for editor-produced text (built-in descriptions, type-check prose,
414
+ * and diagnostic origin labels — the wasm engine's own error bodies, identifiers,
415
+ * and type signatures are never translated). The built-in locales surface in
416
+ * autocomplete, while any string is accepted so a host can select a locale
417
+ * registered through {@link registerExpressionLocale}.
418
+ */
419
+ type ExpressionLocale = BuiltInExpressionLocale | (string & {});
420
+ /**
421
+ * The catalog of editor-produced messages for one locale. All localized text the
422
+ * editor surfaces flows through this interface, so a host can switch language or
423
+ * override individual strings in one typed place — and add a language the library
424
+ * does not ship by passing a full `messages` object to
425
+ * {@link configureExpressionMessages}.
426
+ */
427
+ interface ExpressionMessages {
428
+ /**
429
+ * The diagnostic origin label for a wasm error `type` (`"parserError"` →
430
+ * `"Parser error"`), falling back to a generic label for an unknown type.
431
+ */
432
+ sourceLabel: (type?: string) => string;
433
+ /**
434
+ * Translate a built-in's English `info` description to this locale. Returns the
435
+ * input unchanged for English or when no translation exists.
436
+ */
437
+ completionInfo: (englishInfo: string) => string;
438
+ /**
439
+ * The `source` label shown on type-check (as opposed to syntax) diagnostics.
440
+ */
441
+ typeCheckSource: string;
442
+ /**
443
+ * Warning shown when a unary (test) expression does not evaluate to a boolean.
444
+ */
445
+ expectedBoolean: (actualType: string) => string;
446
+ /**
447
+ * Warning shown when a standard expression's result type does not satisfy the
448
+ * configured expected type.
449
+ */
450
+ expectedType: (expectedType: string, actualType: string) => string;
451
+ }
452
+ /**
453
+ * Built-in English message catalog (the default).
454
+ */
455
+ declare const enMessages: ExpressionMessages;
456
+ /**
457
+ * Built-in Simplified Chinese message catalog.
458
+ */
459
+ declare const zhCNMessages: ExpressionMessages;
460
+ /**
461
+ * Register (or replace) the message catalog for a locale key, making it selectable
462
+ * via {@link configureExpressionMessages}. This is how a host adds a language the
463
+ * library does not ship — the built-in locales are registered the same way, so
464
+ * there is no privileged path.
465
+ */
466
+ declare function registerExpressionLocale(locale: string, messages: ExpressionMessages): void;
467
+ interface ConfigureMessagesOptions {
468
+ /**
469
+ * A registered locale to use as the base — built-in or registered through
470
+ * {@link registerExpressionLocale}. An unknown key keeps the current base; omit
471
+ * to keep the current base.
472
+ */
473
+ locale?: ExpressionLocale;
474
+ /**
475
+ * Per-message overrides merged over the base — a quick way to tweak a few strings
476
+ * without registering a whole locale.
477
+ */
478
+ messages?: Partial<ExpressionMessages>;
479
+ }
480
+ /**
481
+ * Configure the active message catalog. Pass a `locale`, a partial `messages`
482
+ * override, or both (overrides win). Idempotent and module-global, so a host
483
+ * configures it once (e.g. through `ExpressionConfigProvider`).
484
+ */
485
+ declare function configureExpressionMessages({
486
+ locale,
487
+ messages
488
+ }: ConfigureMessagesOptions): void;
489
+ /**
490
+ * The active {@link ExpressionMessages} catalog (English by default).
491
+ */
492
+ declare function getExpressionMessages(): ExpressionMessages;
493
+ //#endregion
494
+ export { type BranchSelection, type BuiltInExpressionLocale, CONDITION_OPERATORS, type ConditionBranchInput, type ConditionGroupInput, type ConditionInput, type ConditionOperator, type ConfigureMessagesOptions, type ExpressionAnalysis, type ExpressionCompletion, type ExpressionConditionInput, type ExpressionContext, type ExpressionDiagnostic, type ExpressionEngine, ExpressionError, type ExpressionLocale, type ExpressionMessages, type ExpressionMode, ExpressionNotReadyError, type ExpressionType, type ExpressionTypeSpan, type FieldConditionInput, type LoadEngineOptions, analyzeTypes, analyzeTypesSync, compileBranch, compileCondition, compileGroup, configureEngine, configureExpressionMessages, enMessages, evaluate, evaluateSync, evaluateUnary, evaluateUnarySync, getCompletionItems, getCompletionItemsSync, getDiagnostics, getDiagnosticsSync, getEngineError, getEngineSync, getExpressionMessages, isEngineReady, loadEngine, registerExpressionLocale, resetEngine, satisfiesType, satisfiesTypeSync, selectBranch, selectBranchWith, toZenLiteral, zhCNMessages };
495
+ //# sourceMappingURL=index.d.ts.map