tilia 5.2.0 → 6.0.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/README.md CHANGED
@@ -13,13 +13,19 @@ and easier to evolve as your domain grows.
13
13
 
14
14
  In short: Tilia helps you write code that matches your business, not your framework.
15
15
 
16
- For more information, check out the [**DDD section**](https://tiliajs.com/docs#ddd) of the website.
16
+ For more information, read the [tilia guide](https://tiliajs.dev/guide).
17
17
 
18
- <a href="https://tiliajs.com">
18
+ <a href="https://tiliajs.dev">
19
19
  <img width="834" height="705" alt="image" src="https://github.com/user-attachments/assets/56dd163a-65a0-4900-9280-aab2a0d7d92a" />
20
20
  </a>
21
21
 
22
- Check the [**website**](https://tiliajs.com) for full documentation and more examples for both TypeScript and ReScript.
22
+ See the [API reference](https://tiliajs.dev/api) for the complete public surface.
23
+ Coding assistants can start with [`llms.txt`](./llms.txt), then use
24
+ [`src/index.d.ts`](./src/index.d.ts) or
25
+ [`src/Tilia.resi`](./src/Tilia.resi) for exact signatures.
26
+
27
+ For core runtime behavior decisions (including computed pruning), see
28
+ [`TRADE_OFFS.md`](./TRADE_OFFS.md).
23
29
 
24
30
  ## Note on exceptions
25
31
 
@@ -28,7 +34,7 @@ logged to `console.error` and re-thrown at the end of the next flush. This is
28
34
  done to avoid breaking the application in case of a bug in the callback but
29
35
  still bubbling the error to the user.
30
36
 
31
- ## API for versin **3.x** (in case the website is not available)
37
+ ## API (in case the website is not available)
32
38
 
33
39
  (TypeScript version below)
34
40
 
@@ -73,10 +79,12 @@ type tilia = {
73
79
  * default context.
74
80
  *
75
81
  * This uses a PUSH model: changes "push" the callback to run.
76
- *
82
+ *
77
83
  * For a PULL model (run only when a value is read), see `computed`.
84
+ *
85
+ * @return A function to stop observing.
78
86
  */
79
- observe: (unit => unit) => unit,
87
+ observe: (unit => unit) => unit => unit,
80
88
  /**
81
89
  * React to value changes.
82
90
  *
@@ -86,8 +94,9 @@ type tilia = {
86
94
  *
87
95
  * @param f The capture function.
88
96
  * @param m The effect function.
97
+ * @return A function to stop watching.
89
98
  */
90
- watch: 'a. (unit => 'a, 'a => unit) => unit,
99
+ watch: 'a. (unit => 'a, 'a => unit) => unit => unit,
91
100
  /**
92
101
  * Run a series of operations in a batch, blocking notifications until the
93
102
  * batch is complete.
@@ -106,6 +115,35 @@ type tilia = {
106
115
  *
107
116
  */
108
117
  derived: 'a. (unit => 'a) => signal<'a>,
118
+ /**
119
+ * Return a reactive source value to be inserted into a tilia object.
120
+ *
121
+ * The setup callback is called once on first value read and whenever any
122
+ * observed value changes. The callback receives a setter function, which
123
+ * can be used to imperatively update the value. The initial value is used
124
+ * before the first update.
125
+ *
126
+ * This is useful for implementing resource loaders, state machines or any state
127
+ * that depends on external or asynchronous events.
128
+ *
129
+ * @param v The initial value.
130
+ * @param f The setup function, receives the previous value and a setter.
131
+ */
132
+ source: 'a 'ignored. ('a, ('a, 'a => unit) => 'ignored) => 'a,
133
+ /**
134
+ * Return a managed value to be inserted into a tilia object.
135
+ *
136
+ * The setup callback runs once when the value is first accessed, and again
137
+ * whenever any observed dependency changes. The callback receives a setter
138
+ * function to imperatively update the value, and should return the initial
139
+ * value.
140
+ *
141
+ * This is useful for implementing event based machines with a simple initial
142
+ * setup.
143
+ *
144
+ * @param f The setup function, receives a setter and returns the current value.
145
+ */
146
+ store: 'a. (('a => unit) => 'a) => 'a,
109
147
  /**
110
148
  * Internal: Register an observer callback.
111
149
  */
@@ -149,8 +187,9 @@ let carve: (deriver<'a> => 'a) => 'a
149
187
  * (run only when a value is read), see `computed`.
150
188
  *
151
189
  * @param f The callback to run on changes.
190
+ * @return A function to stop observing.
152
191
  */
153
- let observe: (unit => unit) => unit
192
+ let observe: (unit => unit) => unit => unit
154
193
 
155
194
  /**
156
195
  * React to changes of captured values.
@@ -165,8 +204,9 @@ let observe: (unit => unit) => unit
165
204
  *
166
205
  * @param f1 The function that captures values to observe.
167
206
  * @param f2 The function called when the captured values change.
207
+ * @return A function to stop watching.
168
208
  */
169
- let watch: (unit => 'a, 'a => unit) => unit
209
+ let watch: (unit => 'a, 'a => unit) => unit => unit
170
210
 
171
211
  /**
172
212
  * Run a series of operations in a batch, blocking notifications until the batch
@@ -235,10 +275,10 @@ let lift: signal<'a> => 'a
235
275
  * This is useful for implementing resource loaders, state machines or any state
236
276
  * that depends on external or asynchronous events.
237
277
  *
238
- * @param f The setup function, receives a setter.
239
278
  * @param v The initial value.
279
+ * @param f The setup function, receives the previous value and a setter.
240
280
  */
241
- let source: (('a => unit) => 'ignored, 'a) => 'a
281
+ let source: ('a, ('a, 'a => unit) => 'ignored) => 'a
242
282
 
243
283
  /**
244
284
  * Return a managed value to be inserted into a tilia object.
@@ -255,29 +295,6 @@ let source: (('a => unit) => 'ignored, 'a) => 'a
255
295
  */
256
296
  let store: (('a => unit) => 'a) => 'a
257
297
 
258
- /**
259
- * Track key-level writes on a tilia-proxied dict.
260
- *
261
- * Takes an accessor `() => dict<'a>` so the tracker can follow source swaps.
262
- *
263
- * Returns `{ changes, mute }`:
264
- * - `changes`: capture function for `watch`. Drains accumulated changes into
265
- * `{ upsert, remove }`. `upsert` contains objects captured at write time.
266
- * `remove` contains keys of deleted entries. Last write wins per key.
267
- * - `mute`: run a callback with this tracker's dirty tracking temporarily
268
- * removed. Writes inside `mute` are still reactive but not tracked.
269
- *
270
- * When a `guard` is provided and returns false, changes accumulate silently
271
- * without triggering the watcher. When the guard becomes true, the
272
- * effect fires with all accumulated changes.
273
- *
274
- * @param accessor Function returning the tilia-proxied dict to track.
275
- * @param ~guard Optional reactive guard function.
276
- */
277
- type changes<'a> = {upsert: array<'a>, remove: array<string>}
278
- type changing<'a> = {changes: unit => changes<'a>, mute: (unit => unit) => unit}
279
- let changing: (unit => dict<'a>, ~guard: unit => bool=?) => changing<'a>
280
-
281
298
  /** ---------- Internal types and functions for library developers ---------- */
282
299
  /**
283
300
  * Internal: Register an observer callback.
@@ -306,6 +323,20 @@ let _clear: observer => unit
306
323
  */
307
324
  let _meta: 'a => nullable<'b>
308
325
 
326
+ /**
327
+ * Internal: Type used by _canopy.
328
+ */
329
+ type canopy = {
330
+ live: Set.t<string>,
331
+ idle: Set.t<string>,
332
+ }
333
+
334
+ /**
335
+ * Internal: Inspect which keys have observers (live) versus
336
+ * the ones that are not observed (idle).
337
+ */
338
+ let _canopy: 'a => canopy
339
+
309
340
  /**
310
341
  * Internal: The default tilia context.
311
342
  */
@@ -316,62 +347,239 @@ let _ctx: tilia
316
347
 
317
348
  ```ts
318
349
  declare const o: unique symbol;
319
- declare const r: unique symbol;
320
350
  export type Observer = { readonly [o]: true };
351
+ /** A reactive holder for a single value, read and written through `value`. */
321
352
  export type Signal<T> = { value: T };
353
+ /** An immutable holder: the `data` field is not tracked nor proxied. */
322
354
  export type Readonly<T> = { readonly data: T };
355
+ /** Imperative update function returned alongside signals and passed to setups. */
323
356
  export type Setter<T> = (v: T) => void;
324
- export type Deriver<U> = { derived: <T>(fn: (p: U) => T) => T };
357
+ /** Stop function returned by `observe` and `watch`. Calling it cancels the subscription. */
358
+ export type Cancel = () => void;
359
+ /** Helper passed to `carve` to declare values derived from the object under construction. */
360
+ export type Deriver<U> = {
361
+ /**
362
+ * Declare a derived (computed) field inside a `carve` definition. Works like
363
+ * `computed`, but the computation receives the carved object itself, so a
364
+ * field can depend on sibling fields.
365
+ *
366
+ * ```ts
367
+ * const alice = carve(({ derived }) => ({
368
+ * birthYear: 1995,
369
+ * age: derived((self) => thisYear - self.birthYear),
370
+ * }));
371
+ * ```
372
+ */
373
+ derived: <T>(fn: (p: U) => T) => T;
374
+ };
375
+
376
+ /** A tilia context: an isolated reactive scope with its own tracking and scheduling. */
325
377
  export type Tilia = {
378
+ /**
379
+ * Transform a regular object or array into a reactive tilia proxy.
380
+ *
381
+ * Reads are tracked per key, including nested objects and arrays, so
382
+ * observers only re-run when a key they actually read changes. Calling
383
+ * `tilia` twice on the same object returns the same proxy.
384
+ */
326
385
  tilia: <T>(branch: T) => T;
386
+ /**
387
+ * Build a reactive object whose derived fields can read the object itself.
388
+ * The callback receives a {@link Deriver} and must return the object to
389
+ * proxy. Use this to co-locate state and computations in one definition.
390
+ */
327
391
  carve: <T>(fn: (deriver: Deriver<T>) => T) => T;
328
- observe: (fn: () => void) => void;
329
- watch: <T>(fn: () => T, effect: (v: T) => void) => void;
392
+ /**
393
+ * Run `fn` now and re-run it whenever any tilia value it read changes
394
+ * (push reactivity).
395
+ *
396
+ * @returns A function that stops the observation.
397
+ */
398
+ observe: (fn: () => void) => Cancel;
399
+ /**
400
+ * React to changes with a clear separation between reading and acting:
401
+ * `fn` captures (reads) values and returns a result; `effect` runs with
402
+ * that result whenever a captured value changes. Unlike `observe`, the
403
+ * effect itself is not tracked, so it can freely read other reactive state.
404
+ *
405
+ * @returns A function that stops watching.
406
+ */
407
+ watch: <T>(fn: () => T, effect: (v: T) => void) => Cancel;
408
+ /**
409
+ * Run several mutations as one batch: notifications are deferred until the
410
+ * batch completes, so observers see a single consistent update. Not needed
411
+ * inside tilia callbacks (`observe`, `computed`, ...) where batching is
412
+ * already active.
413
+ */
330
414
  batch: (fn: () => void) => void;
331
- signal: <T>(value: T) => Signal<T>;
415
+ /**
416
+ * Wrap a single value in a reactive {@link Signal}. Returns the signal and
417
+ * a setter: read with `s.value`, write with the setter.
418
+ */
419
+ signal: <T>(value: T) => [Signal<T>, Setter<T>];
420
+ /**
421
+ * Create a signal whose value is computed from other reactive values and
422
+ * recomputed when they change.
423
+ */
332
424
  derived: <T>(fn: () => T) => Signal<T>;
425
+ /**
426
+ * Create a reactive source value to insert into a tilia object. The setup
427
+ * runs on first read and re-runs when any tilia value it read changes. It
428
+ * receives the previous value and a setter for imperative (possibly async)
429
+ * updates; `initialValue` is used until the first `set`.
430
+ *
431
+ * Useful for resource loaders, state machines, or any state driven by
432
+ * external or asynchronous events.
433
+ */
333
434
  source: <T>(initialValue: T, fn: (previous: T, set: Setter<T>) => unknown) => T;
435
+ /**
436
+ * Create a managed value to insert into a tilia object. The setup runs on
437
+ * first read and re-runs when any tilia value it read changes. It receives
438
+ * a setter for later imperative updates and must return the initial value.
439
+ *
440
+ * Like `source`, but the initial value is produced by the setup itself.
441
+ */
334
442
  store: <T>(fn: (set: Setter<T>) => T) => T;
335
- changing: <T>(accessor: () => Record<string, T>, guard?: () => boolean) => Changing<T>;
336
- // Internal
443
+ /** @internal Register a raw observer (library authors; see `_observe`). */
337
444
  _observe(callback: () => void): Observer;
338
445
  };
339
- export function make(flush?: (fn: () => void) => void, gc?: number): Tilia;
340
446
 
341
- // Default global context
447
+ /**
448
+ * Create a new tilia context with its own `tilia`, `observe`, `batch`, etc.
449
+ * State from different contexts is tracked and flushed independently.
450
+ *
451
+ * @param gc Number of cleared watchers to keep before triggering garbage
452
+ * collection (default: 50).
453
+ */
454
+ export function make(gc?: number): Tilia;
455
+
456
+ /**
457
+ * Transform a regular object or array into a reactive tilia proxy (in the
458
+ * default context).
459
+ *
460
+ * Reads are tracked per key, including nested objects and arrays, so
461
+ * observers only re-run when a key they actually read changes. Calling
462
+ * `tilia` twice on the same object returns the same proxy.
463
+ */
342
464
  export function tilia<T>(branch: T): T;
465
+ /**
466
+ * Build a reactive object whose derived fields can read the object itself.
467
+ * The callback receives a {@link Deriver} and must return the object to
468
+ * proxy. Use this to co-locate state and computations in one definition.
469
+ */
343
470
  export function carve<T>(fn: (deriver: Deriver<T>) => T): T;
344
- export function observe(fn: () => void): void;
345
- export function watch<T>(fn: () => T, effect: (v: T) => void): void;
471
+ /**
472
+ * Run `fn` now and re-run it whenever any tilia value it read changes
473
+ * (push reactivity). For pull reactivity (recompute only when read), see
474
+ * `computed`.
475
+ *
476
+ * @returns A function that stops the observation.
477
+ */
478
+ export function observe(fn: () => void): Cancel;
479
+ /**
480
+ * React to changes with a clear separation between reading and acting:
481
+ * `fn` captures (reads) values and returns a result; `effect` runs with that
482
+ * result whenever a captured value changes. Unlike `observe`, the effect
483
+ * itself is not tracked, so it can freely read other reactive state.
484
+ *
485
+ * The effect should avoid synchronously mutating the values it captures, to
486
+ * prevent recursive updates; use `observe` for such feedback loops.
487
+ *
488
+ * @returns A function that stops watching.
489
+ */
490
+ export function watch<T>(fn: () => T, effect: (v: T) => void): Cancel;
491
+ /**
492
+ * Run several mutations as one batch: notifications are deferred until the
493
+ * batch completes, so observers see a single consistent update. Not needed
494
+ * inside tilia callbacks (`observe`, `computed`, ...) where batching is
495
+ * already active.
496
+ */
346
497
  export function batch(fn: () => void): void;
347
498
 
348
- // Functional reactive programming
499
+ /**
500
+ * Create a computed value to insert into a tilia object (pull reactivity).
501
+ * The value is computed on first read, cached, and invalidated when any tilia
502
+ * value it read changes; it is only recomputed on the next read.
503
+ */
349
504
  export function computed<T>(fn: () => T): T;
505
+ /**
506
+ * Create a reactive source value to insert into a tilia object. The setup
507
+ * runs on first read and re-runs when any tilia value it read changes. It
508
+ * receives the previous value and a setter for imperative (possibly async)
509
+ * updates; `initialValue` is used until the first `set`.
510
+ *
511
+ * Useful for resource loaders, state machines, or any state driven by
512
+ * external or asynchronous events.
513
+ */
350
514
  export function source<T>(
351
515
  initialValue: T,
352
516
  fn: (previous: T, set: Setter<T>) => unknown
353
517
  ): T;
518
+ /**
519
+ * Create a managed value to insert into a tilia object. The setup runs on
520
+ * first read and re-runs when any tilia value it read changes. It receives a
521
+ * setter for later imperative updates and must return the initial value.
522
+ *
523
+ * Like `source`, but the initial value is produced by the setup itself.
524
+ */
354
525
  export function store<T>(fn: (set: Setter<T>) => T): T;
526
+ /**
527
+ * Wrap a value in a {@link Readonly} holder. The wrapped data is not proxied
528
+ * nor tracked: use this to insert immutable or foreign objects (class
529
+ * instances, large blobs) into a tilia object without reactivity overhead.
530
+ */
355
531
  export function readonly<T>(data: T): Readonly<T>;
532
+ /**
533
+ * Wrap a single value in a reactive {@link Signal}. Returns the signal and a
534
+ * setter: read with `s.value`, write with the setter.
535
+ */
356
536
  export function signal<T>(value: T): [Signal<T>, Setter<T>];
537
+ /**
538
+ * Create a signal whose value is computed from other reactive values and
539
+ * recomputed when they change.
540
+ */
357
541
  export function derived<T>(fn: () => T): Signal<T>;
542
+ /**
543
+ * Lift a signal into a computed value to insert into a tilia object: the
544
+ * field tracks the signal's inner `value`.
545
+ *
546
+ * ```ts
547
+ * const app = tilia({ user: lift(userSignal) });
548
+ * app.user; // stays in sync with userSignal.value
549
+ * ```
550
+ */
358
551
  export function lift<T>(s: Signal<T>): T;
359
- export interface Changes<T> { upsert: T[]; remove: string[] }
360
- export interface Changing<T> {
361
- changes: () => Changes<T>;
362
- mute: (fn: () => void) => void;
363
- }
364
- export function changing<T>(accessor: () => Record<string, T>, guard?: () => boolean): Changing<T>;
365
552
 
366
- // Internal
553
+ /** @internal Keys with observers (`live`) versus keys without (`idle`). */
554
+ export type Canopy = { live: Set<string>; idle: Set<string> };
555
+ /** @internal Inspect which keys of a tilia proxy are observed. */
556
+ export function _canopy<T extends object>(tree: T): Canopy;
557
+ /**
558
+ * @internal Register `callback` as an observer and start recording reads.
559
+ * Entry point for library authors building on tilia; pair with `_done` /
560
+ * `_ready` / `_clear`.
561
+ */
367
562
  export function _observe(callback: () => void): Observer;
563
+ /** @internal Stop recording reads for `observer` without subscribing it. */
368
564
  export function _done(observer: Observer): void;
565
+ /**
566
+ * @internal Stop recording and subscribe the observer to the recorded reads.
567
+ * If `notifyIfChanged` is true, notify immediately when a read value already
568
+ * changed during recording.
569
+ */
369
570
  export function _ready(observer: Observer, notifyIfChanged?: boolean): void;
571
+ /** @internal Dispose of an observer that was not notified (notification disposes automatically). */
370
572
  export function _clear(observer: Observer): void;
573
+ /** @internal Get meta information on a tilia proxy (raw target, root, etc.). */
371
574
  export function _meta<T>(tree: T): unknown;
575
+ /** @internal The default tilia context (used by the top-level exports). */
372
576
  export const _ctx: Tilia;
373
577
  ```
374
578
 
579
+ `_canopy(tree)` is an internal helper for library developers. It flushes
580
+ pending notifications, then returns current own keys split into `live` (has
581
+ observers) and `idle` (no observers).
582
+
375
583
  ## Basic Example
376
584
 
377
585
  ```ts
@@ -424,10 +632,6 @@ export function makeTodos(remote: Remote, data: Todo[]) {
424
632
  data,
425
633
  }));
426
634
 
427
- // Sync writes to remote
428
- const { changes, mute } = changing(() => todos);
429
- watch(changes, ({ upsert, remove }) => remote.sync(upsert, remove));
430
-
431
635
  return todos;
432
636
  }
433
637
  ```