@shadow-js/core 1.0.3 → 1.0.4
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/CHANGELOG.md +6 -0
- package/README.md +1 -2
- package/dist/dev/effect.js +8 -11
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/internal/dispose.js +2 -8
- package/dist/dev/internal/dispose.js.map +1 -1
- package/dist/dev/internal/graph.js +3 -3
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/scheduler.js +24 -15
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/internal/state.js +11 -3
- package/dist/dev/internal/state.js.map +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/effect.js.map +1 -1
- package/dist/prod/internal/dispose.js +1 -1
- package/dist/prod/internal/dispose.js.map +1 -1
- package/dist/prod/internal/graph.js +1 -1
- package/dist/prod/internal/graph.js.map +1 -1
- package/dist/prod/internal/scheduler.js +1 -1
- package/dist/prod/internal/scheduler.js.map +1 -1
- package/dist/prod/internal/state.js +1 -1
- package/dist/prod/internal/state.js.map +1 -1
- package/dist/server/effect.js.map +1 -1
- package/dist/server/internal/dispose.js +1 -1
- package/dist/server/internal/dispose.js.map +1 -1
- package/dist/server/internal/graph.js +1 -1
- package/dist/server/internal/graph.js.map +1 -1
- package/dist/server/internal/scheduler.js +1 -1
- package/dist/server/internal/scheduler.js.map +1 -1
- package/dist/server/internal/state.js +1 -1
- package/dist/server/internal/state.js.map +1 -1
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/internal/dispose.js +2 -8
- package/dist/server-dev/internal/dispose.js.map +1 -1
- package/dist/server-dev/internal/graph.js +3 -3
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +24 -15
- package/dist/server-dev/internal/scheduler.js.map +1 -1
- package/dist/server-dev/internal/state.js +11 -3
- package/dist/server-dev/internal/state.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
package/README.md
CHANGED
|
@@ -14,8 +14,7 @@ later is the effects and bindings inside them.
|
|
|
14
14
|
npm install @shadow-js/core
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
repository.
|
|
17
|
+
To try a change that is not released yet, install from a local checkout of this repository.
|
|
19
18
|
Requires Node 22.12 or newer for tooling; the package is ESM only.
|
|
20
19
|
|
|
21
20
|
## Example
|
package/dist/dev/effect.js
CHANGED
|
@@ -2,28 +2,25 @@ import { warn } from "./internal/diagnostics.js";
|
|
|
2
2
|
import { untrack } from "./ownership.js";
|
|
3
3
|
import { createComputation, currentOwner } from "./extend/index.js";
|
|
4
4
|
// src/effect.ts
|
|
5
|
-
function createEffect(
|
|
5
|
+
function createEffect(fn, apply, render, defer, name) {
|
|
6
6
|
if (currentOwner() === null) warn("NO_OWNER_EFFECT");
|
|
7
|
-
let fn = fnIn;
|
|
8
|
-
let apply = applyIn;
|
|
9
|
-
let defer = deferIn;
|
|
10
7
|
const gate = render ? null : currentOwner()?.gate ?? null;
|
|
11
8
|
if (gate !== null) {
|
|
12
9
|
let opened = false;
|
|
13
10
|
let closed = false;
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
|
|
11
|
+
let skip = defer;
|
|
12
|
+
const run = fn;
|
|
13
|
+
const then = apply;
|
|
17
14
|
defer = false;
|
|
18
15
|
fn = (previous) => {
|
|
19
16
|
closed = !opened && gate();
|
|
20
17
|
opened ||= !closed;
|
|
21
|
-
return closed ? void 0 :
|
|
18
|
+
return closed ? void 0 : run(previous);
|
|
22
19
|
};
|
|
23
|
-
if (
|
|
20
|
+
if (then !== null) apply = (value, previous) => {
|
|
24
21
|
if (closed) return void 0;
|
|
25
|
-
if (!
|
|
26
|
-
|
|
22
|
+
if (!skip) return then(value, previous);
|
|
23
|
+
skip = false;
|
|
27
24
|
};
|
|
28
25
|
}
|
|
29
26
|
createComputation({
|
package/dist/dev/effect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effect.js","names":[],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\nfunction createEffect(\n
|
|
1
|
+
{"version":3,"file":"effect.js","names":[],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\nfunction createEffect(\n fn: (previous: never) => unknown,\n apply: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n defer: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (__DEV__ && currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n const gate = render ? null : (currentOwner()?.gate ?? null);\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect. `closed` is what the latest run of `fn`\n // found: `apply` runs right after it, and does nothing for a run that was held. `defer` skips\n // the first real run, not the held one, so it is handled here.\n let opened = false;\n let closed = false;\n let skip = defer;\n const run = fn;\n const then = apply;\n defer = false;\n fn = (previous) => {\n closed = !opened && gate();\n opened ||= !closed;\n return closed ? undefined : run(previous);\n };\n if (then !== null) {\n apply = (value, previous) => {\n if (closed) return undefined;\n if (!skip) return then(value, previous);\n skip = false;\n return undefined;\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n apply: apply ?? undefined,\n name,\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":";;;;AA4BA,SAAS,aACP,IACA,OACA,QACA,OACA,MACM;CAGN,IAAe,aAAa,MAAM,MAAM,KAAK,iBAAiB;CAC9D,MAAM,OAAO,SAAS,OAAQ,aAAa,CAAC,EAAE,QAAQ;CACtD,IAAI,SAAS,MAAM;EAKjB,IAAI,SAAS;EACb,IAAI,SAAS;EACb,IAAI,OAAO;EACX,MAAM,MAAM;EACZ,MAAM,OAAO;EACb,QAAQ;EACR,MAAM,aAAa;GACjB,SAAS,CAAC,UAAU,KAAK;GACzB,WAAW,CAAC;GACZ,OAAO,SAAS,KAAA,IAAY,IAAI,QAAQ;EAC1C;EACA,IAAI,SAAS,MACX,SAAS,OAAO,aAAa;GAC3B,IAAI,QAAQ,OAAO,KAAA;GACnB,IAAI,CAAC,MAAM,OAAO,KAAK,OAAO,QAAQ;GACtC,OAAO;EAET;CAEJ;CACA,kBAAkB;EAChB,MAAM;EACN;EACA;EACA;EACA,OAAO,SAAS,KAAA;EAChB;CACF,CAAC;AACH;AA0DA,SAAgB,UACd,OACA,QACA,OACM;CACN,IAAI,OAAO,WAAW,YACpB,aACE,OACA,QACA,OACA,OAAO,UAAU,MACjB,OAAO,IACT;MACK;EACL,IAAI,MAAM,QAAQ,MAAM,GAAG,KAAK,qBAAqB;EACrD,aAAa,OAAO,MAAM,OAAO,OAAQ,QAAsC,IAAI;CACrF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,gBACd,SACA,OACM;CACN,aACE,SACC,SAAS,MACV,MACA,OACA,KAAA,CACF;AACF;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,QAAQ,IAAgC;CACtD,mBAAmB,QAAQ,EAAE,GAAG,MAAM,OAAO,OAAO,SAAS;AAC/D"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { rt } from "./state.js";
|
|
2
2
|
import { disposeTree as disposeTree$1 } from "./owner.js";
|
|
3
3
|
import { hasPending } from "./queue.js";
|
|
4
|
-
import {
|
|
4
|
+
import { flushThenThrow } from "./scheduler.js";
|
|
5
5
|
// src/internal/dispose.ts
|
|
6
6
|
/**
|
|
7
7
|
* Disposes an owner and everything below it: children first, newest first, then each node's
|
|
@@ -35,13 +35,7 @@ function disposeTree(root) {
|
|
|
35
35
|
failed = true;
|
|
36
36
|
failure = error;
|
|
37
37
|
}
|
|
38
|
-
|
|
39
|
-
flush();
|
|
40
|
-
} catch (error) {
|
|
41
|
-
if (!failed) throw error;
|
|
42
|
-
throw new AggregateError([failure, error], "Disposal and the following flush both threw.");
|
|
43
|
-
}
|
|
44
|
-
if (failed) throw failure;
|
|
38
|
+
flushThenThrow(rt.running === null && rt.batches === 0 && rt.disposing === 0 && !rt.flushing && hasPending(), failed, failure, "Disposal and the following flush both threw.");
|
|
45
39
|
}
|
|
46
40
|
export { disposeTree };
|
|
47
41
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispose.js","names":[],"sources":["../../../src/internal/dispose.ts"],"sourcesContent":["import type { Owner } from \"./owner\";\nimport { disposeTree as disposeSubtree } from \"./owner\";\nimport { hasPending } from \"./queue\";\nimport {
|
|
1
|
+
{"version":3,"file":"dispose.js","names":[],"sources":["../../../src/internal/dispose.ts"],"sourcesContent":["import type { Owner } from \"./owner\";\nimport { disposeTree as disposeSubtree } from \"./owner\";\nimport { hasPending } from \"./queue\";\nimport { flushThenThrow } from \"./scheduler\";\nimport { rt } from \"./state\";\n\n/**\n * Disposes an owner and everything below it: children first, newest first, then each node's\n * cleanups, newest first. Use it to end an owner made with `createOwner`; disposing an owner that is\n * already disposed does nothing. Exported from `@shadow-js/core/extend` as `disposeOwner`.\n *\n * Cleanups run in an implicit batch (O-3): effects that depend on signals a cleanup wrote are\n * flushed before this returns, unless the disposal happens inside a computation, a batch or a flush,\n * whose own exit flushes.\n *\n * @param root The owner to dispose, with its whole subtree.\n * @throws The error of a cleanup that no error handler caught, once the whole tree is disposed\n * (several such errors are thrown together as an `AggregateError`); during a running flush, that\n * flush throws them instead. An error of the flush that\n * follows is thrown as is, or combined with the cleanup errors in an `AggregateError`.\n * @example\n * import { addCleanup, createOwner, disposeOwner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * addCleanup(owner, () => console.log(\"released\"));\n * disposeOwner(owner); // logs \"released\"\n * @see addCleanup\n * @since 1.0.0\n */\nexport function disposeTree(root: Owner): void {\n let failure: unknown;\n let failed = false;\n try {\n disposeSubtree(root);\n } catch (error) {\n failed = true;\n failure = error;\n }\n // Only the outermost disposal flushes: a nested one (a cleanup disposing another owner) would run\n // effects while the tree it sits in is half torn down.\n flushThenThrow(\n rt.running === null && rt.batches === 0 && rt.disposing === 0 && !rt.flushing && hasPending(),\n failed,\n failure,\n __DEV__ ? \"Disposal and the following flush both threw.\" : \"SHADOW_DISPOSE_FLUSH_ERRORS\",\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,SAAgB,YAAY,MAAmB;CAC7C,IAAI;CACJ,IAAI,SAAS;CACb,IAAI;EACF,cAAe,IAAI;CACrB,SAAS,OAAO;EACd,SAAS;EACT,UAAU;CACZ;CAGA,eACE,GAAG,YAAY,QAAQ,GAAG,YAAY,KAAK,GAAG,cAAc,KAAK,CAAC,GAAG,YAAY,WAAW,GAC5F,QACA,SACU,8CACZ;AACF"}
|
|
@@ -390,7 +390,7 @@ function readSignal(signal) {
|
|
|
390
390
|
/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */
|
|
391
391
|
function readMemo(memo) {
|
|
392
392
|
if ((memo.flags & 1) !== 0) throw new ShadowError("CYCLE_DETECTED");
|
|
393
|
-
if (memo.state !== 0 && refreshAncestors(memo)) updateIfNecessary(memo, rt.
|
|
393
|
+
if (memo.state !== 0 && refreshAncestors(memo)) updateIfNecessary(memo, rt.nesting >= DEEP_LIMIT);
|
|
394
394
|
if (rt.listener !== null) track(memo);
|
|
395
395
|
if ((memo.flags & 8) !== 0) throw memo.error;
|
|
396
396
|
return memo.value;
|
|
@@ -416,7 +416,7 @@ function recompute(node) {
|
|
|
416
416
|
rt.owner = node;
|
|
417
417
|
rt.listener = node;
|
|
418
418
|
rt.running = node;
|
|
419
|
-
rt.
|
|
419
|
+
rt.nesting += 1;
|
|
420
420
|
node.state = 0;
|
|
421
421
|
node.flags |= 1;
|
|
422
422
|
node.stamp = nextSequence();
|
|
@@ -433,7 +433,7 @@ function recompute(node) {
|
|
|
433
433
|
rt.owner = previousOwner;
|
|
434
434
|
rt.listener = previousListener;
|
|
435
435
|
rt.running = previousRunning;
|
|
436
|
-
rt.
|
|
436
|
+
rt.nesting -= 1;
|
|
437
437
|
node.flags &= -2;
|
|
438
438
|
unlinkFrom(node, (node.flags & 4) !== 0 ? 0 : node.trackIndex);
|
|
439
439
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"graph.js","names":[],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport {\n addCleanup,\n disposeChildren,\n finishDisposal,\n handleError,\n hasErrorHandler,\n Owner,\n} from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n declare value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n declare equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name?: string) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /** 1 for a memo, 2 for an effect. */\n declare kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n declare state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n declare flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n declare value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n declare equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n declare seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkFrom(this, 0);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n staleObservers((markStack.pop() as Computation).observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at] as Computation;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] as number;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (!needsUpdate(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n if (!refreshAncestors(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n (frameNodes[i] as Computation).flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/** True when `node` is stale, alive and not frozen: running it now is both possible and needed. */\nfunction needsUpdate(node: Computation): boolean {\n return node.state !== CLEAN && (node.flags & FLAG_DISPOSED) === 0 && !isFrozen(node);\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n *\n * @returns Whether `node` still needs updating afterward (an owner's run may have cleaned or disposed it).\n */\nexport function refreshAncestors(node: Computation): boolean {\n if (!needsUpdate(node)) return false;\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (\n owner instanceof Computation &&\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_REFRESHING)) === 0\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i] as Computation;\n if (needsUpdate(ancestor)) updateIfNecessary(ancestor);\n }\n return needsUpdate(node);\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && refreshAncestors(memo)) {\n updateIfNecessary(memo, rt.recomputeDepth >= DEEP_LIMIT);\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n // One disposal for the children and the cleanups: all of them run even when one throws (the errors\n // are held in rt.uncaught), and the node still re-runs (it would stay dirty otherwise).\n rt.disposing += 1;\n try {\n disposeChildren(node);\n node.runCleanups();\n } finally {\n rt.disposing -= 1;\n }\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.recomputeDepth += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.recomputeDepth -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies. A node disposed while it ran\n // (it disposed its own owner) keeps none: reads after the disposal must not leave edges that\n // nothing will ever remove.\n unlinkFrom(node, (node.flags & FLAG_DISPOSED) !== 0 ? 0 : node.trackIndex);\n }\n\n let changed = true;\n if (node.kind === KIND_MEMO) changed = settleMemo(node, result, failed, failure);\n else settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n // The teardown's errors are thrown once the run is settled (unless a flush or an outer disposal collects them).\n rt.disposing += 1;\n finishDisposal();\n}\n\n/**\n * Calls a comparator untracked. It is a user callback: left tracked, the computation that writes (or the\n * reader that pulled the memo, the listener again once the run is over) would subscribe to whatever it\n * reads. Restored in `finally`, so a throwing comparator leaves the register as it found it.\n */\nexport function isEqual<T>(equals: (prev: T, next: T) => boolean, prev: T, next: T): boolean {\n const listener = rt.listener;\n rt.listener = null;\n try {\n return equals(prev, next);\n } finally {\n rt.listener = listener;\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !isEqual(equals, node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0) node.runCleanups();\n }\n}\n"],"mappings":";;;;;;AA+BA,MAAM,aAA4B,OAAO,OAAO,CAA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nC,KAAK,KAAK,QAAA,OAA2B,GAAG,KAAK,YAAY;CAC3D;AACF"}
|
|
1
|
+
{"version":3,"file":"graph.js","names":[],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport {\n addCleanup,\n disposeChildren,\n finishDisposal,\n handleError,\n hasErrorHandler,\n Owner,\n} from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n declare value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n declare equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name?: string) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n // Fields the constructor assigns are `declare`d: a plain field would also emit an empty initializer\n // (`parent;`) that every bundle carries.\n /** 1 for a memo, 2 for an effect. */\n declare kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n declare state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n declare flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n declare value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n declare equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n declare seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n declare name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkFrom(this, 0);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n staleObservers((markStack.pop() as Computation).observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at] as Computation;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] as number;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (!needsUpdate(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n if (!refreshAncestors(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n (frameNodes[i] as Computation).flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/** True when `node` is stale, alive and not frozen: running it now is both possible and needed. */\nfunction needsUpdate(node: Computation): boolean {\n return node.state !== CLEAN && (node.flags & FLAG_DISPOSED) === 0 && !isFrozen(node);\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n *\n * @returns Whether `node` still needs updating afterward (an owner's run may have cleaned or disposed it).\n */\nexport function refreshAncestors(node: Computation): boolean {\n if (!needsUpdate(node)) return false;\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (\n owner instanceof Computation &&\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_REFRESHING)) === 0\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i] as Computation;\n if (needsUpdate(ancestor)) updateIfNecessary(ancestor);\n }\n return needsUpdate(node);\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && refreshAncestors(memo)) {\n updateIfNecessary(memo, rt.nesting >= DEEP_LIMIT);\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n // One disposal for the children and the cleanups: all of them run even when one throws (the errors\n // are held in rt.uncaught), and the node still re-runs (it would stay dirty otherwise).\n rt.disposing += 1;\n try {\n disposeChildren(node);\n node.runCleanups();\n } finally {\n rt.disposing -= 1;\n }\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.nesting += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.nesting -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies. A node disposed while it ran\n // (it disposed its own owner) keeps none: reads after the disposal must not leave edges that\n // nothing will ever remove.\n unlinkFrom(node, (node.flags & FLAG_DISPOSED) !== 0 ? 0 : node.trackIndex);\n }\n\n let changed = true;\n if (node.kind === KIND_MEMO) changed = settleMemo(node, result, failed, failure);\n else settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n // The teardown's errors are thrown once the run is settled (unless a flush or an outer disposal collects them).\n rt.disposing += 1;\n finishDisposal();\n}\n\n/**\n * Calls a comparator untracked. It is a user callback: left tracked, the computation that writes (or the\n * reader that pulled the memo, the listener again once the run is over) would subscribe to whatever it\n * reads. Restored in `finally`, so a throwing comparator leaves the register as it found it.\n */\nexport function isEqual<T>(equals: (prev: T, next: T) => boolean, prev: T, next: T): boolean {\n const listener = rt.listener;\n rt.listener = null;\n try {\n return equals(prev, next);\n } finally {\n rt.listener = listener;\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !isEqual(equals, node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0) node.runCleanups();\n }\n}\n"],"mappings":";;;;;;AA+BA,MAAM,aAA4B,OAAO,OAAO,CAAC,CAAC;;AAGlD,MAAM,aAAa;;;;;;;;;;;;;;;;AA+CnB,IAAa,SAAb,MAAmD;;CAEjD,OAAS;;CAWT,YAAuC;;CAEvC,QAAQ;;;;;;;CAaR,YAAY,OAAU,QAAmB,MAAe;EACtD,KAAK,QAAQ;EACb,KAAK,SAAS;EACd,KAAK,OAAO;EACC,OAAO,eAAe,gBAAgB,MAAM,GAAG,OAAO,MAAM,KAAK;CAChF;AACF;;;;;;;;;;;;;;;;AAiBA,IAAa,cAAb,cAAiC,MAAwB;;CAYvD,QAAiB,KAAA;;CAIjB;;;;;CAKA,QAA6D;;;;;CAK7D,UAAyB;;CAEzB,YAAuC;;CAEvC,QAAQ;;CAER,aAAa;;;;;;;;;;;CAmBb,YACE,QACA,MACA,OACA,IACA,QACA,MACA;EACA,MAAM,MAAM;EACZ,KAAK,OAAO;EACZ,KAAK,QAAQ;EACb,KAAK,QAAA;EACL,KAAK,KAAK;EACV,KAAK,SAAS;EACd,KAAK,OAAO;EACZ,KAAK,QAAQ,KAAA;EACb,KAAK,MAAM,aAAa;EAEtB,OACE,eAAe,qBACf,MACA,QACA,SAAA,IAAqB,SAAS,UAC9B,OACC,QAAA,QAAyB,CAC5B;CAEJ;CAEA,UAAmC;EACjC,KAAK,SAAA;EACL,WAAW,MAAM,CAAC;EAClB,KAAK,KAAK;EACV,KAAK,QAAQ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BAAgB,GAAG;EACzB,MAAM,mBAAmB,GAAG;EAC5B,MAAM,kBAAkB,GAAG;EAC3B,GAAG,QAAQ;EACX,GAAG,WAAW;EAEd,GAAG,UAAU;EACb,IAAI;GACF,UAAW,MAAyD,QAAQ,aAAa;EAC3F,SAAS,OAAO;GACd,IAAI,CAAC,WAAW,MAAM,KAAK,GAAG,YAAY,OAAO,IAAI;GACrD;EACF,UAAU;GACR,GAAG,QAAQ;GACX,GAAG,WAAW;GACd,GAAG,UAAU;EACf;CACF;CACA,IAAI,OAAO,YAAY,YAAY;EACjC,WAAW,MAAM,OAAkB;EAEnC,KAAK,KAAK,QAAA,OAA2B,GAAG,KAAK,YAAY;CAC3D;AACF"}
|
|
@@ -89,7 +89,8 @@ function flush() {
|
|
|
89
89
|
rt.uncaught.push(new ShadowError("INFINITE_LOOP"));
|
|
90
90
|
break;
|
|
91
91
|
}
|
|
92
|
-
|
|
92
|
+
const ran = drain(renderQueue.length > 0 ? renderQueue : userQueue);
|
|
93
|
+
runs += ran;
|
|
93
94
|
}
|
|
94
95
|
} finally {
|
|
95
96
|
rt.flushing = false;
|
|
@@ -136,7 +137,7 @@ function runScheduled() {
|
|
|
136
137
|
* @since 1.0.0
|
|
137
138
|
*/
|
|
138
139
|
function schedule() {
|
|
139
|
-
if (rt.inTransition || rt.
|
|
140
|
+
if (rt.inTransition || rt.batches > 0 || rt.flushing || microtaskScheduled) return;
|
|
140
141
|
microtaskScheduled = true;
|
|
141
142
|
queueMicrotask(runScheduled);
|
|
142
143
|
}
|
|
@@ -162,21 +163,35 @@ function schedule() {
|
|
|
162
163
|
* @since 1.0.0
|
|
163
164
|
*/
|
|
164
165
|
function group(fn) {
|
|
165
|
-
rt.
|
|
166
|
+
rt.batches += 1;
|
|
166
167
|
try {
|
|
167
168
|
return fn();
|
|
168
169
|
} finally {
|
|
169
|
-
rt.
|
|
170
|
-
if (rt.
|
|
170
|
+
rt.batches -= 1;
|
|
171
|
+
if (rt.batches === 0 && hasPending()) schedule();
|
|
171
172
|
}
|
|
172
173
|
}
|
|
173
174
|
/**
|
|
175
|
+
* Flushes when `wanted`, then rethrows `failure` when `failed`. A failing flush is thrown on its own, or
|
|
176
|
+
* together with `failure` (an `AggregateError` with `message`) when both threw.
|
|
177
|
+
* @internal
|
|
178
|
+
*/
|
|
179
|
+
function flushThenThrow(wanted, failed, failure, message) {
|
|
180
|
+
if (wanted) try {
|
|
181
|
+
flush();
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (!failed) throw error;
|
|
184
|
+
throw new AggregateError([failure, error], message);
|
|
185
|
+
}
|
|
186
|
+
if (failed) throw failure;
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
174
189
|
* The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when
|
|
175
190
|
* `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until
|
|
176
191
|
* the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.
|
|
177
192
|
*/
|
|
178
193
|
function runBatched(fn, sync) {
|
|
179
|
-
rt.
|
|
194
|
+
rt.batches += 1;
|
|
180
195
|
let result;
|
|
181
196
|
let failure;
|
|
182
197
|
let failed = false;
|
|
@@ -186,15 +201,9 @@ function runBatched(fn, sync) {
|
|
|
186
201
|
failed = true;
|
|
187
202
|
failure = error;
|
|
188
203
|
} finally {
|
|
189
|
-
rt.
|
|
190
|
-
}
|
|
191
|
-
if (sync || rt.batchDepth === 0 && !rt.flushing && hasPending()) try {
|
|
192
|
-
flush();
|
|
193
|
-
} catch (error) {
|
|
194
|
-
if (failed) throw new AggregateError([failure, error], "Both the callback and the flush threw.");
|
|
195
|
-
throw error;
|
|
204
|
+
rt.batches -= 1;
|
|
196
205
|
}
|
|
197
|
-
|
|
206
|
+
flushThenThrow(sync || rt.batches === 0 && !rt.flushing && hasPending(), failed, failure, "Both the callback and the flush threw.");
|
|
198
207
|
return result;
|
|
199
208
|
}
|
|
200
209
|
/**
|
|
@@ -252,6 +261,6 @@ function flushSync(fn) {
|
|
|
252
261
|
}
|
|
253
262
|
return runBatched(fn, true);
|
|
254
263
|
}
|
|
255
|
-
export { MAX_FLUSH_PASSES, batch, byCreation, flush, flushSync, group, reportUncaught, runQueued, schedule };
|
|
264
|
+
export { MAX_FLUSH_PASSES, batch, byCreation, flush, flushSync, flushThenThrow, group, reportUncaught, runQueued, schedule };
|
|
256
265
|
|
|
257
266
|
//# sourceMappingURL=scheduler.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.js","names":[],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, refreshAncestors, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Runs one queued effect. Its stale owners come first: an owner that is about to re-run disposes the\n * effect, and running it before (a zombie, G-17) would read state that is already out of date.\n * @internal\n */\nexport function runQueued(effect: Computation): void {\n try {\n if (!refreshAncestors(effect)) return;\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n // Effects mostly arrive in creation order already: the sort then finds one ascending run and is O(n).\n batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n // Render effects first, and until none is left; render passes count too: a render effect that\n // keeps writing its own source must abort.\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n runs += drain(renderQueue.length > 0 ? renderQueue : userQueue);\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batchDepth > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batchDepth += 1;\n try {\n return fn();\n } finally {\n rt.batchDepth -= 1;\n if (rt.batchDepth === 0 && hasPending()) schedule();\n }\n}\n\n/**\n * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when\n * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until\n * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.\n */\nfunction runBatched<T>(fn: (() => T) | undefined, sync: boolean): T {\n rt.batchDepth += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batchDepth -= 1;\n }\n if (sync || (rt.batchDepth === 0 && !rt.flushing && hasPending())) {\n try {\n flush();\n } catch (error) {\n if (failed) {\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n }\n throw error;\n }\n }\n if (failed) throw failure;\n return result as T;\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n return runBatched(fn, false);\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.flushing) {\n warn(\"FLUSH_IN_EFFECT\");\n return (fn === undefined ? undefined : fn()) as T;\n }\n return runBatched(fn, true);\n}\n"],"mappings":";;;;;;;;;;;;AAaA,MAAa,mBAAmB;AAEhC,IAAI,qBAAqB;;;;;AAMzB,SAAgB,WAAW,GAAgB,GAAwB;CACjE,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE;AACxC;;;;;;AAOA,SAAgB,UAAU,QAA2B;CACnD,IAAI;EACF,IAAI,CAAC,iBAAiB,MAAM,GAAG;EAE/B,IAAI,OAAO,UAAA,GAAiB,UAAU,MAAM;OACvC,kBAAkB,MAAM;CAC/B,SAAS,OAAO;EACd,YAAY,OAAO,MAAM;CAC3B;AACF;;AAGA,SAAS,MAAM,OAA8B;CAC3C,MAAM,QAAQ,MAAM,OAAO,GAAG,MAAM,MAAM;CAE1C,MAAM,KAAK,UAAU;CACrB,KAAK,MAAM,UAAU,OAAO;EAC1B,OAAO,SAAS;EAChB,KAAK,OAAO,QAAA,OAA2B,GAAG;EAC1C,IAAI,OAAO,SAAS,GAAG;GAErB,OAAO,QAAS,OAAO,QAAQ,CAAC,kBAAmB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U;EACR,GAAG,cAAc;EACjB,IAAI,GAAG,eAAe,KAAK,WAAW,GAAG,SAAS;CACpD;AACF;;;;;;AAOA,SAAS,WAAc,IAA2B,MAAkB;CAClE,GAAG,cAAc;CACjB,IAAI;CACJ,IAAI;CACJ,IAAI,SAAS;CACb,IAAI;EACF,SAAS,OAAO,KAAA,IAAY,KAAA,IAAY,GAAG;CAC7C,SAAS,OAAO;EACd,SAAS;EACT,UAAU;CACZ,UAAU;EACR,GAAG,cAAc;CACnB;CACA,IAAI,QAAS,GAAG,eAAe,KAAK,CAAC,GAAG,YAAY,WAAW,GAC7D,IAAI;EACF,MAAM;CACR,SAAS,OAAO;EACd,IAAI,QACF,MAAM,IAAI,eACR,CAAC,SAAS,KAAK,GACL,wCACZ;EAEF,MAAM;CACR;CAEF,IAAI,QAAQ,MAAM;CAClB,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,MAAS,IAAgB;CACvC,OAAO,WAAW,IAAI,KAAK;AAC7B;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,UAAoB,IAAiB;CACnD,IAAI,GAAG,UAAU;EACf,KAAK,iBAAiB;EACtB,OAAQ,OAAO,KAAA,IAAY,KAAA,IAAY,GAAG;CAC5C;CACA,OAAO,WAAW,IAAI,IAAI;AAC5B"}
|
|
1
|
+
{"version":3,"file":"scheduler.js","names":[],"sources":["../../../src/internal/scheduler.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError, warn } from \"./diagnostics\";\nimport { DIRTY, FLAG_DISPOSED, FLAG_PARKED, FLAG_QUEUED, FLAG_TRANSITION } from \"./flags\";\nimport type { Computation } from \"./graph\";\nimport { recompute, refreshAncestors, updateIfNecessary } from \"./graph\";\nimport { handleError } from \"./owner\";\nimport { clearQueues, hasPending, renderQueue, userQueue } from \"./queue\";\nimport { rt } from \"./state\";\n\n/**\n * Flush passes allowed before the loop guard aborts (R-CODE-12).\n * @internal\n */\nexport const MAX_FLUSH_PASSES = 1000;\n\nlet microtaskScheduled = false;\n\n/**\n * Sort order of queued effects: parents before children (by depth), siblings by creation (G-16).\n * @internal\n */\nexport function byCreation(a: Computation, b: Computation): number {\n return a.depth - b.depth || a.seq - b.seq;\n}\n\n/**\n * Runs one queued effect. Its stale owners come first: an owner that is about to re-run disposes the\n * effect, and running it before (a zombie, G-17) would read state that is already out of date.\n * @internal\n */\nexport function runQueued(effect: Computation): void {\n try {\n if (!refreshAncestors(effect)) return;\n // A directly dirtied effect needs no source verification: skip the frame machinery.\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n}\n\n/** Runs every queued effect of one phase, parents before children, siblings by creation. */\nfunction drain(queue: Computation[]): number {\n const batch = queue.splice(0, queue.length);\n // Effects mostly arrive in creation order already: the sort then finds one ascending run and is O(n).\n batch.sort(byCreation);\n for (const effect of batch) {\n effect.flags &= ~FLAG_QUEUED;\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n // Paused after it was queued: wait (unqueued) until the owner resumes.\n effect.flags = (effect.flags & ~FLAG_TRANSITION) | FLAG_PARKED;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n}\n\nfunction raise(errors: unknown[]): void {\n const [first] = errors;\n if (errors.length === 1) throw first;\n throw new AggregateError(\n errors,\n __DEV__ ? \"Several errors were thrown while flushing effects.\" : \"SHADOW_FLUSH_ERRORS\",\n );\n}\n\n/**\n * Runs every pending effect now: what the scheduled microtask does. Drains the queues until nothing\n * is pending; render effects always run before user effects, parents before children, siblings by\n * creation, and effects woken by a write in the flush run in a following pass. Errors nobody handled\n * are collected and thrown once the queues are empty, so one failing effect never wedges the rest.\n * Does nothing when a flush is already running. Transition-lane effects are not run here: they wait\n * for the lane. Prefer {@link flushSync} in application code.\n *\n * @throws The error of an effect that no error handler caught; several are thrown together as an\n * `AggregateError`.\n * @throws ShadowError `INFINITE_LOOP` when effects keep waking each other for more than 1000 passes:\n * the queued effects are dropped and the flush stops.\n * @example\n * import { flush, writeSignal, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function setNow(signal: SignalNode<number>, value: number): void {\n * writeSignal(signal, value);\n * flush(); // the effects that read the signal have run\n * }\n * @see flushSync\n * @since 1.0.0\n */\nexport function flush(): void {\n if (rt.flushing) return;\n rt.flushing = true;\n let passes = 0;\n let runs = 0;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_START, renderQueue.length, userQueue.length);\n try {\n while (hasPending()) {\n // Render effects first, and until none is left; render passes count too: a render effect that\n // keeps writing its own source must abort.\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const ran = drain(renderQueue.length > 0 ? renderQueue : userQueue);\n if (__DEV__) runs += ran;\n }\n } finally {\n rt.flushing = false;\n if (__DEV__) report(DEVTOOLS_EVENT.FLUSH_END, runs);\n }\n const errors = rt.uncaught;\n if (errors.length > 0) {\n rt.uncaught = [];\n raise(errors);\n }\n}\n\n/**\n * Surfaces an error from the microtask flush where nothing can catch it.\n * @internal\n */\nexport function reportUncaught(error: unknown): void {\n if (typeof reportError === \"function\") reportError(error);\n else queueMicrotask(() => Promise.reject(error));\n}\n\nfunction runScheduled(): void {\n microtaskScheduled = false;\n if (!hasPending()) return;\n try {\n flush();\n } catch (error) {\n reportUncaught(error);\n }\n}\n\n/**\n * Requests a flush in a microtask: call it after marking observers stale by hand, as\n * {@link markObservers} does not. Does nothing when a microtask flush is already due, inside a\n * batch or group (which flushes or schedules on exit), during a flush (which picks the work up), or\n * during a transition (its effects wait for the lane). An error thrown by that flush has no caller\n * to reach: it goes to the global `reportError`, or becomes an unhandled promise rejection.\n *\n * @example\n * import { markObservers, schedule, type SourceNode } from \"@shadow-js/core/extend\";\n *\n * export function touch(source: SourceNode): void {\n * markObservers(source);\n * schedule(); // the effects that read `source` run in a microtask\n * }\n * @see notify\n * @since 1.0.0\n */\nexport function schedule(): void {\n // A transition write waits for the lane (scheduled when the effect is queued), never for a microtask.\n if (rt.inTransition || rt.batches > 0 || rt.flushing || microtaskScheduled) return;\n microtaskScheduled = true;\n queueMicrotask(runScheduled);\n}\n\n/**\n * Groups writes like {@link batch} but never flushes synchronously: when the outermost group ends,\n * the effects wait for the microtask (or an enclosing batch / `flushSync`), exactly as after a\n * single signal write. Store setters use it so that one `setStore(...)` behaves like one `set()`;\n * use it for a primitive whose one call makes several writes.\n *\n * @param fn The writes to group. Its throw is rethrown after the group ends.\n * @returns What `fn` returns.\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n * import { group } from \"@shadow-js/core/extend\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * group(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both run once, in the next microtask\n * @see batch\n * @since 1.0.0\n */\nexport function group<T>(fn: () => T): T {\n rt.batches += 1;\n try {\n return fn();\n } finally {\n rt.batches -= 1;\n if (rt.batches === 0 && hasPending()) schedule();\n }\n}\n\n/**\n * Flushes when `wanted`, then rethrows `failure` when `failed`. A failing flush is thrown on its own, or\n * together with `failure` (an `AggregateError` with `message`) when both threw.\n * @internal\n */\nexport function flushThenThrow(\n wanted: boolean,\n failed: boolean,\n failure: unknown,\n message: string,\n): void {\n if (wanted) {\n try {\n flush();\n } catch (error) {\n if (!failed) throw error;\n throw new AggregateError([failure, error], message);\n }\n }\n if (failed) throw failure;\n}\n\n/**\n * The body `batch` and `flushSync` share: runs `fn` with the effects deferred, then flushes (always when\n * `sync`, else when this was the outermost batch and no flush is running). A throw of `fn` is held until\n * the flush has run, and thrown with the flush's own error as an `AggregateError` when both threw.\n */\nfunction runBatched<T>(fn: (() => T) | undefined, sync: boolean): T {\n rt.batches += 1;\n let result: T | undefined;\n let failure: unknown;\n let failed = false;\n try {\n result = fn === undefined ? undefined : fn();\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.batches -= 1;\n }\n flushThenThrow(\n sync || (rt.batches === 0 && !rt.flushing && hasPending()),\n failed,\n failure,\n __DEV__ ? \"Both the callback and the flush threw.\" : \"SHADOW_BATCH_ERRORS\",\n );\n return result as T;\n}\n\n/**\n * Runs `fn` with effects deferred until the outermost batch ends, then runs them synchronously, so\n * several writes wake each effect once. Reads inside the batch always see fresh values (G-6). Inside\n * a running flush the effects are left to that flush.\n *\n * @param fn The writes to batch.\n * @returns What `fn` returns.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { batch, useSignal } from \"@shadow-js/core\";\n *\n * const [first, setFirst] = useSignal(\"Ada\");\n * const [last, setLast] = useSignal(\"Lovelace\");\n * batch(() => {\n * setFirst(\"Grace\");\n * setLast(\"Hopper\");\n * }); // effects reading both have run once, here\n * @see flushSync\n * @since 1.0.0\n */\nexport function batch<T>(fn: () => T): T {\n return runBatched(fn, false);\n}\n\n/**\n * Runs `fn` (optional) in a batch and runs every pending effect before returning, so the DOM and\n * other effects are up to date on the next line. Use it in tests and before reading layout. Called\n * while a flush is running (from inside an effect), it only runs `fn` and leaves the effects to that\n * flush; development builds warn `FLUSH_IN_EFFECT`.\n *\n * @param fn The writes to make first. Undefined only flushes.\n * @returns What `fn` returns, or undefined without `fn`.\n * @throws What `fn` throws, after the flush. An error of the flush is thrown as {@link flush} throws\n * it (including ShadowError `INFINITE_LOOP`); when `fn` threw as well, both are thrown together as an\n * `AggregateError`.\n * @example\n * import { createRoot, flushSync, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * createRoot(() => {\n * const [count, setCount] = useSignal(0);\n * useEffect(() => console.log(count()));\n * flushSync(); // logs 0\n * flushSync(() => setCount(1)); // logs 1 before this line ends\n * });\n * @see batch\n * @since 1.0.0\n */\nexport function flushSync<T = void>(fn?: () => T): T {\n if (rt.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U;EACR,GAAG,WAAW;CAChB;CACA,eACE,QAAS,GAAG,YAAY,KAAK,CAAC,GAAG,YAAY,WAAW,GACxD,QACA,SACU,wCACZ;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,MAAS,IAAgB;CACvC,OAAO,WAAW,IAAI,KAAK;AAC7B;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,UAAoB,IAAiB;CACnD,IAAI,GAAG,UAAU;EACf,KAAK,iBAAiB;EACtB,OAAQ,OAAO,KAAA,IAAY,KAAA,IAAY,GAAG;CAC5C;CACA,OAAO,WAAW,IAAI,IAAI;AAC5B"}
|
|
@@ -2,14 +2,18 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* The runtime registers (R-CODE-4): the only module-level mutable state of core besides
|
|
4
4
|
* monotonic counters. Every write is paired with a `finally` restore (R-CODE-5).
|
|
5
|
+
*
|
|
6
|
+
* Not a public symbol: `core/extend` re-exports only the types of this module, and the registers stay
|
|
7
|
+
* behind the extension functions (`currentOwner`, `untrack` and friends) so a plugin cannot leave one set.
|
|
8
|
+
* @internal
|
|
5
9
|
*/
|
|
6
10
|
const rt = {
|
|
7
11
|
owner: null,
|
|
8
12
|
listener: null,
|
|
9
13
|
running: null,
|
|
10
|
-
|
|
14
|
+
batches: 0,
|
|
11
15
|
flushing: false,
|
|
12
|
-
|
|
16
|
+
nesting: 0,
|
|
13
17
|
disposing: 0,
|
|
14
18
|
uncaught: [],
|
|
15
19
|
inTransition: false,
|
|
@@ -17,7 +21,11 @@ const rt = {
|
|
|
17
21
|
hooks: null
|
|
18
22
|
};
|
|
19
23
|
let counter = 0;
|
|
20
|
-
/**
|
|
24
|
+
/**
|
|
25
|
+
* Monotonic creation sequence; orders sibling effects (G-16). Not a public symbol: only the engine
|
|
26
|
+
* stamps nodes with it.
|
|
27
|
+
* @internal
|
|
28
|
+
*/
|
|
21
29
|
function nextSequence() {
|
|
22
30
|
counter += 1;
|
|
23
31
|
return counter;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.js","names":[],"sources":["../../../src/internal/state.ts"],"sourcesContent":["import type { Computation } from \"./graph\";\nimport type { Owner } from \"./owner\";\n\n/**\n * A hold for a value a transition builds while its reads wait for data (a `Show` branch built during a\n * transition): the reads that wait count against this hold, not against the Suspense boundary around\n * the value, so the shown value stays until the hold settles. Created by `createTransitionHold`.\n * @since 1.0.0\n */\nexport interface TransitionHold {\n /** Runs `fn` with this hold as the Suspense boundary of the reads inside it. */\n run<T>(fn: () => T): T;\n /** Reads still waiting for data. */\n count(): number;\n /** True once a read in the hold was held (the value is then pending, not ready). */\n engaged(): boolean;\n /** Ends the hold without waking anything (the value is being dropped). */\n drop(): void;\n}\n\n/**\n * The choice a branch slot (Show, Switch) shows: its index, and what decides a rebuild. Renderers\n * extend it with what they need to build the branch.\n * @since 1.0.0\n */\nexport interface SlotChoice {\n /** Which branch is chosen: its position among the slot's branches, or the renderer's fallback index. */\n readonly index: number;\n /** True when the branch is rebuilt whenever `when` changes identity; false when only `index` counts. */\n readonly keyed: boolean;\n /** The condition value that selected the branch. */\n readonly when: unknown;\n}\n\n/**\n * The record of a branch's owner that its accessors read: the value and whether it is being torn down.\n * @since 1.0.0\n */\nexport interface SlotOwned {\n /** The index of the branch this record belongs to (see {@link SlotChoice.index}). */\n index: number;\n /** The latest condition value while the branch is shown; what its accessor returns during teardown. */\n value: unknown;\n /** True while the branch is torn down: its accessor then returns `value` instead of throwing. */\n disposing: boolean;\n}\n\n/**\n * A branch a slot shows, or builds during a transition. A branch without `dispose` is torn down by its memo.\n * @since 1.0.0\n */\nexport interface SlotBranch<C extends SlotChoice> {\n /** The choice the branch was built for. */\n readonly choice: C;\n /** The record its accessors read. */\n readonly owned: SlotOwned;\n /** What the branch produced: the value the slot's output returns while the branch is shown. */\n readonly result: unknown;\n /**\n * Tears the branch down. Set for the branches a transition built: they live under the holder, not\n * under the memo.\n * @default undefined (the slot's memo tears the branch down)\n */\n readonly dispose?: () => void;\n /**\n * The hold a transition built the branch under; null when none of its reads was held.\n * @default undefined (a memo-owned branch has no hold)\n */\n readonly hold?: TransitionHold | null;\n}\n\n/**\n * What a slot's output memo keeps: the branch on screen (its result is the value the output returns).\n * @since 1.0.0\n */\nexport interface SlotState<C extends SlotChoice> {\n /** The branch on screen, or undefined before the first build and while the memo rebuilds it. */\n live: SlotBranch<C> | undefined;\n}\n\n/**\n * The transition layer of one slot, from `transitionHooks()?.slotSwap(...)`: it keeps the shown\n * branch while a transition builds the next one (see `slotSwap` in concurrency.ts).\n * @since 1.0.0\n */\nexport interface SlotSwap<C extends SlotChoice> {\n /**\n * Runs one pass of the slot's memo for `choice`. True when a transition keeps the shown value. False\n * when the usual path follows: the branch on screen has been retired and `state.live` is cleared.\n */\n step(choice: C): boolean;\n}\n\n/**\n * The hold of one Suspense boundary: engaged by a transition read, released when its data arrived.\n * From `transitionHooks()?.boundaryHold()`.\n * @since 1.0.0\n */\nexport interface BoundaryHold {\n /** Engages the hold (a second call changes nothing) so the boundary keeps its content; returns true. */\n engage(): boolean;\n /** When engaged: wakes the readers that waited, then ends the hold. Otherwise does nothing. */\n release(): void;\n /** True while the hold is engaged. */\n holding(): boolean;\n}\n\n/**\n * The transition machinery the engine calls through `rt.hooks`: transition lanes, pauses (Activity)\n * and suspensions (Suspense holds). It is created by the first call of an API that needs it (see\n * concurrency.ts), so an application that never calls one of those APIs carries none of their code.\n * Renderers reach it through `transitionHooks()`.\n * @since 1.0.0\n */\nexport interface Hooks {\n /** The transition layer of one branch slot (see `slotSwap` in concurrency.ts). */\n slotSwap<C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C>;\n /** A Suspense boundary's hold (see `boundaryHold` in concurrency.ts). */\n boundaryHold(): BoundaryHold;\n /** Queues an effect that is due in the transition lane, or parks it while its owner is paused. */\n place(effect: Computation, inLane: boolean): void;\n /** An urgent write reached an effect that waits in the lane or is parked: it moves to the urgent queue. */\n promote(effect: Computation): void;\n /** Forgets the lane queues (the flush loop guard). */\n clear(): void;\n /** Keeps `node` for a transition when `error` is a suspension; returns false for any other error. */\n suspend(node: Computation, error: unknown): boolean;\n /** The engine side of `holdReader`: throws the suspension sentinel when `tracker.hold()` is true. */\n holdReader(tracker: { hold?(): boolean }): void;\n /** The engine side of `startTransition` in the browser. */\n startTransition(fn: () => void): Promise<void>;\n /** The engine side of `beginHold`: counts one more Suspense hold. */\n beginHold(): void;\n /** The engine side of `endHold`: counts one hold less and settles the lane. */\n endHold(): void;\n /** The engine side of `wakeSuspended`. */\n wakeSuspended(): void;\n /** The engine side of `pauseOwner`. */\n pause(owner: Owner): void;\n /** The engine side of `resumeOwner`. */\n resume(owner: Owner): void;\n /** The engine side of `createTransitionHold`. */\n createHold(onSettled: () => void): TransitionHold;\n}\n\n/**\n * The runtime registers (R-CODE-4): the only module-level mutable state of core besides\n * monotonic counters. Every write is paired with a `finally` restore (R-CODE-5).\n */\nexport const rt: {\n /** Owner that adopts newly created nodes. */\n owner: Owner | null;\n /** Computation that records the signals it reads; null while untracked. */\n listener: Computation | null;\n /** Computation currently executing, tracked or not (used by the write-in-memo guard). */\n running: Computation | null;\n /** Nesting depth of batch()/flushSync() calls. */\n
|
|
1
|
+
{"version":3,"file":"state.js","names":[],"sources":["../../../src/internal/state.ts"],"sourcesContent":["import type { Computation } from \"./graph\";\nimport type { Owner } from \"./owner\";\n\n/**\n * A hold for a value a transition builds while its reads wait for data (a `Show` branch built during a\n * transition): the reads that wait count against this hold, not against the Suspense boundary around\n * the value, so the shown value stays until the hold settles. Created by `createTransitionHold`.\n * @since 1.0.0\n */\nexport interface TransitionHold {\n /** Runs `fn` with this hold as the Suspense boundary of the reads inside it. */\n run<T>(fn: () => T): T;\n /** Reads still waiting for data. */\n count(): number;\n /** True once a read in the hold was held (the value is then pending, not ready). */\n engaged(): boolean;\n /** Ends the hold without waking anything (the value is being dropped). */\n drop(): void;\n}\n\n/**\n * The choice a branch slot (Show, Switch) shows: its index, and what decides a rebuild. Renderers\n * extend it with what they need to build the branch.\n * @since 1.0.0\n */\nexport interface SlotChoice {\n /** Which branch is chosen: its position among the slot's branches, or the renderer's fallback index. */\n readonly index: number;\n /** True when the branch is rebuilt whenever `when` changes identity; false when only `index` counts. */\n readonly keyed: boolean;\n /** The condition value that selected the branch. */\n readonly when: unknown;\n}\n\n/**\n * The record of a branch's owner that its accessors read: the value and whether it is being torn down.\n * @since 1.0.0\n */\nexport interface SlotOwned {\n /** The index of the branch this record belongs to (see {@link SlotChoice.index}). */\n index: number;\n /** The latest condition value while the branch is shown; what its accessor returns during teardown. */\n value: unknown;\n /** True while the branch is torn down: its accessor then returns `value` instead of throwing. */\n disposing: boolean;\n}\n\n/**\n * A branch a slot shows, or builds during a transition. A branch without `dispose` is torn down by its memo.\n * @since 1.0.0\n */\nexport interface SlotBranch<C extends SlotChoice> {\n /** The choice the branch was built for. */\n readonly choice: C;\n /** The record its accessors read. */\n readonly owned: SlotOwned;\n /** What the branch produced: the value the slot's output returns while the branch is shown. */\n readonly result: unknown;\n /**\n * Tears the branch down. Set for the branches a transition built: they live under the holder, not\n * under the memo.\n * @default undefined (the slot's memo tears the branch down)\n */\n readonly dispose?: () => void;\n /**\n * The hold a transition built the branch under; null when none of its reads was held.\n * @default undefined (a memo-owned branch has no hold)\n */\n readonly hold?: TransitionHold | null;\n}\n\n/**\n * What a slot's output memo keeps: the branch on screen (its result is the value the output returns).\n * @since 1.0.0\n */\nexport interface SlotState<C extends SlotChoice> {\n /** The branch on screen, or undefined before the first build and while the memo rebuilds it. */\n live: SlotBranch<C> | undefined;\n}\n\n/**\n * The transition layer of one slot, from `transitionHooks()?.slotSwap(...)`: it keeps the shown\n * branch while a transition builds the next one (see `slotSwap` in concurrency.ts).\n * @since 1.0.0\n */\nexport interface SlotSwap<C extends SlotChoice> {\n /**\n * Runs one pass of the slot's memo for `choice`. True when a transition keeps the shown value. False\n * when the usual path follows: the branch on screen has been retired and `state.live` is cleared.\n */\n step(choice: C): boolean;\n}\n\n/**\n * The hold of one Suspense boundary: engaged by a transition read, released when its data arrived.\n * From `transitionHooks()?.boundaryHold()`.\n * @since 1.0.0\n */\nexport interface BoundaryHold {\n /** Engages the hold (a second call changes nothing) so the boundary keeps its content; returns true. */\n engage(): boolean;\n /** When engaged: wakes the readers that waited, then ends the hold. Otherwise does nothing. */\n release(): void;\n /** True while the hold is engaged. */\n holding(): boolean;\n}\n\n/**\n * The transition machinery the engine calls through `rt.hooks`: transition lanes, pauses (Activity)\n * and suspensions (Suspense holds). It is created by the first call of an API that needs it (see\n * concurrency.ts), so an application that never calls one of those APIs carries none of their code.\n * Renderers reach it through `transitionHooks()`.\n * @since 1.0.0\n */\nexport interface Hooks {\n /** The transition layer of one branch slot (see `slotSwap` in concurrency.ts). */\n slotSwap<C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C>;\n /** A Suspense boundary's hold (see `boundaryHold` in concurrency.ts). */\n boundaryHold(): BoundaryHold;\n /** Queues an effect that is due in the transition lane, or parks it while its owner is paused. */\n place(effect: Computation, inLane: boolean): void;\n /** An urgent write reached an effect that waits in the lane or is parked: it moves to the urgent queue. */\n promote(effect: Computation): void;\n /** Forgets the lane queues (the flush loop guard). */\n clear(): void;\n /** Keeps `node` for a transition when `error` is a suspension; returns false for any other error. */\n suspend(node: Computation, error: unknown): boolean;\n /** The engine side of `holdReader`: throws the suspension sentinel when `tracker.hold()` is true. */\n holdReader(tracker: { hold?(): boolean }): void;\n /** The engine side of `startTransition` in the browser. */\n startTransition(fn: () => void): Promise<void>;\n /** The engine side of `beginHold`: counts one more Suspense hold. */\n beginHold(): void;\n /** The engine side of `endHold`: counts one hold less and settles the lane. */\n endHold(): void;\n /** The engine side of `wakeSuspended`. */\n wakeSuspended(): void;\n /** The engine side of `pauseOwner`. */\n pause(owner: Owner): void;\n /** The engine side of `resumeOwner`. */\n resume(owner: Owner): void;\n /** The engine side of `createTransitionHold`. */\n createHold(onSettled: () => void): TransitionHold;\n}\n\n/**\n * The runtime registers (R-CODE-4): the only module-level mutable state of core besides\n * monotonic counters. Every write is paired with a `finally` restore (R-CODE-5).\n *\n * Not a public symbol: `core/extend` re-exports only the types of this module, and the registers stay\n * behind the extension functions (`currentOwner`, `untrack` and friends) so a plugin cannot leave one set.\n * @internal\n */\nexport const rt: {\n /** Owner that adopts newly created nodes. */\n owner: Owner | null;\n /** Computation that records the signals it reads; null while untracked. */\n listener: Computation | null;\n /** Computation currently executing, tracked or not (used by the write-in-memo guard). */\n running: Computation | null;\n /** Nesting depth of batch()/flushSync() calls. */\n batches: number;\n /** True while the flush loop is draining the effect queues. */\n flushing: boolean;\n /** Nesting depth of memo recomputation, used to switch to iterative pulls. */\n nesting: number;\n /** Nesting depth of disposals in progress; errors raised meanwhile are collected, not thrown. */\n disposing: number;\n /** Errors nobody handled during the current flush or disposal; rethrown once it completes. */\n uncaught: unknown[];\n /** True while a transition callback or a transition-lane run is active: writes made now join the lane. */\n inTransition: boolean;\n /** True while `hydrate()` claims server markup (useExternalStore reads its server snapshot). */\n hydrating: boolean;\n /** The transition machinery, or null until an API that needs it is first called. */\n hooks: Hooks | null;\n} = {\n owner: null,\n listener: null,\n running: null,\n batches: 0,\n flushing: false,\n nesting: 0,\n disposing: 0,\n uncaught: [],\n inTransition: false,\n hydrating: false,\n hooks: null,\n};\n\nlet counter = 0;\n/**\n * Monotonic creation sequence; orders sibling effects (G-16). Not a public symbol: only the engine\n * stamps nodes with it.\n * @internal\n */\nexport function nextSequence(): number {\n counter += 1;\n return counter;\n}\n"],"mappings":";;;;;;;;;AA8JA,MAAa,KAuBT;CACF,OAAO;CACP,UAAU;CACV,SAAS;CACT,SAAS;CACT,UAAU;CACV,SAAS;CACT,WAAW;CACX,UAAU,CAAC;CACX,cAAc;CACd,WAAW;CACX,OAAO;AACT;AAEA,IAAI,UAAU;;;;;;AAMd,SAAgB,eAAuB;CACrC,WAAW;CACX,OAAO;AACT"}
|
package/dist/prod/effect.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./internal/diagnostics.js";import{untrack as e}from"./ownership.js";import{createComputation as t,currentOwner as n}from"./extend/index.js";function r(e,r,i,a,o){let s=
|
|
1
|
+
import"./internal/diagnostics.js";import{untrack as e}from"./ownership.js";import{createComputation as t,currentOwner as n}from"./extend/index.js";function r(e,r,i,a,o){let s=i?null:n()?.gate??null;if(s!==null){let t=!1,n=!1,i=a,o=e,c=r;a=!1,e=e=>(n=!t&&s(),t||=!n,n?void 0:o(e)),c!==null&&(r=(e,t)=>{if(!n){if(!i)return c(e,t);i=!1}})}t({kind:`effect`,fn:e,render:i,defer:a,apply:r??void 0,name:o})}function i(e,t,n){typeof t==`function`?r(e,t,!1,n?.defer===!0,n?.name):r(e,null,!1,!1,t?.name)}function a(e,t){r(e,t??null,!0,!1,void 0)}function o(t){r(()=>e(t),null,!1,!1,`onMount`)}export{o as onMount,i as useEffect,a as useRenderEffect};
|
|
2
2
|
//# sourceMappingURL=effect.js.map
|