@isograph/puchi 0.0.0-main-5f205c00

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/LICENSE-MIT ADDED
@@ -0,0 +1,7 @@
1
+ Copyright 2025 Isograph Labs
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,75 @@
1
+ ---
2
+ slug: /puchi
3
+ ---
4
+
5
+ # `@isograph/puchi`
6
+
7
+ Puchi wraps `@isograph/pico` with callable sources and derived values. A derived computation records the sources and derived values it reads. The caller never passes a node to a read.
8
+
9
+ Isograph publishes main builds under the `main` npm tag. A release tag publishes the stable version.
10
+
11
+ ```sh
12
+ npm install @isograph/puchi@main
13
+ ```
14
+
15
+ ```ts
16
+ const price = source(10);
17
+ const quantity = source(2);
18
+ const total = derived(() => price() * quantity());
19
+
20
+ const totals: number[] = [];
21
+ const stop = subscribe(total, (value) => totals.push(value));
22
+ total(); // 20
23
+
24
+ batch(() => {
25
+ price.set(12);
26
+ quantity.set(3);
27
+ });
28
+ total(); // 36
29
+ totals; // [36]
30
+ stop();
31
+ ```
32
+
33
+ A subscription can observe a source or a derived value. Subscribing to a derived value keeps it cached. Its listener runs when the value changes. Subscribing does not call the listener with the initial value. Calling the returned function releases the subscription, and calling it again has no effect.
34
+
35
+ `batch(fn)` returns the result of `fn`. Inside the body, you can write sources and stop subscriptions. Reading a signal, subscribing, or opening another batch throws. Puchi commits the writes and calls subscribers before returning. If the body throws, Puchi commits the preceding writes and rethrows. Keep the body synchronous. With an async function, the batch closes when the function first returns its promise. Writes after an `await` are separate updates. A computation or subscriber can read other nodes but cannot write, change subscriptions, or start a batch.
36
+
37
+ ## Equality
38
+
39
+ Sources and derived values compare successive values with `===` by default. A source can take an equality function as its second argument. Each `set` compares its argument with the last value the source accepted, including earlier writes in the same batch. When the comparison returns true, the source keeps that value and skips the write. A derived value can take an equality function in the same position. An equal result keeps its previous identity and skips notifications to dependents. These comparisons assume that code leaves previously stored objects unchanged.
40
+
41
+ ```ts
42
+ const point = source({ x: 1, y: 2 }, (a, b) => a.x === b.x && a.y === b.y);
43
+ const x = derived(
44
+ () => ({ value: point().x }),
45
+ (a, b) => a.value === b.value,
46
+ );
47
+ ```
48
+
49
+ A computation can receive its previous successful result, as in `derived<number>((previous) => Math.max(previous ?? 0, price()))`, while Pico still has that result cached. It receives `undefined` on its first run, after a failed run, and after Pico disposes its cached value. Computations and equality functions run synchronously. Reads before a throw remain dependencies, so changing one of those inputs can make a failed computation succeed on its next run.
50
+
51
+ ## Errors
52
+
53
+ `derived(fn)` catches an exception inside Pico. Reading the derived value rethrows the original exception to the reader. If a second Puchi computation reads that value, the second computation can catch the exception itself or use one of these constructors.
54
+
55
+ - `derivedOrNull(fn)` returns `T | null` and returns `null` when `fn` throws.
56
+ - `derivedOrError(fn)` returns `T | Err`. An `Err` is an `Error` whose `cause` holds the original thrown value.
57
+ - `derivedResult(fn)` returns `{ ok: true, value: T }` or `{ ok: false, error: unknown }`. The tag distinguishes a failure even when a successful computation can return `null`, an error or a symbol.
58
+ - `derivedOrSymbol(fn)` returns `T | typeof FAILED`. The exported symbol `FAILED` identifies a failure.
59
+
60
+ ```ts
61
+ const text = source('broken');
62
+ const count = derivedResult(() => {
63
+ const n = Number(text());
64
+ if (!Number.isFinite(n)) throw new RangeError('Expected a number');
65
+ return n;
66
+ });
67
+
68
+ const first = count();
69
+ if (!first.ok) console.error(first.error);
70
+ text.set('3');
71
+ const next = count();
72
+ if (next.ok) console.log(next.value); // 3
73
+ ```
74
+
75
+ `subscribe(node, listener, onError)` calls `onError` in a microtask if the listener throws or returns a rejected promise. Subscribing to a throwing `derived` sends a new computation failure to the same handler. Other subscribers continue to run. The default handler logs the error with `console.error`. If a custom error handler throws or rejects, Puchi logs that error too.
package/dist/index.cjs ADDED
@@ -0,0 +1,148 @@
1
+ let _isograph_pico = require("@isograph/pico");
2
+
3
+ //#region src/index.ts
4
+ const observe = Symbol("puchi.subscribe");
5
+ var Err = class extends Error {
6
+ constructor(cause) {
7
+ super("Puchi computation failed", { cause });
8
+ }
9
+ };
10
+ const FAILED = Symbol("puchi.failed");
11
+ let executionContext;
12
+ let isWriteBatchOpen = false;
13
+ function strictEqual(previous, next) {
14
+ return previous === next;
15
+ }
16
+ function requireOutsideComputationOrSubscriber() {
17
+ if (executionContext !== void 0) throw new Error("This operation cannot run inside a computation or subscriber.");
18
+ }
19
+ function source(initial, equal = strictEqual) {
20
+ const handle = (0, _isograph_pico.createSourceNode)(initial);
21
+ let lastAcceptedValue = initial;
22
+ return Object.assign(() => {
23
+ if (isWriteBatchOpen) throw new Error("A source cannot be read inside a write batch.");
24
+ return executionContext === void 0 || executionContext === "subscriber" ? handle.value : (0, _isograph_pico.readSource)(executionContext, handle);
25
+ }, { set(value) {
26
+ requireOutsideComputationOrSubscriber();
27
+ if (!equal(lastAcceptedValue, value)) {
28
+ lastAcceptedValue = value;
29
+ (0, _isograph_pico.writeSource)(handle, value);
30
+ }
31
+ } });
32
+ }
33
+ function batch(fn) {
34
+ requireOutsideComputationOrSubscriber();
35
+ (0, _isograph_pico.startWriteBatch)();
36
+ isWriteBatchOpen = true;
37
+ try {
38
+ return fn();
39
+ } finally {
40
+ isWriteBatchOpen = false;
41
+ (0, _isograph_pico.endWriteBatch)();
42
+ }
43
+ }
44
+ function createResultNode(compute, equal) {
45
+ return (0, _isograph_pico.createDerivedNode)((caller, previous) => {
46
+ const previousContext = executionContext;
47
+ executionContext = caller;
48
+ try {
49
+ const value = compute(previous?.ok === true ? previous.value : void 0);
50
+ return previous?.ok === true && equal(previous.value, value) ? previous : {
51
+ ok: true,
52
+ value
53
+ };
54
+ } catch (error) {
55
+ return previous?.ok === false && previous.error === error ? previous : {
56
+ ok: false,
57
+ error
58
+ };
59
+ } finally {
60
+ executionContext = previousContext;
61
+ }
62
+ });
63
+ }
64
+ function valueOrThrow(result) {
65
+ if (!result.ok) throw result.error;
66
+ return result.value;
67
+ }
68
+ function callHandlerAndForwardErrors(handler, onError) {
69
+ try {
70
+ const result = handler();
71
+ if ((typeof result === "object" && result != null || typeof result === "function") && "then" in result) Promise.resolve(result).catch(onError);
72
+ } catch (error) {
73
+ onError(error);
74
+ }
75
+ }
76
+ function logError(error) {
77
+ console.error(error);
78
+ }
79
+ function createDerivedReader(handle, toPublicValue) {
80
+ function read() {
81
+ if (isWriteBatchOpen) throw new Error("A derived value cannot be read inside a write batch.");
82
+ return toPublicValue(executionContext === void 0 || executionContext === "subscriber" ? (0, _isograph_pico.readDerivedOutsideComputation)(handle) : (0, _isograph_pico.readDerived)(executionContext, handle));
83
+ }
84
+ function listen(listener, onError) {
85
+ requireOutsideComputationOrSubscriber();
86
+ if (isWriteBatchOpen) throw new Error("A subscription cannot start inside a write batch.");
87
+ const reportListenerError = (error) => {
88
+ queueMicrotask(() => callHandlerAndForwardErrors(() => onError(error), logError));
89
+ };
90
+ let retain = (0, _isograph_pico.retainDerivedNode)(handle, (stored) => {
91
+ const previousContext = executionContext;
92
+ executionContext = "subscriber";
93
+ try {
94
+ callHandlerAndForwardErrors(() => listener(toPublicValue(stored)), reportListenerError);
95
+ } finally {
96
+ executionContext = previousContext;
97
+ }
98
+ });
99
+ return () => {
100
+ if (retain !== void 0) {
101
+ requireOutsideComputationOrSubscriber();
102
+ (0, _isograph_pico.releaseRetain)(retain);
103
+ retain = void 0;
104
+ }
105
+ };
106
+ }
107
+ return Object.assign(read, { [observe]: listen });
108
+ }
109
+ function identity(value) {
110
+ return value;
111
+ }
112
+ function derived(compute, equal = strictEqual) {
113
+ return createDerivedReader(createResultNode(compute, equal), valueOrThrow);
114
+ }
115
+ function derivedResult(compute, equal = strictEqual) {
116
+ return createDerivedReader(createResultNode(compute, equal), identity);
117
+ }
118
+ function createDerivedWithFallback(compute, equal, fallback) {
119
+ const result = createResultNode(compute, equal);
120
+ return createDerivedReader((0, _isograph_pico.createDerivedNode)((caller) => {
121
+ const state = (0, _isograph_pico.readDerived)(caller, result);
122
+ return state.ok ? state.value : fallback(state.error);
123
+ }), identity);
124
+ }
125
+ function derivedOrNull(compute, equal = strictEqual) {
126
+ return createDerivedWithFallback(compute, equal, () => null);
127
+ }
128
+ function derivedOrError(compute, equal = strictEqual) {
129
+ return createDerivedWithFallback(compute, equal, (error) => new Err(error));
130
+ }
131
+ function derivedOrSymbol(compute, equal = strictEqual) {
132
+ return createDerivedWithFallback(compute, equal, () => FAILED);
133
+ }
134
+ function subscribe(node, listener, onError = logError) {
135
+ return (observe in node ? node : derived(node))[observe](listener, onError);
136
+ }
137
+
138
+ //#endregion
139
+ exports.Err = Err;
140
+ exports.FAILED = FAILED;
141
+ exports.batch = batch;
142
+ exports.derived = derived;
143
+ exports.derivedOrError = derivedOrError;
144
+ exports.derivedOrNull = derivedOrNull;
145
+ exports.derivedOrSymbol = derivedOrSymbol;
146
+ exports.derivedResult = derivedResult;
147
+ exports.source = source;
148
+ exports.subscribe = subscribe;
@@ -0,0 +1,43 @@
1
+ //#region src/index.d.ts
2
+ type Equal<T> = (previous: T, next: T) => boolean;
3
+ type Compute<T> = (previous: T | undefined) => T;
4
+ type Listener<T> = (value: T) => unknown;
5
+ type ErrorHandler = (error: unknown) => unknown;
6
+ declare const sourceBrand: unique symbol;
7
+ interface Source<T> {
8
+ readonly [sourceBrand]: T;
9
+ (): T;
10
+ readonly set: (value: T) => void;
11
+ }
12
+ declare const observe: unique symbol;
13
+ interface Derived<T> {
14
+ (): T;
15
+ readonly [observe]: (listener: Listener<T>, onError: ErrorHandler) => () => void;
16
+ }
17
+ declare const resultBrand: unique symbol;
18
+ type Result<T> = {
19
+ readonly [resultBrand]: true;
20
+ } & ({
21
+ readonly ok: true;
22
+ readonly value: T;
23
+ } | {
24
+ readonly ok: false;
25
+ readonly error: unknown;
26
+ });
27
+ declare const errBrand: unique symbol;
28
+ declare class Err extends Error {
29
+ readonly [errBrand]: true;
30
+ constructor(cause: unknown);
31
+ }
32
+ declare const FAILED: unique symbol;
33
+ declare function source<T>(initial: T, equal?: Equal<T>): Source<T>;
34
+ declare function batch<T>(fn: () => T): T;
35
+ declare function derived<T>(compute: Compute<T>, equal?: Equal<T>): Derived<T>;
36
+ declare function derivedResult<T>(compute: Compute<T>, equal?: Equal<T>): Derived<Result<T>>;
37
+ declare function derivedOrNull<T>(compute: Compute<T>, equal?: Equal<T>): Derived<T | null>;
38
+ declare function derivedOrError<T>(compute: Compute<T>, equal?: Equal<T>): Derived<T | Err>;
39
+ declare function derivedOrSymbol<T>(compute: Compute<T>, equal?: Equal<T>): Derived<T | typeof FAILED>;
40
+ declare function subscribe<T>(node: Source<T> | Derived<T>, listener: Listener<T>, onError?: ErrorHandler): () => void;
41
+ //#endregion
42
+ export { Derived, Equal, Err, FAILED, Result, Source, batch, derived, derivedOrError, derivedOrNull, derivedOrSymbol, derivedResult, source, subscribe };
43
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";KAgBY,KAAA,OAAY,QAAA,EAAU,CAAA,EAAG,IAAA,EAAM,CAAA;AAAA,KACtC,OAAA,OAAc,QAAA,EAAU,CAAA,iBAAkB,CAAA;AAAA,KAC1C,QAAA,OAAe,KAAA,EAAO,CAAA;AAAA,KACtB,YAAA,IAAgB,KAAA;AAAA,cAEP,WAAA;AAAA,UACG,MAAA;EAAA,UACL,WAAA,GAAc,CAAA;EAAA,IACpB,CAAA;EAAA,SACK,GAAA,GAAM,KAAA,EAAO,CAAA;AAAA;AAAA,cAGlB,OAAA;AAAA,UACW,OAAA;EAAA,IACX,CAAA;EAAA,UACM,OAAA,IACR,QAAA,EAAU,QAAA,CAAS,CAAA,GACnB,OAAA,EAAS,YAAA;AAAA;AAAA,cAIC,WAAA;AAAA,KACF,MAAA;EAAA,UAAwB,WAAA;AAAA;EAAA,SACrB,EAAA;EAAA,SAAmB,KAAA,EAAO,CAAA;AAAA;EAAA,SAC1B,EAAA;EAAA,SAAoB,KAAA;AAAA;AAAA,cAGrB,QAAA;AAAA,cACD,GAAA,SAAY,KAAA;EAAA,UACL,QAAA;cAEN,KAAA;AAAA;AAAA,cAKD,MAAA;AAAA,iBAmBG,MAAA,GAAA,CACd,OAAA,EAAS,CAAA,EACT,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,MAAA,CAAO,CAAA;AAAA,iBAyBM,KAAA,GAAA,CAAS,EAAA,QAAU,CAAA,GAAI,CAAA;AAAA,iBAyHvB,OAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,CAAA;AAAA,iBAIK,aAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,MAAA,CAAO,CAAA;AAAA,iBAiBF,aAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,CAAA;AAAA,iBAIK,cAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,CAAA,GAAI,GAAA;AAAA,iBAIC,eAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,CAAA,UAAW,MAAA;AAAA,iBAQN,SAAA,GAAA,CACd,IAAA,EAAM,MAAA,CAAO,CAAA,IAAK,OAAA,CAAQ,CAAA,GAC1B,QAAA,EAAU,QAAA,CAAS,CAAA,GACnB,OAAA,GAAS,YAAA"}
@@ -0,0 +1,43 @@
1
+ //#region src/index.d.ts
2
+ type Equal<T> = (previous: T, next: T) => boolean;
3
+ type Compute<T> = (previous: T | undefined) => T;
4
+ type Listener<T> = (value: T) => unknown;
5
+ type ErrorHandler = (error: unknown) => unknown;
6
+ declare const sourceBrand: unique symbol;
7
+ interface Source<T> {
8
+ readonly [sourceBrand]: T;
9
+ (): T;
10
+ readonly set: (value: T) => void;
11
+ }
12
+ declare const observe: unique symbol;
13
+ interface Derived<T> {
14
+ (): T;
15
+ readonly [observe]: (listener: Listener<T>, onError: ErrorHandler) => () => void;
16
+ }
17
+ declare const resultBrand: unique symbol;
18
+ type Result<T> = {
19
+ readonly [resultBrand]: true;
20
+ } & ({
21
+ readonly ok: true;
22
+ readonly value: T;
23
+ } | {
24
+ readonly ok: false;
25
+ readonly error: unknown;
26
+ });
27
+ declare const errBrand: unique symbol;
28
+ declare class Err extends Error {
29
+ readonly [errBrand]: true;
30
+ constructor(cause: unknown);
31
+ }
32
+ declare const FAILED: unique symbol;
33
+ declare function source<T>(initial: T, equal?: Equal<T>): Source<T>;
34
+ declare function batch<T>(fn: () => T): T;
35
+ declare function derived<T>(compute: Compute<T>, equal?: Equal<T>): Derived<T>;
36
+ declare function derivedResult<T>(compute: Compute<T>, equal?: Equal<T>): Derived<Result<T>>;
37
+ declare function derivedOrNull<T>(compute: Compute<T>, equal?: Equal<T>): Derived<T | null>;
38
+ declare function derivedOrError<T>(compute: Compute<T>, equal?: Equal<T>): Derived<T | Err>;
39
+ declare function derivedOrSymbol<T>(compute: Compute<T>, equal?: Equal<T>): Derived<T | typeof FAILED>;
40
+ declare function subscribe<T>(node: Source<T> | Derived<T>, listener: Listener<T>, onError?: ErrorHandler): () => void;
41
+ //#endregion
42
+ export { Derived, Equal, Err, FAILED, Result, Source, batch, derived, derivedOrError, derivedOrNull, derivedOrSymbol, derivedResult, source, subscribe };
43
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";KAgBY,KAAA,OAAY,QAAA,EAAU,CAAA,EAAG,IAAA,EAAM,CAAA;AAAA,KACtC,OAAA,OAAc,QAAA,EAAU,CAAA,iBAAkB,CAAA;AAAA,KAC1C,QAAA,OAAe,KAAA,EAAO,CAAA;AAAA,KACtB,YAAA,IAAgB,KAAA;AAAA,cAEP,WAAA;AAAA,UACG,MAAA;EAAA,UACL,WAAA,GAAc,CAAA;EAAA,IACpB,CAAA;EAAA,SACK,GAAA,GAAM,KAAA,EAAO,CAAA;AAAA;AAAA,cAGlB,OAAA;AAAA,UACW,OAAA;EAAA,IACX,CAAA;EAAA,UACM,OAAA,IACR,QAAA,EAAU,QAAA,CAAS,CAAA,GACnB,OAAA,EAAS,YAAA;AAAA;AAAA,cAIC,WAAA;AAAA,KACF,MAAA;EAAA,UAAwB,WAAA;AAAA;EAAA,SACrB,EAAA;EAAA,SAAmB,KAAA,EAAO,CAAA;AAAA;EAAA,SAC1B,EAAA;EAAA,SAAoB,KAAA;AAAA;AAAA,cAGrB,QAAA;AAAA,cACD,GAAA,SAAY,KAAA;EAAA,UACL,QAAA;cAEN,KAAA;AAAA;AAAA,cAKD,MAAA;AAAA,iBAmBG,MAAA,GAAA,CACd,OAAA,EAAS,CAAA,EACT,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,MAAA,CAAO,CAAA;AAAA,iBAyBM,KAAA,GAAA,CAAS,EAAA,QAAU,CAAA,GAAI,CAAA;AAAA,iBAyHvB,OAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,CAAA;AAAA,iBAIK,aAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,MAAA,CAAO,CAAA;AAAA,iBAiBF,aAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,CAAA;AAAA,iBAIK,cAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,CAAA,GAAI,GAAA;AAAA,iBAIC,eAAA,GAAA,CACd,OAAA,EAAS,OAAA,CAAQ,CAAA,GACjB,KAAA,GAAO,KAAA,CAAM,CAAA,IACZ,OAAA,CAAQ,CAAA,UAAW,MAAA;AAAA,iBAQN,SAAA,GAAA,CACd,IAAA,EAAM,MAAA,CAAO,CAAA,IAAK,OAAA,CAAQ,CAAA,GAC1B,QAAA,EAAU,QAAA,CAAS,CAAA,GACnB,OAAA,GAAS,YAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,140 @@
1
+ import { createDerivedNode, createSourceNode, endWriteBatch, readDerived, readDerivedOutsideComputation, readSource, releaseRetain, retainDerivedNode, startWriteBatch, writeSource } from "@isograph/pico";
2
+
3
+ //#region src/index.ts
4
+ const observe = Symbol("puchi.subscribe");
5
+ var Err = class extends Error {
6
+ constructor(cause) {
7
+ super("Puchi computation failed", { cause });
8
+ }
9
+ };
10
+ const FAILED = Symbol("puchi.failed");
11
+ let executionContext;
12
+ let isWriteBatchOpen = false;
13
+ function strictEqual(previous, next) {
14
+ return previous === next;
15
+ }
16
+ function requireOutsideComputationOrSubscriber() {
17
+ if (executionContext !== void 0) throw new Error("This operation cannot run inside a computation or subscriber.");
18
+ }
19
+ function source(initial, equal = strictEqual) {
20
+ const handle = createSourceNode(initial);
21
+ let lastAcceptedValue = initial;
22
+ return Object.assign(() => {
23
+ if (isWriteBatchOpen) throw new Error("A source cannot be read inside a write batch.");
24
+ return executionContext === void 0 || executionContext === "subscriber" ? handle.value : readSource(executionContext, handle);
25
+ }, { set(value) {
26
+ requireOutsideComputationOrSubscriber();
27
+ if (!equal(lastAcceptedValue, value)) {
28
+ lastAcceptedValue = value;
29
+ writeSource(handle, value);
30
+ }
31
+ } });
32
+ }
33
+ function batch(fn) {
34
+ requireOutsideComputationOrSubscriber();
35
+ startWriteBatch();
36
+ isWriteBatchOpen = true;
37
+ try {
38
+ return fn();
39
+ } finally {
40
+ isWriteBatchOpen = false;
41
+ endWriteBatch();
42
+ }
43
+ }
44
+ function createResultNode(compute, equal) {
45
+ return createDerivedNode((caller, previous) => {
46
+ const previousContext = executionContext;
47
+ executionContext = caller;
48
+ try {
49
+ const value = compute(previous?.ok === true ? previous.value : void 0);
50
+ return previous?.ok === true && equal(previous.value, value) ? previous : {
51
+ ok: true,
52
+ value
53
+ };
54
+ } catch (error) {
55
+ return previous?.ok === false && previous.error === error ? previous : {
56
+ ok: false,
57
+ error
58
+ };
59
+ } finally {
60
+ executionContext = previousContext;
61
+ }
62
+ });
63
+ }
64
+ function valueOrThrow(result) {
65
+ if (!result.ok) throw result.error;
66
+ return result.value;
67
+ }
68
+ function callHandlerAndForwardErrors(handler, onError) {
69
+ try {
70
+ const result = handler();
71
+ if ((typeof result === "object" && result != null || typeof result === "function") && "then" in result) Promise.resolve(result).catch(onError);
72
+ } catch (error) {
73
+ onError(error);
74
+ }
75
+ }
76
+ function logError(error) {
77
+ console.error(error);
78
+ }
79
+ function createDerivedReader(handle, toPublicValue) {
80
+ function read() {
81
+ if (isWriteBatchOpen) throw new Error("A derived value cannot be read inside a write batch.");
82
+ return toPublicValue(executionContext === void 0 || executionContext === "subscriber" ? readDerivedOutsideComputation(handle) : readDerived(executionContext, handle));
83
+ }
84
+ function listen(listener, onError) {
85
+ requireOutsideComputationOrSubscriber();
86
+ if (isWriteBatchOpen) throw new Error("A subscription cannot start inside a write batch.");
87
+ const reportListenerError = (error) => {
88
+ queueMicrotask(() => callHandlerAndForwardErrors(() => onError(error), logError));
89
+ };
90
+ let retain = retainDerivedNode(handle, (stored) => {
91
+ const previousContext = executionContext;
92
+ executionContext = "subscriber";
93
+ try {
94
+ callHandlerAndForwardErrors(() => listener(toPublicValue(stored)), reportListenerError);
95
+ } finally {
96
+ executionContext = previousContext;
97
+ }
98
+ });
99
+ return () => {
100
+ if (retain !== void 0) {
101
+ requireOutsideComputationOrSubscriber();
102
+ releaseRetain(retain);
103
+ retain = void 0;
104
+ }
105
+ };
106
+ }
107
+ return Object.assign(read, { [observe]: listen });
108
+ }
109
+ function identity(value) {
110
+ return value;
111
+ }
112
+ function derived(compute, equal = strictEqual) {
113
+ return createDerivedReader(createResultNode(compute, equal), valueOrThrow);
114
+ }
115
+ function derivedResult(compute, equal = strictEqual) {
116
+ return createDerivedReader(createResultNode(compute, equal), identity);
117
+ }
118
+ function createDerivedWithFallback(compute, equal, fallback) {
119
+ const result = createResultNode(compute, equal);
120
+ return createDerivedReader(createDerivedNode((caller) => {
121
+ const state = readDerived(caller, result);
122
+ return state.ok ? state.value : fallback(state.error);
123
+ }), identity);
124
+ }
125
+ function derivedOrNull(compute, equal = strictEqual) {
126
+ return createDerivedWithFallback(compute, equal, () => null);
127
+ }
128
+ function derivedOrError(compute, equal = strictEqual) {
129
+ return createDerivedWithFallback(compute, equal, (error) => new Err(error));
130
+ }
131
+ function derivedOrSymbol(compute, equal = strictEqual) {
132
+ return createDerivedWithFallback(compute, equal, () => FAILED);
133
+ }
134
+ function subscribe(node, listener, onError = logError) {
135
+ return (observe in node ? node : derived(node))[observe](listener, onError);
136
+ }
137
+
138
+ //#endregion
139
+ export { Err, FAILED, batch, derived, derivedOrError, derivedOrNull, derivedOrSymbol, derivedResult, source, subscribe };
140
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["import {\n createDerivedNode,\n createSourceNode,\n endWriteBatch,\n readDerived,\n readDerivedOutsideComputation,\n readSource,\n releaseRetain,\n retainDerivedNode,\n startWriteBatch,\n writeSource,\n type CallingNode,\n type DerivedNode,\n type Retain,\n} from '@isograph/pico';\n\nexport type Equal<T> = (previous: T, next: T) => boolean;\ntype Compute<T> = (previous: T | undefined) => T;\ntype Listener<T> = (value: T) => unknown;\ntype ErrorHandler = (error: unknown) => unknown;\n\ndeclare const sourceBrand: unique symbol;\nexport interface Source<T> {\n readonly [sourceBrand]: T;\n (): T;\n readonly set: (value: T) => void;\n}\n\nconst observe = Symbol('puchi.subscribe');\nexport interface Derived<T> {\n (): T;\n readonly [observe]: (\n listener: Listener<T>,\n onError: ErrorHandler,\n ) => () => void;\n}\n\ndeclare const resultBrand: unique symbol;\nexport type Result<T> = { readonly [resultBrand]: true } & (\n | { readonly ok: true; readonly value: T }\n | { readonly ok: false; readonly error: unknown }\n);\n\ndeclare const errBrand: unique symbol;\nexport class Err extends Error {\n declare readonly [errBrand]: true;\n\n constructor(cause: unknown) {\n super('Puchi computation failed', { cause });\n }\n}\n\nexport const FAILED: unique symbol = Symbol('puchi.failed');\n\n// A computation records reads on its CallingNode. Subscribers can read final\n// values without recording dependencies, and may write only after they return.\nlet executionContext: CallingNode | 'subscriber' | undefined;\nlet isWriteBatchOpen = false;\n\nfunction strictEqual<T>(previous: T, next: T): boolean {\n return previous === next;\n}\n\nfunction requireOutsideComputationOrSubscriber(): void {\n if (executionContext !== undefined) {\n throw new Error(\n 'This operation cannot run inside a computation or subscriber.',\n );\n }\n}\n\nexport function source<T>(\n initial: T,\n equal: Equal<T> = strictEqual,\n): Source<T> {\n const handle = createSourceNode(initial);\n // During a batch, handle.value still holds the committed value. Compare\n // each set with the last accepted write, including pending writes.\n let lastAcceptedValue = initial;\n return Object.assign(\n () => {\n if (isWriteBatchOpen)\n throw new Error('A source cannot be read inside a write batch.');\n return executionContext === undefined || executionContext === 'subscriber'\n ? handle.value\n : readSource(executionContext, handle);\n },\n {\n set(value: T) {\n requireOutsideComputationOrSubscriber();\n if (!equal(lastAcceptedValue, value)) {\n lastAcceptedValue = value;\n writeSource(handle, value);\n }\n },\n },\n ) as Source<T>;\n}\n\nexport function batch<T>(fn: () => T): T {\n requireOutsideComputationOrSubscriber();\n startWriteBatch();\n isWriteBatchOpen = true;\n try {\n return fn();\n } finally {\n // endWriteBatch calls subscribers, which can read the committed values.\n isWriteBatchOpen = false;\n endWriteBatch();\n }\n}\n\nfunction createResultNode<T>(\n compute: Compute<T>,\n equal: Equal<T>,\n): DerivedNode<Result<T>> {\n return createDerivedNode<Result<T>>((caller, previous) => {\n // A nested derived read can enter another computation. Restore its caller\n // in finally so subsequent reads still belong to the outer computation.\n const previousContext = executionContext;\n executionContext = caller;\n try {\n const value = compute(previous?.ok === true ? previous.value : undefined);\n return previous?.ok === true && equal(previous.value, value)\n ? previous\n : ({ ok: true, value } as Result<T>);\n } catch (error) {\n return previous?.ok === false && previous.error === error\n ? previous\n : ({ ok: false, error } as Result<T>);\n } finally {\n executionContext = previousContext;\n }\n });\n}\n\nfunction valueOrThrow<T>(result: Result<T>): T {\n if (!result.ok) throw result.error;\n return result.value;\n}\n\nfunction callHandlerAndForwardErrors(\n handler: () => unknown,\n onError: (error: unknown) => void,\n): void {\n try {\n const result = handler();\n if (\n ((typeof result === 'object' && result != null) ||\n typeof result === 'function') &&\n 'then' in result\n ) {\n // Notification finishes synchronously. Forward a later rejection to\n // onError even though the caller doesn't await the handler's result.\n void Promise.resolve(result).catch(onError);\n }\n } catch (error) {\n onError(error);\n }\n}\n\nfunction logError(error: unknown): void {\n console.error(error);\n}\n\nfunction createDerivedReader<Stored, T>(\n handle: DerivedNode<Stored>,\n toPublicValue: (stored: Stored) => T,\n): Derived<T> {\n function read(): T {\n if (isWriteBatchOpen)\n throw new Error('A derived value cannot be read inside a write batch.');\n const value =\n executionContext === undefined || executionContext === 'subscriber'\n ? readDerivedOutsideComputation(handle)\n : readDerived(executionContext, handle);\n return toPublicValue(value);\n }\n\n function listen(listener: Listener<T>, onError: ErrorHandler): () => void {\n requireOutsideComputationOrSubscriber();\n if (isWriteBatchOpen)\n throw new Error('A subscription cannot start inside a write batch.');\n // Deliver errors after Pico finishes the flush so one listener's error\n // handler runs independently of the remaining subscribers.\n const reportListenerError = (error: unknown) => {\n queueMicrotask(() =>\n callHandlerAndForwardErrors(() => onError(error), logError),\n );\n };\n let retain: Retain<Stored> | undefined = retainDerivedNode(\n handle,\n (stored) => {\n const previousContext = executionContext;\n executionContext = 'subscriber';\n try {\n callHandlerAndForwardErrors(\n () => listener(toPublicValue(stored)),\n reportListenerError,\n );\n } finally {\n executionContext = previousContext;\n }\n },\n );\n return () => {\n if (retain !== undefined) {\n requireOutsideComputationOrSubscriber();\n releaseRetain(retain);\n retain = undefined;\n }\n };\n }\n return Object.assign(read, { [observe]: listen });\n}\n\nfunction identity<T>(value: T): T {\n return value;\n}\n\nexport function derived<T>(\n compute: Compute<T>,\n equal: Equal<T> = strictEqual,\n): Derived<T> {\n return createDerivedReader(createResultNode(compute, equal), valueOrThrow);\n}\n\nexport function derivedResult<T>(\n compute: Compute<T>,\n equal: Equal<T> = strictEqual,\n): Derived<Result<T>> {\n return createDerivedReader(createResultNode(compute, equal), identity);\n}\n\nfunction createDerivedWithFallback<T, F>(\n compute: Compute<T>,\n equal: Equal<T>,\n fallback: (cause: unknown) => F,\n): Derived<T | F> {\n const result = createResultNode(compute, equal);\n const handle = createDerivedNode((caller) => {\n const state = readDerived(caller, result);\n return state.ok ? state.value : fallback(state.error);\n });\n return createDerivedReader(handle, identity);\n}\n\nexport function derivedOrNull<T>(\n compute: Compute<T>,\n equal: Equal<T> = strictEqual,\n): Derived<T | null> {\n return createDerivedWithFallback(compute, equal, () => null);\n}\n\nexport function derivedOrError<T>(\n compute: Compute<T>,\n equal: Equal<T> = strictEqual,\n): Derived<T | Err> {\n return createDerivedWithFallback(compute, equal, (error) => new Err(error));\n}\n\nexport function derivedOrSymbol<T>(\n compute: Compute<T>,\n equal: Equal<T> = strictEqual,\n): Derived<T | typeof FAILED> {\n return createDerivedWithFallback<T, typeof FAILED>(\n compute,\n equal,\n () => FAILED,\n );\n}\n\nexport function subscribe<T>(\n node: Source<T> | Derived<T>,\n listener: Listener<T>,\n onError: ErrorHandler = logError,\n): () => void {\n const observed = observe in node ? node : derived(node);\n return observed[observe](listener, onError);\n}\n"],"mappings":"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"}
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@isograph/puchi",
3
+ "version": "0.0.0-main-5f205c00",
4
+ "description": "Callable sources and derived values with batching, subscriptions, and recoverable errors for pico-js.",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "files": [
9
+ "LICENSE-MIT",
10
+ "dist",
11
+ "src"
12
+ ],
13
+ "main": "./dist/index.cjs",
14
+ "types": "./dist/index.d.cts",
15
+ "license": "MIT",
16
+ "dependencies": {
17
+ "@isograph/pico": "0.0.0-main-5f205c00"
18
+ },
19
+ "devDependencies": {
20
+ "typescript": "5.6.3"
21
+ },
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/isographlabs/isograph.git",
25
+ "directory": "libs/puchi"
26
+ },
27
+ "sideEffects": false,
28
+ "module": "./dist/index.mjs",
29
+ "exports": {
30
+ ".": {
31
+ "module-sync": "./dist/index.mjs",
32
+ "module": "./dist/index.mjs",
33
+ "node": "./dist/index.cjs",
34
+ "default": "./dist/index.mjs"
35
+ },
36
+ "./package.json": "./package.json"
37
+ },
38
+ "scripts": {
39
+ "compile-libs": "tsdown",
40
+ "watch-libs": "tsdown --watch",
41
+ "tsc": "tsc -b",
42
+ "tsc-force": "tsc --build --clean && tsc --build --force"
43
+ }
44
+ }
package/src/index.ts ADDED
@@ -0,0 +1,280 @@
1
+ import {
2
+ createDerivedNode,
3
+ createSourceNode,
4
+ endWriteBatch,
5
+ readDerived,
6
+ readDerivedOutsideComputation,
7
+ readSource,
8
+ releaseRetain,
9
+ retainDerivedNode,
10
+ startWriteBatch,
11
+ writeSource,
12
+ type CallingNode,
13
+ type DerivedNode,
14
+ type Retain,
15
+ } from '@isograph/pico';
16
+
17
+ export type Equal<T> = (previous: T, next: T) => boolean;
18
+ type Compute<T> = (previous: T | undefined) => T;
19
+ type Listener<T> = (value: T) => unknown;
20
+ type ErrorHandler = (error: unknown) => unknown;
21
+
22
+ declare const sourceBrand: unique symbol;
23
+ export interface Source<T> {
24
+ readonly [sourceBrand]: T;
25
+ (): T;
26
+ readonly set: (value: T) => void;
27
+ }
28
+
29
+ const observe = Symbol('puchi.subscribe');
30
+ export interface Derived<T> {
31
+ (): T;
32
+ readonly [observe]: (
33
+ listener: Listener<T>,
34
+ onError: ErrorHandler,
35
+ ) => () => void;
36
+ }
37
+
38
+ declare const resultBrand: unique symbol;
39
+ export type Result<T> = { readonly [resultBrand]: true } & (
40
+ | { readonly ok: true; readonly value: T }
41
+ | { readonly ok: false; readonly error: unknown }
42
+ );
43
+
44
+ declare const errBrand: unique symbol;
45
+ export class Err extends Error {
46
+ declare readonly [errBrand]: true;
47
+
48
+ constructor(cause: unknown) {
49
+ super('Puchi computation failed', { cause });
50
+ }
51
+ }
52
+
53
+ export const FAILED: unique symbol = Symbol('puchi.failed');
54
+
55
+ // A computation records reads on its CallingNode. Subscribers can read final
56
+ // values without recording dependencies, and may write only after they return.
57
+ let executionContext: CallingNode | 'subscriber' | undefined;
58
+ let isWriteBatchOpen = false;
59
+
60
+ function strictEqual<T>(previous: T, next: T): boolean {
61
+ return previous === next;
62
+ }
63
+
64
+ function requireOutsideComputationOrSubscriber(): void {
65
+ if (executionContext !== undefined) {
66
+ throw new Error(
67
+ 'This operation cannot run inside a computation or subscriber.',
68
+ );
69
+ }
70
+ }
71
+
72
+ export function source<T>(
73
+ initial: T,
74
+ equal: Equal<T> = strictEqual,
75
+ ): Source<T> {
76
+ const handle = createSourceNode(initial);
77
+ // During a batch, handle.value still holds the committed value. Compare
78
+ // each set with the last accepted write, including pending writes.
79
+ let lastAcceptedValue = initial;
80
+ return Object.assign(
81
+ () => {
82
+ if (isWriteBatchOpen)
83
+ throw new Error('A source cannot be read inside a write batch.');
84
+ return executionContext === undefined || executionContext === 'subscriber'
85
+ ? handle.value
86
+ : readSource(executionContext, handle);
87
+ },
88
+ {
89
+ set(value: T) {
90
+ requireOutsideComputationOrSubscriber();
91
+ if (!equal(lastAcceptedValue, value)) {
92
+ lastAcceptedValue = value;
93
+ writeSource(handle, value);
94
+ }
95
+ },
96
+ },
97
+ ) as Source<T>;
98
+ }
99
+
100
+ export function batch<T>(fn: () => T): T {
101
+ requireOutsideComputationOrSubscriber();
102
+ startWriteBatch();
103
+ isWriteBatchOpen = true;
104
+ try {
105
+ return fn();
106
+ } finally {
107
+ // endWriteBatch calls subscribers, which can read the committed values.
108
+ isWriteBatchOpen = false;
109
+ endWriteBatch();
110
+ }
111
+ }
112
+
113
+ function createResultNode<T>(
114
+ compute: Compute<T>,
115
+ equal: Equal<T>,
116
+ ): DerivedNode<Result<T>> {
117
+ return createDerivedNode<Result<T>>((caller, previous) => {
118
+ // A nested derived read can enter another computation. Restore its caller
119
+ // in finally so subsequent reads still belong to the outer computation.
120
+ const previousContext = executionContext;
121
+ executionContext = caller;
122
+ try {
123
+ const value = compute(previous?.ok === true ? previous.value : undefined);
124
+ return previous?.ok === true && equal(previous.value, value)
125
+ ? previous
126
+ : ({ ok: true, value } as Result<T>);
127
+ } catch (error) {
128
+ return previous?.ok === false && previous.error === error
129
+ ? previous
130
+ : ({ ok: false, error } as Result<T>);
131
+ } finally {
132
+ executionContext = previousContext;
133
+ }
134
+ });
135
+ }
136
+
137
+ function valueOrThrow<T>(result: Result<T>): T {
138
+ if (!result.ok) throw result.error;
139
+ return result.value;
140
+ }
141
+
142
+ function callHandlerAndForwardErrors(
143
+ handler: () => unknown,
144
+ onError: (error: unknown) => void,
145
+ ): void {
146
+ try {
147
+ const result = handler();
148
+ if (
149
+ ((typeof result === 'object' && result != null) ||
150
+ typeof result === 'function') &&
151
+ 'then' in result
152
+ ) {
153
+ // Notification finishes synchronously. Forward a later rejection to
154
+ // onError even though the caller doesn't await the handler's result.
155
+ void Promise.resolve(result).catch(onError);
156
+ }
157
+ } catch (error) {
158
+ onError(error);
159
+ }
160
+ }
161
+
162
+ function logError(error: unknown): void {
163
+ console.error(error);
164
+ }
165
+
166
+ function createDerivedReader<Stored, T>(
167
+ handle: DerivedNode<Stored>,
168
+ toPublicValue: (stored: Stored) => T,
169
+ ): Derived<T> {
170
+ function read(): T {
171
+ if (isWriteBatchOpen)
172
+ throw new Error('A derived value cannot be read inside a write batch.');
173
+ const value =
174
+ executionContext === undefined || executionContext === 'subscriber'
175
+ ? readDerivedOutsideComputation(handle)
176
+ : readDerived(executionContext, handle);
177
+ return toPublicValue(value);
178
+ }
179
+
180
+ function listen(listener: Listener<T>, onError: ErrorHandler): () => void {
181
+ requireOutsideComputationOrSubscriber();
182
+ if (isWriteBatchOpen)
183
+ throw new Error('A subscription cannot start inside a write batch.');
184
+ // Deliver errors after Pico finishes the flush so one listener's error
185
+ // handler runs independently of the remaining subscribers.
186
+ const reportListenerError = (error: unknown) => {
187
+ queueMicrotask(() =>
188
+ callHandlerAndForwardErrors(() => onError(error), logError),
189
+ );
190
+ };
191
+ let retain: Retain<Stored> | undefined = retainDerivedNode(
192
+ handle,
193
+ (stored) => {
194
+ const previousContext = executionContext;
195
+ executionContext = 'subscriber';
196
+ try {
197
+ callHandlerAndForwardErrors(
198
+ () => listener(toPublicValue(stored)),
199
+ reportListenerError,
200
+ );
201
+ } finally {
202
+ executionContext = previousContext;
203
+ }
204
+ },
205
+ );
206
+ return () => {
207
+ if (retain !== undefined) {
208
+ requireOutsideComputationOrSubscriber();
209
+ releaseRetain(retain);
210
+ retain = undefined;
211
+ }
212
+ };
213
+ }
214
+ return Object.assign(read, { [observe]: listen });
215
+ }
216
+
217
+ function identity<T>(value: T): T {
218
+ return value;
219
+ }
220
+
221
+ export function derived<T>(
222
+ compute: Compute<T>,
223
+ equal: Equal<T> = strictEqual,
224
+ ): Derived<T> {
225
+ return createDerivedReader(createResultNode(compute, equal), valueOrThrow);
226
+ }
227
+
228
+ export function derivedResult<T>(
229
+ compute: Compute<T>,
230
+ equal: Equal<T> = strictEqual,
231
+ ): Derived<Result<T>> {
232
+ return createDerivedReader(createResultNode(compute, equal), identity);
233
+ }
234
+
235
+ function createDerivedWithFallback<T, F>(
236
+ compute: Compute<T>,
237
+ equal: Equal<T>,
238
+ fallback: (cause: unknown) => F,
239
+ ): Derived<T | F> {
240
+ const result = createResultNode(compute, equal);
241
+ const handle = createDerivedNode((caller) => {
242
+ const state = readDerived(caller, result);
243
+ return state.ok ? state.value : fallback(state.error);
244
+ });
245
+ return createDerivedReader(handle, identity);
246
+ }
247
+
248
+ export function derivedOrNull<T>(
249
+ compute: Compute<T>,
250
+ equal: Equal<T> = strictEqual,
251
+ ): Derived<T | null> {
252
+ return createDerivedWithFallback(compute, equal, () => null);
253
+ }
254
+
255
+ export function derivedOrError<T>(
256
+ compute: Compute<T>,
257
+ equal: Equal<T> = strictEqual,
258
+ ): Derived<T | Err> {
259
+ return createDerivedWithFallback(compute, equal, (error) => new Err(error));
260
+ }
261
+
262
+ export function derivedOrSymbol<T>(
263
+ compute: Compute<T>,
264
+ equal: Equal<T> = strictEqual,
265
+ ): Derived<T | typeof FAILED> {
266
+ return createDerivedWithFallback<T, typeof FAILED>(
267
+ compute,
268
+ equal,
269
+ () => FAILED,
270
+ );
271
+ }
272
+
273
+ export function subscribe<T>(
274
+ node: Source<T> | Derived<T>,
275
+ listener: Listener<T>,
276
+ onError: ErrorHandler = logError,
277
+ ): () => void {
278
+ const observed = observe in node ? node : derived(node);
279
+ return observed[observe](listener, onError);
280
+ }