@shadow-js/core 0.1.0 → 1.0.1
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 +17 -0
- package/LICENSE +2 -2
- package/README.md +134 -331
- package/dist/dev/action.d.ts +34 -0
- package/dist/dev/action.js +89 -0
- package/dist/dev/action.js.map +1 -0
- package/dist/dev/cache.d.ts +33 -0
- package/dist/dev/cache.js +61 -0
- package/dist/dev/cache.js.map +1 -0
- package/dist/dev/context.d.ts +104 -0
- package/dist/dev/context.js +110 -0
- package/dist/dev/context.js.map +1 -0
- package/dist/dev/effect.d.ts +120 -0
- package/dist/dev/effect.js +110 -0
- package/dist/dev/effect.js.map +1 -0
- package/dist/dev/env.d.ts +27 -0
- package/dist/dev/env.js +30 -0
- package/dist/dev/env.js.map +1 -0
- package/dist/dev/events.d.ts +26 -0
- package/dist/dev/events.js +32 -0
- package/dist/dev/events.js.map +1 -0
- package/dist/dev/extend/index.d.ts +329 -0
- package/dist/dev/extend/index.js +316 -0
- package/dist/dev/extend/index.js.map +1 -0
- package/dist/dev/external-store.d.ts +58 -0
- package/dist/dev/external-store.js +59 -0
- package/dist/dev/external-store.js.map +1 -0
- package/dist/dev/index.d.ts +29 -0
- package/dist/dev/index.js +26 -0
- package/dist/dev/internal/concurrency.d.ts +211 -0
- package/dist/dev/internal/concurrency.js +631 -0
- package/dist/dev/internal/concurrency.js.map +1 -0
- package/dist/dev/internal/devtools.d.ts +69 -0
- package/dist/dev/internal/devtools.js +76 -0
- package/dist/dev/internal/devtools.js.map +1 -0
- package/dist/dev/internal/diagnostics.d.ts +88 -0
- package/dist/dev/internal/diagnostics.js +101 -0
- package/dist/dev/internal/diagnostics.js.map +1 -0
- package/dist/dev/internal/dispose.d.ts +26 -0
- package/dist/dev/internal/dispose.js +48 -0
- package/dist/dev/internal/dispose.js.map +1 -0
- package/dist/dev/internal/flags.js +10 -0
- package/dist/dev/internal/flags.js.map +1 -0
- package/dist/dev/internal/graph.d.ts +231 -0
- package/dist/dev/internal/graph.js +577 -0
- package/dist/dev/internal/graph.js.map +1 -0
- package/dist/dev/internal/hydration-flag.d.ts +31 -0
- package/dist/dev/internal/hydration-flag.js +45 -0
- package/dist/dev/internal/hydration-flag.js.map +1 -0
- package/dist/dev/internal/messages.d.ts +54 -0
- package/dist/dev/internal/messages.js +53 -0
- package/dist/dev/internal/messages.js.map +1 -0
- package/dist/dev/internal/owner.d.ts +140 -0
- package/dist/dev/internal/owner.js +289 -0
- package/dist/dev/internal/owner.js.map +1 -0
- package/dist/dev/internal/queue.js +45 -0
- package/dist/dev/internal/queue.js.map +1 -0
- package/dist/dev/internal/scheduler.d.ts +111 -0
- package/dist/dev/internal/scheduler.js +286 -0
- package/dist/dev/internal/scheduler.js.map +1 -0
- package/dist/dev/internal/state.d.ts +139 -0
- package/dist/dev/internal/state.js +27 -0
- package/dist/dev/internal/state.js.map +1 -0
- package/dist/dev/internal/suspension.d.ts +41 -0
- package/dist/dev/internal/suspension.js +44 -0
- package/dist/dev/internal/suspension.js.map +1 -0
- package/dist/dev/internal/types.d.ts +44 -0
- package/dist/dev/list.d.ts +91 -0
- package/dist/dev/list.js +281 -0
- package/dist/dev/list.js.map +1 -0
- package/dist/dev/memo.d.ts +58 -0
- package/dist/dev/memo.js +40 -0
- package/dist/dev/memo.js.map +1 -0
- package/dist/dev/optimistic.d.ts +24 -0
- package/dist/dev/optimistic.js +44 -0
- package/dist/dev/optimistic.js.map +1 -0
- package/dist/dev/ownership.d.ts +202 -0
- package/dist/dev/ownership.js +260 -0
- package/dist/dev/ownership.js.map +1 -0
- package/dist/dev/props.d.ts +132 -0
- package/dist/dev/props.js +281 -0
- package/dist/dev/props.js.map +1 -0
- package/dist/dev/reaction.d.ts +27 -0
- package/dist/dev/reaction.js +60 -0
- package/dist/dev/reaction.js.map +1 -0
- package/dist/dev/reducer.d.ts +39 -0
- package/dist/dev/reducer.js +38 -0
- package/dist/dev/reducer.js.map +1 -0
- package/dist/dev/refs.d.ts +50 -0
- package/dist/dev/refs.js +57 -0
- package/dist/dev/refs.js.map +1 -0
- package/dist/dev/resource.d.ts +133 -0
- package/dist/dev/resource.js +176 -0
- package/dist/dev/resource.js.map +1 -0
- package/dist/dev/selector.d.ts +32 -0
- package/dist/dev/selector.js +117 -0
- package/dist/dev/selector.js.map +1 -0
- package/dist/dev/signal.d.ts +40 -0
- package/dist/dev/signal.js +38 -0
- package/dist/dev/signal.js.map +1 -0
- package/dist/dev/store/index.d.ts +5 -0
- package/dist/dev/store/index.js +4 -0
- package/dist/dev/store/nodes.js +191 -0
- package/dist/dev/store/nodes.js.map +1 -0
- package/dist/dev/store/proxies.js +159 -0
- package/dist/dev/store/proxies.js.map +1 -0
- package/dist/dev/store/read.d.ts +37 -0
- package/dist/dev/store/read.js +71 -0
- package/dist/dev/store/read.js.map +1 -0
- package/dist/dev/store/reconcile.d.ts +71 -0
- package/dist/dev/store/reconcile.js +185 -0
- package/dist/dev/store/reconcile.js.map +1 -0
- package/dist/dev/store/types.d.ts +104 -0
- package/dist/dev/store/use-store.d.ts +58 -0
- package/dist/dev/store/use-store.js +167 -0
- package/dist/dev/store/use-store.js.map +1 -0
- package/dist/dev/suspense.d.ts +99 -0
- package/dist/dev/suspense.js +44 -0
- package/dist/dev/suspense.js.map +1 -0
- package/dist/dev/transitions.d.ts +75 -0
- package/dist/dev/transitions.js +100 -0
- package/dist/dev/transitions.js.map +1 -0
- package/dist/prod/action.js +2 -0
- package/dist/prod/action.js.map +1 -0
- package/dist/prod/cache.js +2 -0
- package/dist/prod/cache.js.map +1 -0
- package/dist/prod/context.js +2 -0
- package/dist/prod/context.js.map +1 -0
- package/dist/prod/effect.js +2 -0
- package/dist/prod/effect.js.map +1 -0
- package/dist/prod/env.js +2 -0
- package/dist/prod/env.js.map +1 -0
- package/dist/prod/events.js +2 -0
- package/dist/prod/events.js.map +1 -0
- package/dist/prod/extend/index.js +2 -0
- package/dist/prod/extend/index.js.map +1 -0
- package/dist/prod/external-store.js +2 -0
- package/dist/prod/external-store.js.map +1 -0
- package/dist/prod/index.js +1 -0
- package/dist/prod/internal/concurrency.js +2 -0
- package/dist/prod/internal/concurrency.js.map +1 -0
- package/dist/prod/internal/devtools.js +2 -0
- package/dist/prod/internal/devtools.js.map +1 -0
- package/dist/prod/internal/diagnostics.js +2 -0
- package/dist/prod/internal/diagnostics.js.map +1 -0
- package/dist/prod/internal/dispose.js +2 -0
- package/dist/prod/internal/dispose.js.map +1 -0
- package/dist/prod/internal/flags.js +2 -0
- package/dist/prod/internal/flags.js.map +1 -0
- package/dist/prod/internal/graph.js +2 -0
- package/dist/prod/internal/graph.js.map +1 -0
- package/dist/prod/internal/hydration-flag.js +2 -0
- package/dist/prod/internal/hydration-flag.js.map +1 -0
- package/dist/prod/internal/messages.js +2 -0
- package/dist/prod/internal/messages.js.map +1 -0
- package/dist/prod/internal/owner.js +2 -0
- package/dist/prod/internal/owner.js.map +1 -0
- package/dist/prod/internal/queue.js +2 -0
- package/dist/prod/internal/queue.js.map +1 -0
- package/dist/prod/internal/scheduler.js +2 -0
- package/dist/prod/internal/scheduler.js.map +1 -0
- package/dist/prod/internal/state.js +2 -0
- package/dist/prod/internal/state.js.map +1 -0
- package/dist/prod/internal/suspension.js +2 -0
- package/dist/prod/internal/suspension.js.map +1 -0
- package/dist/prod/list.js +2 -0
- package/dist/prod/list.js.map +1 -0
- package/dist/prod/memo.js +2 -0
- package/dist/prod/memo.js.map +1 -0
- package/dist/prod/optimistic.js +2 -0
- package/dist/prod/optimistic.js.map +1 -0
- package/dist/prod/ownership.js +2 -0
- package/dist/prod/ownership.js.map +1 -0
- package/dist/prod/props.js +2 -0
- package/dist/prod/props.js.map +1 -0
- package/dist/prod/reaction.js +2 -0
- package/dist/prod/reaction.js.map +1 -0
- package/dist/prod/reducer.js +2 -0
- package/dist/prod/reducer.js.map +1 -0
- package/dist/prod/refs.js +2 -0
- package/dist/prod/refs.js.map +1 -0
- package/dist/prod/resource.js +2 -0
- package/dist/prod/resource.js.map +1 -0
- package/dist/prod/selector.js +2 -0
- package/dist/prod/selector.js.map +1 -0
- package/dist/prod/signal.js +2 -0
- package/dist/prod/signal.js.map +1 -0
- package/dist/prod/store/index.js +1 -0
- package/dist/prod/store/nodes.js +2 -0
- package/dist/prod/store/nodes.js.map +1 -0
- package/dist/prod/store/proxies.js +2 -0
- package/dist/prod/store/proxies.js.map +1 -0
- package/dist/prod/store/read.js +2 -0
- package/dist/prod/store/read.js.map +1 -0
- package/dist/prod/store/reconcile.js +2 -0
- package/dist/prod/store/reconcile.js.map +1 -0
- package/dist/prod/store/use-store.js +2 -0
- package/dist/prod/store/use-store.js.map +1 -0
- package/dist/prod/suspense.js +2 -0
- package/dist/prod/suspense.js.map +1 -0
- package/dist/prod/transitions.js +2 -0
- package/dist/prod/transitions.js.map +1 -0
- package/dist/server/action.js +2 -0
- package/dist/server/action.js.map +1 -0
- package/dist/server/cache.js +2 -0
- package/dist/server/cache.js.map +1 -0
- package/dist/server/context.js +2 -0
- package/dist/server/context.js.map +1 -0
- package/dist/server/effect.js +2 -0
- package/dist/server/effect.js.map +1 -0
- package/dist/server/env.js +2 -0
- package/dist/server/env.js.map +1 -0
- package/dist/server/events.js +2 -0
- package/dist/server/events.js.map +1 -0
- package/dist/server/extend/index.js +2 -0
- package/dist/server/extend/index.js.map +1 -0
- package/dist/server/external-store.js +2 -0
- package/dist/server/external-store.js.map +1 -0
- package/dist/server/index.js +1 -0
- package/dist/server/internal/concurrency.js +2 -0
- package/dist/server/internal/concurrency.js.map +1 -0
- package/dist/server/internal/devtools.js +2 -0
- package/dist/server/internal/devtools.js.map +1 -0
- package/dist/server/internal/diagnostics.js +2 -0
- package/dist/server/internal/diagnostics.js.map +1 -0
- package/dist/server/internal/dispose.js +2 -0
- package/dist/server/internal/dispose.js.map +1 -0
- package/dist/server/internal/flags.js +2 -0
- package/dist/server/internal/flags.js.map +1 -0
- package/dist/server/internal/graph.js +2 -0
- package/dist/server/internal/graph.js.map +1 -0
- package/dist/server/internal/hydration-flag.js +2 -0
- package/dist/server/internal/hydration-flag.js.map +1 -0
- package/dist/server/internal/messages.js +2 -0
- package/dist/server/internal/messages.js.map +1 -0
- package/dist/server/internal/owner.js +2 -0
- package/dist/server/internal/owner.js.map +1 -0
- package/dist/server/internal/queue.js +2 -0
- package/dist/server/internal/queue.js.map +1 -0
- package/dist/server/internal/scheduler.js +2 -0
- package/dist/server/internal/scheduler.js.map +1 -0
- package/dist/server/internal/state.js +2 -0
- package/dist/server/internal/state.js.map +1 -0
- package/dist/server/internal/suspension.js +2 -0
- package/dist/server/internal/suspension.js.map +1 -0
- package/dist/server/list.js +2 -0
- package/dist/server/list.js.map +1 -0
- package/dist/server/memo.js +2 -0
- package/dist/server/memo.js.map +1 -0
- package/dist/server/optimistic.js +2 -0
- package/dist/server/optimistic.js.map +1 -0
- package/dist/server/ownership.js +2 -0
- package/dist/server/ownership.js.map +1 -0
- package/dist/server/props.js +2 -0
- package/dist/server/props.js.map +1 -0
- package/dist/server/reaction.js +2 -0
- package/dist/server/reaction.js.map +1 -0
- package/dist/server/reducer.js +2 -0
- package/dist/server/reducer.js.map +1 -0
- package/dist/server/refs.js +2 -0
- package/dist/server/refs.js.map +1 -0
- package/dist/server/resource.js +2 -0
- package/dist/server/resource.js.map +1 -0
- package/dist/server/selector.js +2 -0
- package/dist/server/selector.js.map +1 -0
- package/dist/server/signal.js +2 -0
- package/dist/server/signal.js.map +1 -0
- package/dist/server/store/index.js +1 -0
- package/dist/server/store/nodes.js +2 -0
- package/dist/server/store/nodes.js.map +1 -0
- package/dist/server/store/proxies.js +2 -0
- package/dist/server/store/proxies.js.map +1 -0
- package/dist/server/store/read.js +2 -0
- package/dist/server/store/read.js.map +1 -0
- package/dist/server/store/reconcile.js +2 -0
- package/dist/server/store/reconcile.js.map +1 -0
- package/dist/server/store/use-store.js +2 -0
- package/dist/server/store/use-store.js.map +1 -0
- package/dist/server/suspense.js +2 -0
- package/dist/server/suspense.js.map +1 -0
- package/dist/server/transitions.js +2 -0
- package/dist/server/transitions.js.map +1 -0
- package/dist/server-dev/action.js +89 -0
- package/dist/server-dev/action.js.map +1 -0
- package/dist/server-dev/cache.js +61 -0
- package/dist/server-dev/cache.js.map +1 -0
- package/dist/server-dev/context.js +107 -0
- package/dist/server-dev/context.js.map +1 -0
- package/dist/server-dev/effect.js +55 -0
- package/dist/server-dev/effect.js.map +1 -0
- package/dist/server-dev/env.js +30 -0
- package/dist/server-dev/env.js.map +1 -0
- package/dist/server-dev/events.js +32 -0
- package/dist/server-dev/events.js.map +1 -0
- package/dist/server-dev/extend/index.js +316 -0
- package/dist/server-dev/extend/index.js.map +1 -0
- package/dist/server-dev/external-store.js +45 -0
- package/dist/server-dev/external-store.js.map +1 -0
- package/dist/server-dev/index.js +26 -0
- package/dist/server-dev/internal/concurrency.js +632 -0
- package/dist/server-dev/internal/concurrency.js.map +1 -0
- package/dist/server-dev/internal/devtools.js +76 -0
- package/dist/server-dev/internal/devtools.js.map +1 -0
- package/dist/server-dev/internal/diagnostics.js +101 -0
- package/dist/server-dev/internal/diagnostics.js.map +1 -0
- package/dist/server-dev/internal/dispose.js +48 -0
- package/dist/server-dev/internal/dispose.js.map +1 -0
- package/dist/server-dev/internal/flags.js +10 -0
- package/dist/server-dev/internal/flags.js.map +1 -0
- package/dist/server-dev/internal/graph.js +577 -0
- package/dist/server-dev/internal/graph.js.map +1 -0
- package/dist/server-dev/internal/hydration-flag.js +45 -0
- package/dist/server-dev/internal/hydration-flag.js.map +1 -0
- package/dist/server-dev/internal/messages.js +53 -0
- package/dist/server-dev/internal/messages.js.map +1 -0
- package/dist/server-dev/internal/owner.js +289 -0
- package/dist/server-dev/internal/owner.js.map +1 -0
- package/dist/server-dev/internal/queue.js +45 -0
- package/dist/server-dev/internal/queue.js.map +1 -0
- package/dist/server-dev/internal/scheduler.js +286 -0
- package/dist/server-dev/internal/scheduler.js.map +1 -0
- package/dist/server-dev/internal/state.js +27 -0
- package/dist/server-dev/internal/state.js.map +1 -0
- package/dist/server-dev/internal/suspension.js +44 -0
- package/dist/server-dev/internal/suspension.js.map +1 -0
- package/dist/server-dev/list.js +281 -0
- package/dist/server-dev/list.js.map +1 -0
- package/dist/server-dev/memo.js +40 -0
- package/dist/server-dev/memo.js.map +1 -0
- package/dist/server-dev/optimistic.js +44 -0
- package/dist/server-dev/optimistic.js.map +1 -0
- package/dist/server-dev/ownership.js +260 -0
- package/dist/server-dev/ownership.js.map +1 -0
- package/dist/server-dev/props.js +281 -0
- package/dist/server-dev/props.js.map +1 -0
- package/dist/server-dev/reaction.js +60 -0
- package/dist/server-dev/reaction.js.map +1 -0
- package/dist/server-dev/reducer.js +38 -0
- package/dist/server-dev/reducer.js.map +1 -0
- package/dist/server-dev/refs.js +57 -0
- package/dist/server-dev/refs.js.map +1 -0
- package/dist/server-dev/resource.js +175 -0
- package/dist/server-dev/resource.js.map +1 -0
- package/dist/server-dev/selector.js +81 -0
- package/dist/server-dev/selector.js.map +1 -0
- package/dist/server-dev/signal.js +38 -0
- package/dist/server-dev/signal.js.map +1 -0
- package/dist/server-dev/store/index.js +4 -0
- package/dist/server-dev/store/nodes.js +191 -0
- package/dist/server-dev/store/nodes.js.map +1 -0
- package/dist/server-dev/store/proxies.js +159 -0
- package/dist/server-dev/store/proxies.js.map +1 -0
- package/dist/server-dev/store/read.js +71 -0
- package/dist/server-dev/store/read.js.map +1 -0
- package/dist/server-dev/store/reconcile.js +185 -0
- package/dist/server-dev/store/reconcile.js.map +1 -0
- package/dist/server-dev/store/use-store.js +167 -0
- package/dist/server-dev/store/use-store.js.map +1 -0
- package/dist/server-dev/suspense.js +44 -0
- package/dist/server-dev/suspense.js.map +1 -0
- package/dist/server-dev/transitions.js +85 -0
- package/dist/server-dev/transitions.js.map +1 -0
- package/package.json +111 -50
- package/dist/chunk-6Y3CCWOY.js +0 -887
- package/dist/chunk-6Y3CCWOY.js.map +0 -1
- package/dist/chunk-B5FTYDUG.js +0 -3
- package/dist/chunk-B5FTYDUG.js.map +0 -1
- package/dist/index.cjs +0 -2000
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -609
- package/dist/index.d.ts +0 -609
- package/dist/index.js +0 -1094
- package/dist/index.js.map +0 -1
- package/dist/jsx-Bugil6CJ.d.cts +0 -151
- package/dist/jsx-Bugil6CJ.d.ts +0 -151
- package/dist/jsx-dev-runtime.cjs +0 -742
- package/dist/jsx-dev-runtime.cjs.map +0 -1
- package/dist/jsx-dev-runtime.d.cts +0 -2
- package/dist/jsx-dev-runtime.d.ts +0 -2
- package/dist/jsx-dev-runtime.js +0 -4
- package/dist/jsx-dev-runtime.js.map +0 -1
- package/dist/jsx-runtime.cjs +0 -742
- package/dist/jsx-runtime.cjs.map +0 -1
- package/dist/jsx-runtime.d.cts +0 -36
- package/dist/jsx-runtime.d.ts +0 -36
- package/dist/jsx-runtime.js +0 -4
- package/dist/jsx-runtime.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ownership.js","names":["disposeOwner","untrack","runInScope","fn","createRoot","detached","options","current","currentOwner","root","Owner","disposeTree","error","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/**\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.\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.\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 try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n disposeOwner(root);\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(\"-\")}_${sequence}`;\n}\n"],"mappings":"A,0PAmCA,SAAgBC,EAAW,EAAgB,CACzC,OAAOC,EAAW,CAAE,SAAU,IAAK,EAAGC,CAAE,CAC1C,CAyCA,SAAgBC,EAAc,EAAgC,EAA0B,CACtF,IAAMC,EAAWC,GAAS,WAAa,GACjCC,EAAUC,EAAa,EACvBC,EAAO,IAAIC,EAAML,EAAW,KAAOE,CAAO,EAC5CF,IAAU,EAAK,QAAUE,IAAY,KAAO,KAAOA,EAAQ,SAC/D,GAAI,CACF,OAAOL,EAAW,CAAE,MAAOO,EAAM,SAAU,IAAK,MAASN,MAASH,EAAaS,CAAI,CAAC,CAAC,CACvF,OAASG,EAAO,CAEd,MADAD,E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G,EAAE,GAAGE,GAC/B,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{untrack as e}from"./ownership.js";import{useMemo as t}from"./memo.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=t(()=>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:t=>r().map((n,r)=>e(()=>t(n,r))),forEach:t=>{r().forEach((n,r)=>{e(()=>t(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
|
+
//# sourceMappingURL=props.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"props.js","names":["UNSAFE_KEYS","DYNAMIC_PROPS","isEmptySource","value","ownEnumerableKeys","source","key","defineGetter","target","read","resolveSource","resolveAll","resolved","sources","object","readMerged","index","objects","mergedKeys","seen","keys","readDepth","readStates","stateOf","known","view","state","load","duringRead","run","liveView","mergeProps","inputs","dynamic","merged","splitProps","listed","groups","group","picked","props","restKeys","readRest","rest","flattenChildren","leaves","frames","open","fn","layer","advanced","top","children","memo","useMemo","untrack","leaf"],"sources":["../../src/props.ts"],"sourcesContent":["import { useMemo } from \"./memo\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Keys that never take part in a merge or a split. Reading them through a props object that came\n * from JSON or from user input could reach `Object.prototype`, so they are skipped everywhere.\n */\nconst UNSAFE_KEYS: ReadonlySet<PropertyKey> = new Set<PropertyKey>([\n \"__proto__\",\n \"constructor\",\n \"prototype\",\n]);\n\n/**\n * Results of mergeProps (and splitProps over them) that have at least one function source. Their\n * key set can change between reads, so splitProps builds a live rest object for them. A WeakSet is\n * bounded by the garbage collector.\n */\nconst DYNAMIC_PROPS = new WeakSet<object>();\n\n/** Longest chain of nested accessors that children() follows before it gives up. */\nconst MAX_FUNCTION_LAYERS = 1000;\n\n/**\n * A value accepted by {@link mergeProps}: an object, a function that returns one (called at every\n * read, so it can be reactive), or `null`, `undefined` or `false`, which are skipped. Use it to type\n * a helper that collects sources before merging them.\n * @since 1.0.0\n */\nexport type MergeSource = object | null | undefined | false;\n\n/** The props object a source stands for; functions contribute their return type. */\ntype PropsOf<S> = S extends (...args: never[]) => infer R\n ? Exclude<R, null | undefined | false>\n : S extends null | undefined | false\n ? object\n : S;\n\n/** Later keys replace earlier ones; a later key that may be `undefined` keeps the earlier type too. */\ntype Overlay<A, B> = {\n [K in keyof A | keyof B]: K extends keyof B\n ? K extends keyof A\n ? undefined extends B[K]\n ? Exclude<B[K], undefined> | A[K]\n : B[K]\n : B[K]\n : K extends keyof A\n ? A[K]\n : never;\n};\n\n/**\n * The type of `mergeProps(...sources)`, folded left to right: a later source's key replaces an\n * earlier one, and a later key that may be `undefined` keeps the earlier type as well.\n * @since 1.0.0\n */\nexport type MergeProps<T extends readonly unknown[], Acc = object> = T extends readonly [\n infer Head,\n ...infer Rest,\n]\n ? MergeProps<Rest, Overlay<Acc, PropsOf<Head>>>\n : Acc;\n\n/**\n * The type of `splitProps(props, ...keyLists)`: one object per key list, picking those keys, then\n * the rest without any listed key.\n * @since 1.0.0\n */\nexport type SplitProps<T extends object, K extends readonly (readonly (keyof T)[])[]> = [\n ...{ [I in keyof K]: Pick<T, Extract<K[I][number], keyof T>> },\n Omit<T, K[number][number]>,\n];\n\n/**\n * The value returned by {@link children}: calling it yields one leaf, an array of several leaves,\n * or `undefined` for none; `toArray()` always returns an array. The methods mirror React's\n * `Children` helpers.\n * @since 1.0.0\n */\nexport interface ResolvedChildren {\n /**\n * The current children: one leaf, an array of several leaves, or `undefined` when there is none.\n * The read is tracked like a memo read.\n */\n (): unknown;\n /** A fresh array of the leaves, without `null`, `undefined` or booleans. */\n toArray(): unknown[];\n /** Number of leaves, zero or more (the React `Children.count`). */\n count(): number;\n /** Maps each leaf with its index; the callback runs untracked (React `Children.map`). */\n map<U>(fn: (leaf: unknown, index: number) => U): U[];\n /** Visits each leaf with its index; the callback runs untracked (React `Children.forEach`). */\n forEach(fn: (leaf: unknown, index: number) => void): void;\n /**\n * The single leaf (React `Children.only`). Throws a TypeError (production message\n * `SHADOW_CHILDREN_ONLY`) when there is not exactly one leaf.\n */\n only(): unknown;\n}\n\n/** Whether a source stands for nothing and is skipped. */\nfunction isEmptySource(value: unknown): value is null | undefined | false {\n return value === null || value === undefined || value === false;\n}\n\n/** Own enumerable string and symbol keys, minus the unsafe ones. Reads no getter. */\nfunction ownEnumerableKeys(source: object): Key[] {\n return Reflect.ownKeys(source).filter(\n (key) => !UNSAFE_KEYS.has(key) && Object.prototype.propertyIsEnumerable.call(source, key),\n );\n}\n\n/** Defines an enumerable getter; the target is a fresh object, so this never hits a setter. */\nfunction defineGetter(target: object, key: PropertyKey, read: () => unknown): void {\n Object.defineProperty(target, key, { enumerable: true, configurable: true, get: read });\n}\n\n/** The object a source stands for at this moment, or `undefined` when it is skipped. */\nfunction resolveSource(source: object): object | undefined {\n const value: unknown = typeof source === \"function\" ? (source as () => unknown)() : source;\n if (isEmptySource(value)) return undefined;\n if (typeof value === \"object\" && value !== null) return value;\n throw new TypeError(\n __DEV__\n ? \"mergeProps: a source function must return an object, null, undefined or false\"\n : \"SHADOW_MERGE_SOURCE\",\n );\n}\n\n/** The sources that stand for an object right now, in order; skipped ones are dropped. */\nfunction resolveAll(sources: readonly object[]): object[] {\n const resolved: object[] = [];\n for (const source of sources) {\n const object = resolveSource(source);\n if (object !== undefined) resolved.push(object);\n }\n return resolved;\n}\n\n/**\n * Reads one merged key: the right-most object that has the key and a value other than `undefined`\n * wins. Each getter is read at most once.\n */\nfunction readMerged(objects: readonly object[], key: Key): unknown {\n for (let index = objects.length - 1; index >= 0; index -= 1) {\n const source = objects[index];\n if (source === undefined || !(key in source)) continue;\n const value: unknown = Reflect.get(source, key);\n if (value !== undefined) return value;\n }\n return undefined;\n}\n\n/** Every merged key in first-occurrence order. Reads no getter. */\nfunction mergedKeys(objects: readonly object[]): Key[] {\n const seen = new Set<Key>();\n const keys: Key[] = [];\n for (const source of objects) {\n for (const key of ownEnumerableKeys(source)) {\n if (seen.has(key)) continue;\n seen.add(key);\n keys.push(key);\n }\n }\n return keys;\n}\n\n/** A property name as a Proxy trap sees it. */\ntype Key = string | symbol;\n\n/** The key set and the reader that a live view uses for one access. */\ninterface LiveState {\n readonly keys: ReadonlySet<Key>;\n read(key: Key): unknown;\n}\n\n/**\n * A Proxy whose key set and values are recomputed on every access: `load` runs once per trap, so\n * a function source is called once per access. The target is an ordinary object, so prototype\n * lookups keep their usual meaning, and every write is refused because props are read-only.\n */\n/**\n * How deep the live reads are running, and the state each live view computed during the outermost\n * read. A view's traps read the views beneath it, and those read the views beneath them: without a\n * cache every trap recomputes each level below, and a few nested components (a chain of `{...props}`\n * forwards) take exponential time. Within one outermost read a view's state is computed once, so a\n * read costs time linear in the number of views. The cache is dropped when that read returns, so each\n * read still sees the current values.\n */\nlet readDepth = 0;\nconst readStates = new Map<object, LiveState>();\n\nfunction stateOf(view: object, load: () => LiveState): LiveState {\n const known = readStates.get(view);\n if (known !== undefined) return known;\n const state = load();\n readStates.set(view, state);\n return state;\n}\n\nfunction duringRead<T>(run: () => T): T {\n readDepth += 1;\n try {\n return run();\n } finally {\n readDepth -= 1;\n if (readDepth === 0) readStates.clear();\n }\n}\n\nfunction liveView(load: () => LiveState): object {\n const target: object = {};\n return new Proxy(target, {\n get(_target, key) {\n return duringRead(() => {\n const state = stateOf(target, load);\n return state.keys.has(key) ? state.read(key) : (Reflect.get(target, key) as unknown);\n });\n },\n has(_target, key) {\n return duringRead(() => stateOf(target, load).keys.has(key) || Reflect.has(target, key));\n },\n ownKeys() {\n return duringRead(() => [...stateOf(target, load).keys]);\n },\n getOwnPropertyDescriptor(_target, key) {\n return duringRead(() => {\n if (!stateOf(target, load).keys.has(key)) return undefined;\n return {\n enumerable: true,\n configurable: true,\n get: () => duringRead(() => stateOf(target, load).read(key)),\n };\n });\n },\n set: () => false,\n defineProperty: () => false,\n deleteProperty: () => false,\n });\n}\n\n/**\n * Merges props objects into one getter-preserving object. Reading a key returns the value from the\n * right-most source that has it, unless that value is `undefined`, in which case the next source\n * to the left is tried. Nothing is copied at merge time, so reads stay reactive. Use it to give\n * component props defaults without reading them in the component body.\n *\n * Sources may be objects, `null`, `undefined` or `false` (skipped), or functions that return an\n * object. A function is called on every read, which is how spreads such as `{...props()}` stay\n * reactive. Keys named `__proto__`, `constructor` or `prototype` are ignored.\n *\n * @param sources The props objects, from lowest to highest priority.\n * @returns A read-only object whose keys are the union of the sources' own enumerable keys. With a\n * function source, the key set is recomputed on every access.\n * @throws TypeError (production message `SHADOW_MERGE_SOURCES`) when a source is not an object, a\n * function, `null`, `undefined` or `false`. A read of the result throws TypeError (production\n * message `SHADOW_MERGE_SOURCE`) when a function source returns anything else.\n * @example\n * import { mergeProps } from \"@shadow-js/core\";\n *\n * function Button(props: { size?: \"sm\" | \"md\"; label: string }) {\n * const merged = mergeProps({ size: \"md\" as const }, props);\n * return <button class={`btn-${merged.size}`}>{merged.label}</button>;\n * }\n * @see splitProps\n * @since 1.0.0\n */\nexport function mergeProps<T extends readonly MergeSource[]>(...sources: T): MergeProps<T>;\nexport function mergeProps(...sources: readonly MergeSource[]): object {\n const inputs: object[] = [];\n let dynamic = false;\n for (const source of sources) {\n if (isEmptySource(source)) continue;\n if (typeof source === \"function\") {\n dynamic = true;\n } else if (typeof source !== \"object\") {\n throw new TypeError(\n __DEV__\n ? \"mergeProps: sources must be objects, functions, or null, undefined or false\"\n : \"SHADOW_MERGE_SOURCES\",\n );\n }\n inputs.push(source);\n }\n if (!dynamic) {\n const objects = resolveAll(inputs);\n const merged: object = {};\n for (const key of mergedKeys(objects)) {\n defineGetter(merged, key, () => readMerged(objects, key));\n }\n return merged;\n }\n const view = liveView(() => {\n const objects = resolveAll(inputs);\n return { keys: new Set(mergedKeys(objects)), read: (key) => readMerged(objects, key) };\n });\n DYNAMIC_PROPS.add(view);\n return view;\n}\n\n/**\n * Splits props into one getter-preserving object per key list, followed by an object holding every\n * other key. Each group reads its keys from `props` at access time, so reactivity is preserved. A\n * key listed in two groups appears in both and never in the rest. A listed key that `props` does not\n * have is still present in its group, as `undefined`. Use it to separate the props a component\n * consumes from the ones it forwards to an element.\n *\n * @param props The props to split; plain objects, Proxies and {@link mergeProps} results work.\n * @param keys One or more key lists. Keys named `__proto__`, `constructor` or `prototype` are\n * ignored.\n * @returns `[...groups, rest]`, in the order the key lists were given.\n * @example\n * import { splitProps } from \"@shadow-js/core\";\n *\n * function Field(props: { label: string; value: string; placeholder?: string }) {\n * const [own, input] = splitProps(props, [\"label\"]);\n * return (\n * <label>\n * {own.label}\n * <input {...input} />\n * </label>\n * );\n * }\n * @see mergeProps\n * @since 1.0.0\n */\nexport function splitProps<T extends object, const K extends readonly (readonly (keyof T)[])[]>(\n props: T,\n ...keys: K\n): SplitProps<T, K>;\nexport function splitProps(props: object, ...keys: readonly (readonly PropertyKey[])[]): object[] {\n const listed = new Set<PropertyKey>();\n const groups: object[] = [];\n for (const group of keys) {\n const picked: object = {};\n for (const key of group) {\n if (UNSAFE_KEYS.has(key)) continue;\n listed.add(key);\n defineGetter(picked, key, () => Reflect.get(props, key) as unknown);\n }\n groups.push(picked);\n }\n const restKeys = (): Key[] => ownEnumerableKeys(props).filter((key) => !listed.has(key));\n const readRest = (key: Key): unknown => Reflect.get(props, key) as unknown;\n if (DYNAMIC_PROPS.has(props)) {\n const rest = liveView(() => ({ keys: new Set(restKeys()), read: readRest }));\n return [...groups, rest];\n }\n const rest: object = {};\n for (const key of restKeys()) defineGetter(rest, key, () => readRest(key));\n return [...groups, rest];\n}\n\n/** One level of a children walk: an array being read and the function-layer depth it sits at. */\ninterface Frame {\n readonly items: readonly unknown[];\n next: number;\n readonly layer: number;\n}\n\n/**\n * Resolves children without recursion: arrays flatten in order, accessors are called until a plain\n * value appears, and `null`, `undefined` and booleans are dropped. A cyclic array or more than\n * {@link MAX_FUNCTION_LAYERS} nested accessors is a TypeError.\n */\nfunction flattenChildren(fn: () => unknown): unknown[] {\n const leaves: unknown[] = [];\n const frames: Frame[] = [];\n const open = new Set<readonly unknown[]>();\n let value: unknown = fn;\n let layer = 0;\n for (;;) {\n if (typeof value === \"function\") {\n if (layer >= MAX_FUNCTION_LAYERS) {\n throw new TypeError(\n __DEV__\n ? `children(): more than ${MAX_FUNCTION_LAYERS} nested accessors; a function child may return itself`\n : \"SHADOW_CHILDREN_LAYERS\",\n );\n }\n value = (value as () => unknown)();\n layer += 1;\n continue;\n }\n if (Array.isArray(value)) {\n if (open.has(value))\n throw new TypeError(\n __DEV__ ? \"children(): an array contains itself\" : \"SHADOW_CHILDREN_CYCLE\",\n );\n open.add(value);\n frames.push({ items: value, next: 0, layer });\n } else if (value !== null && value !== undefined && typeof value !== \"boolean\") {\n leaves.push(value);\n }\n let advanced = false;\n while (!advanced) {\n const top = frames.at(-1);\n if (top === undefined) return leaves;\n if (top.next < top.items.length) {\n value = top.items[top.next];\n top.next += 1;\n layer = top.layer;\n advanced = true;\n } else {\n frames.pop();\n open.delete(top.items);\n }\n }\n }\n}\n\n/**\n * Memoizes a `props.children` getter so that it is read at most once per change of its\n * dependencies. Arrays are flattened, accessors are called, and `null`, `undefined` and booleans\n * are dropped. The memo is created in the current owner, so nodes created while resolving are\n * disposed with it. Use it when a component inspects or rearranges its children.\n *\n * @param fn The lazy children accessor, usually `() => props.children`.\n * @returns A {@link ResolvedChildren} accessor with `toArray()`, `count()`, `map()`, `forEach()`\n * and `only()`.\n * @throws TypeError from the returned accessor and its methods when the children contain an array\n * that contains itself (production message `SHADOW_CHILDREN_CYCLE`) or more than 1000 nested\n * accessors (`SHADOW_CHILDREN_LAYERS`). `only()` throws TypeError (`SHADOW_CHILDREN_ONLY`) unless\n * there is exactly one leaf.\n * @example\n * import { children } from \"@shadow-js/core\";\n *\n * function Steps(props: { children?: unknown }) {\n * const steps = children(() => props.children);\n * return (\n * <ol aria-label={`${steps.count()} steps`}>\n * {steps.map((step) => <li>{step as Node | string}</li>)}\n * </ol>\n * );\n * }\n * @since 1.0.0\n */\nexport function children(fn: () => unknown): ResolvedChildren {\n const memo = useMemo(() => flattenChildren(fn), { allowWrites: true });\n const accessor = (): unknown => {\n const leaves = memo();\n if (leaves.length === 1) return leaves[0];\n return leaves.length === 0 ? undefined : leaves;\n };\n return Object.assign(accessor, {\n toArray: (): unknown[] => [...memo()],\n count: (): number => memo().length,\n map: <U>(fn: (leaf: unknown, index: number) => U): U[] =>\n memo().map((leaf, index) => untrack(() => fn(leaf, index))),\n forEach: (fn: (leaf: unknown, index: number) => void): void => {\n memo().forEach((leaf, index) => {\n untrack(() => fn(leaf, index));\n });\n },\n only: (): unknown => {\n const leaves = memo();\n if (leaves.length !== 1) {\n throw new TypeError(\n __DEV__\n ? `children().only(): expected one child, received ${leaves.length}`\n : \"SHADOW_CHILDREN_ONLY\",\n );\n }\n return leaves[0];\n },\n });\n}\n"],"mappings":"A,6EAOA,MAAMA,kBAAwC,IAAI,IAAiB,CACjE,YACA,cACA,WACF,CAAC,EAOKC,kBAAgB,IAAI,QAmF1B,SAASC,EAAc,EAAmD,CACxE,OAAO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AChCA,EAAO,SAAW,EAAI,IAAA,GAAYA,CAC3C,EAC+B,CAC7B,YAA0B,CAAC,GAAGQ,EAAK,CAAC,EACpC,UAAqBA,EAAK,CAAC,CAAC,OAC5B,IAAS,GACPA,EAAK,CAAC,CAAC,KAAK,EAAM,IAAUE,MAAcP,EAAGQ,EAAMxC,CAAK,CAAC,CAAC,EAC5D,QAAU,GAAqD,CAC7DqC,EAAK,CAAC,CAAC,SAAS,EAAM,IAAU,CAC9BE,MAAcP,EAAGQ,EAAMxC,CAAK,CAAC,CAC/B,CAAC,CACH,EACA,SAAqB,CACnB,IAAM6B,EAASQ,EAAK,EACpB,GAAIR,EAAO,SAAW,EACpB,MAAU,UAGJ,sBACN,EAEF,OAAOA,EAAO,EAChB,CACF,CAAC,CACH,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{untrack as e}from"./ownership.js";import{disposeTree as t}from"./internal/dispose.js";import{createComputation as n,createOwner as r,currentOwner as i,runInScope as a}from"./extend/index.js";function o(o){let s=i(),c=null;return i=>{c!==null&&t(c);let l=r(s);c=l;let u=!0;a({owner:l,listener:null},()=>{n({kind:`effect`,render:!0,owner:l,fn:()=>{u?(u=!1,i()):e(o)}})})}}export{o as useReaction};
|
|
2
|
+
//# sourceMappingURL=reaction.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reaction.js","names":["useReaction","owner","currentOwner","scope","disposeTree","next","createOwner","tracking","runInScope","createComputation","track","untrack","onInvalidate"],"sources":["../../src/reaction.ts"],"sourcesContent":["import {\n createComputation,\n createOwner,\n currentOwner,\n disposeOwner,\n type Owner,\n runInScope,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Creates a tracker that reports the first change of what it reads. `useReaction(onInvalidate)`\n * returns `track(fn)`: `fn` runs at once (synchronously) and the signals it reads are recorded.\n * The first change of any of them calls `onInvalidate` once, untracked, and then nothing is\n * observed until `track` is called again. The ShadowJS form of Solid's `createReaction`.\n *\n * Use it when the work that follows a change is not a pure rerun of `fn` (for example, re-fetching\n * after a change and then deciding what to track next). For ordinary effects use `useEffect`.\n *\n * @param onInvalidate Called once, untracked, after a change of a tracked read.\n * @returns `track(fn)`. Each call replaces the previous tracking. Tracking lives in a child of the\n * owner that called `useReaction`, so it stops when that owner is disposed.\n * @example\n * import { useReaction, useSignal } from \"@shadow-js/core\";\n *\n * function Results() {\n * const [filters] = useSignal({ query: \"\" });\n * const [stale, setStale] = useSignal(false);\n * const track = useReaction(() => setStale(true));\n * track(() => filters()); // the first change of filters marks the results stale\n * return <p>{stale() ? \"Refresh to update\" : \"Up to date\"}</p>;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useReaction(onInvalidate: () => void): (track: () => void) => void {\n const owner = currentOwner();\n let scope: Owner | null = null;\n return (track: () => void): void => {\n if (scope !== null) disposeOwner(scope);\n const next = createOwner(owner);\n scope = next;\n let tracking = true;\n runInScope({ owner: next, listener: null }, () => {\n createComputation({\n kind: \"effect\",\n render: true,\n owner: next,\n fn: () => {\n if (tracking) {\n tracking = false;\n track();\n return undefined;\n }\n untrack(onInvalidate);\n return undefined;\n },\n });\n });\n };\n}\n"],"mappings":"A,sMAmCA,SAAgBA,EAAY,EAAuD,CACjF,IAAMC,EAAQC,EAAa,EACvBC,EAAsB,KAC1B,MAAQ,IAA4B,CAC9BA,IAAU,MAAMC,EAAaD,CAAK,EACtC,IAAME,EAAOC,EAAYL,CAAK,EAC9B,EAAQI,EACR,IAAIE,EAAW,GACfC,EAAW,CAAE,MAAOH,EAAM,SAAU,IAAK,MAAS,CAChDI,EAAkB,CAChB,KAAM,SACN,OAAQ,GACR,MAAOJ,EACP,OAAU,CACJE,GACF,EAAW,GACXG,EAAM,GAGRC,EAAQC,CAAY,CAEtB,CACF,CAAC,CACH,CAAC,CACH,CACF,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"reducer.js","names":["useReducer","state","setState","useSignal","initialState","options","reducer","previous","action"],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n const dispatch = (action: A): void => {\n setState((previous) => reducer(previous, action));\n };\n return [state, dispatch];\n}\n"],"mappings":"A,wCAwCA,SAAgBA,EACd,EACA,EACA,EACoC,CACpC,GAAM,CAACC,EAAOC,GAAYC,EAAaC,EAAc,CACnD,OAASC,GAAS,QAAU,OAAO,GACnC,GAAIA,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAQ,IAAK,CAC9D,CAAC,EAID,MAAO,CAACJ,EAHU,GAAoB,CACpCC,EAAU,GAAaI,EAAQC,EAAUC,CAAM,CAAC,CAClD,CACuB,CACzB,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{onCleanup as e,untrack as t}from"./ownership.js";function n(){let e,t=(t=>{e=t});return Object.defineProperty(t,"current",{get:()=>e,enumerable:!0}),t}function r(n,r){n!=null&&(n(t(r)),e(()=>n(void 0)))}export{n as createRef,r as useImperativeHandle};
|
|
2
|
+
//# sourceMappingURL=refs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"refs.js","names":["createRef","current","ref","value","useImperativeHandle","untrack","create","onCleanup"],"sources":["../../src/refs.ts"],"sourcesContent":["import { onCleanup, untrack } from \"./ownership\";\n\n/**\n * A ref object that is also a ref callback: pass it as `ref={r}` (the renderer calls it with the\n * element) and read the element as `r.current`. `undefined` when nothing is attached.\n * @since 1.0.0\n */\nexport interface Ref<T> {\n /** Stores `value` as `current`; `undefined` clears it. The renderer calls it with the element. */\n (value: T | undefined): void;\n /** The value last passed to the ref, or `undefined` when nothing is attached. Not reactive. */\n readonly current: T | undefined;\n}\n\n/**\n * Creates a {@link Ref}. Calling it with a value stores the value; calling it with `undefined`\n * clears it. The same object works as a plain ref callback, so no `forwardRef` is needed.\n * @returns A callable ref with a `current` getter, `undefined` until the ref is called.\n * @example\n * import { createRef } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * const input = createRef<HTMLInputElement>();\n * return <input ref={input} onKeyDown={() => input.current?.select()} />;\n * }\n * @see useImperativeHandle\n * @since 1.0.0\n */\nexport function createRef<T>(): Ref<T> {\n let current: T | undefined;\n const ref = ((value: T | undefined): void => {\n current = value;\n }) as Ref<T>;\n Object.defineProperty(ref, \"current\", { get: () => current, enumerable: true });\n return ref;\n}\n\n/**\n * Publishes an imperative handle to a ref: `create()` runs once, untracked, and its result is\n * passed to `ref`; when the owner is disposed `ref` receives `undefined`. Components run once, so\n * the handle never needs refreshing: put live state behind accessors inside the handle.\n *\n * A missing `ref` is accepted and `create` does not run, so forwarding an optional ref needs no\n * branch.\n *\n * @param ref The ref callback (a {@link Ref}, or any function of the handle). `null` or `undefined`\n * makes the call a no-op.\n * @param create Builds the handle. Runs once, untracked.\n * @example\n * import { createRef, useImperativeHandle } from \"@shadow-js/core\";\n *\n * function FancyInput(props: { ref?: (handle: { focus(): void } | undefined) => void }) {\n * const input = createRef<HTMLInputElement>();\n * useImperativeHandle(props.ref, () => ({ focus: () => input.current?.focus() }));\n * return <input ref={input} />;\n * }\n * @see createRef\n * @since 1.0.0\n */\nexport function useImperativeHandle<T>(\n ref: ((value: T | undefined) => void) | null | undefined,\n create: () => T,\n): void {\n if (ref === undefined || ref === null) return;\n ref(untrack(create));\n onCleanup(() => ref(undefined));\n}\n"],"mappings":"A,wDA4BA,SAAgBA,GAAuB,CACrC,IAAIC,EACEC,GAAQ,GAA+B,CAC3C,EAAUC,CACZ,GAEA,OADA,OAAO,eAAeD,EAAK,UAAW,CAAE,QAAWD,EAAS,WAAY,EAAK,CAAC,EACvEC,CACT,CAwBA,SAAgBE,EACd,EACA,EACM,CACFF,GAA6B,OACjCA,EAAIG,EAAQC,CAAM,CAAC,EACnBC,MAAgBL,EAAI,IAAA,EAAS,CAAC,EAChC,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readSignal as e}from"./internal/graph.js";import{batch as t}from"./internal/scheduler.js";import{onCleanup as n,untrack as r}from"./ownership.js";import{useRenderEffect as i}from"./effect.js";import{useContext as a}from"./context.js";import{ResourceCacheContext as o,SuspenseContext as s}from"./suspense.js";import{holdReader as c,inTransition as l}from"./internal/concurrency.js";import{createSignalNode as u,currentListener as d,writeSignal as f}from"./extend/index.js";function p(t,n){let r=u(t,n?Object.is:!1);return[()=>e(r),e=>{f(r,e,{allowInMemo:!0})}]}function m(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function h(e,u,f){let h=typeof u==`function`,g=h?typeof e==`function`?e:()=>e:()=>!0,_=e,v=h?u:(e,t)=>_(t),y=(h?f:u)??{},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=a(o),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,n)=>P||e!==M?!1:(t(n),L(),!0),z=(e,n)=>{if(A!==void 0&&!j&&!n)return j=!0,F=!0,t(()=>{S(A.value),T(`ready`)}),Promise.resolve(A.value);N?.abort();let i=new AbortController;N=i,M+=1;let a=M;t(()=>{T(F?`refreshing`:`pending`),D(void 0)});let o;try{let t=n||O===null||k===void 0?void 0:O.pending?.(k);o=t===void 0?r(()=>v(e,{signal:i.signal,refetching:n,value:r(x)})):t}catch(e){return R(a,()=>{D(e),T(`errored`)}),Promise.resolve(void 0)}if(m(o))return O!==null&&k!==void 0&&O.track(k,Promise.resolve(o),{deferStream:y.deferStream}),Promise.resolve(o).then(e=>R(a,()=>{F=!0,S(e),T(`ready`)})?e:void 0,e=>{R(a,()=>{D(e),T(`errored`)})});let s=o,c=R(a,()=>{F=!0,S(s),T(`ready`)});return Promise.resolve(c?s: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=a(s);e!==null&&!I.has(e)&&(I.add(e),e.increment()),e!==null&&d()!==null&&l()&&c(e)}return x()});return Object.defineProperties(V,{state:{get:C},loading:{get:()=>C()===`pending`||C()===`refreshing`},error:{get:E},latest:{get:x},refetch:{value:()=>{let e=r(g);return e===!1||e==null?Promise.resolve(void 0):z(e,F)}},mutate:{value:e=>{let n;return t(()=>{n=typeof e==`function`?e(r(x)):e,N?.abort(),M+=1,F=!0,S(n),D(void 0),T(`ready`)}),L(),n}}}),i(g,B),n(()=>{P=!0,N?.abort(),L()}),V}export{h as useResource};
|
|
2
|
+
//# sourceMappingURL=resource.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource.js","names":["cell","node","createSignalNode","initial","distinct","readSignal","writeSignal","next","isPromiseLike","value","useResource","hasSource","second","source","first","oneShot","fetcher","info","options","third","hasInitial","setValue","state","writeState","setState","failure","setFailure","cache","useContext","ResourceCacheContext","cacheKey","cached","usedCache","version","controller","disposed","hasValue","holders","release","held","tracker","settle","id","batch","apply","load","refetching","current","output","joined","untrack","input","error","result","immediate","applied","onSource","read","SuspenseContext","currentListener","inTransition","holdReader","resolved","useRenderEffect","onCleanup"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n createSignalNode,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = createSignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n batch(apply);\n release();\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? (next as (previous: T | undefined) => T)(untrack(value))\n : next;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n release();\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":"A,+dAkGA,SAASA,EAAQ,EAAY,EAAqD,CAChF,IAAMC,EAAOC,EAAoBC,EAASC,EAAW,OAAO,GAAK,EAAK,EACtE,MAAO,KACCC,EAAWJ,CAAI,EACpB,GAAS,CACRK,EAAYL,EAAMM,EAAM,CAAE,YAAa,EAAK,CAAC,CAC/C,CACF,CACF,CAEA,SAASC,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiFA,SAAgBC,EACd,EACA,EACA,EACa,CACb,IAAMC,EAAY,OAAOC,GAAW,WAE9BC,EACJF,EAAa,OAAOG,GAAU,WAAaA,MAAcA,MAAe,GAEpEC,EAAUD,EACVE,EAAWL,EAAYC,GAAU,EAAW,IAA0BG,EAAQE,CAAI,EAIlFC,GAAWP,EAAYQ,EAASP,IAA8C,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AQ,IAAIG,CAAO,EACnBA,EAAQ,UAAU,GAIhBA,IAAY,MAAQmB,EAAgB,IAAM,MAAQC,EAAa,GAAGC,EAAWrB,CAAO,CAC1F,CACA,OAAO/B,EAAM,CACf,GAgDA,OA9CA,OAAO,iBAAiBgD,EAAM,CAC5B,MAAO,CAAE,IAAKnC,CAAM,EACpB,QAAS,CAAE,QAAWA,EAAM,IAAM,WAAaA,EAAM,IAAM,YAAa,EACxE,MAAO,CAAE,IAAKG,CAAQ,EACtB,OAAQ,CAAE,IAAKhB,CAAM,EACrB,QAAS,CACP,UAAqC,CACnC,IAAM0C,EAAQD,EAAQrC,CAAM,EAI5B,OAHIsC,IAAU,IAASA,GAAU,KACxB,QAAQ,QAAQ,IAAA,EAAS,EAE3BN,EAAKM,EAAOf,CAAQ,CAC7B,CACF,EACA,OAAQ,CACN,MAAQ,GAAkD,CACxD,IAAI0B,EAcJ,OAbAnB,MAAY,CACV,EACE,OAAOpC,GAAS,WACXA,EAAwC2C,EAAQzC,CAAK,CAAC,EACvDF,EACN2B,GAAY,MAAM,EAClB,GAAW,EACX,EAAW,GACXb,EAASyC,CAAa,EACtBpC,EAAW,IAAA,EAAS,EACpBF,EAAS,OAAO,CAClB,CAAC,EACDc,EAAQ,EACDwB,CACT,CACF,CACF,CAAC,EAOIC,EAAgBlD,EAAQ2C,CAAQ,EACrCQ,MAAgB,CACd,EAAW,GACX9B,GAAY,MAAM,EAClBI,EAAQ,CACV,CAAC,EACMmB,CACT,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{track as e}from"./internal/graph.js";import{onCleanup as t,untrack as n}from"./ownership.js";import{useRenderEffect as r}from"./effect.js";import{isTracking as i,notify as a}from"./extend/index.js";var o=class{kind=0;observers=null;stamp=0;subscribers=0;key;value;constructor(e,t){this.key=e,this.value=t}};function s(e,t){e.value!==t&&(e.value=t,a(e))}function c(a,c){let l=/* @__PURE__ */ new Map,u=null,d=(e,t)=>c===void 0?e===t:c(e,t),f=()=>u===null?n(a):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,d(e,f()));return l.set(e,t),t};return r(()=>a(),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}),n=>{if(!i())return d(n,a());let r=l.get(n)??m(n);return r.subscribers+=1,t(()=>p(r)),e(r),r.value}}export{c as useSelector};
|
|
2
|
+
//# sourceMappingURL=selector.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"selector.js","names":["Entry","key","value","setEntry","entry","selected","notify","useSelector","entries","last","matches","equals","currentValue","untrack","source","release","create","useRenderEffect","previous","next","before","after","failed","failure","error","isTracking","onCleanup","track"],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n readonly key: unknown;\n /** Whether the key matches the selected value. */\n value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n const entry = new Entry(key, matches(key, currentValue()));\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":"A,6MAQA,IAAMA,EAAN,KAAkC,CAEhC,KAAgB,EAChB,UAAqC,KACrC,MAAQ,EAER,YAAc,EAGd,IAEA,MAEA,YAAY,EAAc,EAAgB,CACxC,KAAK,IAAMC,EACX,KAAK,MAAQC,CACf,CACF,EAGA,SAASC,EAAS,EAAc,EAAyB,CACnDC,EAAM,QAAUC,IACpB,EAAM,MAAQA,EACdC,EAAOF,CAAK,EACd,CAgCA,SAAgBG,EACd,EACA,EACqB,CACrB,IAAMC,kBAAU,IAAI,IAEhBC,EAAqC,KAEnCC,GAAW,EAAQ,IACvBC,IAAW,IAAA,GAAaV,IAAoBC,EAAQS,EAAOV,EAAKC,CAAK,EAEjEU,MAAyBH,IAAS,KAAOI,EAAQC,CAAM,EAAIL,EAAK,MAEhEM,EAAW,GAAuB,CACtC,IAAM,YACFX,EAAM,cAAgB,GAAKI,EAAQ,IAAIJ,EAAM,GAAG,IAAMA,GAAOI,EAAQ,OAAOJ,EAAM,GAAG,CAC3F,EAEMY,EAAU,GAAkB,CAChC,IAAMZ,EAAQ,IAAIJ,EAAMC,EAAKS,EAAQT,EAAKW,EAAa,CAAC,CAAC,EAEzD,OADAJ,EAAQ,IAAIP,EAAKG,CAAK,EACfA,CACT,EA8CA,OAnCAa,MACQH,EAAO,EACZ,GAAS,CACR,IAAMI,EAAWT,EAEjB,GADA,EAAO,CAAE,MAAOU,CAAK,EACjBD,IAAa,MAAQP,IAAW,IAAA,GAAW,CAE7C,GAAIO,EAAS,QAAUC,EAAM,OAC7B,IAAMC,EAASZ,EAAQ,IAAIU,EAAS,KAAK,EACrCE,IAAW,IAAA,IAAWjB,EAASiB,EAAQA,EAAO,MAAQD,CAAI,EAC9D,IAAME,EAAQb,EAAQ,IAAIW,CAAI,EAC1BE,IAAU,IAAA,IAAWlB,EAASkB,EAAOA,EAAM,MAAQF,CAAI,EAC3D,MACF,CAGA,IAAIG,EAAS,GACTC,EACJ,IAAK,IAAMnB,KAASI,EAAQ,OAAO,EAAG,CACpC,IAAIH,EACJ,GAAI,CACF,EAAWK,EAAQN,EAAM,IAAUe,CAAI,CACzC,OAASK,EAAO,CACTF,IACH,EAAS,GACT,EAAUE,GAEZ,QACF,CACArB,EAASC,EAAOC,CAAQ,CAC1B,CACA,GAAIiB,EAAQ,MAAMC,CACpB,CACF,EA1CoB,GAAoB,CACtC,GAAI,CAACE,EAAW,EAAG,OAAOf,EAAQT,EAAKa,EAAO,CAAC,EAC/C,IAAMV,EAAQI,EAAQ,IAAIP,CAAG,GAAKe,EAAOf,CAAG,EAI5C,MAHA,GAAM,aAAe,EACrByB,MAAgBX,EAAQX,CAAK,CAAC,EAC9BuB,EAAMvB,CAAK,EACJA,EAAM,KACf,CAsCF,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{readSignal as e}from"./internal/graph.js";import{untrack as t}from"./ownership.js";import{createSignalNode as n,writeSignal as r}from"./extend/index.js";function i(i,a){let o=a?.equals===void 0?Object.is:a.equals,s=n(i,o,a?.name);return[()=>e(s),(e=>{let n=typeof e==`function`?t(()=>e(s.value)):e;return r(s,n),n})]}export{i as useSignal};
|
|
2
|
+
//# sourceMappingURL=signal.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"signal.js","names":["useSignal","equals","options","signal","createSignalNode","value","readSignal","resolved","next","untrack","writeSignal"],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n type Equals,\n readSignal,\n type Setter,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = createSignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":"A,gKAgDA,SAAgBA,EAAa,EAAU,EAAsD,CAC3F,IAAMC,EAAoBC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OACxEC,EAASC,EAAoBC,EAAOJ,EAAQC,GAAS,IAAI,EAS/D,MAAO,KARyBI,EAAWH,CAAM,GACjC,GAAkB,CAChC,IAAMI,EACJ,OAAOC,GAAS,WAAaC,MAAeD,EAAwBL,EAAO,KAAK,CAAC,EAAIK,EAGvF,OADAE,EAAYP,EAAQI,CAAQ,EACrBA,CACT,EACmB,CACrB,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{snapshot as e,unwrap as t}from"./read.js";import{produce as n,reconcile as r}from"./reconcile.js";import{useStore as i}from"./use-store.js";export{n as produce,r as reconcile,e as snapshot,t as unwrap,i as useStore};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{track as e}from"../internal/graph.js";import{createSignalNode as t,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(e,n){let r=e.signals;r===null&&(r=/* @__PURE__ */ new Map,e.signals=r);let i=r.get(n);return i===void 0&&(i=t(0,!1),r.set(n,i)),i}function h(t,r){n()&&e(m(t,r))}function g(r){n()&&(r.keys===null&&(r.keys=t(0,!1)),e(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 n=a.get(e);return n===void 0||(_(n.signals?.get(t)),_(n.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
|
+
//# sourceMappingURL=nodes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"nodes.js","names":["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","createSignalNode","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import {\n createSignalNode,\n isTracking,\n notify as notifySource,\n type SignalNode,\n track,\n} 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 /** One signal per property read in a tracked context, keyed by property name. */\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\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 signal = createSignalNode(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 = createSignalNode(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,+HASA,MAAMC,kBAAqC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAgB/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,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uD,qBACjE,EAEF,IAAM0B,EAAO7B,EAAM,IAAIwB,CAAM,EAI7B,OAHIK,IAAS,IAAA,KACbS,EAAOT,EAAK,SAAS,IAAI1B,CAAG,CAAC,EAC7BmC,EAAOT,EAAK,IAAI,GACT,EACT,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{RAW as e,deleteRaw as t,isReservedKey as n,isWrappable as r,nodeOf as i,readRaw as a,trackKeys as o,trackProperty as s,unwrapValue as c,writeRaw as l}from"./nodes.js";var u=class{label;open;drafts;handler;constructor(e){this.label=e,this.open=!0,this.drafts=/* @__PURE__ */ new Map,this.handler=_(this)}};function d(e){return typeof e==`symbol`?e.toString():`${e}`,/* @__PURE__ */ TypeError(`SHADOW_STORE_READ_ONLY`)}function f(e,t,n,i){if(!r(n)||!Object.hasOwn(e,t))return n;let a=Reflect.getOwnPropertyDescriptor(e,t);return a!==void 0&&a.configurable===!1&&a.writable===!1?n:i(n)}function p(e,t,n){let i=Reflect.getOwnPropertyDescriptor(e,t);if(i===void 0||typeof t==`symbol`||i.configurable===!1)return i;let a=i.value;return r(a)?{...i,value:n(a)}:i}function m(e,t){return t===`__proto__`&&!Object.hasOwn(e,t)}function h(e,t){for(let n=e;n!==null;n=Object.getPrototypeOf(n)){let e=Reflect.getOwnPropertyDescriptor(n,t);if(e!==void 0)return typeof e.get==`function`}return!1}const g={get(e,t,n){if(typeof t==`symbol`)return Reflect.get(e,t);if(!m(e,t))return s(i(e),t),h(e,t)?Reflect.get(e,t,n):f(e,t,a(e,t),v)},has(e,t){return typeof t!=`symbol`&&s(i(e),t),Reflect.has(e,t)},ownKeys(e){return o(i(e)),Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return p(e,t,v)},set(e,t){throw d(t)},deleteProperty(e,t){throw d(t)},defineProperty(e,t){throw d(t)},setPrototypeOf(){throw d(`[[Prototype]]`)},preventExtensions(){throw d(`[[Extensible]]`)}};function _(e){let r=t=>y(t,e),i=t=>{if(!e.open)throw TypeError(`SHADOW_STORE_DRAFT_STALE`);if(typeof t==`symbol`)throw TypeError(`SHADOW_STORE_SYMBOL_KEY`);return t};return{get(e,t){if(typeof t==`symbol`)return Reflect.get(e,t);if(!m(e,t))return f(e,t,a(e,t),r)},has(e,t){return Reflect.has(e,t)},ownKeys(e){return Reflect.ownKeys(e)},getOwnPropertyDescriptor(e,t){return p(e,t,r)},set(e,t,r){let a=i(t);if(n(a))throw TypeError(`SHADOW_STORE_RESERVED_KEY`);return l(e,a,c(r)),!0},deleteProperty(e,n){return t(e,i(n))},defineProperty(e,t){throw TypeError(`SHADOW_STORE_DEFINE_PROPERTY`)},setPrototypeOf(){throw TypeError(`SHADOW_STORE_PROTOTYPE`)},preventExtensions(){throw TypeError(`SHADOW_STORE_NON_EXTENSIBLE`)}}}function v(t){let n=i(t);if(n.proxy===null){let r=new Proxy(t,g);e.set(r,t),n.proxy=r}return n.proxy}function y(t,n){let r=n.drafts.get(t);if(r!==void 0)return r;let i=new Proxy(t,n.handler);return e.set(i,t),n.drafts.set(t,i),i}export{u as Transaction,y as draftOf,v as readProxyOf};
|
|
2
|
+
//# sourceMappingURL=proxies.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"proxies.js","names":["Transaction","label","draftHandler","readOnly","key","childOf","isWrappable","value","target","descriptor","wrap","describeChild","hidesPrototype","hasGetter","object","READ_HANDLER","trackProperty","nodeOf","receiver","readRaw","readProxyOf","trackKeys","draftOf","raw","tx","writable","name","isReservedKey","writeRaw","unwrapValue","deleteRaw","node","proxy","RAW","existing"],"sources":["../../../src/store/proxies.ts"],"sourcesContent":["import {\n deleteRaw,\n isReservedKey,\n isWrappable,\n nodeOf,\n RAW,\n readRaw,\n trackKeys,\n trackProperty,\n unwrapValue,\n writeRaw,\n} from \"./nodes\";\n\n/**\n * One `setStore` call. Drafts made for it are cached here, so a draft object keeps its identity\n * inside the update, and they stop accepting writes when the call returns.\n */\nexport class Transaction {\n readonly label: string;\n open: boolean;\n readonly drafts: Map<object, object>;\n readonly handler: ProxyHandler<object>;\n\n constructor(label: string) {\n this.label = label;\n this.open = true;\n this.drafts = new Map();\n this.handler = draftHandler(this);\n }\n}\n\nfunction readOnly(key: string | symbol): TypeError {\n const name = typeof key === \"symbol\" ? key.toString() : `\"${key}\"`;\n return new TypeError(\n __DEV__\n ? `ShadowStore: the store is read-only; ${name} can only be changed inside setStore((draft) => ...)`\n : \"SHADOW_STORE_READ_ONLY\",\n );\n}\n\n/**\n * Returns the value to hand out for `key`: a wrapped object when the value is an own, writable\n * wrappable slot, otherwise the raw value. Frozen slots must return the raw value because a proxy\n * may not report a different value for a non-writable, non-configurable property.\n */\nfunction childOf(\n target: object,\n key: string,\n value: unknown,\n wrap: (raw: object) => object,\n): unknown {\n if (!isWrappable(value) || !Object.hasOwn(target, key)) return value;\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (\n descriptor !== undefined &&\n descriptor.configurable === false &&\n descriptor.writable === false\n ) {\n return value;\n }\n return wrap(value);\n}\n\n/** Descriptor passthrough that wraps the value the same way `get` does. */\nfunction describeChild(\n target: object,\n key: string | symbol,\n wrap: (raw: object) => object,\n): PropertyDescriptor | undefined {\n const descriptor = Reflect.getOwnPropertyDescriptor(target, key);\n if (descriptor === undefined || typeof key === \"symbol\") return descriptor;\n if (descriptor.configurable === false) return descriptor;\n const value: unknown = descriptor.value;\n if (!isWrappable(value)) return descriptor;\n return { ...descriptor, value: wrap(value) };\n}\n\n/** `__proto__` is only reachable through the prototype chain, so the store never exposes it. */\nfunction hidesPrototype(target: object, key: string): boolean {\n return key === \"__proto__\" && !Object.hasOwn(target, key);\n}\n\n/** True when `key` resolves to an accessor property (own or inherited). */\nfunction hasGetter(target: object, key: string): boolean {\n for (\n let object: object | null = target;\n object !== null;\n object = Object.getPrototypeOf(object)\n ) {\n const descriptor = Reflect.getOwnPropertyDescriptor(object, key);\n if (descriptor !== undefined) return typeof descriptor.get === \"function\";\n }\n return false;\n}\n\n/** Read-only handler: every read subscribes the running computation to the property it touches. */\nconst READ_HANDLER: ProxyHandler<object> = {\n get(target, key, receiver) {\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n if (hidesPrototype(target, key)) return undefined;\n trackProperty(nodeOf(target), key);\n // A getter runs with the store view as `this`, so what it reads is tracked too.\n if (hasGetter(target, key)) return Reflect.get(target, key, receiver);\n return childOf(target, key, readRaw(target, key), readProxyOf);\n },\n has(target, key) {\n if (typeof key !== \"symbol\") trackProperty(nodeOf(target), key);\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n trackKeys(nodeOf(target));\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n return describeChild(target, key, readProxyOf);\n },\n set(_target, key) {\n throw readOnly(key);\n },\n deleteProperty(_target, key) {\n throw readOnly(key);\n },\n defineProperty(_target, key) {\n throw readOnly(key);\n },\n setPrototypeOf() {\n throw readOnly(\"[[Prototype]]\");\n },\n preventExtensions() {\n throw readOnly(\"[[Extensible]]\");\n },\n};\n\n/** Draft handler for one transaction: writes go through the notifying helpers. */\nfunction draftHandler(tx: Transaction): ProxyHandler<object> {\n const wrap = (raw: object): object => draftOf(raw, tx);\n /** Throws unless the draft is still inside its update and `key` is a string key. */\n const writable = (key: string | symbol): string => {\n if (!tx.open) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): a draft was used after its setStore() call returned; write only inside the update`\n : \"SHADOW_STORE_DRAFT_STALE\",\n );\n }\n if (typeof key === \"symbol\") {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): symbol keys cannot be written`\n : \"SHADOW_STORE_SYMBOL_KEY\",\n );\n }\n return key;\n };\n return {\n get(target, key) {\n if (typeof key === \"symbol\") return Reflect.get(target, key);\n if (hidesPrototype(target, key)) return undefined;\n return childOf(target, key, readRaw(target, key), wrap);\n },\n has(target, key) {\n return Reflect.has(target, key);\n },\n ownKeys(target) {\n return Reflect.ownKeys(target);\n },\n getOwnPropertyDescriptor(target, key) {\n return describeChild(target, key, wrap);\n },\n set(target, key, value) {\n const name = writable(key);\n if (isReservedKey(name)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): \"${name}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n writeRaw(target, name, unwrapValue(value));\n return true;\n },\n deleteProperty(target, key) {\n return deleteRaw(target, writable(key));\n },\n defineProperty(_target, key) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): defineProperty is not supported on drafts; assign the property instead (key \"${String(key)}\")`\n : \"SHADOW_STORE_DEFINE_PROPERTY\",\n );\n },\n setPrototypeOf() {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): drafts cannot change their prototype`\n : \"SHADOW_STORE_PROTOTYPE\",\n );\n },\n preventExtensions() {\n throw new TypeError(\n __DEV__\n ? `ShadowStore (${tx.label}): drafts cannot be made non-extensible`\n : \"SHADOW_STORE_NON_EXTENSIBLE\",\n );\n },\n };\n}\n\n/** Returns the read-only proxy of a raw object. The same raw object always yields the same proxy. */\nexport function readProxyOf(raw: object): object {\n const node = nodeOf(raw);\n if (node.proxy === null) {\n const proxy = new Proxy(raw, READ_HANDLER);\n RAW.set(proxy, raw);\n node.proxy = proxy;\n }\n return node.proxy;\n}\n\n/** Returns the draft proxy of a raw object for one transaction. */\nexport function draftOf(raw: object, tx: Transaction): object {\n const existing = tx.drafts.get(raw);\n if (existing !== undefined) return existing;\n const proxy = new Proxy(raw, tx.handler);\n RAW.set(proxy, raw);\n tx.drafts.set(raw, proxy);\n return proxy;\n}\n"],"mappings":"A,8KAiBA,IAAaA,EAAb,KAAyB,CACvB,MACA,KACA,OACA,QAEA,YAAY,EAAe,CACzB,KAAK,MAAQC,EACb,KAAK,KAAO,GACZ,KAAK,uBAAS,IAAI,IAClB,KAAK,QAAUC,EAAa,IAAI,CAClC,CACF,EAEA,SAASC,EAAS,EAAiC,CAEjD,OADa,OAAOC,GAAQ,SAAWA,EA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QJ,EAAKM,CAAI,CACxC,EACA,IAAI,EAAQ,EAAK,EAAO,CACtB,IAAMgB,EAAOD,EAASrB,CAAG,EACzB,GAAIuB,EAAcD,CAAI,EACpB,MAAU,UAGJ,2BACN,EAGF,OADAE,EAASpB,EAAQkB,EAAMG,EAAYtB,CAAK,CAAC,EAClC,EACT,EACA,eAAe,EAAQ,EAAK,CAC1B,OAAOuB,EAAUtB,EAAQiB,EAASrB,CAAG,CAAC,CACxC,EACA,eAAe,EAAS,EAAK,CAC3B,MAAU,UAGJ,8BACN,CACF,EACA,gBAAiB,CACf,MAAU,UAGJ,wBACN,CACF,EACA,mBAAoB,CAClB,MAAU,UAGJ,6BACN,CACF,CACF,CACF,CAGA,SAAgBgB,EAAY,EAAqB,CAC/C,IAAMW,EAAOd,EAAOM,CAAG,EACvB,GAAIQ,EAAK,QAAU,KAAM,CACvB,IAAMC,EAAQ,IAAI,MAAMT,EAAKR,CAAY,EACzCkB,EAAI,IAAID,EAAOT,CAAG,EAClB,EAAK,MAAQS,CACf,CACA,OAAOD,EAAK,KACd,CAGA,SAAgBT,EAAQ,EAAa,EAAyB,CAC5D,IAAMY,EAAWV,EAAG,OAAO,IAAID,CAAG,EAClC,GAAIW,IAAa,IAAA,GAAW,OAAOA,EACnC,IAAMF,EAAQ,IAAI,MAAMT,EAAKC,EAAG,OAAO,EAGvC,OAFAS,EAAI,IAAID,EAAOT,CAAG,EAClBC,EAAG,OAAO,IAAID,EAAKS,CAAK,EACjBA,CACT,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{isReservedKey as e,isWrappable as t,readRaw as n,unwrapValue as r}from"./nodes.js";function i(e){return r(e)}function a(e){return Array.isArray(e)?Array(e.length):{}}function o(i){let o=r(i);if(!t(o))return o;let s=/* @__PURE__ */ new Map,c=a(o);s.set(o,c);let l=[o];for(let i=l.pop();i!==void 0;i=l.pop()){let o=s.get(i);if(o!==void 0)for(let c of Object.keys(i)){if(e(c))continue;let u=r(n(i,c));if(t(u)){let e=s.get(u);e===void 0&&(e=a(u),s.set(u,e),l.push(u)),Reflect.set(o,c,e)}else Reflect.set(o,c,u)}}return c}export{o as snapshot,i as unwrap};
|
|
2
|
+
//# sourceMappingURL=read.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"read.js","names":["unwrap","unwrapValue","store","shellOf","value","snapshot","root","isWrappable","copies","out","pending","source","copy","key","isReservedKey","readRaw","child"],"sources":["../../../src/store/read.ts"],"sourcesContent":["import { isReservedKey, isWrappable, readRaw, unwrapValue } from \"./nodes\";\nimport type { Mutable, Store } from \"./types\";\n\n/**\n * Returns the raw data behind a store. Reads and writes on the result bypass tracking and\n * notification, so writing to it is a bug; use it for identity checks and passing data on.\n *\n * @param store A store view. A value that is not a store view is returned as is.\n * @returns The underlying object, without proxies. It is the live data, not a copy.\n * @example\n * import { unwrap, useStore } from \"@shadow-js/core\";\n *\n * const initial = { items: [1, 2, 3] };\n * const [list] = useStore(initial);\n * console.log(unwrap(list) === initial); // true: the store wraps its data in place\n * @see snapshot\n * @since 1.0.0\n */\nexport function unwrap<T>(store: Store<T>): Mutable<T> {\n return unwrapValue(store) as Mutable<T>;\n}\n\n/** A new, empty container of the same kind as `value`, with the same length for arrays. */\nfunction shellOf(value: object): object {\n return Array.isArray(value) ? new Array<unknown>((value as unknown[]).length) : {};\n}\n\n/**\n * Returns a deep plain copy of a store's current data. It reads raw data directly, so it does\n * not subscribe the running computation, and the copy is independent of later writes. Cycles and\n * shared objects are preserved. The walk is iterative, so deep data cannot overflow the stack. Use\n * it to serialize a store, send it to a server or keep an undo history.\n *\n * @param store A store view. A value that is not plain data is returned as is.\n * @returns A plain, untracked deep copy.\n * @example\n * import { snapshot, useStore } from \"@shadow-js/core\";\n *\n * const [form, setForm] = useStore({ name: \"Ada\", tags: [\"admin\"] });\n * const saved = snapshot(form);\n * setForm({ name: \"Grace\" });\n * console.log(saved.name, JSON.stringify(saved)); // Ada {\"name\":\"Ada\",\"tags\":[\"admin\"]}\n * @see unwrap\n * @since 1.0.0\n */\nexport function snapshot<T>(store: Store<T>): Mutable<T> {\n const root = unwrapValue(store);\n if (!isWrappable(root)) return root as Mutable<T>;\n const copies = new Map<object, object>();\n const out: object = shellOf(root);\n copies.set(root, out);\n const pending: object[] = [root];\n for (let source = pending.pop(); source !== undefined; source = pending.pop()) {\n const copy = copies.get(source);\n if (copy === undefined) continue;\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) continue;\n const value = unwrapValue(readRaw(source, key));\n if (isWrappable(value)) {\n let child = copies.get(value);\n if (child === undefined) {\n child = shellOf(value);\n copies.set(value, child);\n pending.push(value);\n }\n Reflect.set(copy, key, child);\n } else {\n Reflect.set(copy, key, value);\n }\n }\n }\n return out as Mutable<T>;\n}\n"],"mappings":"A,0FAkBA,SAAgBA,EAAU,EAA6B,CACrD,OAAOC,EAAYC,CAAK,CAC1B,CAGA,SAASC,EAAQ,EAAuB,CACtC,OAAO,MAAM,QAAQC,CAAK,EAAQ,MAAgBA,EAAoB,MAAM,EAAI,CAAC,CACnF,CAoBA,SAAgBC,EAAY,EAA6B,CACvD,IAAMC,EAAOL,EAAYC,CAAK,EAC9B,GAAI,CAACK,EAAYD,CAAI,EAAG,OAAOA,EAC/B,IAAME,kBAAS,IAAI,IACbC,EAAcN,EAAQG,CAAI,EAChCE,EAAO,IAAIF,EAAMG,CAAG,EACpB,IAAMC,EAAoB,CAACJ,CAAI,EAC/B,IAAK,IAAIK,EAASD,EAAQ,IAAI,EAAGC,IAAW,IAAA,GAAW,EAASD,EAAQ,IAAI,EAAG,CAC7E,IAAME,EAAOJ,EAAO,IAAIG,CAAM,EAC9B,GAAIC,IAAS,IAAA,GACb,IAAK,IAAMC,KAAO,OAAO,KAAKF,CAAM,EAAG,CACrC,GAAIG,EAAcD,CAAG,EAAG,SACxB,IAAMT,EAAQH,EAAYc,EAAQJ,EAAQE,CAAG,CAAC,EAC9C,GAAIN,EAAYH,CAAK,EAAG,CACtB,IAAIY,EAAQR,EAAO,IAAIJ,CAAK,EACxBY,IAAU,IAAA,KACZ,EAAQb,EAAQC,CAAK,EACrBI,EAAO,IAAIJ,EAAOY,CAAK,EACvBN,EAAQ,KAAKN,CAAK,GAEpB,QAAQ,IAAIQ,EAAMC,EAAKG,CAAK,CAC9B,MACE,QAAQ,IAAIJ,EAAMC,EAAKT,CAAK,CAEhC,CACF,CACA,OAAOK,CACT,C"}
|
|
@@ -0,0 +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)),!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)}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
|
+
//# sourceMappingURL=reconcile.js.map
|
|
@@ -0,0 +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,C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CC,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"}
|
|
@@ -0,0 +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{applyReconcile as o,reconcile as s,specOf as c}from"./reconcile.js";import{Transaction as l,draftOf as u,readProxyOf as d}from"./proxies.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,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))i.push(...t);else if(typeof t==`object`&&t)i.push(...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))i.push(...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 h(e,t,n){let r=t[t.length-1],s=t.slice(0,-1),l=(e,t)=>{for(let u of m(e,s[t],n)){let d=e;if(t===s.length-1){let e=d[u],t=typeof r==`function`?c(r):void 0;if(t!==void 0){i(e)?o(a(e),t,n):d[u]=t.next;continue}let s=typeof r==`function`?r(e):r;f(s)&&i(e)&&!Array.isArray(e)?g(e,s,n):d[u]=s}else{let e=d[u];if(!i(e))throw TypeError(`SHADOW_STORE_PATH_VALUE`);l(e,t+1)}}};l(e,0)}function g(e,t,n){for(let n of Object.keys(t)){if(r(n))throw TypeError(`SHADOW_STORE_ASSIGN_KEY`);e[n]=t[n]}}function _(n,r){let i=a(n);return[d(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 l(r);try{h(u(i,e),n,r)}finally{e.open=!1}}else if(typeof a==`function`){let e=c(a);if(e!==void 0){o(i,e,r);return}let t=new l(r),n;try{n=a(u(i,t))}finally{t.open=!1}n!==void 0&&v(i,n,r)}else v(i,a,r)}))}]}function v(e,t,n){if(Array.isArray(e)){if(!Array.isArray(t))throw TypeError(`SHADOW_STORE_ARRAY_UPDATE`);let r=c(s(t));r!==void 0&&o(e,r,n);return}if(!f(t))throw TypeError(`SHADOW_STORE_UPDATE_ARGUMENT`);let r=new l(n);try{g(u(e,r),t,n)}finally{r.open=!1}}function y(e,t){let r=t?.name===void 0?``:` (${t.name})`,o=a(e);if(i(o))return _(o,r);let[s,c]=n(b(e),t?.name===void 0?void 0:{name:t.name});return[s,e=>c(typeof e==`function`?t=>b(e(t)):b(e))]}function b(e){let t=a(e);return i(t)?d(t):e}export{y as useStore};
|
|
2
|
+
//# sourceMappingURL=use-store.js.map
|
|
@@ -0,0 +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 * @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,EAAS,EAAgB,EAAe,EAAuC,CACtF,IAAMF,EAA+B,CAAC,EACtC,GAAI,MAAM,QAAQG,CAAM,EAAG,CACzB,GAAI,OAAOC,GAAS,SAAUJ,EAAK,KAAKI,CAAI,OACvC,GAAI,OAAOA,GAAS,WAAY,CACnC,IAAMC,EAASD,EACf,IAAK,IAAIH,EAAI,EAAGA,EAAIE,EAAO,OAAQ,GAAK,EAAOE,EAAOF,EAAOF,GAAIA,CAAC,GAAGD,EAAK,KAAKC,CAAC,CAClF,MAAO,GAAI,MAAM,QAAQG,CAAI,EAA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EAEF,IAAMwB,EAAOC,EAAOqB,EAAU9C,CAAK,CAAC,EAChCwB,IAAS,IAAA,IAAWG,EAAeK,EAAMR,EAAMH,CAAK,EACxD,MACF,CACA,GAAI,CAACtB,EAAcC,CAAK,EACtB,MAAU,UAGJ,8BACN,EAEF,IAAMyC,EAAK,IAAIC,EAAYrB,CAAK,EAChC,GAAI,CACFS,EAAUa,EAAQX,EAAMS,CAAE,EAA8BzC,EAAOqB,CAAK,CACtE,QAAU,CACR,EAAG,KAAO,EACZ,CACF,CA+CA,SAAgB0B,EAAS,EAAkB,EAAiC,CAC1E,IAAM1B,EAAQ2B,GAAS,OAAS,IAAA,GAAY,GAAK,KAAKA,EAAQ,KAAK,GAC7DhB,EAAOJ,EAAYO,CAAO,EAChC,GAAIT,EAAYM,CAAI,EAAG,OAAOE,EAAgBF,EAAMX,CAAK,EAGzD,GAAM,CAAC4B,EAAMC,GAASC,EACpBC,EAASjB,CAAO,EAChBa,GAAS,OAAS,IAAA,GAAY,IAAA,GAAY,CAAE,KAAMA,EAAQ,IAAK,CACjE,EAOA,MAAO,CAACC,EANK,GACXC,EACE,OAAOrB,GAAS,WACX,GAAsBuB,EAAUvB,EAAwCN,CAAQ,CAAC,EAClF6B,EAASvB,CAAI,CACnB,CACe,CACnB,CAGA,SAASuB,EAAS,EAAyB,CACzC,IAAMC,EAAMzB,EAAY5B,CAAK,EAC7B,OAAO0B,EAAY2B,CAAG,EAAIjB,EAAYiB,CAAG,EAAIrD,CAC/C,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"suspense.js","names":["SuspenseContext","ResourceCacheContext"],"sources":["../../src/suspense.ts"],"sourcesContent":["import { type Context, createContext } from \"./context\";\n\n/**\n * Counter protocol between asynchronous sources and the nearest `<Suspense>` boundary.\n * A source calls `increment()` when it starts blocking its readers and `decrement()` exactly once\n * when it settles.\n * @since 1.0.0\n */\nexport interface SuspenseTracker {\n /**\n * Records one more pending source. The boundary shows its fallback while the count is above\n * zero; call it once per source, the first time a reader sees that source pending.\n */\n increment(): void;\n /**\n * Records that one pending source settled (with a value or an error). Call it exactly once per\n * `increment()`; when the count returns to zero the boundary shows its content again.\n */\n decrement(): void;\n /**\n * Called when a transition reads pending data in this boundary. Returns true when the boundary keeps\n * its content meanwhile: the reader then throws the suspension and keeps its previous value until\n * the boundary releases it. Returns false (or is absent) to show the fallback as usual.\n * @default undefined (the boundary never holds its content: the fallback shows as usual)\n */\n hold?(): boolean;\n}\n\n/**\n * The context through which an asynchronous source finds the nearest `<Suspense>` boundary. Each\n * boundary provides its {@link SuspenseTracker}; the value is `null` outside any boundary. Read it\n * when building a data primitive that should hold the boundary while it loads, as `useResource`\n * does.\n *\n * @example\n * import { SuspenseContext, useContext } from \"@shadow-js/core\";\n *\n * function useLoadingHold(promise: Promise<unknown>): void {\n * const tracker = useContext(SuspenseContext); // null outside any <Suspense>\n * if (tracker === null) return;\n * tracker.increment(); // the boundary shows its fallback\n * promise.finally(() => tracker.decrement());\n * }\n * @see useResource\n * @since 1.0.0\n */\nexport const SuspenseContext: Context<SuspenseTracker | null> =\n /* @__PURE__ */ createContext<SuspenseTracker | null>(null, { name: \"Suspense\" });\n\n/**\n * Bridge between resources and the server/hydration runtime. During server rendering it collects\n * in-flight fetches and replays finished ones on the next pass; during hydration it serves the\n * values the server already fetched, so the client does not fetch them again.\n * @since 1.0.0\n */\nexport interface ResourceCache {\n /**\n * Deterministic key for a resource created at this point of the render. `explicit` is the\n * resource's `key` option, or `undefined` when it has none.\n */\n key(explicit: string | undefined): string;\n /** A cached value, wrapped so that `undefined` values are representable. */\n read(key: string): { value: unknown } | undefined;\n /**\n * A fetch started; the cache stores its value under `key` when it resolves. `options.deferStream` is\n * true for a resource that holds the first streamed flush (see `ResourceOptions.deferStream`).\n */\n track(key: string, promise: Promise<unknown>, options?: ResourceTrackOptions): void;\n /**\n * The fetch an earlier pass of the same render started for `key` and that has not settled, when there\n * is one. A resource that finds it waits for that fetch instead of starting another, so a pass that\n * renders again does not fetch twice. Optional: a cache that does not keep earlier fetches omits it.\n */\n pending?(key: string): Promise<unknown> | undefined;\n}\n\n/** What {@link ResourceCache.track} is told about a fetch. @since 1.0.0 */\nexport interface ResourceTrackOptions {\n /** True when the resource was created with `deferStream: true`. */\n readonly deferStream?: boolean | undefined;\n}\n\n/**\n * The context through which `useResource` reaches the renderer's {@link ResourceCache}. Server\n * renderers and hydration provide it; the value is `null` when resources should always fetch. Only\n * a custom renderer needs to provide it.\n *\n * @example\n * import { type ResourceCache, ResourceCacheContext } from \"@shadow-js/core\";\n *\n * const values = new Map<string, unknown>();\n * let created = 0;\n * const cache: ResourceCache = {\n * key: (explicit) => explicit ?? `resource-${created++}`,\n * read: (key) => (values.has(key) ? { value: values.get(key) } : undefined),\n * track: (key, promise) => void promise.then((value) => values.set(key, value)),\n * };\n * const page = <ResourceCacheContext value={cache}><p>Loading data</p></ResourceCacheContext>;\n * @see useResource\n * @since 1.0.0\n */\nexport const ResourceCacheContext: Context<ResourceCache | null> =\n /* @__PURE__ */ createContext<ResourceCache | null>(null, { name: \"ResourceCache\" });\n"],"mappings":"A,6CA8CA,MAAaA,EACK,kBAAsC,KAAM,CAAE,KAAM,UAAW,CAAC,EAsDrEC,EACK,kBAAoC,KAAM,CAAE,KAAM,eAAgB,CAAC,E"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{untrack as e}from"./ownership.js";import{useSignal as t}from"./signal.js";import{registerTransitionLane as n,startTransition as r}from"./internal/concurrency.js";import{createComputation as i}from"./extend/index.js";function a(){let[n,i]=t(!1),a=0;return[n,t=>{a+=1,e(()=>i(!0));let n;try{n=r(t)}catch(t){throw--a,a===0&&e(()=>i(!1)),t}return n.then(()=>{--a,a===0&&e(()=>i(!1))})}]}function o(r,a){n();let[o,s]=t(e(r),{equals:a?.equals??Object.is,...a?.name===void 0?{}:{name:a.name}});return i({kind:`effect`,fn:()=>r(),apply:e=>{s(()=>e)},lane:!0,name:a?.name??`useDeferredValue`}),o}export{o as useDeferredValue,a as useTransition};
|
|
2
|
+
//# sourceMappingURL=transitions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transitions.js","names":["useTransition","pending","setPending","useSignal","running","untrack","applied","startTransition","fn","error","useDeferredValue","registerTransitionLane","value","setValue","source","options","createComputation","next"],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":"A,+NAwDA,SAAgBA,GAAwE,CACtF,GAAM,CAACC,EAASC,GAAcC,EAAU,EAAK,EACzCC,EAAU,EAkBd,MAAO,CAACH,EAjBO,GAAkC,CAC/C,GAAW,EAEXI,MAAcH,EAAW,EAAI,CAAC,EAC9B,IAAII,EACJ,GAAI,CACF,EAAUC,EAAgBC,CAAE,CAC9B,OAASC,EAAO,CAGd,KAFA,IACIL,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,EAC5CO,CACR,CACA,OAAOH,EAAQ,SAAW,CACxB,IACIF,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,CACpD,CAAC,CACH,CACsB,CACxB,CA4BA,SAAgBQ,EACd,EACA,EACa,CAEbC,EAAuB,EACvB,GAAM,CAACC,EAAOC,GAAYV,EAAaE,EAAQS,CAAM,EAAG,CACtD,OAAQC,GAAS,QAAU,OAAO,GAClC,GAAIA,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAQ,IAAK,CAC9D,CAAC,EAYD,OATAC,EAAkB,CAChB,KAAM,SACN,OAAUF,EAAO,EACjB,MAAQ,GAAY,CAClBD,MAAeI,CAAI,CACrB,EACA,KAAM,GACN,KAAMF,GAAS,MAAQ,kBACzB,CAAC,EACMH,CACT,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";import{currentOwner as i}from"./extend/index.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=i(),[l,u]=r(s),[d,f]=r(!1),p=0;return[l,(...r)=>{p+=1;let i=p,s=n(l),d=e=>{i===p&&t(()=>{u(()=>e),f(!1)})},m=t=>{if(i===p){if(f(!1),c===null)throw t;e(t,c)}},h;try{h=n(()=>o(s,...r))}catch(e){return c===null?(i===p&&f(!1),Promise.reject(e)):(m(e),Promise.resolve())}return a(h)?(f(!0),Promise.resolve(h).then(d,m)):(d(h),Promise.resolve())},d]}export{o as useAction};
|
|
2
|
+
//# sourceMappingURL=action.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"action.js","names":["isPromiseLike","value","useAction","owner","currentOwner","state","setState","useSignal","initialState","pending","setPending","latest","args","id","previous","untrack","commit","batch","fail","error","handleError","result","action"],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n if (id !== latest) return;\n setPending(false);\n if (owner === null) throw error;\n handleError(error, owner);\n };\n let result: S | PromiseLike<S>;\n try {\n result = untrack(() => action(previous, ...args));\n } catch (error) {\n if (owner === null) {\n // `fail` would rethrow synchronously; without an owner the promise carries the error.\n if (id === latest) setPending(false);\n return Promise.reject(error);\n }\n fail(error);\n return Promise.resolve();\n }\n if (!isPromiseLike<S>(result)) {\n commit(result);\n return Promise.resolve();\n }\n setPending(true);\n return Promise.resolve(result).then(commit, fail);\n };\n return [state, dispatch, pending];\n}\n"],"mappings":"A,oOAIA,SAASA,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiCA,SAAgBC,EACd,EACA,EAC2F,CAC3F,IAAMC,EAAQC,EAAa,EACrB,CAACC,EAAOC,GAAYC,EAAaC,CAAY,EAC7C,CAACC,EAASC,GAAcH,EAAU,EAAK,EACzCI,EAAS,EAsCb,MAAO,CAACN,GApCU,GAAGO,IAA2B,CAC9C,GAAU,EACV,IAAMC,EAAKF,EACLG,EAAWC,EAAQV,CAAK,EACxBW,EAAU,GAAmB,CAC7BH,IAAOF,GACXM,MAAY,CACVX,MAAeL,CAAK,EACpBS,EAAW,EAAK,CAClB,CAAC,CACH,EACMQ,EAAQ,GAAyB,CACrC,GAAIL,IAAOF,EACX,CACA,GADAD,EAAW,EAAK,EACZP,IAAU,KAAM,MAAMgB,EAC1BC,EAAYD,EAAOhB,CAAK,CAFR,CAGlB,EACIkB,EACJ,GAAI,CACF,EAASN,MAAcO,EAAOR,EAAU,GAAGF,CAAI,CAAC,CAClD,OAASO,EAAO,CAOd,OANIhB,IAAU,MAERU,IAAOF,GAAQD,EAAW,EAAK,EAC5B,QAAQ,OAAOS,CAAK,IAE7BD,EAAKC,CAAK,EACH,QAAQ,QAAQ,EACzB,CAMA,OALKnB,EAAiBqB,CAAM,GAI5BX,EAAW,EAAI,EACR,QAAQ,QAAQW,CAAM,CAAC,CAAC,KAAKL,EAAQE,CAAI,IAJ9CF,EAAOK,CAAM,EACN,QAAQ,QAAQ,EAI3B,EACyBZ,CAAO,CAClC,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{currentOwner as e}from"./extend/index.js";function t(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 n(e){let t=e;for(;t!==null&&t.parent!==null;)t=t.parent;return t}function r(r,i){let a=i?.limit??100;if(!Number.isInteger(a)||a<1)throw RangeError(`SHADOW_CACHE_LIMIT`);let o=/* @__PURE__ */ new WeakMap;return(...i)=>{let s=n(e());if(s===null)return r(...i);let c=o.get(s);c===void 0&&(c=[],o.set(s,c));for(let e of c)if(t(e.args,i))return e.value;let l=r(...i);return c.push({args:i,value:l}),c.length>a&&c.shift(),l}}export{r as cache};
|
|
2
|
+
//# sourceMappingURL=cache.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.js","names":["sameArgs","a","b","i","rootOf","root","owner","cache","limit","options","scopes","args","currentOwner","fn","entries","entry","value"],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return fn(...args);\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = fn(...args);\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":"A,iDAgBA,SAASA,EAAS,EAAuB,EAAgC,CACvE,GAAIC,EAAE,SAAWC,EAAE,OAAQ,MAAO,GAClC,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAE,OAAQ,GAAK,EACjC,GAAI,CAAC,OAAO,GAAGA,EAAEE,GAAID,EAAEC,EAAE,EAAG,MAAO,GAErC,MAAO,EACT,CAGA,SAASC,EAAO,EAAmC,CACjD,IAAIC,EAAOC,EACX,KAAOD,IAAS,MAAQA,EAAK,SAAW,MAAM,EAAOA,EAAK,OAC1D,OAAOA,CACT,CAyBA,SAAgBE,EACd,EACA,EACmB,CACnB,IAAMC,EAAQC,GAAS,OAAS,IAChC,GAAI,CAAC,OAAO,UAAUD,CAAK,GAAKA,EAAQ,EACtC,MAAU,WAC8C,oBACxD,EAEF,IAAME,kBAAS,IAAI,QACnB,OAAQ,GAAGC,IAAe,CACxB,IAAMN,EAAOD,EAAOQ,EAAa,CAAC,EAClC,GAAIP,IAAS,KAAM,OAAOQ,EAAG,GAAGF,CAAI,EACpC,IAAIG,EAAUJ,EAAO,IAAIL,CAAI,EACzBS,IAAY,IAAA,KACd,EAAU,CAAC,EACXJ,EAAO,IAAIL,EAAMS,CAAO,GAE1B,IAAK,IAAMC,KAASD,EAClB,GAAId,EAASe,EAAM,KAAMJ,CAAI,EAAG,OAAOI,EAAM,MAE/C,IAAMC,EAAQH,EAAG,GAAGF,CAAI,EAGxB,OAFAG,EAAQ,KAAK,CAAE,OAAM,OAAM,CAAC,EACxBA,EAAQ,OAASN,GAAOM,EAAQ,MAAM,EACnCE,CACT,CACF,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ShadowError as e}from"./internal/diagnostics.js";import{Owner as t}from"./internal/owner.js";import{runWithOwner as n}from"./ownership.js";import{currentOwner as r}from"./extend/index.js";function i(e,i){let a=Symbol(i?.name??`context`),o=e=>{let i=new t(r()),o=i.context,s=Object.create(o);return s[a]=e.value,i.context=s,n(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(r()),s=Object.create(o.context);return s[e.id]=i,o.context=s,n(o,a)}function o(t){let n=r()?.context;if(n!=null&&t.id in n)return n[t.id];if(t.defaultValue===void 0)throw new e(`CONTEXT_MISSING`);return t.defaultValue}export{i as createContext,a as runWithContext,o as useContext};
|
|
2
|
+
//# sourceMappingURL=context.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.js","names":["createContext","id","options","provider","scope","Owner","currentOwner","inherited","next","props","runWithOwner","built","runWithContext","context","value","fn","useContext","map","ShadowError"],"sources":["../../src/context.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { currentOwner, Owner, ShadowError } from \"./extend\";\nimport { runWithOwner } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * A context made by {@link createContext}: a value that a subtree receives from the nearest provider\n * above it. The context is itself the provider component; `Provider` is the same function.\n * @since 1.0.0\n */\nexport interface Context<T> {\n /**\n * Renders `children` with `value` provided. The value is read once, when the provider is created;\n * provide an accessor or a store for a value that changes. Returns an accessor of the children.\n */\n (props: { value: T; children?: unknown }): unknown;\n /** The unique key the provided value is stored under, described by the context's `name`. */\n readonly id: symbol;\n /** The value {@link useContext} returns without a provider. `undefined` means none: it throws. */\n readonly defaultValue: T | undefined;\n /** The same component, for code written as `<Ctx.Provider value={...}>`. */\n readonly Provider: (props: { value: T; children?: unknown }) => unknown;\n}\n\n/**\n * Options of {@link createContext}.\n * @since 1.0.0\n */\nexport interface ContextOptions {\n /**\n * Label shown in diagnostics and used as the description of the context's `id` symbol.\n * @default \"context\"\n */\n name?: string;\n}\n\n/**\n * Creates a context: a value that components read with {@link useContext} without passing it\n * through props. Render the returned component around a subtree to provide a value. The value is\n * read once; pass a signal accessor or a store to provide something reactive. On the server the\n * provider builds its subtree once.\n *\n * @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined\n * (or omitted) means the context has no default, so reading it without a provider throws.\n * @param options A diagnostics name. Undefined uses the default.\n * @returns The context, which is also its provider component.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n *\n * const Theme = createContext<\"light\" | \"dark\">(\"light\", { name: \"Theme\" });\n *\n * function Label() {\n * return <p>Theme: {useContext(Theme)}</p>;\n * }\n *\n * const app = <Theme.Provider value=\"dark\"><Label /></Theme.Provider>;\n * @see useContext\n * @since 1.0.0\n */\nexport function createContext<T>(defaultValue?: T, options?: ContextOptions): Context<T> {\n const id = Symbol(options?.name ?? \"context\");\n const provider = (props: { value: T; children?: unknown }): unknown => {\n const scope = new Owner(currentOwner());\n const inherited = scope.context;\n const next = Object.create(inherited) as Record<symbol, unknown>;\n next[id] = props.value;\n scope.context = next;\n // A render effect, so a children expression that reads signals stays reactive and still sees\n // the provided value. An effect (not a memo) because component setup may legitimately write\n // signals, and errors thrown while building the subtree must reach the error boundaries.\n return runWithOwner(scope, () => {\n if (__SERVER__) {\n // Nothing is reactive on the server: build the subtree once.\n const built = props.children;\n return () => built;\n }\n const [children, setChildren] = useSignal<unknown>(undefined, { equals: false });\n useRenderEffect(\n () => props.children,\n (value) => {\n setChildren(() => value);\n },\n );\n return children;\n });\n };\n return Object.assign(provider, { id, defaultValue, Provider: provider }) as Context<T>;\n}\n\n/**\n * Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the\n * value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer\n * builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new\n * child owner of the current owner that is disposed with it.\n *\n * @param context The context to provide.\n * @param value The value `useContext(context)` returns inside `fn`.\n * @param fn Runs once, synchronously.\n * @returns What `fn` returns.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n * import { runWithContext } from \"@shadow-js/core/extend\";\n *\n * const Theme = createContext(\"light\");\n * const theme = runWithContext(Theme, \"dark\", () => useContext(Theme));\n * console.log(theme); // \"dark\"\n * @see createContext\n * @since 1.0.0\n */\nexport function runWithContext<T, R>(context: Context<T>, value: T, fn: () => R): R {\n const scope = new Owner(currentOwner());\n const next = Object.create(scope.context) as Record<symbol, unknown>;\n next[context.id] = value;\n scope.context = next;\n return runWithOwner(scope, fn);\n}\n\n/**\n * Reads the nearest provided value of `context`. Falls back to its default; throws when there is\n * neither a provider nor a default, because no correct value exists. The lookup follows the current\n * owner, so call it while a component runs (or in an effect or memo it creates), not after an\n * `await` or in an event handler. The read is not tracked.\n *\n * @param context A context made by {@link createContext}.\n * @returns The value of the nearest provider above the current owner, else the default value.\n * @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the\n * context's default is `undefined`.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n *\n * const User = createContext<{ name: string }>();\n *\n * function Greeting() {\n * const user = useContext(User); // throws CONTEXT_MISSING without a provider\n * return <p>Hello, {user.name}</p>;\n * }\n * @see createContext\n * @since 1.0.0\n */\nexport function useContext<T>(context: Context<T>): T {\n const map = currentOwner()?.context;\n if (map !== null && map !== undefined && context.id in map) return map[context.id] as T;\n if (context.defaultValue === undefined) throw new ShadowError(\"CONTEXT_MISSING\");\n return context.defaultValue;\n}\n"],"mappings":"A,mMA2DA,SAAgBA,EAAiB,EAAkB,EAAsC,CACvF,IAAMC,EAAK,OAAOC,GAAS,MAAQ,SAAS,EACtCC,EAAY,GAAqD,CACrE,IAAMC,EAAQ,IAAIC,EAAMC,EAAa,CAAC,EAChCC,EAAYH,EAAM,QAClBI,EAAO,OAAO,OAAOD,CAAS,EAMpC,MALA,GAAKN,GAAMQ,EAAM,MACjB,EAAM,QAAUD,EAITE,EAAaN,MAAa,CACf,CAEd,IAAMO,EAAQF,EAAM,SACpB,UAAaE,CACf,CASF,CAAC,CACH,EACA,OAAO,OAAO,OAAOR,EAAU,CAAE,KAAI,eAAc,SAAUA,CAAS,CAAC,CACzE,CAsBA,SAAgBS,EAAqB,EAAqB,EAAU,EAAgB,CAClF,IAAMR,EAAQ,IAAIC,EAAMC,EAAa,CAAC,EAChCE,EAAO,OAAO,OAAOJ,EAAM,OAAO,EAGxC,MAFA,GAAKS,EAAQ,IAAMC,EACnB,EAAM,QAAUN,EACTE,EAAaN,EAAOW,CAAE,CAC/B,CAwBA,SAAgBC,EAAc,EAAwB,CACpD,IAAMC,EAAMX,EAAa,CAAC,EAAE,QAC5B,GAAIW,GAAQ,MAA6BJ,EAAQ,MAAMI,EAAK,OAAOA,EAAIJ,EAAQ,IAC/E,GAAIA,EAAQ,eAAiB,IAAA,GAAW,MAAM,IAAIK,EAAY,iBAAiB,EAC/E,OAAOL,EAAQ,YACjB,C"}
|