@shadow-js/core 1.0.3 → 1.0.5
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 +14 -0
- package/README.md +1 -2
- package/dist/dev/action.js +1 -1
- package/dist/dev/cache.js +1 -1
- package/dist/dev/context.js +2 -2
- package/dist/dev/effect.js +9 -12
- package/dist/dev/effect.js.map +1 -1
- package/dist/dev/extend/index.d.ts +4 -4
- package/dist/dev/extend/index.js +5 -5
- package/dist/dev/external-store.js +2 -2
- package/dist/dev/index.d.ts +6 -6
- package/dist/dev/index.js +9 -9
- package/dist/dev/internal/concurrency.js +5 -5
- package/dist/dev/internal/dispose.js +3 -9
- package/dist/dev/internal/dispose.js.map +1 -1
- package/dist/dev/internal/graph.d.ts +1 -1
- package/dist/dev/internal/graph.js +8 -4
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/scheduler.js +26 -17
- package/dist/dev/internal/scheduler.js.map +1 -1
- package/dist/dev/internal/state.d.ts +1 -1
- package/dist/dev/internal/state.js +11 -3
- package/dist/dev/internal/state.js.map +1 -1
- package/dist/dev/list.js +2 -2
- package/dist/dev/optimistic.js +1 -1
- package/dist/dev/ownership.js +6 -1
- package/dist/dev/ownership.js.map +1 -1
- package/dist/dev/props.js +1 -1
- package/dist/dev/reaction.js +2 -2
- package/dist/dev/resource.js +4 -4
- package/dist/dev/selector.js +1 -1
- package/dist/dev/signal.js +1 -1
- package/dist/dev/store/index.d.ts +1 -1
- package/dist/dev/store/nodes.js +7 -3
- package/dist/dev/store/nodes.js.map +1 -1
- package/dist/dev/store/reconcile.js +1 -1
- package/dist/dev/store/reconcile.js.map +1 -1
- package/dist/dev/store/use-store.js +9 -5
- package/dist/dev/store/use-store.js.map +1 -1
- package/dist/dev/transitions.js +2 -2
- package/dist/prod/action.js +1 -1
- package/dist/prod/cache.js +1 -1
- package/dist/prod/context.js +1 -1
- package/dist/prod/effect.js +1 -1
- package/dist/prod/effect.js.map +1 -1
- package/dist/prod/extend/index.js +1 -1
- package/dist/prod/external-store.js +1 -1
- package/dist/prod/index.js +1 -1
- package/dist/prod/internal/concurrency.js +1 -1
- package/dist/prod/internal/concurrency.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/prod/list.js +1 -1
- package/dist/prod/optimistic.js +1 -1
- package/dist/prod/ownership.js +1 -1
- package/dist/prod/ownership.js.map +1 -1
- package/dist/prod/props.js +1 -1
- package/dist/prod/reaction.js +1 -1
- package/dist/prod/resource.js +1 -1
- package/dist/prod/selector.js +1 -1
- package/dist/prod/signal.js +1 -1
- package/dist/prod/store/nodes.js +1 -1
- package/dist/prod/store/nodes.js.map +1 -1
- package/dist/prod/store/reconcile.js +1 -1
- package/dist/prod/store/reconcile.js.map +1 -1
- package/dist/prod/store/use-store.js +1 -1
- package/dist/prod/store/use-store.js.map +1 -1
- package/dist/prod/transitions.js +1 -1
- package/dist/server/action.js +1 -1
- package/dist/server/cache.js +1 -1
- package/dist/server/context.js +1 -1
- package/dist/server/effect.js.map +1 -1
- package/dist/server/extend/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/server/internal/concurrency.js +1 -1
- package/dist/server/internal/concurrency.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/list.js +1 -1
- package/dist/server/optimistic.js +1 -1
- package/dist/server/ownership.js +1 -1
- package/dist/server/ownership.js.map +1 -1
- package/dist/server/props.js +1 -1
- package/dist/server/reaction.js +1 -1
- package/dist/server/resource.js +1 -1
- package/dist/server/selector.js +1 -1
- package/dist/server/signal.js +1 -1
- package/dist/server/store/nodes.js +1 -1
- package/dist/server/store/nodes.js.map +1 -1
- package/dist/server/store/reconcile.js +1 -1
- package/dist/server/store/reconcile.js.map +1 -1
- package/dist/server/store/use-store.js +1 -1
- package/dist/server/store/use-store.js.map +1 -1
- package/dist/server/transitions.js +1 -1
- package/dist/server-dev/action.js +1 -1
- package/dist/server-dev/cache.js +1 -1
- package/dist/server-dev/context.js +1 -1
- package/dist/server-dev/effect.js.map +1 -1
- package/dist/server-dev/extend/index.js +5 -5
- package/dist/server-dev/index.js +9 -9
- package/dist/server-dev/internal/concurrency.js +5 -5
- package/dist/server-dev/internal/dispose.js +3 -9
- package/dist/server-dev/internal/dispose.js.map +1 -1
- package/dist/server-dev/internal/graph.js +8 -4
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +26 -17
- 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/dist/server-dev/list.js +2 -2
- package/dist/server-dev/optimistic.js +1 -1
- package/dist/server-dev/ownership.js +6 -1
- package/dist/server-dev/ownership.js.map +1 -1
- package/dist/server-dev/props.js +1 -1
- package/dist/server-dev/reaction.js +2 -2
- package/dist/server-dev/resource.js +3 -3
- package/dist/server-dev/selector.js +1 -1
- package/dist/server-dev/signal.js +1 -1
- package/dist/server-dev/store/nodes.js +7 -3
- package/dist/server-dev/store/nodes.js.map +1 -1
- package/dist/server-dev/store/reconcile.js +1 -1
- package/dist/server-dev/store/reconcile.js.map +1 -1
- package/dist/server-dev/store/use-store.js +9 -5
- package/dist/server-dev/store/use-store.js.map +1 -1
- package/dist/server-dev/transitions.js +1 -1
- package/package.json +2 -2
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { DEVTOOLS_EVENT, report } from "../internal/devtools.js";
|
|
2
2
|
import { ShadowError } from "../internal/diagnostics.js";
|
|
3
3
|
import { group } from "../internal/scheduler.js";
|
|
4
|
+
import { currentOwner, isComputingMemo } from "../extend/index.js";
|
|
4
5
|
import { untrack } from "../ownership.js";
|
|
5
6
|
import { useSignal } from "../signal.js";
|
|
6
|
-
import { currentOwner, isComputingMemo } from "../extend/index.js";
|
|
7
7
|
import { isReservedKey, isWrappable, unwrapValue } from "./nodes.js";
|
|
8
|
+
import { Transaction, draftOf, readProxyOf } from "./proxies.js";
|
|
8
9
|
import { snapshot } from "./read.js";
|
|
9
10
|
import { applyReconcile, reconcile, specOf } from "./reconcile.js";
|
|
10
|
-
import { Transaction, draftOf, readProxyOf } from "./proxies.js";
|
|
11
11
|
// src/store/use-store.ts
|
|
12
12
|
function isPlainObject(value) {
|
|
13
13
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
@@ -26,6 +26,10 @@ function rangeKeys(range, length) {
|
|
|
26
26
|
}
|
|
27
27
|
return keys;
|
|
28
28
|
}
|
|
29
|
+
/** Appends `items` to `keys` one by one: a spread into `push` overflows the call stack for a long list. */
|
|
30
|
+
function appendKeys(keys, items) {
|
|
31
|
+
for (const item of items) keys.push(item);
|
|
32
|
+
}
|
|
29
33
|
/** The keys one path step addresses on `target` (a draft). */
|
|
30
34
|
function stepKeys(target, step, label) {
|
|
31
35
|
const keys = [];
|
|
@@ -34,11 +38,11 @@ function stepKeys(target, step, label) {
|
|
|
34
38
|
else if (typeof step === "function") {
|
|
35
39
|
const filter = step;
|
|
36
40
|
for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);
|
|
37
|
-
} else if (Array.isArray(step)) keys
|
|
38
|
-
else if (typeof step === "object" && step !== null) keys
|
|
41
|
+
} else if (Array.isArray(step)) appendKeys(keys, step);
|
|
42
|
+
else if (typeof step === "object" && step !== null) appendKeys(keys, rangeKeys(step, target.length));
|
|
39
43
|
else throw new TypeError(`ShadowStore${label}: bad path step for an array`);
|
|
40
44
|
} else if (typeof step === "string" || typeof step === "number") keys.push(step);
|
|
41
|
-
else if (Array.isArray(step)) keys
|
|
45
|
+
else if (Array.isArray(step)) appendKeys(keys, step);
|
|
42
46
|
else throw new TypeError(`ShadowStore${label}: bad path step for an object`);
|
|
43
47
|
for (const key of keys) if (typeof key === "string" && isReservedKey(key)) throw new TypeError(`ShadowStore${label}: the key "${key}" cannot be used in a path`);
|
|
44
48
|
return keys;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-store.js","names":[],"sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) keys.push(...(step as number[]));\n else if (typeof step === \"object\" && step !== null)\n keys.push(...rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n keys.push(...(step as Array<string | number>));\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * A property read in a tracked context gets a small notifier. Reading many transient keys\n * (`store.byId[id]` with churning ids) does not grow it for the life of the store: once an object\n * has collected a few hundred notifiers, the ones nothing observes any more are dropped, and a key\n * read again gets a fresh one that reflects the current value.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\n const raw = unwrapValue(value);\n return isWrappable(raw) ? readProxyOf(raw) : value;\n}\n"],"mappings":";;;;;;;;;;;AA4BA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,UAAU,OAAoD,QAA0B;CAC/F,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,KAAK,MAAM,MAAM,SAAS;CAChC,MAAM,KAAK,MAAM,MAAM;CACvB,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,OAAO,GACjC,MAAM,IAAI,UACE,4CACZ;CACF,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI;EACtD,KAAK,KAAK,CAAC;EACX,IAAI,KAAK,SAAS,SAAS,GAAG;CAChC;CACA,OAAO;AACT;;AAGA,SAAS,SAAS,QAAgB,MAAe,OAAuC;CACtF,MAAM,OAA+B,CAAC;CACtC,IAAI,MAAM,QAAQ,MAAM,GAAG;EACzB,IAAI,OAAO,SAAS,UAAU,KAAK,KAAK,IAAI;OACvC,IAAI,OAAO,SAAS,YAAY;GACnC,MAAM,SAAS;GACf,KAAK,IAAI,IAAI,GAAG,I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,IAAY,KAAA,IAAY,EAAE,MAAM,QAAQ,KAAK,CACjE;CACA,MAAM,OAAO,SACX,MACE,OAAO,SAAS,cACX,aAAsB,SAAU,KAAwC,QAAQ,CAAC,IAClF,SAAS,IAAI,CACnB;CACF,OAAO,CAAC,MAAM,GAAG;AACnB;;AAGA,SAAS,SAAS,OAAyB;CACzC,MAAM,MAAM,YAAY,KAAK;CAC7B,OAAO,YAAY,GAAG,IAAI,YAAY,GAAG,IAAI;AAC/C"}
|
|
1
|
+
{"version":3,"file":"use-store.js","names":[],"sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** Appends `items` to `keys` one by one: a spread into `push` overflows the call stack for a long list. */\nfunction appendKeys(keys: Array<string | number>, items: ReadonlyArray<string | number>): void {\n for (const item of items) keys.push(item);\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) appendKeys(keys, step as number[]);\n else if (typeof step === \"object\" && step !== null)\n appendKeys(keys, rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n appendKeys(keys, step as Array<string | number>);\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * A property read in a tracked context gets a small notifier. Reading many transient keys\n * (`store.byId[id]` with churning ids) does not grow it for the life of the store: once an object\n * has collected a few hundred notifiers, the ones nothing observes any more are dropped, and a key\n * read again gets a fresh one that reflects the current value.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\n const raw = unwrapValue(value);\n return isWrappable(raw) ? readProxyOf(raw) : value;\n}\n"],"mappings":";;;;;;;;;;;AA4BA,SAAS,cAAc,OAAkD;CACvE,IAAI,OAAO,UAAU,YAAY,UAAU,QAAQ,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,YAAY,OAAO,eAAe,KAAK;CAC7C,OAAO,cAAc,OAAO,aAAa,cAAc;AACzD;AAEA,SAAS,UAAU,OAAoD,QAA0B;CAC/F,MAAM,OAAO,MAAM,QAAQ;CAC3B,MAAM,KAAK,MAAM,MAAM,SAAS;CAChC,MAAM,KAAK,MAAM,MAAM;CACvB,IAAI,CAAC,OAAO,SAAS,EAAE,KAAK,OAAO,GACjC,MAAM,IAAI,UACE,4CACZ;CACF,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,IAAI,MAAM,KAAK,IAAI,KAAK,KAAK,KAAK,IAAI,KAAK,IAAI;EACtD,KAAK,KAAK,CAAC;EACX,IAAI,KAAK,SAAS,SAAS,GAAG;CAChC;CACA,OAAO;AACT;;AAGA,SAAS,WAAW,MAA8B,OAA6C;CAC7F,KAAK,MAAM,QAAQ,OAAO,KAAK,KAAK,IAAI;AAC1C;;AAGA,SAAS,SAAS,QAAgB,MAAe,OAAuC;CACtF,MAAM,OAA+B,CAAC;C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AO,YAAY,OAAO;CAChC,IAAI,YAAY,IAAI,GAAG,OAAO,gBAAgB,MAAM,KAAK;CAGzD,MAAM,CAAC,MAAM,SAAS,UACpB,SAAS,OAAO,GAChB,SAAS,SAAS,KAAA,IAAY,KAAA,IAAY,EAAE,MAAM,QAAQ,KAAK,CACjE;CACA,MAAM,OAAO,SACX,MACE,OAAO,SAAS,cACX,aAAsB,SAAU,KAAwC,QAAQ,CAAC,IAClF,SAAS,IAAI,CACnB;CACF,OAAO,CAAC,MAAM,GAAG;AACnB;;AAGA,SAAS,SAAS,OAAyB;CACzC,MAAM,MAAM,YAAY,KAAK;CAC7B,OAAO,YAAY,GAAG,IAAI,YAAY,GAAG,IAAI;AAC/C"}
|
package/dist/dev/transitions.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
+
import { createComputation } from "./extend/index.js";
|
|
1
2
|
import { untrack } from "./ownership.js";
|
|
2
|
-
import { useSignal } from "./signal.js";
|
|
3
3
|
import { registerTransitionLane, startTransition } from "./internal/concurrency.js";
|
|
4
|
-
import {
|
|
4
|
+
import { useSignal } from "./signal.js";
|
|
5
5
|
// src/transitions.ts
|
|
6
6
|
/**
|
|
7
7
|
* Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:
|
package/dist/prod/action.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{
|
|
1
|
+
import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{currentOwner as n}from"./extend/index.js";import{untrack as r}from"./ownership.js";import{useSignal as i}from"./signal.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=n(),[l,u]=i(s),[d,f]=i(!1),p=0;return[l,(...n)=>{p+=1;let i=p,s=r(l),d=e=>{i===p&&t(()=>{u(()=>e),f(!1)})},m=t=>{if(i===p&&f(!1),c===null)throw t;try{e(t,c)}catch(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}},h;try{h=r(()=>o(s,...n))}catch(e){try{m(e)}catch(e){return Promise.reject(e)}return Promise.resolve()}return a(h)?(f(!0),Promise.resolve(h).then(d,m)):(d(h),Promise.resolve())},d]}export{o as useAction};
|
|
2
2
|
//# sourceMappingURL=action.js.map
|
package/dist/prod/cache.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{currentOwner as e}from"./extend/index.js";import{untrack as t}from"./ownership.js";function n(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0}function r(e){let t=e;for(;t!==null&&t.parent!==null;)t=t.parent;return t}function i(i,a){let o=a?.limit??100;if(!Number.isInteger(o)||o<1)throw RangeError(`SHADOW_CACHE_LIMIT`);let s=/* @__PURE__ */ new WeakMap;return(...a)=>{let c=r(e());if(c===null)return t(()=>i(...a));let l=s.get(c);l===void 0&&(l=[],s.set(c,l));for(let e of l)if(n(e.args,a))return e.value;let u=t(()=>i(...a));return l.push({args:a,value:u}),l.length>o&&l.shift(),u}}export{i as cache};
|
|
2
2
|
//# sourceMappingURL=cache.js.map
|
package/dist/prod/context.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t}from"./internal/owner.js";import{
|
|
1
|
+
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t}from"./internal/owner.js";import{useRenderEffect as n}from"./effect.js";import{currentOwner as r}from"./extend/index.js";import{runWithOwner as i}from"./ownership.js";import{useSignal as a}from"./signal.js";function o(e,o){let s=Symbol(o?.name??`context`),c=e=>{let o=new t(r()),c=o.context,l=Object.create(c);return l[s]=e.value,o.context=l,i(o,()=>{let[t,r]=a(void 0,{equals:!1});return n(()=>e.children,e=>{r(()=>e)}),t})};return Object.assign(c,{id:s,defaultValue:e,Provider:c})}function s(e,n,a){let o=new t(r()),s=Object.create(o.context);return s[e.id]=n,o.context=s,i(o,a)}function c(t){let n=r()?.context;if(n!=null&&t.id in n)return n[t.id];if(t.defaultValue===void 0)throw new e(`CONTEXT_MISSING`);return t.defaultValue}export{o as createContext,s as runWithContext,c as useContext};
|
|
2
2
|
//# sourceMappingURL=context.js.map
|
package/dist/prod/effect.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import"./internal/diagnostics.js";import{
|
|
1
|
+
import"./internal/diagnostics.js";import{createComputation as e,currentOwner as t}from"./extend/index.js";import{untrack as n}from"./ownership.js";function r(n,r,i,a,o){let s=i?null:t()?.gate??null;if(s!==null){let e=!1,t=!1,i=a,o=n,c=r;a=!1,n=n=>(t=!e&&s(),e||=!t,t?void 0:o(n)),c!==null&&(r=(e,n)=>{if(!t){if(!i)return c(e,n);i=!1}})}e({kind:`effect`,fn:n,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(e){r(()=>n(e),null,!1,!1,`onMount`)}export{o as onMount,i as useEffect,a as useRenderEffect};
|
|
2
2
|
//# sourceMappingURL=effect.js.map
|
package/dist/prod/effect.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"effect.js","names":["createEffect","
|
|
1
|
+
{"version":3,"file":"effect.js","names":["createEffect","gate","render","currentOwner","opened","closed","skip","defer","run","fn","then","apply","previous","value","createComputation","useEffect","second","first","third","useRenderEffect","compute","onMount","untrack"],"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":"A,mJA4BA,SAASA,EACP,EACA,EACA,EACA,EACA,EACM,CAIN,IAAMC,EAAOC,EAAS,KAAQC,EAAa,CAAC,EAAE,MAAQ,KACtD,GAAIF,IAAS,KAAM,CAKjB,IAAIG,EAAS,GACTC,EAAS,GACTC,EAAOC,EACLC,EAAMC,EACNC,EAAOC,EACb,EAAQ,GACR,EAAM,IACJ,EAAS,CAACP,GAAUH,EAAK,EACzB,IAAW,CAACI,EACLA,EAAS,IAAA,GAAYG,EAAII,CAAQ,GAEtCF,IAAS,OACX,GAAS,EAAO,IAAa,CAC3B,GAAI,GACJ,IAAI,CAACJ,EAAM,OAAOI,EAAKG,EAAOD,CAAQ,EACtC,EAAO,EAD+B,CAGxC,EAEJ,CACAE,EAAkB,CAChB,KAAM,SACN,KACA,SACA,QACA,MAAOH,GAAS,IAAA,GAChB,MACF,CAAC,CACH,CA0DA,SAAgBI,EACd,EACA,EACA,EACM,CACF,OAAOC,GAAW,WACpBhB,EACEiB,EACAD,EACA,GACAE,GAAO,QAAU,GACjBA,GAAO,IACT,EAGAlB,EAAaiB,EAAO,KAAM,GAAO,GAAQD,GAAsC,IAAI,CAEvF,CAyBA,SAAgBG,EACd,EACA,EACM,CACNnB,EACEoB,EACCT,GAAS,KACV,GACA,GACA,IAAA,EACF,CACF,CAoBA,SAAgBU,EAAQ,EAAgC,CACtDrB,MAAmBsB,EAAQb,CAAE,EAAG,KAAM,GAAO,GAAO,SAAS,CAC/D,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{DEVTOOLS_EVENT as e,report as t}from"../internal/devtools.js";import{
|
|
1
|
+
import{DEVTOOLS_EVENT as e,report as t}from"../internal/devtools.js";import{ShadowError as n,resetWarningDedupe as r,setWarningListener as i,warn as a}from"../internal/diagnostics.js";import{Computation as o,Signal as s,hasObservers as c,isEqual as l,markObservers as u,observersOf as d,readMemo as f,readSignal as p,recompute as m,sourcesOf as h,track as g,updateIfNecessary as _}from"../internal/graph.js";import{Owner as v,addCleanup as y,handleError as b}from"../internal/owner.js";import{enqueue as x}from"../internal/queue.js";import{batch as S,flush as C,flushSync as w,group as T,schedule as E}from"../internal/scheduler.js";import{rt as D}from"../internal/state.js";import{runWithContext as O}from"../context.js";import{beginHold as k,createTransitionHold as A,endHold as j,holdReader as M,inTransition as ee,pauseOwner as N,registerTransitionLane as P,resumeOwner as F,startTransition as I,transitionHooks as L,wakeSuspended as R}from"../internal/concurrency.js";import{disposeTree as z}from"../internal/dispose.js";import{isHydrating as B,withHydration as V}from"../internal/hydration-flag.js";import{MESSAGES as H,formatMessage as U}from"../internal/messages.js";import{SUSPENSION as W,isSuspension as G}from"../internal/suspension.js";function K(){return D.owner}function q(){return D.listener}function J(){return D.listener!==null}function Y(){return D.disposing===0&&D.running!==null&&D.running.kind===1&&!(D.running.flags&256)}function X(e,t){let n=D.owner,r=D.listener;try{let n=e.owner;n!==void 0&&(D.owner=n);let r=e.listener;return r!==void 0&&(D.listener=r),t()}finally{D.owner=n,D.listener=r}}function Z(e,t,n){return new s(e,t,n)}function Q(e,t,n){let r=e.equals;return r!==!1&&l(r,e.value,t)?!1:(e.value=t,$(e),!0)}function $(e){c(e)&&(u(e),E())}function te(e){let t=e.owner===void 0?D.owner:e.owner,n=e.kind===`memo`,r=new o(t,n?1:2,n?32|(e.allowWrites===!0?256:0):(e.render===!0?16:0)|(e.defer===!0?64:0)|(e.lane===!0?512:0),e.fn,n?e.equals??Object.is:!1,e.name);return n?(e.lazy!==!0&&_(r),r):(r.apply=e.apply??null,e.render===!0?m(r):(x(r),E()),r)}function ne(e){return f(e)}function re(e){_(e)}function ie(e){return new v(e===void 0?D.owner:e)}export{o as ComputationNode,e as DEVTOOLS_EVENT,H as MESSAGES,v as Owner,W as SUSPENSION,n as ShadowError,s as SignalNode,y as addCleanup,S as batch,k as beginHold,te as createComputation,ie as createOwner,Z as createSignalNode,A as createTransitionHold,q as currentListener,K as currentOwner,t as devtoolsReport,z as disposeOwner,j as endHold,C as flush,w as flushSync,U as formatMessage,T as group,b as handleError,M as holdReader,ee as inTransition,Y as isComputingMemo,B as isHydrating,G as isSuspension,J as isTracking,u as markObservers,$ as notify,d as observersOf,N as pauseOwner,ne as readComputation,p as readSignal,re as refresh,P as registerTransitionLane,r as resetWarningDedupe,F as resumeOwner,X as runInScope,O as runWithContext,E as schedule,i as setWarningListener,h as sourcesOf,I as startTransition,g as track,L as transitionHooks,R as wakeSuspended,a as warn,V as withHydration,Q as writeSignal};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{useEffect as e}from"./effect.js";import{isHydrating as t}from"./internal/hydration-flag.js";import{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";function i(i,a,o){let s=t()&&o?.getServerSnapshot!==void 0?o.getServerSnapshot:a,[c,l]=r(n(s),{equals:o?.equals??Object.is,name:o?.name}),u=()=>{let e=n(a);l(()=>e)};return e(()=>{let e=n(()=>i(u));try{u()}catch(t){throw e(),t}return e}),c}export{i as useExternalStore};
|
|
2
2
|
//# sourceMappingURL=external-store.js.map
|
package/dist/prod/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{useAction as e}from"./action.js";import{cache as t}from"./cache.js";import{createContext as n,useContext as r}from"./context.js";import{onMount as i,useEffect as a,useRenderEffect as o}from"./effect.js";import{isDev as s,isServer as c}from"./env.js";import{useEvent as l}from"./events.js";import{batch as u,flushSync as d}from"./internal/scheduler.js";import{startTransition as f}from"./internal/concurrency.js";import{useExternalStore as p}from"./external-store.js";import{indexArray as m,mapArray as h}from"./list.js";import{useMemo as g}from"./memo.js";import{useOptimistic as _}from"./optimistic.js";import{catchError as v,createRoot as y,getOwner as b,onCleanup as x,onError as S,runWithOwner as C,untrack as w,useId as T}from"./ownership.js";import{children as E,mergeProps as D,splitProps as O}from"./props.js";import{useReaction as k}from"./reaction.js";import{useReducer as A}from"./reducer.js";import{createRef as j,useImperativeHandle as M}from"./refs.js";import{useResource as N}from"./resource.js";import{useSelector as P}from"./selector.js";import{useSignal as F}from"./signal.js";import{produce as I,reconcile as L}from"./store/reconcile.js";import{snapshot as R,unwrap as z}from"./store/read.js";import{useStore as B}from"./store/use-store.js";import{ResourceCacheContext as V,SuspenseContext as H}from"./suspense.js";import{useDeferredValue as U,useTransition as W}from"./transitions.js";export{V as ResourceCacheContext,H as SuspenseContext,u as batch,t as cache,v as catchError,E as children,n as createContext,j as createRef,y as createRoot,d as flushSync,b as getOwner,m as indexArray,s as isDev,c as isServer,h as mapArray,D as mergeProps,x as onCleanup,S as onError,i as onMount,I as produce,L as reconcile,C as runWithOwner,R as snapshot,O as splitProps,f as startTransition,w as untrack,z as unwrap,e as useAction,r as useContext,U as useDeferredValue,a as useEffect,l as useEvent,p as useExternalStore,T as useId,M as useImperativeHandle,g as useMemo,_ as useOptimistic,k as useReaction,A as useReducer,o as useRenderEffect,N as useResource,P as useSelector,F as useSignal,B as useStore,W as useTransition};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{runWithContext as e}from"../context.js";import{SuspenseContext as t}from"../suspense.js";import{ShadowError as n}from"./diagnostics.js";import{disposeTree as r}from"./dispose.js";import{FLAG_PARKED as i,FLAG_TRANSITION as a}from"./flags.js";import{Computation as o,Signal as s,hasObservers as c,markObservers as l,readSignal as u}from"./graph.js";import{Owner as d,addCleanup as f,finishDisposal as p}from"./owner.js";import{clearQueues as m,hasPending as h,place as g,renderQueue as _,userQueue as v}from"./queue.js";import{byCreation as y,reportUncaught as b,runQueued as x,schedule as S}from"./scheduler.js";import{rt as C}from"./state.js";import{SUSPENSION as w,isSuspension as T}from"./suspension.js";function E(e,t){let n=[e];for(;n.length>0;){let e=n.pop();t(e);for(let t=e.lastChild;t!==null;t=t.prevSibling)n.push(t)}}function D(){let D=[],O=[],k=null,A=null,j=/* @__PURE__ */ new Set,M=0,N=!1,P=()=>D.length>0||O.length>0,F=()=>P()||M>0,I=(e,t)=>{let n=e.splice(0,t);n.sort(y);for(let e of n)e.flags&1024&&(e.flags&=~(2|a),e.flags&4||(e.pauses>0?e.flags|=i|a:x(e)));return n.length},L=()=>{if(F()||A===null)return;let e=A;k=A=null,e()},R=()=>{N||(N=!0,setTimeout(z,0))},z=()=>{if(N=!1,C.flushing){R();return}let e=C.inTransition;C.inTransition=!0,C.flushing=!0;let t=64,r=0;try{for(;t>0&&P();){if(r+=1,r>1e3){m(),C.uncaught.push(new n(`INFINITE_LOOP`));break}let e=D.length>0?D:O;t-=I(e,t)}}finally{C.inTransition=e,C.flushing=!1}let i=C.uncaught.splice(0,C.uncaught.length);for(let e of i)b(e);P()?R():L(),h()&&S()},B=e=>{let t=C.inTransition,n=C.listener;C.inTransition=!0,C.listener=null;try{e()}finally{C.inTransition=t,C.listener=n}k??=new Promise(e=>{A=e});let r=k;return L(),r},V=(e,t)=>{if(e.pauses>0){e.flags=t?e.flags|i|a:(e.flags|i)&~a;return}let n=!!(e.flags&16);e.flags=e.flags&~i|2|a,n?D.push(e):O.push(e),R()},H=e=>{e.flags&512||e.pauses>0||(e.flags&2048?g(e,!1):(e.flags&1026)==1026&&(e.flags&=~a,e.flags&16?_.push(e):v.push(e)))},U=()=>{for(let e of[D,O]){for(let t of e)t.flags&=~(2|a),t.state=0;e.length=0}},W=(e,t)=>{if(t!==w)return!1;if(!j.has(e)){let t=j.size;if(t>=64&&!(t&t-1))for(let e of j)e.disposed&&j.delete(e);j.add(e)}return!0},G=e=>{if(e.hold?.()===!0)throw w},K=()=>{M+=1},q=()=>{M>0&&--M,P()&&R(),L()},J=()=>{let e=Array.from(j);j.clear();let t=C.inTransition;C.inTransition=!0;try{for(let t of e)t.disposed||(t.state=2,t.kind===2?g(t,!0):l(t))}finally{C.inTransition=t}S()},Y=e=>{let t=[];E(e,e=>{e.pauses+=1,t.push(e)}),C.disposing+=1;try{for(let e=t.length-1;e>=0;--e){let n=t[e];n instanceof o&&n.kind===2&&!(n.flags&16)&&!n.disposed&&n.runCleanups()}}finally{p()}},X=n=>{let r=0,i=!1,a=!1,o={increment(){r+=1},decrement(){--r,r===0&&(i&&(i=!1,J(),q()),n())},hold(){return a=!0,i||(i=!0,K()),!0}};return{run:n=>e(t,o,n),count:()=>r,engaged:()=>a,drop:()=>{i&&(i=!1,q())}}};return{place:V,promote:H,clear:U,suspend:W,holdReader:G,startTransition:B,beginHold:K,endHold:q,wakeSuspended:J,pause:Y,resume:e=>{E(e,e=>{if(e.pauses>0&&--e.pauses,e instanceof o&&e.pauses===0&&!e.disposed){if(e.kind===2){if(e.flags&16&&!(e.flags&2048))return;e.state=2,g(e,!1)}else e.state!==0&&l(e)}}),S()},createHold:X,slotSwap:(e,t,n,i)=>{let a,o=new d(i),p=new s(0,!1,void 0),m=()=>{p.value+=1,c(p)&&(l(p),S())},h=e=>{e.owned.disposing=!0;try{e.hold?.drop(),e.dispose?.()}finally{e.owned.disposing=!1}},g=t=>{let n=e.live;e.live=t,n!==void 0&&h(n)},_=e=>{let n={index:e.index,value:e.when,disposing:!1},i=X(()=>{a!==void 0&&a.hold===i&&m()}),s=new d(o),c=C.owner,l=C.listener;C.owner=s,C.listener=null;let u;try{try{u=i.run(()=>t(e,n,!0))}catch(e){if(!T(e))throw e}let r=new d(s);f(r,()=>{n.disposing=!0})}finally{C.owner=c,C.listener=l}return{choice:e,owned:n,result:u,dispose:()=>r(s),hold:i.engaged()?i:null}};return{step(t){if(u(p),a!==void 0){if(!n(a.choice,t)){let e=a;a=void 0,e.hold?.drop(),e.dispose?.()}else if((a.hold?.count()??0)>0)return!0;else{let e=a;return a=void 0,g(e),!0}}if(e.live!==void 0&&C.inTransition){let e=_(t);return e.hold===null?g(e):a=e,!0}let r=e.live;return e.live=void 0,r!==void 0&&h(r),!1}}},boundaryHold:()=>{let e=!1;return{engage:()=>(e||(e=!0,K()),!0),release:()=>{e&&(e=!1,J(),q())},holding:()=>e}}}}function O(){let e=C.hooks;if(e!==null)return e;let t=D();return C.hooks=t,t}function k(){O()}function A(e){return O().startTransition(e)}function j(){C.hooks?.beginHold()}function M(){C.hooks?.endHold()}function N(){C.hooks?.wakeSuspended()}function P(e){C.hooks?.holdReader(e)}function F(){return C.inTransition}function I(e){let t=C.hooks;return t===null?null:t.createHold(e)}function L(){return C.inTransition?C.hooks:null}function R(e){O().pause(e)}function z(e){C.hooks?.resume(e)}export{j as beginHold,I as createTransitionHold,M as endHold,P as holdReader,F as inTransition,R as pauseOwner,k as registerTransitionLane,z as resumeOwner,A as startTransition,L as transitionHooks,N as wakeSuspended};
|
|
2
2
|
//# sourceMappingURL=concurrency.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","applied","resolveApplied","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","runQueued","settleLane","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","error","reportUncaught","hasPending","schedule","startTransition","listener","fn","shared","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","size","entry","holdReader","tracker","beginHold","endHold","wakeSuspended","woken","markObservers","pause","nodes","owner","i","Computation","finishDisposal","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport { Computation, hasObservers, markObservers, readSignal, Signal } from \"./graph\";\nimport { addCleanup, finishDisposal, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, runQueued, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** The length of the suspended list from which the disposed nodes are dropped, at each power of two. */\nconst SUSPENDED_SWEEP_AT = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop() as Owner;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /**\n * The promise every transition that waits for the lane shares (`waiting` counts the callers, for\n * devtools). One promise instead of one resolver per call: while a hold stays engaged the list of resolvers grew\n * with every `startTransition`, and all of them resolve at the same moment anyway.\n */\n let applied: Promise<void> | null = null;\n let resolveApplied: (() => void) | null = null;\n let waiting = 0;\n /**\n * Memos and effects that caught a suspension; woken all at once when a boundary releases them. A\n * node is listed once (it is a set), and the disposed ones are dropped each time the list\n * length is a power of two from `SUSPENDED_SWEEP_AT` on, so a hold that stays engaged cannot make the list, or the nodes it keeps alive,\n * grow with the number of nodes that came and went.\n */\n const suspended = new Set<Computation>();\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || resolveApplied === null) return;\n const resolve = resolveApplied;\n applied = resolveApplied = null;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.TRANSITION_END, waiting);\n waiting = 0;\n }\n resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n if (__DEV__) waiting += 1;\n applied ??= new Promise<void>((resolve) => {\n resolveApplied = resolve;\n });\n const shared = applied;\n settleLane();\n return shared;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n // Listed once: a node that suspends again before the wake-up is already in the set.\n if (!suspended.has(node)) {\n const size = suspended.size;\n if (size >= SUSPENDED_SWEEP_AT && (size & (size - 1)) === 0) {\n // A disposed node never wakes, so keeping it would leak it for as long as the hold lasts.\n for (const entry of suspended) {\n if (entry.disposed) suspended.delete(entry);\n }\n }\n suspended.add(node);\n }\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const woken = Array.from(suspended);\n suspended.clear();\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of woken) {\n if (node.disposed) continue;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n // Every node is paused before any cleanup runs: a cleanup that throws must not leave the rest\n // unpaused. Preorder reversed is the disposal order: children first, newest first.\n const nodes: Owner[] = [];\n walk(owner, (node) => {\n node.pauses += 1;\n nodes.push(node);\n });\n rt.disposing += 1;\n try {\n for (let i = nodes.length - 1; i >= 0; i -= 1) {\n const node = nodes[i];\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n }\n } finally {\n finishDisposal();\n }\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const 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 transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":"A,ysBAgDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvBG,EAAMD,CAAI,EACV,IAAK,IAAIE,EAAQF,EAAK,UAAWE,IAAU,KAAM,EAAQA,EAAM,YAAaJ,EAAM,KAAKI,CAAK,CAC9F,CACF,CAGA,SAASC,GAAqB,CAC5B,IAAMC,EAA4B,CAAC,EAC7BC,EAA0B,CAAC,EAM7BC,EAAgC,KAChCC,EAAsC,KAQpCC,kBAAY,IAAI,IAElBC,EAAQ,EACRC,EAAY,GAEVC,MAAgCP,EAAW,OAAS,GAAKC,EAAS,OAAS,EAC3EO,MAA0BD,EAAe,GAAKF,EAAQ,EAMtDI,GAAa,EAAsB,IAA0B,CACjE,IAAMC,EAAQC,EAAM,OAAO,EAAGC,CAAK,EACnCF,EAAM,KAAKG,CAAU,EACrB,IAAK,IAAMC,KAAUJ,EACdI,EAAO,MAAA,OACZ,EAAO,OAAS,EAAA,EAAgBC,GAC3B,IAAO,MAAA,KACRD,EAAO,OAAS,EAClB,EAAO,OAASE,EAAcD,EAGhCE,EAAUH,CAAM,IAElB,OAAOJ,EAAM,MACf,EAGMQ,MAAyB,CAC7B,GAAIV,EAAS,GAAKL,IAAmB,KAAM,OAC3C,IAAMgB,EAAUhB,EAChB,EAAU,EAAiB,KAK3BgB,EAAQ,CACV,EAGMC,MAA2B,CAC3Bd,IACJ,EAAY,GACZ,WAAWe,EAAW,CAAC,EACzB,EAOMA,MAAwB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kBA,SAAgB8B,GAAgB,CAC9B9B,EAAG,OAAO,QAAQ,CACpB,CAkBA,SAAgB+B,GAAsB,CACpC/B,EAAG,OAAO,cAAc,CAC1B,CAuBA,SAAgB2B,EAAW,EAAqC,CAC9D3B,EAAG,OAAO,WAAW4B,CAAO,CAC9B,CAmBA,SAAgBqD,GAAwB,CACtC,OAAOjF,EAAG,YACZ,CAmBA,SAAgBkF,EAAqB,EAA8C,CACjF,IAAMC,EAAQnF,EAAG,MACjB,OAAOmF,IAAU,KAAO,KAAOA,EAAM,WAAWvC,CAAS,CAC3D,CAkBA,SAAgBwC,GAAgC,CAC9C,OAAOpF,EAAG,aAAeA,EAAG,MAAQ,IACtC,CAkBA,SAAgBqF,EAAW,EAAoB,CAC7CR,EAAY,CAAC,CAAC,MAAMzC,CAAK,CAC3B,CAmBA,SAAgBkD,EAAY,EAAoB,CAC9CtF,EAAG,OAAO,OAAOoC,CAAK,CACxB,C"}
|
|
1
|
+
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","applied","resolveApplied","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","runQueued","settleLane","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","error","reportUncaught","hasPending","schedule","startTransition","listener","fn","shared","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","size","entry","holdReader","tracker","beginHold","endHold","wakeSuspended","woken","markObservers","pause","nodes","owner","i","Computation","finishDisposal","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport { Computation, hasObservers, markObservers, readSignal, Signal } from \"./graph\";\nimport { addCleanup, finishDisposal, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, MAX_FLUSH_PASSES, reportUncaught, runQueued, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** The length of the suspended list from which the disposed nodes are dropped, at each power of two. */\nconst SUSPENDED_SWEEP_AT = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop() as Owner;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /**\n * The promise every transition that waits for the lane shares (`waiting` counts the callers, for\n * devtools). One promise instead of one resolver per call: while a hold stays engaged the list of resolvers grew\n * with every `startTransition`, and all of them resolve at the same moment anyway.\n */\n let applied: Promise<void> | null = null;\n let resolveApplied: (() => void) | null = null;\n let waiting = 0;\n /**\n * Memos and effects that caught a suspension; woken all at once when a boundary releases them. A\n * node is listed once (it is a set), and the disposed ones are dropped each time the list\n * length is a power of two from `SUSPENDED_SWEEP_AT` on, so a hold that stays engaged cannot make the list, or the nodes it keeps alive,\n * grow with the number of nodes that came and went.\n */\n const suspended = new Set<Computation>();\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n runQueued(effect);\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || resolveApplied === null) return;\n const resolve = resolveApplied;\n applied = resolveApplied = null;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.TRANSITION_END, waiting);\n waiting = 0;\n }\n resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n if (__DEV__) waiting += 1;\n applied ??= new Promise<void>((resolve) => {\n resolveApplied = resolve;\n });\n const shared = applied;\n settleLane();\n return shared;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n // Listed once: a node that suspends again before the wake-up is already in the set.\n if (!suspended.has(node)) {\n const size = suspended.size;\n if (size >= SUSPENDED_SWEEP_AT && (size & (size - 1)) === 0) {\n // A disposed node never wakes, so keeping it would leak it for as long as the hold lasts.\n for (const entry of suspended) {\n if (entry.disposed) suspended.delete(entry);\n }\n }\n suspended.add(node);\n }\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const woken = Array.from(suspended);\n suspended.clear();\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of woken) {\n if (node.disposed) continue;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n // Every node is paused before any cleanup runs: a cleanup that throws must not leave the rest\n // unpaused. Preorder reversed is the disposal order: children first, newest first.\n const nodes: Owner[] = [];\n walk(owner, (node) => {\n node.pauses += 1;\n nodes.push(node);\n });\n rt.disposing += 1;\n try {\n for (let i = nodes.length - 1; i >= 0; i -= 1) {\n const node = nodes[i];\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n }\n } finally {\n finishDisposal();\n }\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const 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 transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function resumeOwner(owner: Owner): void {\n rt.hooks?.resume(owner);\n}\n"],"mappings":"A,ysBAgDA,SAASA,EAAK,EAAa,EAAoC,CAC7D,IAAMC,EAAiB,CAACC,CAAI,EAC5B,KAAOD,EAAM,OAAS,GAAG,CACvB,IAAME,EAAOF,EAAM,IAAI,EACvBG,EAAMD,CAAI,EACV,IAAK,IAAIE,EAAQF,EAAK,UAAWE,IAAU,KAAM,EAAQA,EAAM,YAAaJ,EAAM,KAAKI,CAAK,CAC9F,CACF,CAGA,SAASC,GAAqB,CAC5B,IAAMC,EAA4B,CAAC,EAC7BC,EAA0B,CAAC,EAM7BC,EAAgC,KAChCC,EAAsC,KAQpCC,kBAAY,IAAI,IAElBC,EAAQ,EACRC,EAAY,GAEVC,MAAgCP,EAAW,OAAS,GAAK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enThrow as n}from"./scheduler.js";import{rt as r}from"./state.js";function i(i){let a,o=!1;try{e(i)}catch(e){o=!0,a=e}n(r.running===null&&r.batches===0&&r.disposing===0&&!r.flushing&&t(),o,a,`SHADOW_DISPOSE_FLUSH_ERRORS`)}export{i as disposeTree};
|
|
2
2
|
//# sourceMappingURL=dispose.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"dispose.js","names":["disposeTree$1","disposeTree","failure","failed","root","error","
|
|
1
|
+
{"version":3,"file":"dispose.js","names":["disposeTree$1","disposeTree","failure","failed","root","error","flushThenThrow","rt","hasPending"],"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":"A,iKA6BA,SAAgBC,EAAY,EAAmB,CAC7C,IAAIC,EACAC,EAAS,GACb,GAAI,CACFH,EAAeI,CAAI,CACrB,OAASC,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,CAGAC,EACEC,EAAG,UAAY,MAAQA,EAAG,UAAY,GAAKA,EAAG,YAAc,GAAK,CAACA,EAAG,UAAYC,EAAW,EAC5FL,EACAD,EAC2D,6BAC7D,CACF,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{ShadowError as e}from"./diagnostics.js";import{
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{Owner as t,addCleanup as n,disposeChildren as r,finishDisposal as i,handleError as a,hasErrorHandler as o}from"./owner.js";import{enqueue as s}from"./queue.js";import{nextSequence as c,rt as l}from"./state.js";const u=Object.freeze([]);var d=class{kind=0;observers=null;stamp=0;constructor(e,t,n){this.value=e,this.equals=t,this.name=n}},f=class extends t{error=void 0;fn;apply=null;sources=u;observers=null;stamp=0;trackIndex=0;constructor(e,t,n,r,i,a){super(e),this.kind=t,this.flags=n,this.state=2,this.fn=r,this.equals=i,this.name=a,this.value=void 0,this.seq=c()}release(){this.flags|=4,m(this,0),this.fn=null,this.apply=null}};function p(e,t){let n=e.observers;if(n===null)return;let r=n.length-2;if(t!==r){let e=n[r],i=n[r+1];n[t]=e,n[t+1]=i,e.sources[i+1]=t}n.length=r}function m(e,t){let n=e.sources;if(!(n.length<=t)){for(let e=n.length-2;e>=t;e-=2)p(n[e],n[e+1]);n.length=t}}function h(e,t,n){let r=e.length;if(r>=16)return e.push(t,n),e;let i=Array(r+2);for(let t=0;t<r;t+=1)i[t]=e[t];return i[r]=t,i[r+1]=n,i}function g(e){let t=l.listener;if(t===null||e.stamp===t.stamp)return;e.stamp=t.stamp;let n=t.trackIndex;if(n<t.sources.length){if(t.sources[n]===e){t.trackIndex=n+2;return}m(t,n)}let r=e.observers,i=t.sources,a=r===null?0:r.length,o=i.length;e.observers=r===null?[t,o]:h(r,t,o),t.sources=h(i,e,a),t.trackIndex=o+2}function _(e){return b(e.sources)}function v(e){return e.observers===null?[]:b(e.observers)}function y(e){return e.observers!==null&&e.observers.length>0}function b(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(e[n]);return t}const x=[];function S(e,t){let n=e.state;e.kind===2?(n<t&&(e.state=t),n===0?s(e):l.inTransition||l.hooks?.promote(e)):n>=t||(e.state=t,n===0&&e.observers!==null&&e.observers.length>0&&x.push(e))}function C(e,t){return l.hooks?.suspend(e,t)===!0}function w(e){return e.pauses>0&&!(e.flags&32)}function T(e){for(E(e.observers,2);x.length>0;)E(x.pop().observers,1)}function E(e,t){if(e!==null)for(let n=0;n<e.length;n+=2)S(e[n],t)}const D=[],O=[];let k=0;function A(t,n=!1){if(t.state===0)return;let r=k;D[k]=t,O[k]=0,k+=1,t.flags|=128;try{for(;k>r;){let t=k-1,r=D[t];if(r.state===1||r.state===2&&n){let n=r.sources,i=O[t],a=!1;for(;i<n.length;){let r=n[i];if(i+=2,r.kind===0)continue;let o=r;if(j(o)){if(o.flags&1)throw new e(`CYCLE_DETECTED`);if(M(o)){O[t]=i,D[k]=o,O[k]=0,k+=1,o.flags|=128,a=!0;break}}}if(a)continue}r.state===2?F(r):r.state=0,r.flags&=-129,--k}}finally{for(let e=r;e<k;e+=1)D[e].flags&=-129;D.length=r,O.length=r,k=r}}function j(e){return e.state!==0&&!(e.flags&4)&&!w(e)}function M(e){if(!j(e))return!1;let t=[];for(let n=e.parent;n!==null;n=n.parent)n instanceof f&&n.state!==0&&!(n.flags&129)&&t.push(n);for(let e=t.length-1;e>=0;--e){let n=t[e];j(n)&&A(n)}return j(e)}function N(e){return l.listener!==null&&g(e),e.value}function P(t){if(t.flags&1)throw new e(`CYCLE_DETECTED`);if(t.state!==0&&M(t)&&A(t,l.nesting>=128),l.listener!==null&&g(t),t.flags&8)throw t.error;return t.value}function F(e){let t=e.fn;if(t===null)return;l.disposing+=1;try{r(e),e.runCleanups()}finally{--l.disposing}e.trackIndex=0,e.errorHandlers=null,e.idCount=0,e.childCount=0;let n=l.owner,a=l.listener,o=l.running;l.owner=e,l.listener=e,l.running=e,l.nesting+=1,e.state=0,e.flags|=1,e.stamp=c();let s,u=!1,d;try{s=t(e.value)}catch(e){u=!0,d=e}finally{l.owner=n,l.listener=a,l.running=o,--l.nesting,e.flags&=-2,m(e,e.flags&4?0:e.trackIndex)}e.kind===1?L(e,s,u,d):z(e,s,u,d),l.disposing+=1,e.flags&4&&(r(e),e.runCleanups()),i()}function I(e,t,n){let r=l.listener;l.listener=null;try{return e(t,n)}finally{l.listener=r}}function L(e,t,n,r){if(n&&C(e,r))return!1;let i=!!(e.flags&32);e.flags&=-33;let a=!!(e.flags&8),o;if(n&&R(e,r))return!1;if(n)e.flags|=8,e.error=r,o=!0;else{e.flags&=-9,e.error=void 0;let n=e.equals;try{o=i||a||n===!1||!I(n,e.value,t),o&&(e.value=t)}catch(t){e.flags|=8,e.error=t,o=!0}}if(!o||i)return o;let s=e.observers;if(s===null)return o;for(let e=0;e<s.length;e+=2){let t=s[e];t.state===1&&(t.state=2)}return o}function R(e,t){if(!o(e))return!1;e.flags&=-9,e.error=void 0;try{a(t,e)}catch(t){e.flags|=8,e.error=t}return!0}function z(e,t,r,i){if(r){C(e,i)||a(i,e);return}let o=e.apply,s;if(o===null)s=t;else{let n=!!(e.flags&64);e.flags&=-65;let r=e.value;if(e.value=t,n)return;let i=l.owner,c=l.listener,u=l.running;l.owner=e,l.listener=null,l.running=e;try{s=o(t,r)}catch(t){C(e,t)||a(t,e);return}finally{l.owner=i,l.listener=c,l.running=u}}typeof s==`function`&&(n(e,s),e.flags&4&&e.runCleanups())}export{f as Computation,d as Signal,y as hasObservers,I as isEqual,w as isFrozen,T as markObservers,v as observersOf,P as readMemo,N as readSignal,F as recompute,M as refreshAncestors,_ as sourcesOf,g as track,A as updateIfNecessary};
|
|
2
2
|
//# sourceMappingURL=graph.js.map
|