@sladg/apex-state 3.2.1 → 3.4.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.
@@ -1,1554 +0,0 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
2
- import { ReactNode } from 'react';
3
-
4
- /**
5
- * Hash key type for Record-based paths
6
- *
7
- * Use in template strings to construct paths through Record/HashMap properties.
8
- * This type represents the literal string '[*]' used for indexing into Records.
9
- *
10
- * @example
11
- * ```typescript
12
- * type Path = `users.${HASH_KEY}.name` // "users.[*].name"
13
- * ```
14
- */
15
- type HASH_KEY = '[*]';
16
-
17
- /**
18
- * DeepKey utility type
19
- *
20
- * Generates a union of all possible dot-notation paths for nested objects.
21
- * Supports nested objects up to depth 20 to handle deeply nested data structures.
22
- * Handles arrays and complex object hierarchies.
23
- *
24
- * Examples of supported paths:
25
- * - Simple: "name", "email"
26
- * - Nested: "user.address.street"
27
- * - Deep: "g.p.data.optionsCommon.base.ccyPair.forCurrency.id" (11 levels)
28
- *
29
- * @example
30
- * ```typescript
31
- * type User = {
32
- * name: string
33
- * address: {
34
- * street: string
35
- * city: string
36
- * }
37
- * }
38
- *
39
- * // DeepKey<User> = "name" | "address" | "address.street" | "address.city"
40
- * ```
41
- */
42
-
43
- type Primitive = string | number | boolean | bigint | symbol | null | undefined;
44
- type IsAny$1<T> = 0 extends 1 & T ? true : false;
45
- type DeepKey<T, Depth extends number = 20> = Depth extends 0 ? never : IsAny$1<T> extends true ? never : T extends Primitive ? never : T extends readonly any[] ? never : string extends keyof T ? HASH_KEY | (T[string] extends Primitive ? never : T[string] extends readonly any[] ? never : DeepKey<T[string], Prev<Depth>> extends infer DK ? DK extends string ? `${HASH_KEY}.${DK}` : never : never) : {
46
- [K in keyof T & (string | number)]: `${K & string}` | (T[K] extends Primitive ? never : T[K] extends readonly any[] ? never : DeepKey<T[K], Prev<Depth>> extends infer DK ? DK extends string ? `${K & string}.${DK}` : never : never);
47
- }[keyof T & (string | number)];
48
- type Prev<N extends number> = N extends 20 ? 19 : N extends 19 ? 18 : N extends 18 ? 17 : N extends 17 ? 16 : N extends 16 ? 15 : N extends 15 ? 14 : N extends 14 ? 13 : N extends 13 ? 12 : N extends 12 ? 11 : N extends 11 ? 10 : N extends 10 ? 9 : N extends 9 ? 8 : N extends 8 ? 7 : N extends 7 ? 6 : N extends 6 ? 5 : N extends 5 ? 4 : N extends 4 ? 3 : N extends 3 ? 2 : N extends 2 ? 1 : N extends 1 ? 0 : never;
49
-
50
- /**
51
- * Boolean logic DSL type definitions
52
- *
53
- * Type-safe conditional expression DSL used by concerns and side effects
54
- * for reactive condition checking against state.
55
- */
56
-
57
- /**
58
- * Primitive types that can be compared in BoolLogic expressions
59
- */
60
- type ComparableValue = string | number | boolean | null | undefined;
61
- /**
62
- * Boolean logic DSL for conditional expressions
63
- *
64
- * Provides a declarative way to express conditions against state paths.
65
- * Used by concerns (disabledWhen, visibleWhen) and side effects.
66
- *
67
- * Operators:
68
- * - IS_EQUAL: Compare path value to expected value
69
- * - EXISTS: Check if path value is not null/undefined
70
- * - IS_EMPTY: Check if path value is empty (string/array/object)
71
- * - AND/OR/NOT: Boolean combinators
72
- * - GT/LT/GTE/LTE: Numeric comparisons
73
- * - IN: Check if path value is in allowed list
74
- *
75
- * @example
76
- * ```typescript
77
- * // Simple equality check
78
- * const isAdmin: BoolLogic<State> = { IS_EQUAL: ['user.role', 'admin'] }
79
- *
80
- * // Combined conditions
81
- * const canEdit: BoolLogic<State> = {
82
- * AND: [
83
- * { IS_EQUAL: ['user.role', 'editor'] },
84
- * { EXISTS: 'document.id' },
85
- * { NOT: { IS_EQUAL: ['document.status', 'locked'] } }
86
- * ]
87
- * }
88
- *
89
- * // Numeric comparison
90
- * const isExpensive: BoolLogic<State> = { GT: ['product.price', 100] }
91
- * ```
92
- */
93
- type BoolLogic<STATE> = {
94
- IS_EQUAL: [DeepKey<STATE>, ComparableValue];
95
- } | {
96
- EXISTS: DeepKey<STATE>;
97
- } | {
98
- IS_EMPTY: DeepKey<STATE>;
99
- } | {
100
- AND: BoolLogic<STATE>[];
101
- } | {
102
- OR: BoolLogic<STATE>[];
103
- } | {
104
- NOT: BoolLogic<STATE>;
105
- } | {
106
- GT: [DeepKey<STATE>, number];
107
- } | {
108
- LT: [DeepKey<STATE>, number];
109
- } | {
110
- GTE: [DeepKey<STATE>, number];
111
- } | {
112
- LTE: [DeepKey<STATE>, number];
113
- } | {
114
- IN: [DeepKey<STATE>, ComparableValue[]];
115
- };
116
-
117
- /**
118
- * DeepValue utility type
119
- *
120
- * Extracts the value type for a given dot-notation path string.
121
- * Handles nested objects, arrays, and optional properties.
122
- *
123
- * @example
124
- * ```typescript
125
- * type User = {
126
- * address: {
127
- * street: string
128
- * city: string
129
- * }
130
- * }
131
- *
132
- * // DeepValue<User, "address.street"> = string
133
- * // DeepValue<User, "address"> = { street: string, city: string }
134
- * ```
135
- */
136
-
137
- type IsAny<T> = 0 extends 1 & T ? true : false;
138
- type DeepValue<T, Path extends string> = IsAny<T> extends true ? never : T extends readonly any[] ? T[number] : Path extends `${infer First}.${infer Rest}` ? First extends keyof T ? DeepValue<T[First], Rest> : string extends keyof T ? First extends HASH_KEY ? DeepValue<T[string], Rest> : unknown : unknown : Path extends HASH_KEY ? string extends keyof T ? T[string] : unknown : Path extends keyof T ? T[Path] : unknown;
139
-
140
- /**
141
- * GenericMeta interface
142
- *
143
- * Base metadata type for change tracking with standard properties.
144
- * Can be extended with custom properties for specific use cases.
145
- *
146
- * @example
147
- * ```typescript
148
- * interface CustomMeta extends GenericMeta {
149
- * timestamp: number
150
- * userId: string
151
- * }
152
- * ```
153
- */
154
- interface GenericMeta {
155
- /**
156
- * Indicates if the change originated from a sync path side-effect.
157
- * Used to track cascading changes triggered by synchronization logic.
158
- */
159
- isSyncPathChange?: boolean;
160
- /**
161
- * Indicates if the change originated from a flip path side-effect.
162
- * Used to track bidirectional synchronization changes.
163
- */
164
- isFlipPathChange?: boolean;
165
- /**
166
- * Indicates if the change was triggered programmatically rather than by user action.
167
- * Useful for distinguishing between automated and manual state updates.
168
- */
169
- isProgramaticChange?: boolean;
170
- /**
171
- * Indicates if the change originated from an aggregation side-effect.
172
- * Used to track changes triggered by aggregation logic.
173
- */
174
- isAggregationChange?: boolean;
175
- /**
176
- * Indicates if the change originated from a listener side-effect.
177
- * Used to track changes triggered by listener callbacks.
178
- */
179
- isListenerChange?: boolean;
180
- /**
181
- * Identifies the originator of the change.
182
- * Can be a user ID, component name, or any identifier string.
183
- */
184
- sender?: string;
185
- }
186
-
187
- /**
188
- * ArrayOfChanges type
189
- *
190
- * Represents an array of changes with paths, values, and metadata.
191
- * Each change is a tuple of [path, value, metadata].
192
- *
193
- * @example
194
- * ```typescript
195
- * type User = {
196
- * name: string
197
- * age: number
198
- * }
199
- *
200
- * const changes: ArrayOfChanges<User, GenericMeta> = [
201
- * ["name", "John", { sender: "user-123" }],
202
- * ["age", 30, { isProgramaticChange: true }]
203
- * ]
204
- * ```
205
- */
206
-
207
- /**
208
- * Represents an array of change tuples.
209
- * Each tuple contains:
210
- * - path: A valid deep key path for the data structure
211
- * - value: The value at that path (properly typed based on the path)
212
- * - meta: Metadata about the change
213
- */
214
- type ArrayOfChanges<DATA, META extends GenericMeta = GenericMeta> = {
215
- [K in DeepKey<DATA>]: [K, DeepValue<DATA, K>, META];
216
- }[DeepKey<DATA>][];
217
-
218
- /**
219
- * Concern type utilities
220
- *
221
- * Generic type helpers for working with concern arrays and extracting
222
- * their return types for proper type-safe concern registration and reading.
223
- */
224
-
225
- /**
226
- * Validation schema interface — the minimal contract for validation.
227
- *
228
- * Any library whose schema exposes `safeParse()` with this shape works
229
- * out of the box (Zod, Valibot, ArkType, or a plain object).
230
- */
231
- interface ValidationSchema<T = unknown> {
232
- safeParse(data: unknown): {
233
- success: true;
234
- data: T;
235
- } | {
236
- success: false;
237
- error: {
238
- errors: {
239
- path: (string | number)[];
240
- message: string;
241
- }[];
242
- };
243
- };
244
- }
245
- /**
246
- * Config type for the validationState concern at a specific path.
247
- *
248
- * Defined here (not in concerns/prebuilts/validation-state.ts) to avoid
249
- * circular imports when used in ConcernRegistrationMap.
250
- *
251
- * Can be a schema for the path's own value type, or a scoped schema
252
- * targeting a different path in the same state.
253
- */
254
- type ValidationStateInput<DATA, PATH extends DeepKey<DATA>> = {
255
- schema: ValidationSchema<DeepValue<DATA, PATH>>;
256
- } | {
257
- [SCOPE in DeepKey<DATA>]: {
258
- scope: SCOPE;
259
- schema: ValidationSchema<DeepValue<DATA, SCOPE>>;
260
- };
261
- }[DeepKey<DATA>];
262
- /**
263
- * Get the appropriate registration config type for a concern at a given path.
264
- *
265
- * - validationState: schema must match DeepValue<DATA, PATH> — path-dependent
266
- * - BoolLogic-based concerns: boolLogic paths are typed against DATA
267
- * - Template-based concerns: fixed { template: string }
268
- * - Custom concerns: fall back to Record<string, unknown>
269
- */
270
- type ConcernConfigFor<C, DATA extends object, PATH extends DeepKey<DATA>> = C extends {
271
- name: 'validationState';
272
- } ? ValidationStateInput<DATA, PATH> : C extends {
273
- evaluate: (props: infer P) => any;
274
- } ? P extends {
275
- boolLogic: any;
276
- } ? {
277
- boolLogic: BoolLogic<DATA>;
278
- } : Omit<P, 'state' | 'path' | 'value'> : Record<string, unknown>;
279
- /**
280
- * Extract the return type from a concern's evaluate function
281
- *
282
- * Used internally to determine what a concern evaluates to,
283
- * enabling type-safe concern result objects.
284
- *
285
- * @example
286
- * ```typescript
287
- * type MyConcern = { evaluate: (...args: any[]) => boolean }
288
- * type Result = ExtractEvaluateReturn<MyConcern> // boolean
289
- * ```
290
- */
291
- type ExtractEvaluateReturn<T> = T extends {
292
- evaluate: (...args: any[]) => infer R;
293
- } ? R : never;
294
- /**
295
- * Dynamically build an evaluated concerns object from a CONCERNS array
296
- *
297
- * Maps each concern's name to its return type, creating a properly typed
298
- * object that represents all concerns that can be registered/evaluated.
299
- *
300
- * @example
301
- * ```typescript
302
- * const concerns = [
303
- * { name: 'validationState', evaluate: () => ({ isError: boolean, errors: [] }) },
304
- * { name: 'tooltip', evaluate: () => string }
305
- * ] as const
306
- *
307
- * type Evaluated = EvaluatedConcerns<typeof concerns>
308
- * // { validationState?: { isError: boolean, errors: [] }, tooltip?: string }
309
- * ```
310
- */
311
- type EvaluatedConcerns<CONCERNS extends readonly any[]> = {
312
- [K in CONCERNS[number] as K['name']]?: ExtractEvaluateReturn<K>;
313
- };
314
- /**
315
- * Maps field paths to per-concern config objects.
316
- *
317
- * When CONCERNS is provided (e.g., from createGenericStore's CONCERNS generic),
318
- * each concern config is type-checked against:
319
- * - The concern's own EXTRA_PROPS (e.g., `{ boolLogic: ... }` for disabledWhen)
320
- * - The path's value type for validationState (schema must match DeepValue<DATA, PATH>)
321
- *
322
- * Without CONCERNS (standalone usage), falls back to loose typing for backward compatibility.
323
- *
324
- * @example
325
- * ```typescript
326
- * // Works with any library implementing ValidationSchema (Zod, Valibot, ArkType, etc.)
327
- * const registration: ConcernRegistrationMap<MyFormState> = {
328
- * email: { validationState: { schema: emailSchema } },
329
- * name: { validationState: { schema: nameSchema } },
330
- * }
331
- * ```
332
- */
333
- type ConcernRegistrationMap<DATA extends object, CONCERNS extends readonly any[] = readonly any[]> = Partial<{
334
- [PATH in DeepKey<DATA>]: Partial<{
335
- [C in CONCERNS[number] as C extends {
336
- name: string;
337
- } ? C['name'] : never]: ConcernConfigFor<C, DATA, PATH>;
338
- }>;
339
- }>;
340
-
341
- /**
342
- * PathsOfSameValue - Type-safe path tuples for side effects
343
- *
344
- * Simple tuple-based API for syncPaths, flipPaths, and aggregations.
345
- *
346
- * @example
347
- * ```typescript
348
- * type State = {
349
- * user: { email: string }
350
- * profile: { email: string }
351
- * count: number
352
- * }
353
- *
354
- * // ✓ Valid: both paths are string
355
- * const sync: SyncPair<State> = ['user.email', 'profile.email']
356
- *
357
- * // ✗ Error: 'user.email' (string) can't sync with 'count' (number)
358
- * const invalid: SyncPair<State> = ['user.email', 'count']
359
- * ```
360
- */
361
-
362
- /**
363
- * Get all paths in DATA that have the same value type as the value at PATH
364
- */
365
- type PathsWithSameValueAs<DATA extends object, PATH extends DeepKey<DATA>> = {
366
- [K in DeepKey<DATA>]: DeepValue<DATA, K> extends DeepValue<DATA, PATH> ? DeepValue<DATA, PATH> extends DeepValue<DATA, K> ? K : never : never;
367
- }[DeepKey<DATA>];
368
- /**
369
- * A tuple of two paths that must have the same value type.
370
- * Format: [path1, path2]
371
- *
372
- * @example
373
- * const pair: SyncPair<State> = ['user.email', 'profile.email']
374
- */
375
- type SyncPair<DATA extends object> = {
376
- [P1 in DeepKey<DATA>]: [P1, PathsWithSameValueAs<DATA, P1>];
377
- }[DeepKey<DATA>];
378
- /**
379
- * A tuple of two paths for flip (alias for SyncPair)
380
- * Format: [path1, path2]
381
- *
382
- * @example
383
- * const pair: FlipPair<State> = ['isActive', 'isInactive']
384
- */
385
- type FlipPair<DATA extends object> = SyncPair<DATA>;
386
- /**
387
- * A tuple for aggregation: [target, source]
388
- * First element (left) is ALWAYS the target (aggregated) path.
389
- * Second element is a source path.
390
- *
391
- * Multiple pairs can point to same target for multi-source aggregation.
392
- *
393
- * @example
394
- * // target <- source (target is always first/left)
395
- * const aggs: AggregationPair<State>[] = [
396
- * ['total', 'price1'],
397
- * ['total', 'price2'],
398
- * ]
399
- */
400
- type AggregationPair<DATA extends object> = SyncPair<DATA>;
401
-
402
- /** Recursively makes all properties required, stripping undefined */
403
- type DeepRequired<T> = {
404
- [K in keyof T]-?: NonNullable<T[K]> extends object ? DeepRequired<NonNullable<T[K]>> : NonNullable<T[K]>;
405
- };
406
- /** Recursively makes all properties optional (allows undefined values) */
407
- type DeepPartial<T> = {
408
- [K in keyof T]?: NonNullable<T[K]> extends object ? DeepPartial<NonNullable<T[K]>> | undefined : T[K] | undefined;
409
- };
410
-
411
- interface BaseConcernProps<STATE, PATH extends string> {
412
- state: STATE;
413
- path: PATH;
414
- value: unknown;
415
- }
416
- interface ConcernType<NAME extends string = string, EXTRA_PROPS = Record<string, unknown>, RETURN_TYPE = unknown> {
417
- name: NAME;
418
- description: string;
419
- /** Evaluated inside effect() - all state accesses are tracked */
420
- evaluate: (props: BaseConcernProps<Record<string, unknown>, string> & EXTRA_PROPS) => RETURN_TYPE;
421
- }
422
- interface ConcernRegistration {
423
- id: string;
424
- path: string;
425
- concernName: string;
426
- concern: ConcernType;
427
- config: Record<string, unknown>;
428
- dispose: () => void;
429
- }
430
-
431
- /**
432
- * Debug Timing Utilities
433
- *
434
- * Provides timing measurement for concerns and listeners
435
- * to detect slow operations during development.
436
- */
437
- type TimingType = 'concerns' | 'listeners' | 'registration';
438
- interface TimingMeta {
439
- path: string;
440
- name: string;
441
- }
442
- interface Timing {
443
- run: <T>(type: TimingType, fn: () => T, meta: TimingMeta) => T;
444
- reportBatch: (type: TimingType) => void;
445
- }
446
-
447
- /**
448
- * WASM Bridge — Thin namespace over Rust/WASM exports.
449
- *
450
- * Uses serde-wasm-bindgen for hot-path functions (processChanges,
451
- * shadowInit) — JS objects cross the boundary directly without JSON
452
- * string intermediary. Registration functions still use JSON strings
453
- * (cold path, simpler).
454
- *
455
- * Loading is handled by `wasm/lifecycle.ts`. After loading, all bridge
456
- * functions are synchronous.
457
- *
458
- * @module wasm/bridge
459
- */
460
-
461
- /** A single state change (input or output). */
462
- interface Change {
463
- path: string;
464
- value: unknown;
465
- }
466
- /** A single dispatch entry with sequential ID and input change references. */
467
- interface DispatchEntry {
468
- dispatch_id: number;
469
- subscriber_id: number;
470
- scope_path: string;
471
- /** Indexes into ProcessResult.changes array. */
472
- input_change_ids: number[];
473
- }
474
- /** A group of dispatches to execute sequentially. */
475
- interface DispatchGroup {
476
- dispatches: DispatchEntry[];
477
- }
478
- /** A target for propagating produced changes from child to parent dispatch. */
479
- interface PropagationTarget {
480
- target_dispatch_id: number;
481
- /** Prefix to prepend to child's relative paths for the target's scope. */
482
- remap_prefix: string;
483
- }
484
- /** Pre-computed execution plan with propagation map. */
485
- interface FullExecutionPlan {
486
- groups: DispatchGroup[];
487
- /** propagation_map[dispatch_id] = targets to forward produced changes to. */
488
- propagation_map: PropagationTarget[][];
489
- }
490
- /** Validator dispatch info for JS-side execution. */
491
- interface ValidatorDispatch {
492
- validator_id: number;
493
- output_path: string;
494
- dependency_values: Record<string, string>;
495
- }
496
- /** Consolidated registration input for side effects (sync, flip, aggregation, clear, listeners). */
497
- interface SideEffectsRegistration {
498
- registration_id: string;
499
- sync_pairs?: [string, string][];
500
- flip_pairs?: [string, string][];
501
- aggregation_pairs?: [string, string][];
502
- clear_paths?: {
503
- triggers: string[];
504
- targets: string[];
505
- }[];
506
- listeners?: {
507
- subscriber_id: number;
508
- topic_path: string;
509
- scope_path: string;
510
- }[];
511
- }
512
- /** Consolidated registration output from side effects registration. */
513
- interface SideEffectsResult {
514
- sync_changes: Change[];
515
- aggregation_changes: Change[];
516
- registered_listener_ids: number[];
517
- }
518
- /** Consolidated registration input for concerns (BoolLogic, validators, and ValueLogic). */
519
- interface ConcernsRegistration {
520
- registration_id: string;
521
- bool_logics?: {
522
- output_path: string;
523
- tree_json: string;
524
- }[];
525
- validators?: {
526
- validator_id: number;
527
- output_path: string;
528
- dependency_paths: string[];
529
- scope: string;
530
- }[];
531
- value_logics?: {
532
- output_path: string;
533
- tree_json: string;
534
- }[];
535
- }
536
- /** Consolidated registration output from concerns registration. */
537
- interface ConcernsResult {
538
- bool_logic_changes: Change[];
539
- registered_logic_ids: number[];
540
- registered_validator_ids: number[];
541
- value_logic_changes: Change[];
542
- registered_value_logic_ids: number[];
543
- }
544
- /** Result of processChanges (Phase 1). */
545
- interface ProcessChangesResult {
546
- state_changes: Change[];
547
- changes: Change[];
548
- validators_to_run: ValidatorDispatch[];
549
- execution_plan: FullExecutionPlan | null;
550
- has_work: boolean;
551
- }
552
- /**
553
- * An isolated WASM pipeline instance.
554
- * Each store gets its own pipeline so multiple Providers don't interfere.
555
- * All methods are pre-bound to the pipeline's ID — consumers never pass IDs.
556
- */
557
- interface WasmPipeline {
558
- readonly id: number;
559
- shadowInit: (state: object) => void;
560
- shadowDump: () => unknown;
561
- processChanges: (changes: Change[]) => ProcessChangesResult;
562
- pipelineFinalize: (jsChanges: Change[]) => {
563
- state_changes: Change[];
564
- };
565
- registerSideEffects: (reg: SideEffectsRegistration) => SideEffectsResult;
566
- unregisterSideEffects: (registrationId: string) => void;
567
- registerConcerns: (reg: ConcernsRegistration) => ConcernsResult;
568
- unregisterConcerns: (registrationId: string) => void;
569
- registerBoolLogic: (outputPath: string, tree: unknown) => number;
570
- unregisterBoolLogic: (logicId: number) => void;
571
- pipelineReset: () => void;
572
- destroy: () => void;
573
- /** Per-instance storage for validation schemas (can't cross WASM boundary). */
574
- validatorSchemas: Map<number, ValidationSchema>;
575
- }
576
-
577
- /**
578
- * PathGroups Data Structure
579
- *
580
- * A custom data structure that provides O(1) connected component lookups
581
- * instead of O(V+E) recomputation on every change like graphology's connectedComponents.
582
- *
583
- * When wasmGraphType is set ('sync' | 'flip'), addEdge/removeEdge automatically
584
- * mirror registrations to WASM bridge for pipeline processing.
585
- *
586
- * Operations complexity:
587
- * - getAllGroups(): O(G) where G is number of groups (typically small)
588
- * - getGroupPaths(path): O(1) lookup
589
- * - addEdge(p1, p2): O(n) where n is smaller group size (merge)
590
- * - removeEdge(p1, p2): O(n) for affected component
591
- * - hasPath(path): O(1)
592
- * - hasEdge(p1, p2): O(1)
593
- */
594
- /** Graph type for WASM mirroring. When set, addEdge/removeEdge mirror to WASM. */
595
- type WasmGraphType = 'sync' | 'flip';
596
- /**
597
- * PathGroups maintains connected components with O(1) lookups.
598
- *
599
- * Internal structure:
600
- * - pathToGroup: Maps each path to its group ID
601
- * - groupToPaths: Maps each group ID to the set of paths in that group
602
- * - edges: Set of edge keys for edge existence checks and proper removal
603
- * - adjacency: Maps each path to its direct neighbors (for split detection on removal)
604
- * - nextGroupId: Counter for generating unique group IDs
605
- */
606
- interface PathGroups {
607
- pathToGroup: Map<string, number>;
608
- groupToPaths: Map<number, Set<string>>;
609
- edges: Set<string>;
610
- adjacency: Map<string, Set<string>>;
611
- nextGroupId: number;
612
- wasmGraphType?: WasmGraphType;
613
- }
614
-
615
- /**
616
- * Graph Type Definitions
617
- *
618
- * Type aliases for the PathGroups data structure used in sync and flip operations.
619
- * These aliases maintain backward compatibility with the previous graphology-based API.
620
- */
621
-
622
- /**
623
- * Sync graph: Paths that must have synchronized values
624
- * Type alias for PathGroups - maintains backward compatibility
625
- */
626
- type SyncGraph = PathGroups;
627
- /**
628
- * Flip graph: Paths with inverted boolean values
629
- * Type alias for PathGroups - maintains backward compatibility
630
- */
631
- type FlipGraph = PathGroups;
632
-
633
- /**
634
- * Core Store Types
635
- *
636
- * Foundational type definitions for the store instance.
637
- * These types are used throughout the library.
638
- */
639
-
640
- /**
641
- * Debug configuration for development tooling
642
- */
643
- interface DebugConfig {
644
- /** Enable timing measurement for concerns and listeners */
645
- timing?: boolean;
646
- /** Threshold in milliseconds for slow operation warnings (default: 5ms) */
647
- timingThreshold?: number;
648
- /** Enable tracking of processChanges calls and applied changes for testing/debugging */
649
- track?: boolean;
650
- }
651
- /**
652
- * A single recorded processChanges invocation
653
- */
654
- interface DebugTrackEntry {
655
- /** Input changes passed to processChanges as [path, value, meta] tuples */
656
- input: [string, unknown, unknown][];
657
- /** Changes actually applied to state proxy */
658
- applied: {
659
- path: string;
660
- value: unknown;
661
- }[];
662
- /** Changes applied to _concerns proxy */
663
- appliedConcerns: {
664
- path: string;
665
- value: unknown;
666
- }[];
667
- /** Timestamp of the call */
668
- timestamp: number;
669
- }
670
- /**
671
- * Debug tracking data exposed on StoreInstance when debug.track is enabled.
672
- * Provides an append-only log of all processChanges calls and their effects.
673
- */
674
- interface DebugTrack {
675
- /** All recorded processChanges calls (append-only) */
676
- calls: DebugTrackEntry[];
677
- /** Reset all tracking data */
678
- clear: () => void;
679
- }
680
- interface StoreConfig {
681
- /** Error storage path (default: "_errors") */
682
- errorStorePath?: string;
683
- /** Max iterations for change processing (default: 100) */
684
- maxIterations?: number;
685
- /** Debug configuration for development tooling */
686
- debug?: DebugConfig;
687
- /** Use legacy TypeScript implementation instead of WASM (default: false) */
688
- useLegacyImplementation?: boolean;
689
- }
690
- interface ProviderProps<DATA extends object> {
691
- initialState: DATA;
692
- children: ReactNode;
693
- }
694
- interface Aggregation {
695
- id?: string;
696
- targetPath: string;
697
- sourcePaths: string[];
698
- }
699
- /** Reacts to scoped changes - receives relative paths and scoped state. Only fires for NESTED paths, not the path itself. */
700
- type OnStateListener<DATA extends object = object, SUB_STATE = DATA, META extends GenericMeta = GenericMeta> = (changes: ArrayOfChanges<SUB_STATE, META>, state: SUB_STATE) => ArrayOfChanges<DATA, META> | undefined;
701
- /**
702
- * Listener registration with path (what to watch) and scope (how to present data)
703
- *
704
- * @example
705
- * ```typescript
706
- * // Watch user.profile.name, get full state
707
- * {
708
- * path: 'user.profile.name',
709
- * scope: null,
710
- * fn: (changes, state) => {
711
- * // changes: [['user.profile.name', 'Alice', {}]] - FULL path
712
- * // state: full DATA object
713
- * }
714
- * }
715
- *
716
- * // Watch user.profile.*, get scoped state
717
- * {
718
- * path: 'user.profile',
719
- * scope: 'user.profile',
720
- * fn: (changes, state) => {
721
- * // changes: [['name', 'Alice', {}]] - RELATIVE to scope
722
- * // state: user.profile object
723
- * }
724
- * }
725
- *
726
- * // Watch deep path, get parent scope
727
- * {
728
- * path: 'p.123.g.abc.data.strike',
729
- * scope: 'p.123.g.abc',
730
- * fn: (changes, state) => {
731
- * // changes: [['data.strike', value, {}]] - relative to scope
732
- * // state: p.123.g.abc object
733
- * }
734
- * }
735
- * ```
736
- */
737
- interface ListenerRegistration<DATA extends object = object, META extends GenericMeta = GenericMeta> {
738
- /**
739
- * Path to watch - only changes under this path will trigger the listener
740
- * null = watch all top-level paths
741
- */
742
- path: DeepKey<DATA> | null;
743
- /**
744
- * Scope for state and changes presentation
745
- * - If null: state is full DATA, changes use FULL paths
746
- * - If set: state is value at scope, changes use paths RELATIVE to scope
747
- *
748
- * Note: Changes are filtered based on `path`, even when scope is null
749
- */
750
- scope: DeepKey<DATA> | null;
751
- fn: OnStateListener<DATA, any, META>;
752
- }
753
- interface ListenerHandlerRef {
754
- scope: string | null;
755
- fn: (...args: unknown[]) => unknown;
756
- }
757
- interface SideEffectGraphs<DATA extends object = object, META extends GenericMeta = GenericMeta> {
758
- sync: SyncGraph;
759
- flip: FlipGraph;
760
- listeners: Map<string, ListenerRegistration<DATA, META>[]>;
761
- sortedListenerPaths: string[];
762
- /** O(1) lookup: subscriber_id -> handler ref. Populated by registerListener. */
763
- listenerHandlers: Map<number, ListenerHandlerRef>;
764
- }
765
- interface Registrations {
766
- concerns: Map<string, ConcernType[]>;
767
- effectCleanups: Set<() => void>;
768
- sideEffectCleanups: Map<string, () => void>;
769
- aggregations: Map<string, Aggregation[]>;
770
- }
771
- interface ProcessingState<DATA extends object = object, META extends GenericMeta = GenericMeta> {
772
- queue: ArrayOfChanges<DATA, META>;
773
- }
774
- /** Internal store state (NOT tracked - wrapped in ref()) */
775
- interface InternalState<DATA extends object = object, META extends GenericMeta = GenericMeta> {
776
- graphs: SideEffectGraphs<DATA, META>;
777
- registrations: Registrations;
778
- processing: ProcessingState<DATA, META>;
779
- timing: Timing;
780
- config: DeepRequired<StoreConfig>;
781
- /** Per-store WASM pipeline instance (null when using legacy implementation). */
782
- pipeline: WasmPipeline | null;
783
- /** Pending deferred destroy timer — cancelled on StrictMode re-mount. */
784
- _destroyTimer?: ReturnType<typeof setTimeout> | undefined;
785
- }
786
- type ConcernValues = Record<string, Record<string, unknown>>;
787
- /** Two-proxy pattern: state and _concerns are independent to prevent infinite loops */
788
- interface StoreInstance<DATA extends object, META extends GenericMeta = GenericMeta> {
789
- state: DATA;
790
- _concerns: ConcernValues;
791
- _internal: InternalState<DATA, META>;
792
- /** Debug tracking data, only populated when debug.track is enabled */
793
- _debug: DebugTrack | null;
794
- }
795
-
796
- interface ValidationError {
797
- field?: string;
798
- message: string;
799
- }
800
- interface ValidationStateResult {
801
- isError: boolean;
802
- errors: ValidationError[];
803
- }
804
- interface ValidationStateConcern {
805
- name: 'validationState';
806
- description: string;
807
- evaluate: <SUB_STATE, PATH extends DeepKey<SUB_STATE>>(props: BaseConcernProps<SUB_STATE, PATH> & ValidationStateInput<SUB_STATE, PATH>) => ValidationStateResult;
808
- }
809
- declare const validationState: ValidationStateConcern;
810
-
811
- /**
812
- * Concern lookup by name
813
- *
814
- * @param name The concern name to look up
815
- * @param concerns Optional array of concerns to search (defaults to prebuilts)
816
- * @returns The concern definition, or undefined if not found
817
- */
818
- declare const findConcern: (name: string, concerns?: readonly any[]) => ConcernType | undefined;
819
- /**
820
- * Default concerns provided by apex-state
821
- */
822
- declare const defaultConcerns: readonly [ValidationStateConcern, ConcernType<"disabledWhen", {
823
- boolLogic: BoolLogic<any>;
824
- }, boolean>, ConcernType<"readonlyWhen", {
825
- boolLogic: BoolLogic<any>;
826
- }, boolean>, ConcernType<"visibleWhen", {
827
- boolLogic: BoolLogic<any>;
828
- }, boolean>, ConcernType<"dynamicTooltip", {
829
- template: string;
830
- }, string>, ConcernType<"dynamicLabel", {
831
- template: string;
832
- }, string>, ConcernType<"dynamicPlaceholder", {
833
- template: string;
834
- }, string>];
835
-
836
- declare const disabledWhen: ConcernType<'disabledWhen', {
837
- boolLogic: BoolLogic<any>;
838
- }, boolean>;
839
-
840
- /**
841
- * Read-only condition concern
842
- *
843
- * Evaluates a boolean logic expression to determine if a field should be read-only.
844
- * Automatically tracks all state paths accessed in the condition.
845
- *
846
- * Returns true if read-only, false if editable.
847
- *
848
- * @example
849
- * ```typescript
850
- * store.useConcerns('my-concerns', {
851
- * 'productId': {
852
- * readonlyWhen: { boolLogic: { IS_EQUAL: ['order.status', 'completed'] } }
853
- * }
854
- * })
855
- * // Returns: true if order status is 'completed', false otherwise
856
- * ```
857
- */
858
-
859
- declare const readonlyWhen: ConcernType<'readonlyWhen', {
860
- boolLogic: BoolLogic<any>;
861
- }, boolean>;
862
-
863
- /**
864
- * Visibility condition concern
865
- *
866
- * Evaluates a boolean logic expression to determine if a field should be visible.
867
- * Automatically tracks all state paths accessed in the condition.
868
- *
869
- * Returns true if visible, false if hidden.
870
- *
871
- * @example
872
- * ```typescript
873
- * store.useConcerns('my-concerns', {
874
- * 'advancedOptions': {
875
- * visibleWhen: { boolLogic: { IS_EQUAL: ['settings.mode', 'advanced'] } }
876
- * }
877
- * })
878
- * // Returns: true if settings.mode is 'advanced', false otherwise
879
- * ```
880
- */
881
-
882
- declare const visibleWhen: ConcernType<'visibleWhen', {
883
- boolLogic: BoolLogic<any>;
884
- }, boolean>;
885
-
886
- /**
887
- * Dynamic label template concern
888
- *
889
- * Interpolates a template string with values from state.
890
- * Automatically tracks all state paths referenced in the template.
891
- *
892
- * Returns the interpolated string.
893
- *
894
- * @example
895
- * ```typescript
896
- * store.useConcerns('my-concerns', {
897
- * 'priceField': {
898
- * dynamicLabel: { template: "Price: ${{product.price}}" }
899
- * }
900
- * })
901
- * // Result: "Price: $99.99"
902
- * ```
903
- */
904
-
905
- declare const dynamicLabel: ConcernType<'dynamicLabel', {
906
- template: string;
907
- }, string>;
908
-
909
- /**
910
- * Dynamic placeholder template concern
911
- *
912
- * Interpolates a template string with values from state.
913
- * Automatically tracks all state paths referenced in the template.
914
- *
915
- * Returns the interpolated string.
916
- *
917
- * @example
918
- * ```typescript
919
- * store.useConcerns('my-concerns', {
920
- * 'inputField': {
921
- * dynamicPlaceholder: { template: "Enter {{field.name}}" }
922
- * }
923
- * })
924
- * // Result: "Enter email address"
925
- * ```
926
- */
927
-
928
- declare const dynamicPlaceholder: ConcernType<'dynamicPlaceholder', {
929
- template: string;
930
- }, string>;
931
-
932
- /**
933
- * Dynamic tooltip template concern
934
- *
935
- * Interpolates a template string with values from state.
936
- * Automatically tracks all state paths referenced in the template.
937
- *
938
- * Returns the interpolated string.
939
- *
940
- * @example
941
- * ```typescript
942
- * store.useConcerns('my-concerns', {
943
- * 'strikePrice': {
944
- * dynamicTooltip: { template: "Strike at {{market.spot}}" }
945
- * }
946
- * })
947
- * // Result: "Strike at 105"
948
- * ```
949
- */
950
-
951
- declare const dynamicTooltip: ConcernType<'dynamicTooltip', {
952
- template: string;
953
- }, string>;
954
-
955
- /**
956
- * All pre-built concerns as a tuple (for use with findConcern)
957
- */
958
- declare const prebuilts: readonly [ValidationStateConcern, ConcernType<"disabledWhen", {
959
- boolLogic: BoolLogic<any>;
960
- }, boolean>, ConcernType<"readonlyWhen", {
961
- boolLogic: BoolLogic<any>;
962
- }, boolean>, ConcernType<"visibleWhen", {
963
- boolLogic: BoolLogic<any>;
964
- }, boolean>, ConcernType<"dynamicTooltip", {
965
- template: string;
966
- }, string>, ConcernType<"dynamicLabel", {
967
- template: string;
968
- }, string>, ConcernType<"dynamicPlaceholder", {
969
- template: string;
970
- }, string>];
971
- /**
972
- * Namespace style access for pre-builts
973
- */
974
- declare const prebuiltsNamespace: {
975
- validationState: ValidationStateConcern;
976
- disabledWhen: ConcernType<"disabledWhen", {
977
- boolLogic: BoolLogic<any>;
978
- }, boolean>;
979
- readonlyWhen: ConcernType<"readonlyWhen", {
980
- boolLogic: BoolLogic<any>;
981
- }, boolean>;
982
- visibleWhen: ConcernType<"visibleWhen", {
983
- boolLogic: BoolLogic<any>;
984
- }, boolean>;
985
- dynamicTooltip: ConcernType<"dynamicTooltip", {
986
- template: string;
987
- }, string>;
988
- dynamicLabel: ConcernType<"dynamicLabel", {
989
- template: string;
990
- }, string>;
991
- dynamicPlaceholder: ConcernType<"dynamicPlaceholder", {
992
- template: string;
993
- }, string>;
994
- };
995
-
996
- type index_ValidationError = ValidationError;
997
- type index_ValidationStateResult = ValidationStateResult;
998
- declare const index_disabledWhen: typeof disabledWhen;
999
- declare const index_dynamicLabel: typeof dynamicLabel;
1000
- declare const index_dynamicPlaceholder: typeof dynamicPlaceholder;
1001
- declare const index_dynamicTooltip: typeof dynamicTooltip;
1002
- declare const index_prebuilts: typeof prebuilts;
1003
- declare const index_prebuiltsNamespace: typeof prebuiltsNamespace;
1004
- declare const index_readonlyWhen: typeof readonlyWhen;
1005
- declare const index_validationState: typeof validationState;
1006
- declare const index_visibleWhen: typeof visibleWhen;
1007
- declare namespace index {
1008
- export { type index_ValidationError as ValidationError, type index_ValidationStateResult as ValidationStateResult, index_disabledWhen as disabledWhen, index_dynamicLabel as dynamicLabel, index_dynamicPlaceholder as dynamicPlaceholder, index_dynamicTooltip as dynamicTooltip, index_prebuilts as prebuilts, index_prebuiltsNamespace as prebuiltsNamespace, index_readonlyWhen as readonlyWhen, index_validationState as validationState, index_visibleWhen as visibleWhen };
1009
- }
1010
-
1011
- /**
1012
- * SideEffects type definition
1013
- *
1014
- * Configuration types for side effects passed to useSideEffects hook.
1015
- * Simple tuple-based API: [path1, path2]
1016
- */
1017
-
1018
- /**
1019
- * Clear path rule - "when trigger paths change, set target paths to null"
1020
- *
1021
- * Format: [triggers[], targets[], options?]
1022
- * - triggers: paths that activate the rule
1023
- * - targets: paths to set to null
1024
- * - expandMatch: if true, [*] in targets expands to ALL keys (not just matched key)
1025
- */
1026
- type ClearPathRule<DATA extends object> = [
1027
- DeepKey<DATA>[],
1028
- DeepKey<DATA>[],
1029
- {
1030
- expandMatch?: boolean;
1031
- }?
1032
- ];
1033
- /**
1034
- * Side effects configuration for useSideEffects hook
1035
- *
1036
- * @example
1037
- * ```typescript
1038
- * useSideEffects('my-effects', {
1039
- * syncPaths: [
1040
- * ['user.email', 'profile.email'],
1041
- * ],
1042
- * flipPaths: [
1043
- * ['isActive', 'isInactive'],
1044
- * ],
1045
- * aggregations: [
1046
- * ['total', 'price1'], // target <- source (target always first)
1047
- * ['total', 'price2'],
1048
- * ],
1049
- * listeners: [
1050
- * {
1051
- * path: 'user.profile', // Watch user.profile.* changes
1052
- * scope: 'user.profile', // Receive scoped state
1053
- * fn: (changes, state) => {
1054
- * // changes: [['name', 'Alice', {}]] // RELATIVE to scope
1055
- * // state: user.profile sub-object
1056
- * return [['status', 'updated', {}]] // Return FULL paths
1057
- * }
1058
- * },
1059
- * {
1060
- * path: 'user.profile.name', // Watch specific path
1061
- * scope: null, // Get full state
1062
- * fn: (changes, state) => {
1063
- * // changes: [['user.profile.name', 'Alice', {}]] // FULL path
1064
- * // state: full DATA object
1065
- * return undefined
1066
- * }
1067
- * },
1068
- * {
1069
- * path: 'p.123.g.abc.data.strike', // Watch deep path
1070
- * scope: 'p.123.g.abc', // Get parent scope
1071
- * fn: (changes, state) => {
1072
- * // changes: [['data.strike', value, {}]] // RELATIVE to scope
1073
- * // state: p.123.g.abc object
1074
- * return [['some.value.elsewhere', computed, {}]] // FULL path
1075
- * }
1076
- * }
1077
- * ]
1078
- * })
1079
- * ```
1080
- */
1081
- interface SideEffects<DATA extends object, META extends GenericMeta = GenericMeta> {
1082
- /**
1083
- * Sync paths - keeps specified paths synchronized
1084
- * Format: [path1, path2] - both paths stay in sync
1085
- */
1086
- syncPaths?: SyncPair<DATA>[];
1087
- /**
1088
- * Flip paths - keeps specified paths with opposite values
1089
- * Format: [path1, path2] - paths have inverse boolean values
1090
- */
1091
- flipPaths?: FlipPair<DATA>[];
1092
- /**
1093
- * Aggregations - aggregates sources into target
1094
- * Format: [target, source] - target is ALWAYS first (left)
1095
- * Multiple pairs can point to same target for multi-source aggregation
1096
- */
1097
- aggregations?: AggregationPair<DATA>[];
1098
- /**
1099
- * Clear paths - "when X changes, set Y to null"
1100
- * Format: [triggers[], targets[], { expandMatch?: boolean }?]
1101
- * - Default: [*] in target correlates with trigger's [*] (same key)
1102
- * - expandMatch: true → [*] in target expands to ALL keys
1103
- */
1104
- clearPaths?: ClearPathRule<DATA>[];
1105
- /**
1106
- * Listeners - react to state changes with scoped state
1107
- */
1108
- listeners?: ListenerRegistration<DATA, META>[];
1109
- }
1110
-
1111
- declare const createGenericStore: <DATA extends object, META extends GenericMeta = GenericMeta, CONCERNS extends readonly ConcernType<string, any, any>[] = typeof defaultConcerns>(config?: StoreConfig) => {
1112
- Provider: {
1113
- (props: ProviderProps<DATA>): react_jsx_runtime.JSX.Element;
1114
- displayName: string;
1115
- };
1116
- useFieldStore: <P extends DeepKey<DATA>>(path: P) => {
1117
- value: DeepValue<DATA, P>;
1118
- setValue: (newValue: DeepValue<DATA, P>, meta?: META) => void;
1119
- } & Record<string, unknown>;
1120
- useStore: <P extends DeepKey<DATA>>(path: P) => [DeepValue<DATA, P>, (value: DeepValue<DATA, P>, meta?: META) => void];
1121
- useJitStore: () => {
1122
- proxyValue: DATA;
1123
- setChanges: (changes: ArrayOfChanges<DATA, META>) => void;
1124
- getState: () => DATA;
1125
- };
1126
- useSideEffects: (id: string, effects: SideEffects<DATA, META>) => void;
1127
- useConcerns: <CUSTOM extends readonly ConcernType<string, any, any>[] = readonly []>(id: string, registration: ConcernRegistrationMap<DATA, readonly [...CONCERNS, ...CUSTOM]>, customConcerns?: CUSTOM) => void;
1128
- withConcerns: <SELECTION extends Partial<Record<Extract<CONCERNS[number], {
1129
- name: string;
1130
- }>["name"], boolean>>>(selection: SELECTION) => {
1131
- useFieldStore: <P extends DeepKey<DATA>>(path: P) => {
1132
- value: DATA extends readonly any[] ? DATA[number] : P extends `${infer First}.${infer Rest}` ? First extends keyof DATA ? DeepValue<DATA[First], Rest> : string extends keyof DATA ? First extends "[*]" ? DeepValue<DATA[keyof DATA & string], Rest> : unknown : unknown : P extends "[*]" ? string extends keyof DATA ? DATA[keyof DATA & string] : unknown : P extends keyof DATA ? DATA[P] : unknown;
1133
- setValue: (newValue: DATA extends readonly any[] ? DATA[number] : P extends `${infer First}.${infer Rest}` ? First extends keyof DATA ? DeepValue<DATA[First], Rest> : string extends keyof DATA ? First extends "[*]" ? DeepValue<DATA[keyof DATA & string], Rest> : unknown : unknown : P extends "[*]" ? string extends keyof DATA ? DATA[keyof DATA & string] : unknown : P extends keyof DATA ? DATA[P] : unknown, meta?: META) => void;
1134
- } & { [K in keyof SELECTION as SELECTION[K] extends true ? K : never]?: K extends keyof EvaluatedConcerns<CONCERNS> ? EvaluatedConcerns<CONCERNS>[K] : never; };
1135
- };
1136
- };
1137
- /** Return type of createGenericStore — used by testing mock for 1:1 type safety */
1138
- type GenericStoreApi<DATA extends object, META extends GenericMeta = GenericMeta, CONCERNS extends readonly ConcernType<string, any, any>[] = typeof defaultConcerns> = ReturnType<typeof createGenericStore<DATA, META, CONCERNS>>;
1139
-
1140
- /**
1141
- * Minimal field interface that useBufferedField accepts
1142
- */
1143
- interface FieldInput$2<T> {
1144
- value: T;
1145
- setValue: (v: T) => void;
1146
- }
1147
- /**
1148
- * Extended interface with buffering capabilities
1149
- */
1150
- interface BufferedField<T> extends FieldInput$2<T> {
1151
- commit: () => void;
1152
- cancel: () => void;
1153
- isDirty: boolean;
1154
- }
1155
- /**
1156
- * Adds buffered editing to any field hook.
1157
- * Local changes are held until explicitly committed or cancelled.
1158
- *
1159
- * @param field - Field hook with { value, setValue }
1160
- * @returns Buffered field with commit/cancel/isDirty
1161
- *
1162
- * @example
1163
- * ```typescript
1164
- * const field = useFieldStore('user.name')
1165
- * const buffered = useBufferedField(field)
1166
- *
1167
- * // User types - updates local only
1168
- * buffered.setValue('new value')
1169
- *
1170
- * // Enter/Tab - commit to store
1171
- * buffered.commit()
1172
- *
1173
- * // Esc - revert to stored value
1174
- * buffered.cancel()
1175
- *
1176
- * // Check if user has unsaved changes
1177
- * if (buffered.isDirty) { ... }
1178
- * ```
1179
- */
1180
- declare const useBufferedField: <T>(field: FieldInput$2<T>) => BufferedField<T>;
1181
-
1182
- /**
1183
- * Option for keyboard selection
1184
- */
1185
- interface SelectOption<T> {
1186
- value: T;
1187
- label: string;
1188
- }
1189
- /**
1190
- * Configuration for keyboard select behavior
1191
- */
1192
- interface KeyboardSelectConfig<T> {
1193
- /** Available options to select from */
1194
- options: SelectOption<T>[];
1195
- /** Time window to accumulate keystrokes (ms). Default: 500 */
1196
- debounceMs?: number;
1197
- /** Match from start of label only. Default: true */
1198
- matchFromStart?: boolean;
1199
- }
1200
- /**
1201
- * Minimal field interface that useKeyboardSelect accepts
1202
- */
1203
- interface FieldInput$1<T> {
1204
- value: T;
1205
- setValue: (v: T) => void;
1206
- }
1207
- /**
1208
- * Adds keyboard-driven selection to any field hook.
1209
- * Typing letters auto-selects matching options.
1210
- *
1211
- * @param field - Field hook with { value, setValue, ...rest }
1212
- * @param config - Options and behavior configuration
1213
- * @returns Field with onKeyDown handler added
1214
- *
1215
- * @example
1216
- * ```typescript
1217
- * const field = useFieldStore('user.country')
1218
- * const { onKeyDown, ...rest } = useKeyboardSelect(field, {
1219
- * options: [
1220
- * { value: 'us', label: 'United States' },
1221
- * { value: 'uk', label: 'United Kingdom' },
1222
- * { value: 'ca', label: 'Canada' },
1223
- * ]
1224
- * })
1225
- *
1226
- * // User types "u" -> selects "United States"
1227
- * // User types "un" quickly -> still "United States"
1228
- * // User types "c" -> selects "Canada"
1229
- *
1230
- * <input onKeyDown={onKeyDown} {...rest} />
1231
- * ```
1232
- */
1233
- declare const useKeyboardSelect: <T, TField extends FieldInput$1<T>>(field: TField, config: KeyboardSelectConfig<T>) => TField & {
1234
- onKeyDown: (e: React.KeyboardEvent) => void;
1235
- };
1236
-
1237
- /**
1238
- * Minimal field interface for throttling
1239
- * Supports setValue with optional additional arguments (e.g., meta)
1240
- */
1241
- interface ThrottleFieldInput<T, Args extends unknown[] = unknown[]> {
1242
- value: T;
1243
- setValue: (v: T, ...args: Args) => void;
1244
- }
1245
- /**
1246
- * Throttle configuration
1247
- */
1248
- interface ThrottleConfig {
1249
- /** Minimum milliseconds between setValue calls to the underlying field */
1250
- ms: number;
1251
- }
1252
- /**
1253
- * Adds throttling to any field hook.
1254
- * First setValue executes immediately, subsequent calls are rate-limited.
1255
- * Last value wins when multiple calls occur within the throttle window.
1256
- * Preserves the full setValue signature including additional arguments like meta.
1257
- *
1258
- * @param field - Field hook with { value, setValue, ...rest }
1259
- * @param config - Throttle configuration { ms }
1260
- * @returns Field with throttled setValue, plus any passthrough props
1261
- *
1262
- * @example
1263
- * ```typescript
1264
- * const field = useFieldStore('spotPrice')
1265
- * const throttled = useThrottledField(field, { ms: 100 })
1266
- *
1267
- * // Rapid updates from WebSocket
1268
- * throttled.setValue(1.234) // Immediate
1269
- * throttled.setValue(1.235) // Buffered
1270
- * throttled.setValue(1.236) // Buffered (replaces 1.235)
1271
- * // After 100ms: 1.236 is applied
1272
- * ```
1273
- *
1274
- * @example
1275
- * ```typescript
1276
- * // With meta argument
1277
- * const field = useFieldStore('price')
1278
- * const throttled = useThrottledField(field, { ms: 100 })
1279
- * throttled.setValue(42, { source: 'websocket' })
1280
- * ```
1281
- *
1282
- * @example
1283
- * ```typescript
1284
- * // Composable with other wrappers
1285
- * const field = useFieldStore('price')
1286
- * const transformed = useTransformedField(field, {
1287
- * to: (cents) => cents / 100,
1288
- * from: (dollars) => Math.round(dollars * 100)
1289
- * })
1290
- * const throttled = useThrottledField(transformed, { ms: 50 })
1291
- * ```
1292
- */
1293
- declare const useThrottledField: <T, Args extends unknown[] = unknown[], TField extends ThrottleFieldInput<T, Args> = ThrottleFieldInput<T, Args>>(field: TField, config: ThrottleConfig) => TField;
1294
-
1295
- /**
1296
- * Transform configuration for field values
1297
- */
1298
- interface TransformConfig<TStored, TDisplay> {
1299
- /** Transform from stored value to display value */
1300
- to: (stored: TStored) => TDisplay;
1301
- /** Transform from display value to stored value */
1302
- from: (display: TDisplay) => TStored;
1303
- }
1304
- /**
1305
- * Minimal field interface that useTransformedField accepts
1306
- */
1307
- interface FieldInput<T> {
1308
- value: T;
1309
- setValue: (v: T) => void;
1310
- }
1311
- /**
1312
- * Adds value transformation to any field hook.
1313
- * Converts between storage format and display format.
1314
- * Passes through any additional properties from the input field.
1315
- *
1316
- * @param field - Field hook with { value, setValue, ...rest }
1317
- * @param config - Transform functions { to, from }
1318
- * @returns Field with transformed types, plus any passthrough props
1319
- *
1320
- * @example
1321
- * ```typescript
1322
- * const field = useFieldStore('user.birthdate')
1323
- * const formatted = useTransformedField(field, {
1324
- * to: (iso) => format(new Date(iso), 'MM/dd/yyyy'),
1325
- * from: (display) => parse(display, 'MM/dd/yyyy').toISOString()
1326
- * })
1327
- *
1328
- * // formatted.value is "01/15/2024"
1329
- * // formatted.setValue("01/20/2024") stores ISO string
1330
- * ```
1331
- *
1332
- * @example
1333
- * ```typescript
1334
- * // Works with buffered fields - passes through commit/cancel/isDirty
1335
- * const field = useFieldStore('price')
1336
- * const buffered = useBufferedField(field)
1337
- * const formatted = useTransformedField(buffered, {
1338
- * to: (cents) => (cents / 100).toFixed(2),
1339
- * from: (dollars) => Math.round(parseFloat(dollars) * 100)
1340
- * })
1341
- *
1342
- * formatted.setValue("15.99") // local only
1343
- * formatted.commit() // stores 1599
1344
- * ```
1345
- */
1346
- declare const useTransformedField: <TStored, TDisplay, TField extends FieldInput<TStored>>(field: TField, config: TransformConfig<TStored, TDisplay>) => Omit<TField, "value" | "setValue"> & FieldInput<TDisplay>;
1347
-
1348
- /** Legacy JS implementation - uses JS graph structure */
1349
- declare const registerFlipPair: <DATA extends object, META extends GenericMeta = GenericMeta>(store: StoreInstance<DATA, META>, path1: string & {}, path2: string & {}) => (() => void);
1350
-
1351
- /** Legacy JS implementation - uses JS listener maps and sorted paths */
1352
- declare const registerListenerLegacy: <DATA extends object, META extends GenericMeta = GenericMeta>(store: StoreInstance<DATA, META>, registration: ListenerRegistration<DATA, META>) => (() => void);
1353
-
1354
- /**
1355
- * Legacy batch version of registerSyncPair. Adds all edges first, then computes
1356
- * initial sync changes across all final groups and calls processChanges once.
1357
- * This avoids cascading effect re-evaluations when registering many pairs.
1358
- */
1359
- declare const registerSyncPairsBatch: <DATA extends object, META extends GenericMeta = GenericMeta>(store: StoreInstance<DATA, META>, pairs: [string & {}, string & {}][]) => (() => void);
1360
-
1361
- declare const registerSideEffects: <DATA extends object, META extends GenericMeta = GenericMeta>(store: StoreInstance<DATA, META>, id: string, effects: SideEffects<DATA, META>) => (() => void);
1362
-
1363
- declare const evaluateBoolLogic: <STATE extends object>(logic: BoolLogic<STATE>, state: STATE) => boolean;
1364
-
1365
- /**
1366
- * Template string interpolation utilities
1367
- *
1368
- * Core utility for interpolating state values into template strings.
1369
- * Used by concerns and side effects for dynamic text generation.
1370
- */
1371
- /**
1372
- * Extract all {{path}} placeholders from a template string
1373
- *
1374
- * @param template The template string with {{path}} placeholders
1375
- * @returns Array of path strings found in the template
1376
- *
1377
- * @example
1378
- * extractPlaceholders("Hello {{user.name}}, you have {{count}} messages")
1379
- * // ["user.name", "count"]
1380
- */
1381
- declare const extractPlaceholders: (template: string) => string[];
1382
- /**
1383
- * Interpolate {{path}} placeholders with values from state
1384
- *
1385
- * Replaces {{path.to.value}} with actual values from state.
1386
- * Only replaces if value is a string, number, or boolean.
1387
- * Missing/null/undefined/object values leave the original {{path}} for debugging.
1388
- *
1389
- * @param template The template string with {{path}} placeholders
1390
- * @param state The state object to read values from
1391
- * @returns The interpolated string
1392
- *
1393
- * @example
1394
- * interpolateTemplate("Value is {{market.spot}}", state)
1395
- * // "Value is 105"
1396
- *
1397
- * @example
1398
- * interpolateTemplate("Hello {{user.name}}, missing: {{invalid.path}}", state)
1399
- * // "Hello Alice, missing: {{invalid.path}}"
1400
- */
1401
- declare const interpolateTemplate: <STATE extends object>(template: string, state: STATE) => string;
1402
-
1403
- /**
1404
- * Deep access utilities for safe nested object access
1405
- *
1406
- * Uses native Reflect for reads (~2x faster) and writes (~3x faster) vs lodash.
1407
- * Maintains valtio reactivity when setting values.
1408
- */
1409
-
1410
- /**
1411
- * Unified namespace for dot notation path operations
1412
- *
1413
- * Provides type-safe and unsafe variants for working with nested objects
1414
- * using dot notation paths (e.g., 'user.address.city')
1415
- */
1416
- declare const dot: {
1417
- get: <T extends object, P extends DeepKey<T>>(obj: T, path: P) => DeepValue<T, P>;
1418
- get__unsafe: <P extends string>(obj: unknown, path: P) => unknown;
1419
- set: <T extends object, P extends DeepKey<T>>(obj: T, path: P, value: DeepValue<T, P>) => void;
1420
- set__unsafe: <T extends object, P extends string>(obj: T, path: P, value: unknown) => void;
1421
- has: <T extends object, P extends DeepKey<T>>(obj: T, path: P) => boolean;
1422
- same: <T extends object, P extends string>(obj: T, ...paths: P[]) => boolean;
1423
- };
1424
-
1425
- /**
1426
- * Hash key utilities
1427
- *
1428
- * Utilities for working with hash key notation in Record-based paths.
1429
- * Hash keys ([*]) are type-level markers for indexing into Records/HashMaps.
1430
- *
1431
- * @example
1432
- * ```typescript
1433
- * import { _, hashKey } from '@sladg/apex-state'
1434
- *
1435
- * // Use _ in template strings
1436
- * const path = `users.${_('u1')}.posts.${_('p1')}.name`
1437
- *
1438
- * // Use hashKey namespace for validation
1439
- * hashKey.rejectDynamic(path)
1440
- * ```
1441
- */
1442
-
1443
- /**
1444
- * Converts a concrete ID to hash key notation for inline template string usage
1445
- * Returns the concrete ID typed as HASH_KEY for Record/HashMap indexing
1446
- *
1447
- * @param id - The concrete ID (e.g., "u1", "p1", "c1")
1448
- * @returns The concrete ID typed as HASH_KEY
1449
- *
1450
- * @example
1451
- * ```typescript
1452
- * const path = `users.${_('u1')}.posts.${_('p1')}.name`
1453
- * // → "users.u1.posts.p1.name" (typed as containing HASH_KEY)
1454
- * ```
1455
- */
1456
- declare const _: (id: string) => HASH_KEY;
1457
- /**
1458
- * Hash key utilities namespace
1459
- *
1460
- * Provides utilities for working with hash keys in Record-based paths
1461
- */
1462
- declare const hashKey: {
1463
- /** Reject paths with dynamic hash keys */
1464
- readonly rejectDynamic: <P extends string>(path: P) => void;
1465
- /** Alias for _ function */
1466
- readonly _: (id: string) => HASH_KEY;
1467
- };
1468
-
1469
- /**
1470
- * Type checking utilities — similar to lodash type guards
1471
- *
1472
- * Provides type-safe predicates for common type checks with TypeScript support
1473
- */
1474
- /**
1475
- * Unified namespace for type checking
1476
- *
1477
- * @example
1478
- * ```typescript
1479
- * import { is } from './utils/is'
1480
- *
1481
- * if (is.object(value)) { ... }
1482
- * if (is.array(value)) { ... }
1483
- * if (is.nil(value)) { ... }
1484
- *
1485
- * // Negated versions
1486
- * if (is.not.object(value)) { ... }
1487
- * if (is.not.array(value)) { ... }
1488
- * ```
1489
- */
1490
- declare const is: {
1491
- nil: (value: unknown) => value is null | undefined;
1492
- undefined: (value: unknown) => value is undefined;
1493
- null: (value: unknown) => value is null;
1494
- object: (value: unknown) => value is Record<string, unknown>;
1495
- array: (value: unknown) => value is unknown[];
1496
- string: (value: unknown) => value is string;
1497
- number: (value: unknown) => value is number;
1498
- boolean: (value: unknown) => value is boolean;
1499
- function: (value: unknown) => value is (...args: unknown[]) => unknown;
1500
- symbol: (value: unknown) => value is symbol;
1501
- date: (value: unknown) => value is Date;
1502
- regexp: (value: unknown) => value is RegExp;
1503
- primitive: (value: unknown) => value is string | number | boolean | symbol | bigint | null | undefined;
1504
- empty: (value: unknown) => boolean;
1505
- equal: (a: unknown, b: unknown) => boolean;
1506
- not: {
1507
- nil: <T>(value: T | null | undefined) => value is T;
1508
- undefined: <T>(value: T | undefined) => value is T;
1509
- null: <T>(value: T | null) => value is T;
1510
- object: (value: unknown) => boolean;
1511
- array: (value: unknown) => boolean;
1512
- string: (value: unknown) => boolean;
1513
- number: (value: unknown) => boolean;
1514
- boolean: (value: unknown) => boolean;
1515
- function: (value: unknown) => boolean;
1516
- symbol: (value: unknown) => boolean;
1517
- date: (value: unknown) => boolean;
1518
- regexp: (value: unknown) => boolean;
1519
- primitive: (value: unknown) => boolean;
1520
- empty: (value: unknown) => boolean;
1521
- equal: (a: unknown, b: unknown) => boolean;
1522
- };
1523
- };
1524
-
1525
- /**
1526
- * Apply Changes Utility
1527
- *
1528
- * Applies an array of changes to an object, returning a new object.
1529
- */
1530
-
1531
- /**
1532
- * Applies changes to an object, returning a new object with changes applied.
1533
- * Does not mutate the original object.
1534
- *
1535
- * @param obj - Source object
1536
- * @param changes - Array of [path, value, meta] tuples
1537
- * @returns New object with changes applied
1538
- *
1539
- * @example
1540
- * ```typescript
1541
- * const state = { user: { name: 'Alice', age: 30 } }
1542
- * const changes: ArrayOfChanges<typeof state> = [
1543
- * ['user.name', 'Bob', {}],
1544
- * ['user.age', 31, {}],
1545
- * ]
1546
- *
1547
- * const newState = applyChangesToObject(state, changes)
1548
- * // newState: { user: { name: 'Bob', age: 31 } }
1549
- * // state is unchanged
1550
- * ```
1551
- */
1552
- declare const applyChangesToObject: <T extends object>(obj: T, changes: ArrayOfChanges<T>) => T;
1553
-
1554
- export { useKeyboardSelect as $, type Aggregation as A, type BaseConcernProps as B, type ConcernRegistration as C, type DeepKey as D, type EvaluatedConcerns as E, type FieldInput$2 as F, type GenericMeta as G, evaluateBoolLogic as H, extractPlaceholders as I, findConcern as J, type KeyboardSelectConfig as K, type ListenerRegistration as L, hashKey as M, interpolateTemplate as N, type OnStateListener as O, type PathsWithSameValueAs as P, is as Q, index as R, type SelectOption as S, type ThrottleConfig as T, registerFlipPair as U, type ValidationError as V, registerListenerLegacy as W, registerSideEffects as X, registerSyncPairsBatch as Y, useBufferedField as Z, _, type DeepValue as a, useThrottledField as a0, useTransformedField as a1, type GenericStoreApi as a2, type AggregationPair as b, type ArrayOfChanges as c, type BoolLogic as d, type BufferedField as e, type ConcernRegistrationMap as f, type ConcernType as g, type DebugConfig as h, type DebugTrack as i, type DebugTrackEntry as j, type DeepPartial as k, type DeepRequired as l, type ExtractEvaluateReturn as m, type FlipPair as n, type ProviderProps as o, type SideEffects as p, type StoreConfig as q, type StoreInstance as r, type SyncPair as s, type TransformConfig as t, type ValidationSchema as u, type ValidationStateResult as v, applyChangesToObject as w, createGenericStore as x, defaultConcerns as y, dot as z };