@shadow-js/core 1.0.4 → 1.0.6
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/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 +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 +1 -1
- package/dist/dev/internal/graph.d.ts +1 -1
- package/dist/dev/internal/graph.js +5 -1
- package/dist/dev/internal/graph.js.map +1 -1
- package/dist/dev/internal/scheduler.js +2 -2
- package/dist/dev/internal/state.d.ts +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/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/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/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/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/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/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/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 +1 -1
- package/dist/server-dev/internal/graph.js +5 -1
- package/dist/server-dev/internal/graph.js.map +1 -1
- package/dist/server-dev/internal/scheduler.js +2 -2
- 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ownership.js","names":["disposeOwner","untrack","runInScope","fn","createRoot","detached","options","current","currentOwner","root","Owner","disposeTree","error","cleanupError","getOwner","runWithOwner","target","owner","onCleanup","addCleanup","onError","handler","catchError","scope","handleError","useId","ShadowError","host","hosted","path","node","sequence"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/** Where the copies of core list themselves; `Symbol.for` makes the key the same in every copy. */\nconst REGISTRY_KEY = \"shadow-js.core.instances\";\n\n/**\n * The most copies the registry lists. Real programs have one, a misconfigured one two or three; the\n * limit keeps a program that loads core in a loop (a hot-reload bug) from growing the shared map.\n */\nconst MAX_LISTED_COPIES = 8;\n\n/**\n * The identity of this copy of the module (every evaluation of the module makes its own) and the build it is:\n * the server build and the client build are different files by design, and tests that render on the server\n * and hydrate in one process load one of each, so only copies of the same build count as duplicates.\n */\nconst COPY: { readonly server: boolean } = { server: __SERVER__ };\n\n/** The registry of the copies of core and how many roots each has alive, or undefined before any root exists. */\nfunction copyRegistry(): Map<{ readonly server: boolean }, number> | undefined {\n const found = (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)];\n return found instanceof Map ? found : undefined;\n}\n\n/** Development only. Counts a disposed root out of this copy's entry; the entry goes with its last root. */\nfunction releaseRoot(): void {\n const registry = copyRegistry();\n const live = registry?.get(COPY);\n if (registry === undefined || live === undefined) return;\n if (live > 1) registry.set(COPY, live - 1);\n else registry.delete(COPY);\n}\n\n/**\n * Development only. Lists a new root under this copy of core in a registry on `globalThis`, which counts the\n * live roots of every copy, and warns `DUPLICATE_CORE` (once per copy) when another copy of the same build has\n * live roots: two copies cannot see each other's signals. A copy leaves the registry when its last root is disposed, so copies\n * that never run at the same time (separate test files, a reload) do not warn. Called from `createRoot` only\n * behind `__DEV__`, and only when a root is created, never when the module is imported. The release is one\n * shared function, so a root costs no closure: rows of a list make a root each.\n */\nfunction listRoot(root: Owner): void {\n let registry = copyRegistry();\n if (registry === undefined) {\n registry = new Map();\n (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)] = registry;\n }\n const listed = registry.has(COPY);\n for (const copy of registry.keys()) {\n if (copy !== COPY && copy.server === COPY.server) {\n warn(\"DUPLICATE_CORE\");\n break;\n }\n }\n // A copy past the limit is not listed; the warning above has been given by then.\n if (!listed && registry.size >= MAX_LISTED_COPIES) return;\n registry.set(COPY, (registry.get(COPY) ?? 0) + 1);\n addCleanup(root, releaseRoot);\n}\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects. Development builds also use the root to find a second copy of core: a root\n * created while a root of another copy is alive warns `DUPLICATE_CORE` once.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed. When a cleanup of the root throws as well, both errors are thrown together as an\n * `AggregateError` (the body's first), so the body's error is never replaced.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n if (__DEV__) listRoot(root);\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n try {\n disposeOwner(root);\n } catch (cleanupError) {\n // The body's error says what went wrong; a cleanup error must not replace it.\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"The root body threw and so did its disposal.\" : \"SHADOW_ROOT_ERRORS\",\n );\n }\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n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OAASS,EAAO,CACPY,EAAiBZ,EAAOW,CAAK,EAApC,MACF,CACF,CAyBA,SAAgBE,GAAgB,CAC9B,IAAMR,EAAQT,EAAa,EAC3B,GAAIS,IAAU,KAAM,MAAM,IAAIS,EAAY,aAAa,EAIvD,IAAK,IAAIC,EAAqBV,EAAOU,IAAS,KAAM,EAAOA,EAAK,OAAQ,CACtE,GAAIA,EAAK,WAAa,IAAA,GAAW,SACjC,IAAMC,EAASD,EAAK,QAEpB,MADA,GAAK,SAAW,EACT,IAAIA,EAAK,WAAWC,GAC7B,CACA,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAqBb,EAAOa,IAAS,KAAM,EAAOA,EAAK,OAAQD,EAAK,KAAKC,EAAK,KAAK,EAC5FD,EAAK,QAAQ,EACb,IAAME,EAAWd,EAAM,QAEvB,MADA,GAAM,SAAW,EACV,IAAIY,EAAK,KAAK,GAAG,EAAE,GAAGE,GAC/B,C"}
|
|
1
|
+
{"version":3,"file":"ownership.js","names":["disposeOwner","untrack","runInScope","fn","createRoot","detached","options","current","currentOwner","root","Owner","result","disposeTree","error","cleanupError","getOwner","runWithOwner","target","owner","onCleanup","addCleanup","onError","handler","catchError","scope","handleError","useId","ShadowError","host","hosted","path","node","sequence"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/** Where the copies of core list themselves; `Symbol.for` makes the key the same in every copy. */\nconst REGISTRY_KEY = \"shadow-js.core.instances\";\n\n/**\n * The most copies the registry lists. Real programs have one, a misconfigured one two or three; the\n * limit keeps a program that loads core in a loop (a hot-reload bug) from growing the shared map.\n */\nconst MAX_LISTED_COPIES = 8;\n\n/**\n * The identity of this copy of the module (every evaluation of the module makes its own) and the build it is:\n * the server build and the client build are different files by design, and tests that render on the server\n * and hydrate in one process load one of each, so only copies of the same build count as duplicates.\n */\nconst COPY: { readonly server: boolean } = { server: __SERVER__ };\n\n/** The registry of the copies of core and how many roots each has alive, or undefined before any root exists. */\nfunction copyRegistry(): Map<{ readonly server: boolean }, number> | undefined {\n const found = (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)];\n return found instanceof Map ? found : undefined;\n}\n\n/** Development only. Counts a disposed root out of this copy's entry; the entry goes with its last root. */\nfunction releaseRoot(): void {\n const registry = copyRegistry();\n const live = registry?.get(COPY);\n if (registry === undefined || live === undefined) return;\n if (live > 1) registry.set(COPY, live - 1);\n else registry.delete(COPY);\n}\n\n/**\n * Development only. Lists a new root under this copy of core in a registry on `globalThis`, which counts the\n * live roots of every copy, and warns `DUPLICATE_CORE` (once per copy) when another copy of the same build has\n * live roots: two copies cannot see each other's signals. A copy leaves the registry when its last root is disposed, so copies\n * that never run at the same time (separate test files, a reload) do not warn. Called from `createRoot` only\n * behind `__DEV__`, and only when a root is created, never when the module is imported. The release is one\n * shared function, so a root costs no closure: rows of a list make a root each.\n */\nfunction listRoot(root: Owner): void {\n let registry = copyRegistry();\n if (registry === undefined) {\n registry = new Map();\n (globalThis as { [key: symbol]: unknown })[Symbol.for(REGISTRY_KEY)] = registry;\n }\n const listed = registry.has(COPY);\n for (const copy of registry.keys()) {\n if (copy !== COPY && copy.server === COPY.server) {\n warn(\"DUPLICATE_CORE\");\n break;\n }\n }\n // A copy past the limit is not listed; the warning above has been given by then.\n if (!listed && registry.size >= MAX_LISTED_COPIES) return;\n registry.set(COPY, (registry.get(COPY) ?? 0) + 1);\n addCleanup(root, releaseRoot);\n}\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects. Development builds also use the root to find a second copy of core: a root\n * created while a root of another copy is alive warns `DUPLICATE_CORE` once.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed. When a cleanup of the root throws as well, both errors are thrown together as an\n * `AggregateError` (the body's first), so the body's error is never replaced.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n if (__DEV__) listRoot(root);\n try {\n const result = runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n // The body disposed its own root and kept going: what it created after that has no owner left to dispose it.\n if (root.disposed) {\n disposeOwner(root);\n root.runCleanups();\n }\n return result;\n } catch (error) {\n try {\n disposeOwner(root);\n } catch (cleanupError) {\n // The body's error says what went wrong; a cleanup error must not replace it.\n throw new AggregateError(\n [error, cleanupError],\n __DEV__ ? \"The root body threw and so did its disposal.\" : \"SHADOW_ROOT_ERRORS\",\n );\n }\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\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,EAAaQ,EAAOrB,CAAE,CAC/B,OAASU,EAAO,CACPY,EAAiBZ,EAAOW,CAAK,EAApC,MACF,CACF,CAyBA,SAAgBE,GAAgB,CAC9B,IAAMR,EAAQV,EAAa,EAC3B,GAAIU,IAAU,KAAM,MAAM,IAAIS,EAAY,aAAa,EAIvD,IAAK,IAAIC,EAAqBV,EAAOU,IAAS,KAAM,EAAOA,EAAK,OAAQ,CACtE,GAAIA,EAAK,WAAa,IAAA,GAAW,SACjC,IAAMC,EAASD,EAAK,QAEpB,MADA,GAAK,SAAW,EACT,IAAIA,EAAK,WAAWC,GAC7B,CACA,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAqBb,EAAOa,IAAS,KAAM,EAAOA,EAAK,OAAQD,EAAK,KAAKC,EAAK,KAAK,EAC5FD,EAAK,QAAQ,EACb,IAAME,EAAWd,EAAM,QAEvB,MADA,GAAM,SAAW,EACV,IAAIY,EAAK,KAAK,GAAG,EAAE,GAAGE,GAC/B,C"}
|
package/dist/prod/props.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{useMemo as e}from"./memo.js";import{untrack as t}from"./ownership.js";const n=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),r=/* @__PURE__ */ new WeakSet;function i(e){return e==null||e===!1}function a(e){return Reflect.ownKeys(e).filter(t=>!n.has(t)&&Object.prototype.propertyIsEnumerable.call(e,t))}function o(e,t,n){Object.defineProperty(e,t,{enumerable:!0,configurable:!0,get:n})}function s(e){let t=typeof e==`function`?e():e;if(!i(t)){if(typeof t==`object`&&t)return t;throw TypeError(`SHADOW_MERGE_SOURCE`)}}function c(e){let t=[];for(let n of e){let e=s(n);e!==void 0&&t.push(e)}return t}function l(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(r===void 0||!(t in r))continue;let i=Reflect.get(r,t);if(i!==void 0)return i}}function u(e){let t=/* @__PURE__ */ new Set,n=[];for(let r of e)for(let e of a(r))t.has(e)||(t.add(e),n.push(e));return n}let d=0;const f=/* @__PURE__ */ new Map;function p(e,t){let n=f.get(e);if(n!==void 0)return n;let r=t();return f.set(e,r),r}function m(e){d+=1;try{return e()}finally{--d,d===0&&f.clear()}}function h(e){let t={};return new Proxy(t,{get(n,r){return m(()=>{let n=p(t,e);return n.keys.has(r)?n.read(r):Reflect.get(t,r)})},has(n,r){return m(()=>p(t,e).keys.has(r)||Reflect.has(t,r))},ownKeys(){return m(()=>[...p(t,e).keys])},getOwnPropertyDescriptor(n,r){return m(()=>{if(p(t,e).keys.has(r))return{enumerable:!0,configurable:!0,get:()=>m(()=>p(t,e).read(r))}})},set:()=>!1,defineProperty:()=>!1,deleteProperty:()=>!1})}function g(...e){let t=[],n=!1;for(let r of e)if(!i(r)){if(typeof r==`function`)n=!0;else if(typeof r!=`object`)throw TypeError(`SHADOW_MERGE_SOURCES`);t.push(r)}if(!n){let e=c(t),n={};for(let t of u(e))o(n,t,()=>l(e,t));return n}let a=h(()=>{let e=c(t);return{keys:new Set(u(e)),read:t=>l(e,t)}});return r.add(a),a}function _(e,...t){let i=/* @__PURE__ */ new Set,s=[];for(let r of t){let t={};for(let a of r)n.has(a)||(i.add(a),o(t,a,()=>Reflect.get(e,a)));s.push(t)}let c=()=>a(e).filter(e=>!i.has(e)),l=t=>Reflect.get(e,t);if(r.has(e)){let e=h(()=>({keys:new Set(c()),read:l}));return[...s,e]}let u={};for(let e of c())o(u,e,()=>l(e));return[...s,u]}function v(e){let t=[],n=[],r=/* @__PURE__ */ new Set,i=e,a=0;for(;;){if(typeof i==`function`){if(a>=1e3)throw TypeError(`SHADOW_CHILDREN_LAYERS`);i=i(),a+=1;continue}if(Array.isArray(i)){if(r.has(i))throw TypeError(`SHADOW_CHILDREN_CYCLE`);r.add(i),n.push({items:i,next:0,layer:a})}else i!=null&&typeof i!=`boolean`&&t.push(i);let e=!1;for(;!e;){let o=n.at(-1);if(o===void 0)return t;o.next<o.items.length?(i=o.items[o.next],o.next+=1,a=o.layer,e=!0):(n.pop(),r.delete(o.items))}}}function y(n){let r=e(()=>v(n),{allowWrites:!0});return Object.assign(()=>{let e=r();return e.length===1?e[0]:e.length===0?void 0:e},{toArray:()=>[...r()],count:()=>r().length,map:e=>r().map((n,r)=>t(()=>e(n,r))),forEach:e=>{r().forEach((n,r)=>{t(()=>e(n,r))})},only:()=>{let e=r();if(e.length!==1)throw TypeError(`SHADOW_CHILDREN_ONLY`);return e[0]}})}export{y as children,g as mergeProps,_ as splitProps};
|
|
2
2
|
//# sourceMappingURL=props.js.map
|
package/dist/prod/reaction.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createComputation as e,createOwner as t,currentOwner as n,runInScope as r}from"./extend/index.js";import{disposeTree as i}from"./internal/dispose.js";import{untrack as a}from"./ownership.js";function o(o){let s=n(),c=null;return n=>{if(c!==null&&i(c),s?.disposed===!0){c=null;return}let l=t(s);c=l;let u=!0;r({owner:l,listener:null},()=>{e({kind:`effect`,render:!0,owner:l,fn:()=>{u?(u=!1,n()):a(o)}})})}}export{o as useReaction};
|
|
2
2
|
//# sourceMappingURL=reaction.js.map
|
package/dist/prod/resource.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Signal as e,readSignal as t}from"./internal/graph.js";import{batch as n}from"./internal/scheduler.js";import{
|
|
1
|
+
import{Signal as e,readSignal as t}from"./internal/graph.js";import{batch as n}from"./internal/scheduler.js";import{useContext as r}from"./context.js";import{useRenderEffect as i}from"./effect.js";import{currentListener as a,writeSignal as o}from"./extend/index.js";import{onCleanup as s,untrack as c}from"./ownership.js";import{holdReader as l,inTransition as u}from"./internal/concurrency.js";import{ResourceCacheContext as d,SuspenseContext as f}from"./suspense.js";function p(n,r){let i=new e(n,r?Object.is:!1);return[()=>t(i),e=>{o(i,e,{allowInMemo:!0})}]}function m(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function h(e,t,o){let h=typeof t==`function`,g=h?typeof e==`function`?e:()=>e:()=>!0,_=e,v=h?t:(e,t)=>_(t),y=(h?o:t)??{},b=`initialValue`in y,[x,S]=p(y.initialValue,!1),[C,w]=p(b?`ready`:`unresolved`,!0),T=e=>{w(e)},[E,D]=p(void 0,!1),O=r(d),k=O===null?void 0:O.key(y.key),A=O!==null&&k!==void 0?O.read(k):void 0,j=!1,M=0,N,P=!1,F=b,I=/* @__PURE__ */ new Set,L=()=>{if(I.size===0)return;let e=[...I];I.clear();for(let t of e)t.decrement()},R=(e,t)=>{if(P||e!==M)return!1;try{n(t)}finally{L()}return!0},z=(e,t)=>{if(A!==void 0&&!j&&!t)return j=!0,F=!0,n(()=>{S(A.value),T(`ready`)}),Promise.resolve(A.value);N?.abort();let r=new AbortController;N=r,M+=1;let i=M;n(()=>{T(F?`refreshing`:`pending`),D(void 0)});let a;try{let n=t||O===null||k===void 0?void 0:O.pending?.(k);a=n===void 0?c(()=>v(e,{signal:r.signal,refetching:t,value:c(x)})):n}catch(e){return R(i,()=>{D(e),T(`errored`)}),Promise.resolve(void 0)}if(m(a))return O!==null&&k!==void 0&&O.track(k,Promise.resolve(a),{deferStream:y.deferStream}),Promise.resolve(a).then(e=>R(i,()=>{F=!0,S(e),T(`ready`)})?e:void 0,e=>{R(i,()=>{D(e),T(`errored`)})});let o=a,s=R(i,()=>{F=!0,S(o),T(`ready`)});return Promise.resolve(s?o:void 0)},B=e=>{e===!1||e==null?(N?.abort(),M+=1,L(),T(F?`ready`:`unresolved`)):z(e,F)},V=(()=>{let e=C();if(e===`errored`)throw E();if(e===`pending`){let e=r(f);e!==null&&!I.has(e)&&(I.add(e),e.increment()),e!==null&&a()!==null&&u()&&l(e)}return x()});return Object.defineProperties(V,{state:{get:C},loading:{get:()=>C()===`pending`||C()===`refreshing`},error:{get:E},latest:{get:x},refetch:{value:()=>{if(P)return Promise.resolve(void 0);let e=c(g);return e===!1||e==null?Promise.resolve(void 0):z(e,F)}},mutate:{value:e=>{let t,r=!1;try{n(()=>{t=typeof e==`function`?c(()=>e(x())):e,r=!0,N?.abort(),M+=1,F=!0,S(t),D(void 0),T(`ready`)})}finally{r&&L()}return t}}}),i(g,B),s(()=>{P=!0,N?.abort(),L()}),V}export{h as useResource};
|
|
2
2
|
//# sourceMappingURL=resource.js.map
|
package/dist/prod/selector.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{track as e}from"./internal/graph.js";import{
|
|
1
|
+
import{track as e}from"./internal/graph.js";import{useRenderEffect as t}from"./effect.js";import{isTracking as n,notify as r}from"./extend/index.js";import{onCleanup as i,untrack as a}from"./ownership.js";var o=class{kind=0;observers=null;stamp=0;subscribers=0;constructor(e,t){this.key=e,this.value=t}};function s(e,t){e.value!==t&&(e.value=t,r(e))}function c(r,c){let l=/* @__PURE__ */ new Map,u=null,d=(e,t)=>c===void 0?e===t:c(e,t),f=()=>u===null?a(r):u.value,p=e=>{--e.subscribers,e.subscribers===0&&l.get(e.key)===e&&l.delete(e.key)},m=e=>{let t=new o(e,a(()=>d(e,f())));return l.set(e,t),t};return t(()=>r(),e=>{let t=u;if(u={value:e},t!==null&&c===void 0){if(t.value===e)return;let n=l.get(t.value);n!==void 0&&s(n,n.key===e);let r=l.get(e);r!==void 0&&s(r,r.key===e);return}let n=!1,r;for(let t of l.values()){let i;try{i=d(t.key,e)}catch(e){n||(n=!0,r=e);continue}s(t,i)}if(n)throw r}),t=>{if(!n())return d(t,r());let a=l.get(t)??m(t);return a.subscribers+=1,i(()=>p(a)),e(a),a.value}}export{c as useSelector};
|
|
2
2
|
//# sourceMappingURL=selector.js.map
|
package/dist/prod/signal.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Signal as e,readSignal as t}from"./internal/graph.js";import{
|
|
1
|
+
import{Signal as e,readSignal as t}from"./internal/graph.js";import{writeSignal as n}from"./extend/index.js";import{untrack as r}from"./ownership.js";function i(i,a){let o=a?.equals===void 0?Object.is:a.equals,s=new e(i,o,a?.name);return[()=>t(s),(e=>{let t=typeof e==`function`?r(()=>e(s.value)):e;return n(s,t),t})]}export{i as useSignal};
|
|
2
2
|
//# sourceMappingURL=signal.js.map
|
package/dist/prod/store/nodes.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Signal as e,track as t}from"../internal/graph.js";import{isTracking as n,notify as r}from"../extend/index.js";const i=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),a=/* @__PURE__ */ new WeakMap,o=/* @__PURE__ */ new WeakMap;function s(e){return i.has(e)}function c(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;if(e===Object.prototype)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function l(e){return typeof e!=`object`||!e?e:o.get(e)??e}function u(e){let t=/* @__PURE__ */ new Set([e]),n=[e];for(;n.length>0;){let e=n.pop();for(let r of Object.keys(e)){let i=Reflect.get(e,r);if(typeof i==`object`&&i){if(o.has(i))return!0;c(i)&&!t.has(i)&&(t.add(i),n.push(i))}}}return!1}function d(e){let t=l(e);if(t!==e||!c(t)||!u(t))return t;let n=/* @__PURE__ */ new Map,r=e=>{let t=n.get(e);if(t!==void 0)return t;let r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return n.set(e,r),r},i=r(t),a=[t];for(let e=0;e<a.length;e+=1){let t=a[e],i=n.get(t);for(let e of Object.keys(t)){let s=Reflect.get(t,e);if(typeof s==`object`&&s){let i=o.get(s);if(i!==void 0)s=i;else if(c(s)){let i=n.has(s);s=r(s),i||a.push(Reflect.get(t,e))}}Object.defineProperty(i,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return i}function f(e,t){return Reflect.get(e,t)}function p(e){let t=a.get(e);return t===void 0&&(t={signals:null,keys:null,proxy:null},a.set(e,t)),t}function m(t,n){let r=t.signals;r===null&&(r=/* @__PURE__ */ new Map,t.signals=r);let i=r.get(n);if(i===void 0){let t=r.size;if(t>=256&&!(t&t-1))for(let[e,t]of r)(t.observers?.length??0)===0&&r.delete(e);i=new e(0,!1),r.set(n,i)}return i}function h(e,r){n()&&t(m(e,r))}function g(r){n()&&(r.keys===null&&(r.keys=new e(0,!1)),t(r.keys))}function _(e){e!=null&&r(e)}function v(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===e}function y(e,t){let n=e.signals;if(n!==null)for(let[e,r]of n)v(e)&&Number(e)>=t&&_(r)}function b(e,t,n){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_KEY`);n=d(n);let r=Array.isArray(e),i=Object.hasOwn(e,t);if(i&&Object.is(f(e,t),n))return!1;let o=r?e.length:0;if(!Reflect.set(e,t,n))throw TypeError(`SHADOW_STORE_PROP_READ_ONLY`);let c=a.get(e);if(c===void 0)return!0;if(_(c.signals?.get(t)),i||_(c.keys),r){let t=e.length;t!==o&&(_(c.signals?.get(`length`)),_(c.keys),t<o&&y(c,t))}return!0}function x(e,t){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_DELETE`);if(!Object.hasOwn(e,t))return!0;if(!Reflect.deleteProperty(e,t))throw TypeError(`SHADOW_STORE_DELETE`);let
|
|
1
|
+
import{Signal as e,track as t}from"../internal/graph.js";import{isTracking as n,notify as r}from"../extend/index.js";const i=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),a=/* @__PURE__ */ new WeakMap,o=/* @__PURE__ */ new WeakMap;function s(e){return i.has(e)}function c(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;if(e===Object.prototype)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function l(e){return typeof e!=`object`||!e?e:o.get(e)??e}function u(e){let t=/* @__PURE__ */ new Set([e]),n=[e];for(;n.length>0;){let e=n.pop();for(let r of Object.keys(e)){let i=Reflect.get(e,r);if(typeof i==`object`&&i){if(o.has(i))return!0;c(i)&&!t.has(i)&&(t.add(i),n.push(i))}}}return!1}function d(e){let t=l(e);if(t!==e||!c(t)||!u(t))return t;let n=/* @__PURE__ */ new Map,r=e=>{let t=n.get(e);if(t!==void 0)return t;let r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return n.set(e,r),r},i=r(t),a=[t];for(let e=0;e<a.length;e+=1){let t=a[e],i=n.get(t);for(let e of Object.keys(t)){let s=Reflect.get(t,e);if(typeof s==`object`&&s){let i=o.get(s);if(i!==void 0)s=i;else if(c(s)){let i=n.has(s);s=r(s),i||a.push(Reflect.get(t,e))}}Object.defineProperty(i,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return i}function f(e,t){return Reflect.get(e,t)}function p(e){let t=a.get(e);return t===void 0&&(t={signals:null,keys:null,proxy:null},a.set(e,t)),t}function m(t,n){let r=t.signals;r===null&&(r=/* @__PURE__ */ new Map,t.signals=r);let i=r.get(n);if(i===void 0){let t=r.size;if(t>=256&&!(t&t-1))for(let[e,t]of r)(t.observers?.length??0)===0&&r.delete(e);i=new e(0,!1),r.set(n,i)}return i}function h(e,r){n()&&t(m(e,r))}function g(r){n()&&(r.keys===null&&(r.keys=new e(0,!1)),t(r.keys))}function _(e){e!=null&&r(e)}function v(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===e}function y(e,t){let n=e.signals;if(n!==null)for(let[e,r]of n)v(e)&&Number(e)>=t&&_(r)}function b(e,t,n){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_KEY`);n=d(n);let r=Array.isArray(e),i=Object.hasOwn(e,t);if(i&&Object.is(f(e,t),n))return!1;let o=r?e.length:0;if(!Reflect.set(e,t,n))throw TypeError(`SHADOW_STORE_PROP_READ_ONLY`);let c=a.get(e);if(c===void 0)return!0;if(_(c.signals?.get(t)),i||_(c.keys),r){let t=e.length;t!==o&&(_(c.signals?.get(`length`)),_(c.keys),t<o&&y(c,t))}return!0}function x(e,t,n=!1){if(!n&&s(t))throw TypeError(`SHADOW_STORE_RESERVED_DELETE`);if(!Object.hasOwn(e,t))return!0;if(!Reflect.deleteProperty(e,t))throw TypeError(`SHADOW_STORE_DELETE`);let r=a.get(e);return r===void 0||(_(r.signals?.get(t)),_(r.keys)),!0}export{a as NODES,o as RAW,x as deleteRaw,s as isReservedKey,c as isWrappable,p as nodeOf,f as readRaw,g as trackKeys,h as trackProperty,d as unwrapDeep,l as unwrapValue,b as writeRaw};
|
|
2
2
|
//# sourceMappingURL=nodes.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nodes.js","names":["SignalNode","notify$1","RESERVED_KEYS","NODES","RAW","isReservedKey","key","isWrappable","value","prototype","unwrapValue","containsProxy","seen","root","stack","container","member","unwrapDeep","first","copies","copyOf","existing","source","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","size","other","Signal","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import { isTracking, notify as notifySource, SignalNode, track } from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /**\n * One signal per property read in a tracked context, keyed by property name. A signal is only a\n * notifier (it holds no value), so one that nothing observes any more is dropped by a sweep (see\n * `signalFor`) and a later read simply makes a new one.\n */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\n/** The map size at which the first sweep of unobserved key signals runs. */\nconst SWEEP_AT = 256;\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n // Reading many transient keys (`store.byId[id]` with churning ids) would keep one signal per key\n // for the life of the store. The sweep runs when the map reaches a power of two from SWEEP_AT on,\n // so its cost is amortized O(1) per new key, and the map stays within about twice the number of\n // keys that are observed at that moment (plus SWEEP_AT).\n const size = signals.size;\n if (size >= SWEEP_AT && (size & (size - 1)) === 0) {\n // Safe at any time: a signal carries no value, and the next read of its key makes a fresh one.\n for (const [other, node] of signals) {\n if ((node.observers?.length ?? 0) === 0) signals.delete(other);\n }\n }\n signal = new SignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = new SignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/** Deletes one own property of a raw object and notifies its signal and the key set. */\nexport function deleteRaw(target: object, key: string): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":"A,qHAGA,MAAME,kBAAqC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAoB/EC,kBAAoC,IAAI,QAGxCC,kBAA+B,IAAI,QAGhD,SAAgBC,EAAc,EAAsB,CAClD,OAAOH,EAAc,IAAII,CAAG,CAC9B,CAGA,SAAgBC,EAAY,EAAiC,CAC3D,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,GAAI,MAAM,QAAQA,CAAK,EAAG,MAAO,GACjC,GAAIA,IAAU,OAAO,UAAW,MAAO,GACvC,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAGA,SAAgBC,EAAY,EAAyB,CAEnD,OADI,OAAOF,GAAU,WAAYA,EAAuBA,EACjDJ,EAAI,IAAII,CAAK,GAAKA,CAC3B,CAGA,SAASG,EAAc,EAAuB,CAC5C,IAAMC,kBAAO,IAAI,IAAY,CAACC,CAAI,CAAC,EAC7BC,EAAkB,CAACD,CAAI,EAC7B,KAAOC,EAAM,OAAS,GAAG,CACvB,IAAMC,EAAYD,EAAM,IAAI,EAC5B,IAAK,IAAMR,KAAO,OAAO,KAAKS,CAAS,EAAG,CACxC,IAAMC,EAAkB,QAAQ,IAAID,EAAWT,CAAG,EAClD,GAAI,OAAOU,GAAW,UAAYA,EAClC,IAAIZ,EAAI,IAAIY,CAAM,EAAG,MAAO,GACxBT,EAAYS,CAAM,GAAK,CAACJ,EAAK,IAAII,CAAM,IACzCJ,EAAK,IAAII,CAAM,EACfF,EAAM,KAAKE,CAAM,EAHS,CAK9B,CACF,CACA,MAAO,EACT,CAQA,SAAgBC,EAAW,EAAyB,CAClD,IAAMC,EAAQR,EAAYF,CAAK,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","unwrapValue","containsProxy","seen","root","stack","container","member","unwrapDeep","first","copies","copyOf","existing","source","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","size","other","Signal","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw","cleanup"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import { isTracking, notify as notifySource, SignalNode, track } from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /**\n * One signal per property read in a tracked context, keyed by property name. A signal is only a\n * notifier (it holds no value), so one that nothing observes any more is dropped by a sweep (see\n * `signalFor`) and a later read simply makes a new one.\n */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\n/** The map size at which the first sweep of unobserved key signals runs. */\nconst SWEEP_AT = 256;\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n // Reading many transient keys (`store.byId[id]` with churning ids) would keep one signal per key\n // for the life of the store. The sweep runs when the map reaches a power of two from SWEEP_AT on,\n // so its cost is amortized O(1) per new key, and the map stays within about twice the number of\n // keys that are observed at that moment (plus SWEEP_AT).\n const size = signals.size;\n if (size >= SWEEP_AT && (size & (size - 1)) === 0) {\n // Safe at any time: a signal carries no value, and the next read of its key makes a fresh one.\n for (const [other, node] of signals) {\n if ((node.observers?.length ?? 0) === 0) signals.delete(other);\n }\n }\n signal = new SignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = new SignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/**\n * Deletes one own property of a raw object and notifies its signal and the key set. A reserved key is\n * refused unless `cleanup` is set: removing an own data property named `__proto__` (it arrived in parsed\n * JSON) cannot reach a prototype, and `reconcile` must be able to clear it like any other stale key.\n */\nexport function deleteRaw(target: object, key: string, cleanup = false): boolean {\n if (!cleanup && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":"A,qHAGA,MAAME,kBAAqC,IAAI,IA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ACrC,GAAI4C,GAAO,OAAO,GAAGpB,EAAQH,EAAQrB,CAAG,EAAGE,CAAK,EAAG,MAAO,GAC1D,IAAM2C,EAASF,EAAStB,EAAqB,OAAS,EACtD,GAAI,CAAC,QAAQ,IAAIA,EAAQrB,EAAKE,CAAK,EACjC,MAAU,UAGJ,6BACN,EAEF,IAAMwB,EAAO7B,EAAM,IAAIwB,CAAM,EAC7B,GAAIK,IAAS,IAAA,GAAW,MAAO,GAG/B,GAFAW,EAAOX,EAAK,SAAS,IAAI1B,CAAG,CAAC,EACxB4C,GAAKP,EAAOX,EAAK,IAAI,EACtBiB,EAAO,CACT,IAAMG,EAASzB,EAAqB,OAChCyB,IAAUD,IACZR,EAAOX,EAAK,SAAS,IAAI,QAAQ,CAAC,EAClCW,EAAOX,EAAK,IAAI,EACZoB,EAAQD,GAAQL,EAAkBd,EAAMoB,CAAK,EAErD,CACA,MAAO,EACT,CAOA,SAAgBC,EAAU,EAAgB,EAAa,EAAU,GAAgB,CAC/E,GAAI,CAACC,GAAWjD,EAAcC,CAAG,EAC/B,MAAU,UAGJ,8BACN,EAEF,GAAI,CAAC,OAAO,OAAOqB,EAAQrB,CAAG,EAAG,MAAO,GACxC,GAAI,CAAC,QAAQ,eAAeqB,EAAQrB,CAAG,EACrC,MAAU,UACuD,qBACjE,EAEF,IAAM0B,EAAO7B,EAAM,IAAIwB,CAAM,EAI7B,OAHIK,IAAS,IAAA,KACbW,EAAOX,EAAK,SAAS,IAAI1B,CAAG,CAAC,EAC7BqC,EAAOX,EAAK,IAAI,GACT,EACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{deleteRaw as e,isReservedKey as t,isWrappable as n,unwrapValue as r,writeRaw as i}from"./nodes.js";const a=/* @__PURE__ */ new WeakMap;function o(e){return a.get(e)}function s(e,t){let n={next:e,key:t?.key??`id`,merge:t?.merge===!0},r=()=>{throw TypeError(`SHADOW_STORE_RECONCILE`)};return a.set(r,n),r}function c(e,t){if(n(e))return typeof t==`function`?t(e):Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function l(e,t){return Array.isArray(e)===Array.isArray(t)}function u(e,t,i){let a=r(t.next);if(!n(a)||!l(e,a))throw TypeError(`SHADOW_STORE_RECONCILE_SHAPE`);let o=[],s=/* @__PURE__ */ new Map,c=(e,t)=>{let n=s.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,s.set(t,n))
|
|
1
|
+
import{deleteRaw as e,isReservedKey as t,isWrappable as n,unwrapValue as r,writeRaw as i}from"./nodes.js";const a=/* @__PURE__ */ new WeakMap;function o(e){return a.get(e)}function s(e,t){let n={next:e,key:t?.key??`id`,merge:t?.merge===!0},r=()=>{throw TypeError(`SHADOW_STORE_RECONCILE`)};return a.set(r,n),r}function c(e,t){if(n(e))return typeof t==`function`?t(e):Object.hasOwn(e,t)?Reflect.get(e,t):void 0}function l(e,t){return Array.isArray(e)===Array.isArray(t)}function u(e,t,i){let a=r(t.next);if(!n(a)||!l(e,a))throw TypeError(`SHADOW_STORE_RECONCILE_SHAPE`);let o=[],s=/* @__PURE__ */ new Map,c=(e,t)=>{let n=s.get(t);n===void 0&&(n=/* @__PURE__ */ new Set,s.set(t,n)),n.has(e)||(n.add(e),o.push({target:e,source:t}))};c(e,a);for(let e=o.pop();e!==void 0;e=o.pop())Array.isArray(e.source)?f(e.target,e.source,t,c):d(e.target,e.source,t,c)}function d(a,o,s,c){for(let e of Object.keys(o)){if(t(e))continue;let s=r(Reflect.get(o,e)),u=Object.hasOwn(a,e),d=u?Reflect.get(a,e):void 0;u&&Object.is(d,s)||(u&&n(d)&&n(s)&&l(d,s)?c(d,s):i(a,e,s))}if(!s.merge)for(let t of Object.keys(a))Object.hasOwn(o,t)||e(a,t,!0)}function f(e,t,a,o){let s=e,u=t,d=s.slice(),f=d.map(e=>c(e,a.key)),p=/* @__PURE__ */ new Map;for(let e=0;e<d.length;e+=1){let t=f[e];t!==void 0&&!p.has(t)&&p.set(t,e)}let m=Array(d.length).fill(!1),h=[];for(let e=0;e<u.length;e+=1){let t=c(r(u[e]),a.key),n=-1;if(t!==void 0){let e=p.get(t);e!==void 0&&m[e]!==!0&&(n=e)}else e<d.length&&f[e]===void 0&&m[e]!==!0&&(n=e);n!==-1&&(m[n]=!0),h.push(n)}let g=[];for(let e=0;e<u.length;e+=1){let t=r(u[e]),i=h[e]??-1;if(i===-1){g.push(t);continue}let a=d[i];n(a)&&n(t)&&l(a,t)?(a!==t&&o(a,t),g.push(a)):g.push(t)}if(a.merge)for(let e=0;e<d.length;e+=1)m[e]!==!0&&g.push(d[e]);for(let t=0;t<g.length;t+=1)i(e,String(t),g[t]);s.length>g.length&&i(e,`length`,g.length)}function p(e){return e}export{u as applyReconcile,p as produce,s as reconcile,o as specOf};
|
|
2
2
|
//# sourceMappingURL=reconcile.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"reconcile.js","names":["SPECS","specOf","update","reconcile","spec","options","reconciler","identityOf","isWrappable","item","key","sameKind","a","b","applyReconcile","next","unwrapValue","root","stack","seen","enqueue","targets","source","target","frame","mergeArray","mergeObject","isReservedKey","value","had","current","writeRaw","deleteRaw","list","incoming","original","identities","byIdentity","index","identity","used","matches","position","match","found","values","previous","produce"],"sources":["../../../src/store/reconcile.ts"],"sourcesContent":["import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from \"./nodes\";\nimport type { Reconciler } from \"./types\";\n\n/**\n * Options of {@link reconcile}.\n * @since 1.0.0\n */\nexport interface ReconcileOptions {\n /**\n * Identity of array items: the name of a field (`\"id\"`) or a function returning the identity.\n * Items without an identity (not an object, or the field is absent, or the function returns\n * `undefined`) are matched by position.\n * @default \"id\"\n */\n key?: string | ((item: unknown) => unknown);\n /**\n * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`\n * are deleted and arrays are truncated to its length; when true, unmatched old array items are\n * kept after the new ones.\n * @default false\n */\n merge?: boolean;\n}\n\n/**\n * What a reconciler carries from `reconcile()` to `setStore`. Not re-exported by any entry: only\n * the store setter reads it.\n * @internal\n */\nexport interface ReconcileSpec {\n /** The desired data, as passed to `reconcile()` (it may still be a store proxy). */\n readonly next: unknown;\n /** Identity of array items, resolved from {@link ReconcileOptions.key}. */\n readonly key: string | ((item: unknown) => unknown);\n /** Whether keys and items absent from `next` are kept, from {@link ReconcileOptions.merge}. */\n readonly merge: boolean;\n}\n\n/** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */\nconst SPECS: WeakMap<object, ReconcileSpec> = new WeakMap();\n\n/**\n * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the\n * store setter uses it to tell a reconciler from a draft updater.\n *\n * @param update Any function or object passed to `setStore`.\n * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.\n * @internal\n */\nexport function specOf(update: object): ReconcileSpec | undefined {\n return SPECS.get(update);\n}\n\n/**\n * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the\n * current state: objects are merged key by key, arrays are matched by `key` so retained items keep\n * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.\n * Use it to apply fresh server data to a store without re-rendering what did not change.\n *\n * @param next The desired data. Store proxies are accepted and unwrapped.\n * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses\n * the defaults (`key: \"id\"`, `merge: false`).\n * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is\n * called directly instead of being passed to `setStore`. `setStore` throws TypeError\n * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or\n * array) as the value it reconciles.\n * @example\n * import { reconcile, useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n *\n * async function refresh(): Promise<void> {\n * const response = await fetch(\"/api/todos\");\n * setTodos(\"items\", reconcile((await response.json()) as Todo[], { key: \"id\" }));\n * }\n * @see useStore\n * @since 1.0.0\n */\nexport function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T> {\n const spec: ReconcileSpec = {\n next,\n key: options?.key ?? \"id\",\n merge: options?.merge === true,\n };\n const reconciler: Reconciler<T> = () => {\n throw new TypeError(\n __DEV__\n ? \"ShadowStore: a reconcile() result must be passed to setStore()\"\n : \"SHADOW_STORE_RECONCILE\",\n );\n };\n SPECS.set(reconciler, spec);\n return reconciler;\n}\n\ninterface Frame {\n readonly target: object;\n readonly source: object;\n}\n\n/** Field name or function giving an item's identity; `undefined` means the item has none. */\nfunction identityOf(item: unknown, key: string | ((item: unknown) => unknown)): unknown {\n if (!isWrappable(item)) return undefined;\n if (typeof key === \"function\") return key(item);\n return Object.hasOwn(item, key) ? Reflect.get(item, key) : undefined;\n}\n\n/** Same container kind: both arrays or both objects. */\nfunction sameKind(a: object, b: object): boolean {\n return Array.isArray(a) === Array.isArray(b);\n}\n\n/**\n * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs\n * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call\n * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any\n * entry: only the store setter calls it, inside its transaction.\n *\n * @param root The raw (unwrapped) object or array to update in place.\n * @param spec The reconciler's spec, from {@link specOf}.\n * @param label The store label for messages (` (name)`, or an empty string).\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the\n * same kind of container as `root`.\n * @internal\n */\nexport function applyReconcile(root: object, spec: ReconcileSpec, label: string): void {\n const next = unwrapValue(spec.next);\n if (!isWrappable(next) || !sameKind(root, next)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`\n : \"SHADOW_STORE_RECONCILE_SHAPE\",\n );\n }\n const stack: Frame[] = [];\n const seen = new Map<object, Set<object>>();\n const enqueue = (target: object, source: object): void => {\n let targets = seen.get(source);\n if (targets === undefined) {\n targets = new Set();\n seen.set(source, targets);\n }\n if (targets.has(target)) return;\n targets.add(target);\n stack.push({ target, source });\n };\n\n enqueue(root, next);\n for (let frame = stack.pop(); frame !== undefined; frame = stack.pop()) {\n if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);\n else mergeObject(frame.target, frame.source, spec, enqueue);\n }\n}\n\nfunction mergeObject(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(Reflect.get(source, key));\n const had = Object.hasOwn(target, key);\n const current: unknown = had ? Reflect.get(target, key) : undefined;\n if (had && Object.is(current, value)) continue;\n if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {\n enqueue(current, value);\n continue;\n }\n writeRaw(target, key, value);\n }\n if (spec.merge) return;\n for (const key of Object.keys(target)) {\n if (!Object.hasOwn(source, key)) deleteRaw(target, key);\n }\n}\n\nfunction mergeArray(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n const list = target as unknown[];\n const incoming = source as unknown[];\n // Copy first: matching reads the old positions, while the writes below move items.\n const original = list.slice();\n const identities = original.map((item) => identityOf(item, spec.key));\n const byIdentity = new Map<unknown, number>();\n for (let index = 0; index < original.length; index += 1) {\n const identity = identities[index];\n if (identity !== undefined && !byIdentity.has(identity)) byIdentity.set(identity, index);\n }\n\n const used: boolean[] = new Array<boolean>(original.length).fill(false);\n const matches: number[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const identity = identityOf(item, spec.key);\n let match = -1;\n if (identity !== undefined) {\n const found = byIdentity.get(identity);\n if (found !== undefined && used[found] !== true) match = found;\n } else if (position < original.length && identities[position] === undefined) {\n if (used[position] !== true) match = position;\n }\n if (match !== -1) used[match] = true;\n matches.push(match);\n }\n\n const values: unknown[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const match = matches[position] ?? -1;\n if (match === -1) {\n values.push(item);\n continue;\n }\n const previous = original[match];\n if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {\n if (previous !== item) enqueue(previous, item);\n values.push(previous);\n } else {\n values.push(item);\n }\n }\n if (spec.merge) {\n for (let index = 0; index < original.length; index += 1) {\n if (used[index] !== true) values.push(original[index]);\n }\n }\n\n for (let position = 0; position < values.length; position += 1) {\n writeRaw(target, String(position), values[position]);\n }\n if (list.length > values.length) writeRaw(target, \"length\", values.length);\n}\n\n/**\n * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is\n * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.\n *\n * @param update The draft updater: it mutates the draft it receives.\n * @returns `update`, unchanged.\n * @example\n * import { produce, useStore } from \"@shadow-js/core\";\n *\n * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });\n * setCart(\n * produce((draft) => {\n * draft.items.push(\"apple\");\n * draft.count += 1;\n * }),\n * );\n * console.log(cart.count); // 1\n * @see useStore\n * @since 1.0.0\n */\nexport function produce<T>(update: (draft: T) => void): (draft: T) => void {\n return update;\n}\n"],"mappings":"A,0GAuCA,MAAMA,kBAAwC,IAAI,QAUlD,SAAgBC,EAAO,EAA2C,CAChE,OAAOD,EAAM,IAAIE,CAAM,CACzB,CA6BA,SAAgBC,EAAa,EAAS,EAA2C,CAC/E,IAAMC,EAAsB,CAC1B,OACA,IAAKC,GAAS,KAAO,KACrB,MAAOA,GAAS,QAAU,EAC5B,EACMC,MAAkC,CACtC,MAAU,UAGJ,wBACN,CACF,EAEA,OADAN,EAAM,IAAIM,EAAYF,CAAI,EACnBE,CACT,CAQA,SAASC,EAAW,EAAe,EAAqD,CACtF,GAAKC,EAAYC,CAAI,EAErB,OADI,OAAOC,GAAQ,WAAmBA,EAAID,CAAI,EACvC,OAAO,OAAOA,EAAMC,CAAG,EAAI,QAAQ,IAAID,EAAMC,CAAG,EAAI,IAAA,EAC7D,CAGA,SAASC,EAAS,EAAW,EAAoB,CAC/C,OA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AU,GAAI,CAChBE,EAAO,KAAKpC,CAAI,EAChB,QACF,CACA,IAAMqC,EAAWX,EAASQ,GACtBnC,EAAYsC,CAAQ,GAAKtC,EAAYC,CAAI,GAAKE,EAASmC,EAAUrC,CAAI,GACnEqC,IAAarC,GAAMW,EAAQ0B,EAAUrC,CAAI,EAC7CoC,EAAO,KAAKC,CAAQ,GAEpBD,EAAO,KAAKpC,CAAI,CAEpB,CACA,GAAIL,EAAK,MACF,IAAA,IAAIkC,EAAQ,EAAGA,EAAQH,EAAS,OAAQ,GAAS,EAChDK,EAAKF,KAAW,IAAMO,EAAO,KAAKV,EAASG,EAAM,EAIzD,IAAK,IAAII,EAAW,EAAGA,EAAWG,EAAO,OAAQ,GAAY,EAC3Dd,EAASR,EAAQ,OAAOmB,CAAQ,EAAGG,EAAOH,EAAS,EAEjDT,EAAK,OAASY,EAAO,QAAQd,EAASR,EAAQ,SAAUsB,EAAO,MAAM,CAC3E,CAsBA,SAAgBE,EAAW,EAAgD,CACzE,OAAO7C,CACT,C"}
|
|
1
|
+
{"version":3,"file":"reconcile.js","names":["SPECS","specOf","update","reconcile","spec","options","reconciler","identityOf","isWrappable","item","key","sameKind","a","b","applyReconcile","next","unwrapValue","root","stack","seen","enqueue","targets","source","target","frame","mergeArray","mergeObject","isReservedKey","value","had","current","writeRaw","deleteRaw","list","incoming","original","identities","byIdentity","index","identity","used","matches","position","match","found","values","previous","produce"],"sources":["../../../src/store/reconcile.ts"],"sourcesContent":["import { deleteRaw, isReservedKey, isWrappable, unwrapValue, writeRaw } from \"./nodes\";\nimport type { Reconciler } from \"./types\";\n\n/**\n * Options of {@link reconcile}.\n * @since 1.0.0\n */\nexport interface ReconcileOptions {\n /**\n * Identity of array items: the name of a field (`\"id\"`) or a function returning the identity.\n * Items without an identity (not an object, or the field is absent, or the function returns\n * `undefined`) are matched by position.\n * @default \"id\"\n */\n key?: string | ((item: unknown) => unknown);\n /**\n * Keep keys, and array items, that `next` does not contain. When false, keys missing from `next`\n * are deleted and arrays are truncated to its length; when true, unmatched old array items are\n * kept after the new ones.\n * @default false\n */\n merge?: boolean;\n}\n\n/**\n * What a reconciler carries from `reconcile()` to `setStore`. Not re-exported by any entry: only\n * the store setter reads it.\n * @internal\n */\nexport interface ReconcileSpec {\n /** The desired data, as passed to `reconcile()` (it may still be a store proxy). */\n readonly next: unknown;\n /** Identity of array items, resolved from {@link ReconcileOptions.key}. */\n readonly key: string | ((item: unknown) => unknown);\n /** Whether keys and items absent from `next` are kept, from {@link ReconcileOptions.merge}. */\n readonly merge: boolean;\n}\n\n/** Each reconciler function maps to its spec. Keys are the reconciler functions themselves. */\nconst SPECS: WeakMap<object, ReconcileSpec> = new WeakMap();\n\n/**\n * Looks up the spec of a reconciler created by {@link reconcile}. Not re-exported by any entry: the\n * store setter uses it to tell a reconciler from a draft updater.\n *\n * @param update Any function or object passed to `setStore`.\n * @returns The spec, or `undefined` when `update` is not a `reconcile()` result.\n * @internal\n */\nexport function specOf(update: object): ReconcileSpec | undefined {\n return SPECS.get(update);\n}\n\n/**\n * Describes a new value for a store. Passed to `setStore`, it changes only what differs from the\n * current state: objects are merged key by key, arrays are matched by `key` so retained items keep\n * their identity, and unchanged leaves are not written. Nothing is applied until `setStore` runs.\n * Use it to apply fresh server data to a store without re-rendering what did not change.\n *\n * @param next The desired data. Store proxies are accepted and unwrapped.\n * @param options Item identity (`key`) and whether to keep absent keys (`merge`). Undefined uses\n * the defaults (`key: \"id\"`, `merge: false`).\n * @returns A reconciler to pass to `setStore`, alone or as the last argument of a path.\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE`) when the returned reconciler is\n * called directly instead of being passed to `setStore`. `setStore` throws TypeError\n * (`SHADOW_STORE_RECONCILE_SHAPE`) when `next` is not the same kind of container (object or\n * array) as the value it reconciles.\n * @example\n * import { reconcile, useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n *\n * async function refresh(): Promise<void> {\n * const response = await fetch(\"/api/todos\");\n * setTodos(\"items\", reconcile((await response.json()) as Todo[], { key: \"id\" }));\n * }\n * @see useStore\n * @since 1.0.0\n */\nexport function reconcile<T>(next: T, options?: ReconcileOptions): Reconciler<T> {\n const spec: ReconcileSpec = {\n next,\n key: options?.key ?? \"id\",\n merge: options?.merge === true,\n };\n const reconciler: Reconciler<T> = () => {\n throw new TypeError(\n __DEV__\n ? \"ShadowStore: a reconcile() result must be passed to setStore()\"\n : \"SHADOW_STORE_RECONCILE\",\n );\n };\n SPECS.set(reconciler, spec);\n return reconciler;\n}\n\ninterface Frame {\n readonly target: object;\n readonly source: object;\n}\n\n/** Field name or function giving an item's identity; `undefined` means the item has none. */\nfunction identityOf(item: unknown, key: string | ((item: unknown) => unknown)): unknown {\n if (!isWrappable(item)) return undefined;\n if (typeof key === \"function\") return key(item);\n return Object.hasOwn(item, key) ? Reflect.get(item, key) : undefined;\n}\n\n/** Same container kind: both arrays or both objects. */\nfunction sameKind(a: object, b: object): boolean {\n return Array.isArray(a) === Array.isArray(b);\n}\n\n/**\n * Applies a reconciler to the store root. The diff is iterative: pending (target, source) pairs\n * live on an explicit stack, so data nested thousands of levels deep cannot overflow the call\n * stack. Each pair is visited once, which also terminates on cyclic input. Not re-exported by any\n * entry: only the store setter calls it, inside its transaction.\n *\n * @param root The raw (unwrapped) object or array to update in place.\n * @param spec The reconciler's spec, from {@link specOf}.\n * @param label The store label for messages (` (name)`, or an empty string).\n * @throws TypeError (production message `SHADOW_STORE_RECONCILE_SHAPE`) when `spec.next` is not the\n * same kind of container as `root`.\n * @internal\n */\nexport function applyReconcile(root: object, spec: ReconcileSpec, label: string): void {\n const next = unwrapValue(spec.next);\n if (!isWrappable(next) || !sameKind(root, next)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: reconcile() needs data of the same shape as the store root (an object or an array)`\n : \"SHADOW_STORE_RECONCILE_SHAPE\",\n );\n }\n const stack: Frame[] = [];\n const seen = new Map<object, Set<object>>();\n const enqueue = (target: object, source: object): void => {\n let targets = seen.get(source);\n if (targets === undefined) {\n targets = new Set();\n seen.set(source, targets);\n }\n if (targets.has(target)) return;\n targets.add(target);\n stack.push({ target, source });\n };\n\n enqueue(root, next);\n for (let frame = stack.pop(); frame !== undefined; frame = stack.pop()) {\n if (Array.isArray(frame.source)) mergeArray(frame.target, frame.source, spec, enqueue);\n else mergeObject(frame.target, frame.source, spec, enqueue);\n }\n}\n\nfunction mergeObject(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(Reflect.get(source, key));\n const had = Object.hasOwn(target, key);\n const current: unknown = had ? Reflect.get(target, key) : undefined;\n if (had && Object.is(current, value)) continue;\n if (had && isWrappable(current) && isWrappable(value) && sameKind(current, value)) {\n enqueue(current, value);\n continue;\n }\n writeRaw(target, key, value);\n }\n if (spec.merge) return;\n for (const key of Object.keys(target)) {\n if (!Object.hasOwn(source, key)) deleteRaw(target, key, true);\n }\n}\n\nfunction mergeArray(\n target: object,\n source: object,\n spec: ReconcileSpec,\n enqueue: (target: object, source: object) => void,\n): void {\n const list = target as unknown[];\n const incoming = source as unknown[];\n // Copy first: matching reads the old positions, while the writes below move items.\n const original = list.slice();\n const identities = original.map((item) => identityOf(item, spec.key));\n const byIdentity = new Map<unknown, number>();\n for (let index = 0; index < original.length; index += 1) {\n const identity = identities[index];\n if (identity !== undefined && !byIdentity.has(identity)) byIdentity.set(identity, index);\n }\n\n const used: boolean[] = new Array<boolean>(original.length).fill(false);\n const matches: number[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const identity = identityOf(item, spec.key);\n let match = -1;\n if (identity !== undefined) {\n const found = byIdentity.get(identity);\n if (found !== undefined && used[found] !== true) match = found;\n } else if (position < original.length && identities[position] === undefined) {\n if (used[position] !== true) match = position;\n }\n if (match !== -1) used[match] = true;\n matches.push(match);\n }\n\n const values: unknown[] = [];\n for (let position = 0; position < incoming.length; position += 1) {\n const item = unwrapValue(incoming[position]);\n const match = matches[position] ?? -1;\n if (match === -1) {\n values.push(item);\n continue;\n }\n const previous = original[match];\n if (isWrappable(previous) && isWrappable(item) && sameKind(previous, item)) {\n if (previous !== item) enqueue(previous, item);\n values.push(previous);\n } else {\n values.push(item);\n }\n }\n if (spec.merge) {\n for (let index = 0; index < original.length; index += 1) {\n if (used[index] !== true) values.push(original[index]);\n }\n }\n\n for (let position = 0; position < values.length; position += 1) {\n writeRaw(target, String(position), values[position]);\n }\n if (list.length > values.length) writeRaw(target, \"length\", values.length);\n}\n\n/**\n * Marks a draft updater. It is the function itself (`setStore(produce((d) => { d.n += 1 }))` is\n * `setStore((d) => { d.n += 1 })`); it exists so code written for other libraries migrates as is.\n *\n * @param update The draft updater: it mutates the draft it receives.\n * @returns `update`, unchanged.\n * @example\n * import { produce, useStore } from \"@shadow-js/core\";\n *\n * const [cart, setCart] = useStore({ items: [] as string[], count: 0 });\n * setCart(\n * produce((draft) => {\n * draft.items.push(\"apple\");\n * draft.count += 1;\n * }),\n * );\n * console.log(cart.count); // 1\n * @see useStore\n * @since 1.0.0\n */\nexport function produce<T>(update: (draft: T) => void): (draft: T) => void {\n return update;\n}\n"],"mappings":"A,0GAuCA,MAAMA,kBAAwC,IAAI,QAUlD,SAAgBC,EAAO,EAA2C,CAChE,OAAOD,EAAM,IAAIE,CAAM,CACzB,CA6BA,SAAgBC,EAAa,EAAS,EAA2C,CAC/E,IAAMC,EAAsB,CAC1B,OACA,IAAKC,GAAS,KAAO,KACrB,MAAOA,GAAS,QAAU,EAC5B,EACMC,MAAkC,CACtC,MAAU,UAGJ,wBACN,CACF,EAEA,OADAN,EAAM,IAAIM,EAAYF,CAAI,EACnBE,CACT,CAQA,SAASC,EAAW,EAAe,EAAqD,CACtF,GAAKC,EAAYC,CAAI,EAErB,OADI,OAAOC,GAAQ,WAAmBA,EAAID,CAAI,EACvC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,EAAGA,EAAWR,EAAS,OAAQ,GAAY,EAAG,CAChE,IAAMzB,EAAOO,EAAYkB,EAASQ,EAAS,EACrCC,EAAQF,EAAQC,IAAa,GACnC,GAAIC,IAAU,GAAI,CAChBE,EAAO,KAAKpC,CAAI,EAChB,QACF,CACA,IAAMqC,EAAWX,EAASQ,GACtBnC,EAAYsC,CAAQ,GAAKtC,EAAYC,CAAI,GAAKE,EAASmC,EAAUrC,CAAI,GACnEqC,IAAarC,GAAMW,EAAQ0B,EAAUrC,CAAI,EAC7CoC,EAAO,KAAKC,CAAQ,GAEpBD,EAAO,KAAKpC,CAAI,CAEpB,CACA,GAAIL,EAAK,MACF,IAAA,IAAIkC,EAAQ,EAAGA,EAAQH,EAAS,OAAQ,GAAS,EAChDK,EAAKF,KAAW,IAAMO,EAAO,KAAKV,EAASG,EAAM,EAIzD,IAAK,IAAII,EAAW,EAAGA,EAAWG,EAAO,OAAQ,GAAY,EAC3Dd,EAASR,EAAQ,OAAOmB,CAAQ,EAAGG,EAAOH,EAAS,EAEjDT,EAAK,OAASY,EAAO,QAAQd,EAASR,EAAQ,SAAUsB,EAAO,MAAM,CAC3E,CAsBA,SAAgBE,EAAW,EAAgD,CACzE,OAAO7C,CACT,C"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{group as e}from"../internal/scheduler.js";import{untrack as t}from"../ownership.js";import{useSignal as n}from"../signal.js";import{isReservedKey as r,isWrappable as i,unwrapValue as a}from"./nodes.js";import{
|
|
1
|
+
import{group as e}from"../internal/scheduler.js";import{untrack as t}from"../ownership.js";import{useSignal as n}from"../signal.js";import{isReservedKey as r,isWrappable as i,unwrapValue as a}from"./nodes.js";import{Transaction as o,draftOf as s,readProxyOf as c}from"./proxies.js";import{applyReconcile as l,reconcile as u,specOf as d}from"./reconcile.js";function f(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function p(e,t){let n=e.from??0,r=e.to??t-1,i=e.by??1;if(!Number.isFinite(i)||i===0)throw TypeError(`SHADOW_STORE_RANGE`);let a=[];for(let e=n;(i>0?e<=r:e>=r)&&(a.push(e),!(a.length>t+1));e+=i);return a}function m(e,t){for(let n of t)e.push(n)}function h(e,t,n){let i=[];if(Array.isArray(e)){if(typeof t==`number`)i.push(t);else if(typeof t==`function`){let n=t;for(let t=0;t<e.length;t+=1)n(e[t],t)&&i.push(t)}else if(Array.isArray(t))m(i,t);else if(typeof t==`object`&&t)m(i,p(t,e.length));else throw TypeError(`SHADOW_STORE_PATH_ARRAY`)}else if(typeof t==`string`||typeof t==`number`)i.push(t);else if(Array.isArray(t))m(i,t);else throw TypeError(`SHADOW_STORE_PATH_OBJECT`);for(let e of i)if(typeof e==`string`&&r(e))throw TypeError(`SHADOW_STORE_PATH_KEY`);return i}function g(e,t,n){let r=t[t.length-1],o=t.slice(0,-1),s=(e,t)=>{for(let c of h(e,o[t],n)){let u=e;if(t===o.length-1){let e=u[c],t=typeof r==`function`?d(r):void 0;if(t!==void 0){i(e)?l(a(e),t,n):u[c]=t.next;continue}let o=typeof r==`function`?r(e):r;f(o)&&i(e)&&!Array.isArray(e)?_(e,o,n):u[c]=o}else{let e=u[c];if(!i(e))throw TypeError(`SHADOW_STORE_PATH_VALUE`);s(e,t+1)}}};s(e,0)}function _(e,t,n){for(let n of Object.keys(t)){if(r(n))throw TypeError(`SHADOW_STORE_ASSIGN_KEY`);e[n]=t[n]}}function v(n,r){let i=a(n);return[c(i),(...n)=>{if(n.length===0)throw TypeError(`SHADOW_STORE_NO_ARGUMENT`);let a=n[0];e(()=>t(()=>{if(n.length>1){let e=new o(r);try{g(s(i,e),n,r)}finally{e.open=!1}}else if(typeof a==`function`){let e=d(a);if(e!==void 0){l(i,e,r);return}let t=new o(r),n;try{n=a(s(i,t))}finally{t.open=!1}n!==void 0&&y(i,n,r)}else y(i,a,r)}))}]}function y(e,t,n){if(Array.isArray(e)){if(!Array.isArray(t))throw TypeError(`SHADOW_STORE_ARRAY_UPDATE`);let r=d(u(t));r!==void 0&&l(e,r,n);return}if(!f(t))throw TypeError(`SHADOW_STORE_UPDATE_ARGUMENT`);let r=new o(n);try{_(s(e,r),t,n)}finally{r.open=!1}}function b(e,t){let r=t?.name===void 0?``:` (${t.name})`,o=a(e);if(i(o))return v(o,r);let[s,c]=n(x(e),t?.name===void 0?void 0:{name:t.name});return[s,e=>c(typeof e==`function`?t=>x(e(t)):x(e))]}function x(e){let t=a(e);return i(t)?c(t):e}export{b as useStore};
|
|
2
2
|
//# sourceMappingURL=use-store.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-store.js","names":["setStore","isPlainObject","value","prototype","rangeKeys","from","range","to","length","by","keys","i","stepKeys","target","step","filter","key","isReservedKey","applyPath","path","steps","walk","depth","label","holder","previous","spec","specOf","isWrappable","applyReconcile","unwrapValue","next","mergeInto","child","root","source","createDeepStore","initial","readProxyOf","args","first","group","untrack","tx","Transaction","draftOf","result","replaceWith","reconcile","useStore","options","read","write","useSignal","wrapCell","raw"],"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":"A,qWA4BA,SAASC,EAAc,EAAkD,CACvE,GAAI,OAAOC,GAAU,WAAYA,GAAkB,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMC,EAAY,OAAO,eAAeD,CAAK,EAC7C,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAEA,SAASC,EAAU,EAAoD,EAA0B,CAC/F,IAAMC,EAAOC,EAAM,MAAQ,EACrBC,EAAKD,EAAM,IAAME,EAAS,EAC1BC,EAAKH,EAAM,IAAM,EACvB,GAAI,CAAC,OAAO,SAASG,CAAE,GAAKA,IAAO,EACjC,MAAU,UACiD,oBAC3D,EACF,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAIN,GAAMI,EAAK,EAAIE,GAAKJ,EAAKI,GAAKJ,KACzCG,EAAK,KAAKC,CAAC,EACP,IAAK,OAASH,EAAS,IAFkB,GAAKC,GAIpD,OAA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C7B,OAAO0B,EAAY2B,CAAG,EAAIjB,EAAYiB,CAAG,EAAIrD,CAC/C,C"}
|
|
1
|
+
{"version":3,"file":"use-store.js","names":["setStore","isPlainObject","value","prototype","rangeKeys","from","range","to","length","by","keys","i","appendKeys","item","items","stepKeys","target","step","filter","key","isReservedKey","applyPath","path","steps","walk","depth","label","holder","previous","spec","specOf","isWrappable","applyReconcile","unwrapValue","next","mergeInto","child","root","source","createDeepStore","initial","readProxyOf","args","first","group","untrack","tx","Transaction","draftOf","result","replaceWith","reconcile","useStore","options","read","write","useSignal","wrapCell","raw"],"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":"A,qWA4BA,SAASC,EAAc,EAAkD,CACvE,GAAI,OAAOC,GAAU,WAAYA,GAAkB,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMC,EAAY,OAAO,eAAeD,CAAK,EAC7C,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAEA,SAASC,EAAU,EAAoD,EAA0B,CAC/F,IAAMC,EAAOC,EAAM,MAAQ,EACrBC,EAAKD,EAAM,IAAME,EAAS,EAC1BC,EAAKH,EAAM,IAAM,EACvB,GAAI,CAAC,OAAO,SAASG,CAAE,GAAKA,IAAO,EACjC,MAAU,UACiD,oBAC3D,EACF,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAIN,GAAMI,EAAK,EAAIE,GAAKJ,EAAKI,GAAKJ,KACzCG,EAAK,KAAKC,CAAC,EACP,IAAK,OAASH,EAAS,IAFkB,GAAKC,GAIpD,OAAOC,CACT,CAGA,SAASE,EAAW,EAA8B,EAA6C,CAC7F,IAAK,IAAMC,KAAQC,EAAOJ,EAAK,KAAKG,CAAI,CAC1C,CAGA,SAASE,EAAS,EAAgB,EAAe,EAAuC,CACtF,IAAML,EAA+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/transitions.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{createComputation as e}from"./extend/index.js";import{untrack as t}from"./ownership.js";import{registerTransitionLane as n,startTransition as r}from"./internal/concurrency.js";import{useSignal as i}from"./signal.js";function a(){let[e,n]=i(!1),a=0;return[e,e=>{a+=1,t(()=>n(!0));let i;try{i=r(e)}catch(e){throw--a,a===0&&t(()=>n(!1)),e}return i.then(()=>{--a,a===0&&t(()=>n(!1))})}]}function o(r,a){n();let[o,s]=i(t(r),{equals:a?.equals??Object.is,name:a?.name});return e({kind:`effect`,fn:()=>r(),apply:e=>{s(()=>e)},lane:!0,name:a?.name??`useDeferredValue`}),o}export{o as useDeferredValue,a as useTransition};
|
|
2
2
|
//# sourceMappingURL=transitions.js.map
|
package/dist/server/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/server/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/server/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{currentOwner as n}from"./extend/index.js";import{runWithOwner as r}from"./ownership.js";function i(e,i){let a=Symbol(i?.name??`context`),o=e=>{let i=new t(n()),o=i.context,s=Object.create(o);return s[a]=e.value,i.context=s,r(i,()=>{{let t=e.children;return()=>t}})};return Object.assign(o,{id:a,defaultValue:e,Provider:o})}function a(e,i,a){let o=new t(n()),s=Object.create(o.context);return s[e.id]=i,o.context=s,r(o,a)}function o(t){let r=n()?.context;if(r!=null&&t.id in r)return r[t.id];if(t.defaultValue===void 0)throw new e(`CONTEXT_MISSING`);return t.defaultValue}export{i as createContext,a as runWithContext,o as useContext};
|
|
2
2
|
//# sourceMappingURL=context.js.map
|
|
@@ -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
|
package/dist/server/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 e(),Promise.resolve()}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
|