@shadow-js/core 0.1.0 → 1.0.0
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 +11 -0
- package/LICENSE +2 -2
- package/README.md +134 -331
- package/dist/dev/action.d.ts +36 -0
- package/dist/dev/action.js +90 -0
- package/dist/dev/action.js.map +1 -0
- package/dist/dev/cache.d.ts +35 -0
- package/dist/dev/cache.js +62 -0
- package/dist/dev/cache.js.map +1 -0
- package/dist/dev/context.d.ts +106 -0
- package/dist/dev/context.js +111 -0
- package/dist/dev/context.js.map +1 -0
- package/dist/dev/effect.d.ts +122 -0
- package/dist/dev/effect.js +111 -0
- package/dist/dev/effect.js.map +1 -0
- package/dist/dev/env.d.ts +29 -0
- package/dist/dev/env.js +31 -0
- package/dist/dev/env.js.map +1 -0
- package/dist/dev/events.d.ts +28 -0
- package/dist/dev/events.js +33 -0
- package/dist/dev/events.js.map +1 -0
- package/dist/dev/extend/index.d.ts +331 -0
- package/dist/dev/extend/index.js +317 -0
- package/dist/dev/extend/index.js.map +1 -0
- package/dist/dev/external-store.d.ts +60 -0
- package/dist/dev/external-store.js +60 -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 +213 -0
- package/dist/dev/internal/concurrency.js +632 -0
- package/dist/dev/internal/concurrency.js.map +1 -0
- package/dist/dev/internal/devtools.d.ts +71 -0
- package/dist/dev/internal/devtools.js +77 -0
- package/dist/dev/internal/devtools.js.map +1 -0
- package/dist/dev/internal/diagnostics.d.ts +90 -0
- package/dist/dev/internal/diagnostics.js +102 -0
- package/dist/dev/internal/diagnostics.js.map +1 -0
- package/dist/dev/internal/dispose.d.ts +28 -0
- package/dist/dev/internal/dispose.js +49 -0
- package/dist/dev/internal/dispose.js.map +1 -0
- package/dist/dev/internal/flags.js +11 -0
- package/dist/dev/internal/flags.js.map +1 -0
- package/dist/dev/internal/graph.d.ts +233 -0
- package/dist/dev/internal/graph.js +578 -0
- package/dist/dev/internal/graph.js.map +1 -0
- package/dist/dev/internal/hydration-flag.d.ts +33 -0
- package/dist/dev/internal/hydration-flag.js +46 -0
- package/dist/dev/internal/hydration-flag.js.map +1 -0
- package/dist/dev/internal/messages.d.ts +56 -0
- package/dist/dev/internal/messages.js +54 -0
- package/dist/dev/internal/messages.js.map +1 -0
- package/dist/dev/internal/owner.d.ts +142 -0
- package/dist/dev/internal/owner.js +290 -0
- package/dist/dev/internal/owner.js.map +1 -0
- package/dist/dev/internal/queue.js +46 -0
- package/dist/dev/internal/queue.js.map +1 -0
- package/dist/dev/internal/scheduler.d.ts +113 -0
- package/dist/dev/internal/scheduler.js +287 -0
- package/dist/dev/internal/scheduler.js.map +1 -0
- package/dist/dev/internal/state.d.ts +141 -0
- package/dist/dev/internal/state.js +28 -0
- package/dist/dev/internal/state.js.map +1 -0
- package/dist/dev/internal/suspension.d.ts +43 -0
- package/dist/dev/internal/suspension.js +45 -0
- package/dist/dev/internal/suspension.js.map +1 -0
- package/dist/dev/internal/types.d.ts +46 -0
- package/dist/dev/list.d.ts +93 -0
- package/dist/dev/list.js +282 -0
- package/dist/dev/list.js.map +1 -0
- package/dist/dev/memo.d.ts +60 -0
- package/dist/dev/memo.js +41 -0
- package/dist/dev/memo.js.map +1 -0
- package/dist/dev/optimistic.d.ts +26 -0
- package/dist/dev/optimistic.js +45 -0
- package/dist/dev/optimistic.js.map +1 -0
- package/dist/dev/ownership.d.ts +204 -0
- package/dist/dev/ownership.js +261 -0
- package/dist/dev/ownership.js.map +1 -0
- package/dist/dev/props.d.ts +134 -0
- package/dist/dev/props.js +282 -0
- package/dist/dev/props.js.map +1 -0
- package/dist/dev/reaction.d.ts +29 -0
- package/dist/dev/reaction.js +61 -0
- package/dist/dev/reaction.js.map +1 -0
- package/dist/dev/reducer.d.ts +41 -0
- package/dist/dev/reducer.js +39 -0
- package/dist/dev/reducer.js.map +1 -0
- package/dist/dev/refs.d.ts +52 -0
- package/dist/dev/refs.js +58 -0
- package/dist/dev/refs.js.map +1 -0
- package/dist/dev/resource.d.ts +135 -0
- package/dist/dev/resource.js +177 -0
- package/dist/dev/resource.js.map +1 -0
- package/dist/dev/selector.d.ts +34 -0
- package/dist/dev/selector.js +118 -0
- package/dist/dev/selector.js.map +1 -0
- package/dist/dev/signal.d.ts +42 -0
- package/dist/dev/signal.js +39 -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 +192 -0
- package/dist/dev/store/nodes.js.map +1 -0
- package/dist/dev/store/proxies.js +160 -0
- package/dist/dev/store/proxies.js.map +1 -0
- package/dist/dev/store/read.d.ts +39 -0
- package/dist/dev/store/read.js +72 -0
- package/dist/dev/store/read.js.map +1 -0
- package/dist/dev/store/reconcile.d.ts +73 -0
- package/dist/dev/store/reconcile.js +186 -0
- package/dist/dev/store/reconcile.js.map +1 -0
- package/dist/dev/store/types.d.ts +106 -0
- package/dist/dev/store/use-store.d.ts +60 -0
- package/dist/dev/store/use-store.js +168 -0
- package/dist/dev/store/use-store.js.map +1 -0
- package/dist/dev/suspense.d.ts +101 -0
- package/dist/dev/suspense.js +45 -0
- package/dist/dev/suspense.js.map +1 -0
- package/dist/dev/transitions.d.ts +77 -0
- package/dist/dev/transitions.js +101 -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 +90 -0
- package/dist/server-dev/action.js.map +1 -0
- package/dist/server-dev/cache.js +62 -0
- package/dist/server-dev/cache.js.map +1 -0
- package/dist/server-dev/context.js +108 -0
- package/dist/server-dev/context.js.map +1 -0
- package/dist/server-dev/effect.js +56 -0
- package/dist/server-dev/effect.js.map +1 -0
- package/dist/server-dev/env.js +31 -0
- package/dist/server-dev/env.js.map +1 -0
- package/dist/server-dev/events.js +33 -0
- package/dist/server-dev/events.js.map +1 -0
- package/dist/server-dev/extend/index.js +317 -0
- package/dist/server-dev/extend/index.js.map +1 -0
- package/dist/server-dev/external-store.js +46 -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 +633 -0
- package/dist/server-dev/internal/concurrency.js.map +1 -0
- package/dist/server-dev/internal/devtools.js +77 -0
- package/dist/server-dev/internal/devtools.js.map +1 -0
- package/dist/server-dev/internal/diagnostics.js +102 -0
- package/dist/server-dev/internal/diagnostics.js.map +1 -0
- package/dist/server-dev/internal/dispose.js +49 -0
- package/dist/server-dev/internal/dispose.js.map +1 -0
- package/dist/server-dev/internal/flags.js +11 -0
- package/dist/server-dev/internal/flags.js.map +1 -0
- package/dist/server-dev/internal/graph.js +578 -0
- package/dist/server-dev/internal/graph.js.map +1 -0
- package/dist/server-dev/internal/hydration-flag.js +46 -0
- package/dist/server-dev/internal/hydration-flag.js.map +1 -0
- package/dist/server-dev/internal/messages.js +54 -0
- package/dist/server-dev/internal/messages.js.map +1 -0
- package/dist/server-dev/internal/owner.js +290 -0
- package/dist/server-dev/internal/owner.js.map +1 -0
- package/dist/server-dev/internal/queue.js +46 -0
- package/dist/server-dev/internal/queue.js.map +1 -0
- package/dist/server-dev/internal/scheduler.js +287 -0
- package/dist/server-dev/internal/scheduler.js.map +1 -0
- package/dist/server-dev/internal/state.js +28 -0
- package/dist/server-dev/internal/state.js.map +1 -0
- package/dist/server-dev/internal/suspension.js +45 -0
- package/dist/server-dev/internal/suspension.js.map +1 -0
- package/dist/server-dev/list.js +282 -0
- package/dist/server-dev/list.js.map +1 -0
- package/dist/server-dev/memo.js +41 -0
- package/dist/server-dev/memo.js.map +1 -0
- package/dist/server-dev/optimistic.js +45 -0
- package/dist/server-dev/optimistic.js.map +1 -0
- package/dist/server-dev/ownership.js +261 -0
- package/dist/server-dev/ownership.js.map +1 -0
- package/dist/server-dev/props.js +282 -0
- package/dist/server-dev/props.js.map +1 -0
- package/dist/server-dev/reaction.js +61 -0
- package/dist/server-dev/reaction.js.map +1 -0
- package/dist/server-dev/reducer.js +39 -0
- package/dist/server-dev/reducer.js.map +1 -0
- package/dist/server-dev/refs.js +58 -0
- package/dist/server-dev/refs.js.map +1 -0
- package/dist/server-dev/resource.js +176 -0
- package/dist/server-dev/resource.js.map +1 -0
- package/dist/server-dev/selector.js +82 -0
- package/dist/server-dev/selector.js.map +1 -0
- package/dist/server-dev/signal.js +39 -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 +192 -0
- package/dist/server-dev/store/nodes.js.map +1 -0
- package/dist/server-dev/store/proxies.js +160 -0
- package/dist/server-dev/store/proxies.js.map +1 -0
- package/dist/server-dev/store/read.js +72 -0
- package/dist/server-dev/store/read.js.map +1 -0
- package/dist/server-dev/store/reconcile.js +186 -0
- package/dist/server-dev/store/reconcile.js.map +1 -0
- package/dist/server-dev/store/use-store.js +168 -0
- package/dist/server-dev/store/use-store.js.map +1 -0
- package/dist/server-dev/suspense.js +45 -0
- package/dist/server-dev/suspense.js.map +1 -0
- package/dist/server-dev/transitions.js +86 -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":"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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I,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"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"effect.js","names":["useEffect","second","third","useRenderEffect","onMount"],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\n/** What a held effect computes while its gate is closed: nothing for `apply` to act on. */\nconst HELD: unique symbol = Symbol(\"held\");\n\n/** The nearest gate above the current owner (see `Owner.gate`), or null. */\nfunction nearestGate(): (() => boolean) | null {\n for (let owner = currentOwner(); owner !== null; owner = owner.parent) {\n if (owner.gate !== null) return owner.gate;\n }\n return null;\n}\n\nfunction createEffect(\n fnIn: (previous: never) => unknown,\n applyIn: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n deferIn: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n let fn = fnIn;\n let apply = applyIn;\n let defer = deferIn;\n const gate = render ? null : nearestGate();\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect.\n let opened = false;\n const held = (): boolean => {\n if (opened) return false;\n if (gate()) return true;\n opened = true;\n return false;\n };\n if (apply === null) {\n const inner = fn;\n fn = (previous) => (held() ? undefined : inner(previous));\n } else {\n const innerFn = fn;\n const innerApply = apply;\n // `defer` skips the first real run, not the held one, so it is handled here.\n let skipFirst = defer;\n defer = false;\n fn = (previous) => (held() ? HELD : innerFn(previous));\n apply = (value, previous) => {\n if ((value as unknown) === HELD) return undefined;\n if (skipFirst) {\n skipFirst = false;\n return undefined;\n }\n return innerApply(value, ((previous as unknown) === HELD ? undefined : previous) as never);\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n ...(apply === null ? {} : { apply }),\n ...(name === undefined ? {} : { name }),\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":"A,kCAqJA,SAAgBA,EACd,EACA,EACA,EACM,CACF,OAAOC,GAAW,YACpBC,GAIS,MACPA,GAAO,MAITD,GAA+E,IAEnF,CAyBA,SAAgBE,EACd,EACA,EACM,CAQR,CAoBA,SAAgBC,EAAQ,EAAgC,CAExD,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"env.js","names":["isServer","isDev"],"sources":["../../src/env.ts"],"sourcesContent":["/**\n * True in the server condition build, where effects never run and rendering produces strings. Use\n * it to skip browser-only work. The value is fixed per build: the package export conditions\n * (`node`, `worker`, `browser`, ...) choose the build, not a runtime check.\n *\n * @example\n * import { isServer } from \"@shadow-js/core\";\n *\n * const width = isServer ? 1024 : window.innerWidth;\n * @see isDev\n * @since 1.0.0\n */\nexport const isServer: boolean = __SERVER__;\n\n/**\n * True in development builds; false in production builds where `__DEV__` is compiled away. The\n * `development` export condition selects the development build. Use it to guard checks and logging\n * meant for development only.\n *\n * @example\n * import { isDev } from \"@shadow-js/core\";\n *\n * if (isDev) console.info(\"debug panel enabled\");\n * @see isServer\n * @since 1.0.0\n */\nexport const isDev: boolean = __DEV__;\n"],"mappings":"AAYA,MAAaA,EAAA,GAcAC,EAAA,G"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"events.js","names":["useEvent","args","untrack","handler"],"sources":["../../src/events.ts"],"sourcesContent":["import { untrack } from \"./ownership\";\n\n/**\n * A stable callback that always runs its handler untracked. The ShadowJS form of React's\n * `useEffectEvent`: components run once and props are getters, so the handler already sees the\n * latest values. What it adds is the untracked call: an effect that calls the event does not\n * subscribe to the signals the handler reads.\n *\n * @param handler The handler. Its arguments and result are passed through.\n * @returns A new function with the same signature that calls `handler` untracked. Create it once,\n * in the component body, and keep the reference.\n * @example\n * import { useEffect, useEvent, useSignal } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const [count] = useSignal(0);\n * const onTick = useEvent(() => console.log(count())); // count() is not tracked by the effect\n * useEffect(() => {\n * const id = setInterval(() => onTick(), 1000);\n * return () => clearInterval(id);\n * });\n * return null;\n * }\n * @see untrack\n * @since 1.0.0\n */\nexport function useEvent<A extends unknown[], R>(handler: (...args: A) => R): (...args: A) => R {\n return (...args: A): R => untrack(() => handler(...args));\n}\n"],"mappings":"A,yCA0BA,SAAgBA,EAAiC,EAA+C,CAC9F,OAAQ,GAAGC,IAAeC,MAAcC,EAAQ,GAAGF,CAAI,CAAC,CAC1D,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{DEVTOOLS_EVENT as e,report as t}from"../internal/devtools.js";import{MESSAGES as n,formatMessage as r}from"../internal/messages.js";import{ShadowError as i,resetWarningDedupe as a,setWarningListener as o,warn as s}from"../internal/diagnostics.js";import{rt as c}from"../internal/state.js";import{Owner as l,addCleanup as u,handleError as d}from"../internal/owner.js";import{enqueue as f}from"../internal/queue.js";import{Computation as p,Signal as m,hasObservers as h,markObservers as g,observersOf as _,readMemo as v,readSignal as y,recompute as b,sourcesOf as x,track as S,updateIfNecessary as C}from"../internal/graph.js";import{batch as w,flush as T,flushSync as E,group as D,schedule as O}from"../internal/scheduler.js";import{runWithContext as k}from"../context.js";import{disposeTree as A}from"../internal/dispose.js";import{SUSPENSION as j,isSuspension as M}from"../internal/suspension.js";import{beginHold as ee,createTransitionHold as N,endHold as P,holdReader as F,inTransition as I,pauseOwner as L,registerTransitionLane as R,resumeOwner as z,startTransition as B,transitionHooks as V,wakeSuspended as H}from"../internal/concurrency.js";import{isHydrating as U,withHydration as W}from"../internal/hydration-flag.js";function G(){return c.owner}function K(){return c.listener}function q(){return c.listener!==null}function J(){return c.disposing===0&&c.running!==null&&c.running.kind===1&&!(c.running.flags&256)}function Y(e,t){let n=c.owner,r=c.listener;try{let n=e.owner;n!==void 0&&(c.owner=n);let r=e.listener;return r!==void 0&&(c.listener=r),t()}finally{c.owner=n,c.listener=r}}function X(e,t,n){return new m(e,t,n)}function Z(e,t,n){let r=e.equals;return r!==!1&&r(e.value,t)?!1:(e.value=t,Q(e),!0)}function Q(e){h(e)&&(g(e),O())}function $(e){let t=e.owner===void 0?c.owner:e.owner;if(e.kind===`memo`){let n=new p(t,1,32|(e.allowWrites===!0?256:0),e.fn,e.equals??Object.is,e.name);return e.lazy!==!0&&C(n),n}let n=(e.render===!0?16:0)|(e.defer===!0?64:0)|(e.lane===!0?512:0),r=new p(t,2,n,e.fn,!1,e.name);return r.apply=e.apply??null,e.render===!0?b(r):(f(r),O()),r}function te(e){return v(e)}function ne(e){C(e)}function re(e){return new l(e===void 0?c.owner:e)}export{p as ComputationNode,e as DEVTOOLS_EVENT,n as MESSAGES,l as Owner,j as SUSPENSION,i as ShadowError,m as SignalNode,u as addCleanup,w as batch,ee as beginHold,$ as createComputation,re as createOwner,X as createSignalNode,N as createTransitionHold,K as currentListener,G as currentOwner,t as devtoolsReport,A as disposeOwner,P as endHold,T as flush,E as flushSync,r as formatMessage,D as group,d as handleError,F as holdReader,I as inTransition,J as isComputingMemo,U as isHydrating,M as isSuspension,q as isTracking,g as markObservers,Q as notify,_ as observersOf,L as pauseOwner,te as readComputation,y as readSignal,ne as refresh,R as registerTransitionLane,a as resetWarningDedupe,z as resumeOwner,Y as runInScope,k as runWithContext,O as schedule,o as setWarningListener,x as sourcesOf,B as startTransition,S as track,V as transitionHooks,H as wakeSuspended,s as warn,W as withHydration,Z as writeSignal};
|
|
2
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["OwnerClass","currentOwner","rt","currentListener","isTracking","isComputingMemo","runInScope","owner","listener","nextOwner","scope","nextListener","fn","createSignalNode","Signal","value","equals","name","writeSignal","signal","next","notify","hasObservers","source","markObservers","schedule","createComputation","options","node","Computation","updateIfNecessary","flags","recompute","enqueue","readComputation","readMemo","refresh","createOwner","Owner","parent","DEVTOOLS_EVENT","MESSAGES","SUSPENSION","ShadowError","addCleanup","batch","beginHold","createTransitionHold","report","disposeTree","endHold","flush","flushSync","formatMessage","group","handleError","holdReader","inTransition","isHydrating","isSuspension","observersOf","pauseOwner","readSignal","registerTransitionLane","resetWarningDedupe","resumeOwner","runWithContext","setWarningListener","sourcesOf","startTransition","track","transitionHooks","wakeSuspended","warn","withHydration"],"sources":["../../../src/extend.ts"],"sourcesContent":["/**\n * The extension API: everything the built-in hooks (`useSignal`, `useMemo`, `useEffect`,\n * `useStore`, `useResource`, `mapArray`, `useSelector`, contexts, ...) are built from. They import\n * ONLY this module, never the engine internals, so a third-party package can create hooks with the\n * same behavior, performance and diagnostics. A test (`public-api.test.ts`) enforces that.\n *\n * Import from `@shadow-js/core/extend`. These functions are stable but low level: prefer the hooks\n * unless you are building a new primitive.\n *\n * @packageDocumentation\n */\n\nimport { DEVTOOLS_EVENT, report } from \"./internal/devtools\";\nimport { ShadowError } from \"./internal/diagnostics\";\nimport {\n FLAG_ALLOW_WRITES,\n FLAG_DEFER,\n FLAG_LANE,\n FLAG_RENDER,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n} from \"./internal/flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n observersOf,\n readMemo,\n readSignal,\n recompute,\n Signal,\n type Source,\n sourcesOf,\n track,\n updateIfNecessary,\n} from \"./internal/graph\";\nimport { type Owner, Owner as OwnerClass } from \"./internal/owner\";\nimport { enqueue } from \"./internal/queue\";\nimport { schedule } from \"./internal/scheduler\";\nimport { rt } from \"./internal/state\";\nimport type { Equals } from \"./internal/types\";\n\nexport { runWithContext } from \"./context\";\nexport {\n beginHold,\n createTransitionHold,\n endHold,\n holdReader,\n inTransition,\n pauseOwner,\n registerTransitionLane,\n resumeOwner,\n startTransition,\n transitionHooks,\n wakeSuspended,\n} from \"./internal/concurrency\";\nexport { DEVTOOLS_EVENT, report as devtoolsReport } from \"./internal/devtools\";\nexport type { WarningListener } from \"./internal/diagnostics\";\nexport { resetWarningDedupe, ShadowError, setWarningListener, warn } from \"./internal/diagnostics\";\nexport { disposeTree as disposeOwner } from \"./internal/dispose\";\nexport { isHydrating, withHydration } from \"./internal/hydration-flag\";\nexport type { MessageCode } from \"./internal/messages\";\nexport { formatMessage, MESSAGES } from \"./internal/messages\";\nexport type { ContextMap } from \"./internal/owner\";\nexport { addCleanup, handleError, Owner } from \"./internal/owner\";\nexport { batch, flush, flushSync, group } from \"./internal/scheduler\";\nexport type {\n BoundaryHold,\n SlotBranch,\n SlotChoice,\n SlotOwned,\n SlotState,\n SlotSwap,\n TransitionHold,\n} from \"./internal/state\";\nexport { isSuspension, SUSPENSION } from \"./internal/suspension\";\nexport type {\n Accessor,\n AnyFunction,\n Cleanup,\n Equals,\n ErrorHandler,\n Setter,\n} from \"./internal/types\";\nexport type { Source as SourceNode };\nexport { Computation as ComputationNode, Signal as SignalNode };\n\n// ---------- registers ----------\n\n/**\n * Returns the owner that adopts nodes created right now. The extension-API form of `getOwner`: use\n * it in a primitive that attaches a node or a cleanup to its caller's owner.\n *\n * @returns The current owner, or `null` outside any owner.\n * @example\n * import { addCleanup, currentOwner } from \"@shadow-js/core/extend\";\n *\n * function useInterval(fn: () => void, ms: number): void {\n * const timer = setInterval(fn, ms);\n * const owner = currentOwner();\n * if (owner !== null) addCleanup(owner, () => clearInterval(timer));\n * }\n * @see createOwner\n * @since 1.0.0\n */\nexport function currentOwner(): Owner | null {\n return rt.owner;\n}\n\n/**\n * Returns the computation that records reads right now. Use it in a primitive whose read behaves\n * differently for a tracked reader, for example one that holds a boundary only for a listening\n * memo or effect.\n *\n * @returns The listening memo or effect, or `null` when reads are untracked.\n * @example\n * import { currentListener } from \"@shadow-js/core/extend\";\n *\n * function readWithStats<T>(read: () => T, stats: { tracked: number }): T {\n * if (currentListener() !== null) stats.tracked += 1;\n * return read();\n * }\n * @see isTracking\n * @since 1.0.0\n */\nexport function currentListener(): Computation | null {\n return rt.listener;\n}\n\n/**\n * Says whether reads are being recorded as dependencies right now. Use it to skip subscription\n * work, or to warn, when a primitive is read outside an effect or a memo.\n *\n * @returns `true` while an effect or a memo runs tracked, `false` otherwise (module scope,\n * `untrack`, event handlers).\n * @example\n * import { untrack, useMemo } from \"@shadow-js/core\";\n * import { isTracking } from \"@shadow-js/core/extend\";\n *\n * const inMemo = useMemo(() => isTracking());\n * console.log(inMemo(), untrack(() => isTracking())); // true false\n * @see currentListener\n * @since 1.0.0\n */\nexport function isTracking(): boolean {\n return rt.listener !== null;\n}\n\n/**\n * Says whether a memo (not an effect) is computing right now: writing signals is a mistake there.\n * Cleanups that run while a memo tears down rows or children may write, so a disposal in progress\n * is not a violation, and neither is a memo created with `allowWrites`. Use it to guard a custom\n * write path the way {@link writeSignal} does.\n *\n * @returns `true` while a memo without `allowWrites` computes and no disposal is running.\n * @example\n * import { isComputingMemo, ShadowError } from \"@shadow-js/core/extend\";\n *\n * function appendLog(log: string[], entry: string): void {\n * if (isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n * log.push(entry);\n * }\n * @since 1.0.0\n */\nexport function isComputingMemo(): boolean {\n return (\n rt.disposing === 0 &&\n rt.running !== null &&\n rt.running.kind === KIND_MEMO &&\n (rt.running.flags & FLAG_ALLOW_WRITES) === 0\n );\n}\n\n/**\n * Runs `fn` with the given owner and listener in effect, and restores both afterward, even when\n * `fn` throws. The low-level form of `runWithOwner` and `untrack`; unlike `runWithOwner` it does\n * not check whether the owner is disposed.\n *\n * @param scope `owner` and `listener` to install. For each, `undefined` (or absent) keeps the\n * current one and `null` clears it.\n * Getters are evaluated once; a failed getter restores the original scope.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates after the registers are\n * restored.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * runInScope({ owner, listener: null }, () => {\n * onCleanup(() => console.log(\"released\"));\n * });\n * disposeOwner(owner); // logs \"released\"\n * @see createOwner\n * @since 1.0.0\n */\nexport function runInScope<T>(\n scope: { owner?: Owner | null; listener?: Computation | null },\n fn: () => T,\n): T {\n const owner = rt.owner;\n const listener = rt.listener;\n try {\n const nextOwner = scope.owner;\n if (nextOwner !== undefined) rt.owner = nextOwner;\n const nextListener = scope.listener;\n if (nextListener !== undefined) rt.listener = nextListener;\n return fn();\n } finally {\n rt.owner = owner;\n rt.listener = listener;\n }\n}\n\n// ---------- reactive cells ----------\n\n/**\n * Creates the storage of a signal: its value, its equality and the observers that read it. Read it\n * with `readSignal` and write it with {@link writeSignal}; `useSignal` is built this way.\n *\n * @param value Initial value.\n * @param equals Decides whether a write is a change: readers are notified only when it returns\n * `false`. `false` notifies on every write.\n * @param name Label shown by devtools. Undefined leaves the signal unnamed.\n * @returns The signal node. It has no owner: it lives as long as something references it.\n * @example\n * import { createSignalNode, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const temperature = createSignalNode<number>(20, Object.is, \"temperature\");\n * const read = () => readSignal(temperature);\n * writeSignal(temperature, 21);\n * console.log(read()); // 21\n * @see writeSignal\n * @since 1.0.0\n */\nexport function createSignalNode<T>(value: T, equals: Equals<T>, name?: string): Signal<T> {\n return new Signal<T>(value, equals, name);\n}\n\n/**\n * Options of {@link writeSignal}.\n * @since 1.0.0\n */\nexport interface WriteOptions {\n /**\n * Permit the write while a memo computes, for bookkeeping signals owned by a primitive (a\n * Suspense counter, a resource's state). Turns the development `WRITE_IN_MEMO` check off for\n * this write.\n * @default false\n */\n allowInMemo?: boolean;\n}\n\n/**\n * Stores a new value in a signal node and notifies its readers when the value differs by the\n * signal's equality. Effects that read it run on the next flush; memos recompute on their next\n * read.\n *\n * @param signal The node, from {@link createSignalNode}.\n * @param next The new value. A function is stored as is: there is no updater form.\n * @param options `allowInMemo` permits the write while a memo computes. Undefined uses the default.\n * @returns `true` when the value changed and was stored, `false` when the equality kept the old\n * value (nobody is notified then).\n * @throws ShadowError `WRITE_IN_MEMO`, in development builds only, when a memo is computing and\n * `allowInMemo` is not set.\n * @example\n * import { createSignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const status = createSignalNode<string>(\"idle\", Object.is);\n * console.log(writeSignal(status, \"loading\")); // true\n * console.log(writeSignal(status, \"loading\")); // false: an equal value notifies nobody\n * @see notify\n * @since 1.0.0\n */\nexport function writeSignal<T>(signal: Signal<T>, next: T, options?: WriteOptions): boolean {\n if (__DEV__ && options?.allowInMemo !== true && isComputingMemo()) {\n throw new ShadowError(\"WRITE_IN_MEMO\");\n }\n const equals = signal.equals;\n if (equals !== false && equals(signal.value, next)) return false;\n signal.value = next;\n if (__DEV__) {\n report(DEVTOOLS_EVENT.SIGNAL_WRITTEN, signal, next, rt.running, observersOf(signal));\n }\n notify(signal);\n return true;\n}\n\n/**\n * Marks the observers of `source` stale and schedules a flush. Call it after changing a source's\n * value in place (for example after mutating an array a signal node holds), where\n * {@link writeSignal} cannot see the change.\n *\n * @param source A signal or memo node. A source nobody observes is left alone.\n * @example\n * import { createSignalNode, notify } from \"@shadow-js/core/extend\";\n *\n * const list = createSignalNode<string[]>([], false);\n * list.value.push(\"milk\"); // an in-place change: no equality can see it\n * notify(list); // the readers of `list` run again\n * @see writeSignal\n * @since 1.0.0\n */\nexport function notify(source: Source): void {\n if (!hasObservers(source)) return;\n markObservers(source);\n schedule();\n}\n\nexport { markObservers, observersOf, readSignal, schedule, sourcesOf, track };\n\n// ---------- computations (memos and effects) ----------\n\n/**\n * Options of {@link createComputation}.\n * @since 1.0.0\n */\nexport interface ComputationOptions {\n /**\n * `\"memo\"` creates a cached value that readers pull with {@link readComputation}; `\"effect\"`\n * creates a side effect that the scheduler runs.\n */\n kind: \"memo\" | \"effect\";\n /**\n * The computation. It is tracked: every source it reads becomes a dependency. It receives the\n * previous value (a memo's last value, or an effect's last computed value when `apply` is set;\n * `undefined` otherwise). A memo stores its result; an effect without `apply` may return a\n * cleanup function.\n */\n fn: (previous: never) => unknown;\n /**\n * Memos: decides whether a recomputation changed the value; readers are notified only when it\n * returns `false`, and `false` always propagates. Ignored for effects.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the node is unnamed)\n */\n name?: string;\n /**\n * Effects: run in the render phase, synchronously at creation and before user effects in each\n * flush. Ignored for memos.\n * @default false\n */\n render?: boolean;\n /**\n * Effects with `apply`: skip the first call of `apply`; `fn` still runs and tracks.\n * @default false\n */\n defer?: boolean;\n /**\n * Memos: do not compute until the first read.\n * @default false (the memo computes once at creation)\n */\n lazy?: boolean;\n /**\n * Memos that run component setup (such as a hot-reload wrapper): writing signals inside is\n * legitimate there, so the dev-mode write guard stays off.\n * @default false\n */\n allowWrites?: boolean;\n /**\n * Effects: second stage, run untracked with the value `fn` computed and the previous one. It may\n * return a cleanup function.\n * @default undefined (`fn` is the whole effect)\n */\n apply?: (value: never, previous: never) => unknown;\n /**\n * Owner to attach to. `null` creates a node that no owner disposes.\n * @default the current owner\n */\n owner?: Owner | null;\n /**\n * Effects: always run in the transition lane (the watcher behind `useDeferredValue`).\n * @default false\n */\n lane?: boolean;\n}\n\n/**\n * Creates a memo or effect node: the building block of `useMemo`, `useEffect` and the render\n * effects of a renderer. Memos compute immediately unless `lazy`; render effects run immediately;\n * user effects are queued for the next flush. The node is owned and disposed with its owner.\n * Errors of a memo are stored and rethrown to its readers; errors of an effect go to the owner's\n * error handler.\n *\n * @param options What to create, how it runs and where it is owned.\n * @returns The node. Read a memo with {@link readComputation}; an effect needs no handle.\n * @throws The error of a render effect's first run when no error handler takes it and no flush is\n * running.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode<number>(10, Object.is);\n * const withTax = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 1.2 });\n * createComputation({\n * kind: \"effect\",\n * fn: () => console.log(readComputation<number>(withTax)),\n * });\n * writeSignal(price, 20); // the effect logs 24 on the next flush\n * @see readComputation\n * @since 1.0.0\n */\nexport function createComputation(options: ComputationOptions): Computation {\n const owner = options.owner === undefined ? rt.owner : options.owner;\n if (options.kind === \"memo\") {\n const node = new Computation(\n owner,\n KIND_MEMO,\n FLAG_UNINIT | (options.allowWrites === true ? FLAG_ALLOW_WRITES : 0),\n options.fn,\n options.equals ?? Object.is,\n options.name,\n );\n if (options.lazy !== true) updateIfNecessary(node);\n return node;\n }\n const flags =\n (options.render === true ? FLAG_RENDER : 0) |\n (options.defer === true ? FLAG_DEFER : 0) |\n (options.lane === true ? FLAG_LANE : 0);\n const node = new Computation(owner, KIND_EFFECT, flags, options.fn, false, options.name);\n node.apply = options.apply ?? null;\n if (options.render === true) {\n // A suspended render effect keeps its DOM and waits on its own: its creator completes normally\n // (the branch that holds it decides whether to commit; see createBranches).\n recompute(node);\n } else {\n enqueue(node);\n schedule();\n }\n return node;\n}\n\n/**\n * Reads a memo node: brings it up to date if a source changed, subscribes the running computation\n * to it, and rethrows the error its last run stored. The accessor `useMemo` returns is this call.\n *\n * @param node A memo node from {@link createComputation}.\n * @returns The memo's current value.\n * @throws The error the memo's last computation threw, when no error handler took it. ShadowError\n * `CYCLE_DETECTED` when the memo is read while it computes.\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const first = createSignalNode<string>(\"Ada\", Object.is);\n * const greeting = createComputation({ kind: \"memo\", fn: () => `Hello, ${readSignal(first)}` });\n * console.log(readComputation<string>(greeting)); // \"Hello, Ada\"\n * @see createComputation\n * @since 1.0.0\n */\nexport function readComputation<T>(node: Computation): T {\n return readMemo<T>(node);\n}\n\n/**\n * Brings a memo or effect node up to date if one of its sources changed, without tracking it. Use\n * it to settle a node before reading its fields directly.\n *\n * @param node A node from {@link createComputation}. A node that is up to date is left as is.\n * @throws ShadowError `CYCLE_DETECTED` when a dependency is still computing (a cycle). An effect\n * that re-runs routes its errors to its owner's error handler.\n * @example\n * import { createComputation, createSignalNode, readSignal, refresh, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is);\n * const doubled = createComputation({ kind: \"memo\", fn: () => readSignal(count) * 2 });\n * writeSignal(count, 2);\n * refresh(doubled);\n * console.log(doubled.value); // 4\n * @see readComputation\n * @since 1.0.0\n */\nexport function refresh(node: Computation): void {\n updateIfNecessary(node);\n}\n\n/**\n * Creates a plain owner: a scope that adopts the nodes and cleanups created under it and disposes\n * them together. The building block of `createRoot` and of control-flow branches.\n *\n * @param parent The owner to attach to and inherit context from. Undefined (or omitted) uses the\n * current owner; `null` creates a root with no context that only an explicit dispose ends.\n * @returns The new owner. Dispose it with `disposeOwner`.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n * import { createOwner, disposeOwner, runInScope } from \"@shadow-js/core/extend\";\n *\n * const branch = createOwner();\n * runInScope({ owner: branch, listener: null }, () => {\n * useEffect(() => console.log(\"branch effect\"));\n * });\n * disposeOwner(branch); // the effect and its cleanups are gone\n * @see runInScope\n * @since 1.0.0\n */\nexport function createOwner(parent?: Owner | null): Owner {\n return new OwnerClass(parent === undefined ? rt.owner : parent);\n}\n"],"mappings":"A,mtCA0GA,SAAgBC,GAA6B,CAC3C,OAAOC,EAAG,KACZ,CAkBA,SAAgBC,GAAsC,CACpD,OAAOD,EAAG,QACZ,CAiBA,SAAgBE,GAAsB,CACpC,OAAOF,EAAG,WAAa,IACzB,CAkBA,SAAgBG,GAA2B,CACzC,OACEH,EAAG,YAAc,GACjBA,EAAG,UAAY,MACfA,EAAG,QAAQ,OAAA,GAAA,EACVA,EAAG,QAAQ,MAAA,IAEhB,CAyBA,SAAgBI,EACd,EACA,EACG,CACH,IAAMC,EAAQL,EAAG,MACXM,EAAWN,EAAG,SACpB,GAAI,CACF,IAAMO,EAAYC,EAAM,MACpBD,IAAc,IAAA,KAAW,EAAG,MAAQA,GACxC,IAAME,EAAeD,EAAM,SAE3B,OADIC,IAAiB,IAAA,KAAW,EAAG,SAAWA,GACvCC,EAAG,CACZ,QAAU,CACR,EAAG,MAAQL,EACX,EAAG,SAAWC,CAChB,CACF,CAuBA,SAAgBK,EAAoB,EAAU,EAAmB,EAA0B,CACzF,OAAO,IAAIC,EAAUC,EAAOC,EAAQC,CAAI,CAC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ore","snapshot","untrack","options","getSnapshot"],"sources":["../../src/external-store.ts"],"sourcesContent":["import { useEffect } from \"./effect\";\nimport type { Accessor, Equals } from \"./extend\";\nimport { isHydrating } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useExternalStore}. @since 1.0.0 */\nexport interface ExternalStoreOptions<T> {\n /**\n * The snapshot the server renders (there is no subscription there). Without it the server reads\n * `getSnapshot` once. Keep it equal to what the browser reads on its first render: a difference is\n * corrected only after subscribing, and no hydration test covers that case yet. While hydrating,\n * the browser's first render also uses it.\n * @default undefined (the server, and hydration, read `getSnapshot`)\n */\n getServerSnapshot?: () => T;\n /**\n * Decides whether a new snapshot is a change: the accessor updates only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\n/**\n * Reads a value that lives outside ShadowJS (a store, a browser API, an observable) as a reactive\n * accessor. The one bridge for every external source, and the ShadowJS form of React's\n * `useSyncExternalStore` and Solid's `from`.\n *\n * `subscribe(notify)` is called in an effect after the owner is created and returns the\n * unsubscribe function, which runs when the owner is disposed. `getSnapshot()` is read untracked\n * at creation, on every notification, and once after subscribing (so a change made between the\n * first read and the subscription is not lost). The accessor updates only when the snapshot differs\n * by `equals`. On the server nothing is subscribed: the accessor returns `getServerSnapshot()`.\n *\n * @param subscribe Registers `notify`; returns the unsubscribe function.\n * @param getSnapshot Returns the current value. Reads inside it are not tracked.\n * @param options Server snapshot, equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the current snapshot.\n * @example\n * import { useExternalStore } from \"@shadow-js/core\";\n *\n * function subscribe(notify: () => void): () => void {\n * window.addEventListener(\"online\", notify);\n * window.addEventListener(\"offline\", notify);\n * return () => {\n * window.removeEventListener(\"online\", notify);\n * window.removeEventListener(\"offline\", notify);\n * };\n * }\n *\n * function OnlineBadge() {\n * const online = useExternalStore(subscribe, () => navigator.onLine, { getServerSnapshot: () => true });\n * return <span>{online() ? \"online\" : \"offline\"}</span>;\n * }\n * @see useSignal\n * @since 1.0.0\n */\nexport function useExternalStore<T>(\n subscribe: (notify: () => void) => () => void,\n getSnapshot: () => T,\n options?: ExternalStoreOptions<T>,\n): Accessor<T> {\n if (__SERVER__) {\n const snapshot = untrack(options?.getServerSnapshot ?? getSnapshot);\n return () => snapshot;\n }\n // While hydrating, the first render must equal the server markup: the server snapshot, when given.\n // The browser's snapshot is applied by the subscription below.\n const first =\n isHydrating() && options?.getServerSnapshot !== undefined\n ? options.getServerSnapshot\n : getSnapshot;\n const [value, setValue] = useSignal<T>(untrack(first), {\n equals: options?.equals ?? Object.is,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n const sync = (): void => {\n const next = untrack(getSnapshot);\n setValue(() => next);\n };\n useEffect(() => {\n const unsubscribe = subscribe(sync);\n // Catch up with changes made between the first read and the subscription.\n sync();\n return unsubscribe;\n });\n return value;\n}\n"],"mappings":"A,yCA8DA,SAAgBA,EACd,EACA,EACA,EACa,CACG,CACd,IAAMC,EAAWC,EAAQC,GAAS,mBAAqBC,CAAW,EAClE,UAAaH,CACf,CAsBF,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{batch as e,flushSync as t}from"./internal/scheduler.js";import{catchError as n,createRoot as r,getOwner as i,onCleanup as a,onError as o,runWithOwner as s,untrack as c,useId as l}from"./ownership.js";import{onMount as u,useEffect as d,useRenderEffect as f}from"./effect.js";import{useSignal as p}from"./signal.js";import{createContext as m,useContext as h}from"./context.js";import{ResourceCacheContext as g,SuspenseContext as _}from"./suspense.js";import{startTransition as v}from"./internal/concurrency.js";import{useAction as y}from"./action.js";import{cache as b}from"./cache.js";import{isDev as x,isServer as S}from"./env.js";import{useEvent as C}from"./events.js";import{useExternalStore as w}from"./external-store.js";import{useMemo as T}from"./memo.js";import{indexArray as E,mapArray as D}from"./list.js";import{useOptimistic as O}from"./optimistic.js";import{children as k,mergeProps as A,splitProps as j}from"./props.js";import{useReaction as M}from"./reaction.js";import{useReducer as N}from"./reducer.js";import{createRef as P,useImperativeHandle as F}from"./refs.js";import{useResource as I}from"./resource.js";import{useSelector as L}from"./selector.js";import{snapshot as R,unwrap as z}from"./store/read.js";import{produce as B,reconcile as V}from"./store/reconcile.js";import{useStore as H}from"./store/use-store.js";import{useDeferredValue as U,useTransition as W}from"./transitions.js";export{g as ResourceCacheContext,_ as SuspenseContext,e as batch,b as cache,n as catchError,k as children,m as createContext,P as createRef,r as createRoot,t as flushSync,i as getOwner,E as indexArray,x as isDev,S as isServer,D as mapArray,A as mergeProps,a as onCleanup,o as onError,u as onMount,B as produce,V as reconcile,s as runWithOwner,R as snapshot,j as splitProps,v as startTransition,c as untrack,z as unwrap,y as useAction,h as useContext,U as useDeferredValue,d as useEffect,C as useEvent,w as useExternalStore,l as useId,F as useImperativeHandle,T as useMemo,O as useOptimistic,M as useReaction,N as useReducer,f as useRenderEffect,I as useResource,L as useSelector,p as useSignal,H as useStore,W as useTransition};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{FLAG_PARKED as t,FLAG_SUSPENDED as n,FLAG_TRANSITION as r}from"./flags.js";import{rt as i}from"./state.js";import{Owner as a,addCleanup as o,handleError as s}from"./owner.js";import{clearQueues as c,hasPending as l,place as u,renderQueue as d,userQueue as f}from"./queue.js";import{Computation as p,Signal as m,hasObservers as h,markObservers as g,readSignal as _,recompute as v,updateIfNecessary as y}from"./graph.js";import{byCreation as b,isOrdered as x,reportUncaught as S,schedule as C}from"./scheduler.js";import{runWithContext as w}from"../context.js";import{SuspenseContext as T}from"../suspense.js";import{disposeTree as E}from"./dispose.js";import{SUSPENSION as D,isSuspension as O}from"./suspension.js";function k(e,t){let n=[e];for(;n.length>0;){let e=n.pop();if(e===void 0)break;t(e);for(let t=e.lastChild;t!==null;t=t.prevSibling)n.push(t)}}function A(){let A=[],j=[],M=[],N=[],P=0,F=!1,I=()=>A.length>0||j.length>0,L=()=>I()||P>0,R=(e,n)=>{let i=e.splice(0,n);x(i)||i.sort(b);for(let e of i)if(e.flags&1024&&(e.flags&=~(2|r),!(e.flags&4))){if(e.pauses>0)e.flags|=t|r;else try{e.state===2?v(e):y(e)}catch(t){s(t,e)}}return i.length},z=()=>{if(L()||M.length===0)return;let e=M.splice(0,M.length);for(let t of e)t()},B=()=>{F||(F=!0,setTimeout(V,0))},V=()=>{if(F=!1,i.flushing){B();return}let t=i.inTransition;i.inTransition=!0,i.flushing=!0;let n=64,r=0;try{for(;n>0&&I();){if(r+=1,r>1e3){c(),i.uncaught.push(new e(`INFINITE_LOOP`));break}let t=A.length>0?A:j;n-=R(t,n)}}finally{i.inTransition=t,i.flushing=!1}let a=i.uncaught.splice(0,i.uncaught.length);for(let e of a)S(e);I()?B():z(),l()&&C()},H=e=>{let t=i.inTransition,n=i.listener;i.inTransition=!0,i.listener=null;try{e()}finally{i.inTransition=t,i.listener=n}let r=new Promise(e=>{M.push(e)});return z(),r},U=(e,n)=>{if(e.pauses>0){e.flags=n?e.flags|t|r:(e.flags|t)&~r;return}let i=!!(e.flags&16);e.flags=e.flags&~t|2|r,i?A.push(e):j.push(e),B()},W=e=>{e.flags&512||e.pauses>0||(e.flags&2048?u(e,!1):(e.flags&1026)==1026&&(e.flags&=~r,e.flags&16?d.push(e):f.push(e)))},G=()=>{for(let e of[A,j]){for(let t of e)t.flags&=~(2|r),t.state=0;e.length=0}},K=(e,t)=>t===D&&(e.flags|=n,N.push(e),!0),q=e=>{if(e.hold?.()===!0)throw D},J=()=>{P+=1},Y=()=>{P>0&&--P,I()&&B(),z()},X=()=>{let e=N.splice(0,N.length),t=i.inTransition;i.inTransition=!0;try{for(let t of e)t.flags&4096&&!t.disposed&&(t.flags&=~n,t.state=2,t.kind===2?u(t,!0):g(t))}finally{i.inTransition=t}C()},Z=e=>{k(e,e=>{e.pauses+=1,e instanceof p&&e.kind===2&&!(e.flags&16)&&!e.disposed&&e.runCleanups()})},Q=e=>{let t=0,n=!1,r=!1,i={increment(){t+=1},decrement(){--t,t===0&&(n&&(n=!1,X(),Y()),e())},hold(){return r=!0,n||(n=!0,J()),!0}};return{run:e=>w(T,i,e),count:()=>t,engaged:()=>r,drop:()=>{n&&(n=!1,Y())}}};return{place:U,promote:W,clear:G,suspend:K,holdReader:q,startTransition:H,beginHold:J,endHold:Y,wakeSuspended:X,pause:Z,resume:e=>{k(e,e=>{if(e.pauses>0&&--e.pauses,e instanceof p&&e.pauses===0&&!e.disposed){if(e.kind===2){if(e.flags&16&&!(e.flags&2048))return;e.state=2,u(e,!1)}else e.state!==0&&g(e)}}),C()},createHold:Q,slotSwap:(e,t,n,r)=>{let s,c=new a(r),l=new m(0,!1,void 0),u=()=>{l.value+=1,h(l)&&(g(l),C())},d=e=>{e.owned.disposing=!0;try{e.hold?.drop(),e.dispose?.()}finally{e.owned.disposing=!1}},f=t=>{let n=e.live;e.live=t,n!==void 0&&d(n)},p=e=>{let n={index:e.index,value:e.when,disposing:!1},r=Q(()=>{s!==void 0&&s.hold===r&&u()}),l=new a(c),d=i.owner,f=i.listener;i.owner=l,i.listener=null;let p;try{try{p=r.run(()=>t(e,n,!0))}catch(e){if(!O(e))throw e}let i=new a(l);o(i,()=>{n.disposing=!0})}finally{i.owner=d,i.listener=f}return{choice:e,owned:n,result:p,dispose:()=>E(l),hold:r.engaged()?r:null}};return{step(t){if(_(l),s!==void 0){if(!n(s.choice,t)){let e=s;s=void 0,e.hold?.drop(),e.dispose?.()}else if((s.hold?.count()??0)>0)return!0;else{let e=s;return s=void 0,f(e),!0}}if(e.live!==void 0&&i.inTransition){let e=p(t);return e.hold===null?f(e):s=e,!0}let r=e.live;return e.live=void 0,r!==void 0&&d(r),!1}}},boundaryHold:()=>{let e=!1;return{engage:()=>(e||(e=!0,J()),!0),release:()=>{e&&(e=!1,X(),Y())},holding:()=>e}}}}function j(){let e=i.hooks;if(e!==null)return e;let t=A();return i.hooks=t,t}function M(){j()}function N(e){return e(),Promise.resolve()}function P(){i.hooks?.beginHold()}function F(){i.hooks?.endHold()}function I(){i.hooks?.wakeSuspended()}function L(e){i.hooks?.holdReader(e)}function R(){return i.inTransition}function z(e){let t=i.hooks;return t===null?null:t.createHold(e)}function B(){return i.inTransition?i.hooks:null}function V(e){j().pause(e)}function H(e){i.hooks?.resume(e)}export{P as beginHold,z as createTransitionHold,F as endHold,L as holdReader,R as inTransition,V as pauseOwner,M as registerTransitionLane,H as resumeOwner,N as startTransition,B as transitionHooks,I as wakeSuspended};
|
|
2
|
+
//# sourceMappingURL=concurrency.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"concurrency.js","names":["walk","stack","root","node","visit","child","createHooks","laneRender","laneUser","waiters","suspended","holds","scheduled","hasLanePending","laneBusy","drainLane","batch","queue","limit","isOrdered","byCreation","effect","FLAG_TRANSITION","FLAG_PARKED","recompute","updateIfNecessary","error","handleError","settleLane","resolved","resolve","scheduleLane","flushLane","rt","previous","budget","passes","clearQueues","ShadowError","errors","reportUncaught","hasPending","schedule","startTransition","listener","fn","applied","parkOrLane","inLane","render","promote","place","renderQueue","userQueue","clear","suspend","SUSPENSION","FLAG_SUSPENDED","holdReader","tracker","beginHold","endHold","wakeSuspended","waiting","markObservers","pause","owner","Computation","createHold","count","holding","engagedOnce","onSettled","runWithContext","SuspenseContext","pending","holder","Owner","parent","settled","Signal","settle","hasObservers","retireBranch","branch","commit","state","buildPending","owned","choice","hold","previousOwner","previousListener","result","build","isSuspension","marker","addCleanup","disposeTree","readSignal","same","dropped","ready","built","live","ensureHooks","existing","created","registerTransitionLane","inTransition","createTransitionHold","hooks","transitionHooks","pauseOwner","resumeOwner"],"sources":["../../../src/internal/concurrency.ts"],"sourcesContent":["import { runWithContext } from \"../context\";\nimport { SuspenseContext } from \"../suspense\";\nimport { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport { disposeTree } from \"./dispose\";\nimport {\n CLEAN,\n DIRTY,\n FLAG_DISPOSED,\n FLAG_LANE,\n FLAG_PARKED,\n FLAG_QUEUED,\n FLAG_RENDER,\n FLAG_SUSPENDED,\n FLAG_TRANSITION,\n KIND_EFFECT,\n} from \"./flags\";\nimport {\n Computation,\n hasObservers,\n markObservers,\n readSignal,\n recompute,\n Signal,\n updateIfNecessary,\n} from \"./graph\";\nimport { addCleanup, handleError, Owner } from \"./owner\";\nimport { clearQueues, hasPending, place, renderQueue, userQueue } from \"./queue\";\nimport { byCreation, isOrdered, MAX_FLUSH_PASSES, reportUncaught, schedule } from \"./scheduler\";\nimport {\n type BoundaryHold,\n type Hooks,\n rt,\n type SlotBranch,\n type SlotChoice,\n type SlotOwned,\n type SlotState,\n type SlotSwap,\n type TransitionHold,\n} from \"./state\";\nimport { isSuspension, SUSPENSION } from \"./suspension\";\n\n/*\n * Transitions, Activity pauses and Suspense holds. Nothing here runs unless an API that needs it is\n * called (startTransition, useTransition, useDeferredValue, pauseOwner, a Suspense hold inside a\n * transition): the first of those creates the hooks (`ensureHooks`), and the engine reaches them only\n * through `rt.hooks`. Module level holds no state of its own: the queues, waiters and holds are\n * closure variables of `createHooks`.\n */\n\n/** Transition-lane effects run per macrotask; between two chunks urgent work and input can run. */\nconst LANE_CHUNK = 64;\n\n/** Visits `root` and every node below it. Iterative: the depth is user controlled. */\nfunction walk(root: Owner, visit: (node: Owner) => void): void {\n const stack: Owner[] = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n if (node === undefined) break;\n visit(node);\n for (let child = node.lastChild; child !== null; child = child.prevSibling) stack.push(child);\n }\n}\n\n/** Creates the transition machinery. Called once, by the first API that needs it. */\nfunction createHooks(): Hooks {\n const laneRender: Computation[] = [];\n const laneUser: Computation[] = [];\n /** Resolvers of the transitions waiting for the lane to go idle. */\n const waiters: Array<() => void> = [];\n /** Memos and effects that caught a suspension; woken all at once when a boundary releases them. */\n const suspended: Computation[] = [];\n /** Suspense boundaries currently holding a transition (the lane is busy while any holds). */\n let holds = 0;\n let scheduled = false;\n\n const hasLanePending = (): boolean => laneRender.length > 0 || laneUser.length > 0;\n const laneBusy = (): boolean => hasLanePending() || holds > 0;\n\n /**\n * Runs one chunk of a lane queue. An entry without FLAG_TRANSITION was promoted to the urgent queue\n * after it was queued here; it is skipped (the urgent queue owns its FLAG_QUEUED).\n */\n const drainLane = (queue: Computation[], limit: number): number => {\n const batch = queue.splice(0, limit);\n if (!isOrdered(batch)) batch.sort(byCreation);\n for (const effect of batch) {\n if ((effect.flags & FLAG_TRANSITION) === 0) continue;\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n if ((effect.flags & FLAG_DISPOSED) !== 0) continue;\n if (effect.pauses > 0) {\n effect.flags |= FLAG_PARKED | FLAG_TRANSITION;\n continue;\n }\n try {\n if (effect.state === DIRTY) recompute(effect);\n else updateIfNecessary(effect);\n } catch (error) {\n handleError(error, effect);\n }\n }\n return batch.length;\n };\n\n /** Resolves the transitions that wait for the lane, once the lane is idle. */\n const settleLane = (): void => {\n if (laneBusy() || waiters.length === 0) return;\n const resolved = waiters.splice(0, waiters.length);\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_END, resolved.length);\n for (const resolve of resolved) resolve();\n };\n\n /** Asks for one lane macrotask (the timer lets the browser paint and take input first). */\n const scheduleLane = (): void => {\n if (scheduled) return;\n scheduled = true;\n setTimeout(flushLane, 0);\n };\n\n /**\n * Runs the transition lane: one chunk per macrotask, render effects first. Writes made here belong to\n * the lane, so the effects they wake join it. Errors nobody handled are reported, not thrown, because\n * no caller is waiting for this macrotask.\n */\n const flushLane = (): void => {\n scheduled = false;\n if (rt.flushing) {\n scheduleLane();\n return;\n }\n const previous = rt.inTransition;\n rt.inTransition = true;\n rt.flushing = true;\n let budget = LANE_CHUNK;\n let passes = 0;\n try {\n while (budget > 0 && hasLanePending()) {\n passes += 1;\n if (passes > MAX_FLUSH_PASSES) {\n clearQueues();\n rt.uncaught.push(new ShadowError(\"INFINITE_LOOP\"));\n break;\n }\n const queue = laneRender.length > 0 ? laneRender : laneUser;\n budget -= drainLane(queue, budget);\n }\n } finally {\n rt.inTransition = previous;\n rt.flushing = false;\n }\n const errors = rt.uncaught.splice(0, rt.uncaught.length);\n for (const error of errors) reportUncaught(error);\n if (hasLanePending()) scheduleLane();\n else settleLane();\n if (hasPending()) schedule();\n };\n\n const startTransition = (fn: () => void): Promise<void> => {\n // A user callback runs untracked and as a transition: its reads are not subscriptions of the caller.\n const previous = rt.inTransition;\n const listener = rt.listener;\n rt.inTransition = true;\n rt.listener = null;\n try {\n fn();\n } finally {\n rt.inTransition = previous;\n rt.listener = listener;\n }\n if (__DEV__) report(DEVTOOLS_EVENT.TRANSITION_START);\n const applied = new Promise<void>((resolve) => {\n waiters.push(resolve);\n });\n settleLane();\n return applied;\n };\n\n /** The hook's `place`: parks a paused effect or queues a lane effect. */\n const parkOrLane = (effect: Computation, inLane: boolean): void => {\n if (effect.pauses > 0) {\n // Paused: parked (unqueued) until the owner resumes. A lane effect keeps its lane.\n effect.flags = inLane\n ? effect.flags | FLAG_PARKED | FLAG_TRANSITION\n : (effect.flags | FLAG_PARKED) & ~FLAG_TRANSITION;\n return;\n }\n const render = (effect.flags & FLAG_RENDER) !== 0;\n effect.flags = (effect.flags & ~FLAG_PARKED) | FLAG_QUEUED | FLAG_TRANSITION;\n if (render) laneRender.push(effect);\n else laneUser.push(effect);\n scheduleLane();\n };\n\n const promote = (effect: Computation): void => {\n // Lane-only effects (useDeferredValue's watcher) and paused effects stay where they are.\n if ((effect.flags & FLAG_LANE) !== 0 || effect.pauses > 0) return;\n if ((effect.flags & FLAG_PARKED) !== 0) {\n place(effect, false);\n return;\n }\n if ((effect.flags & (FLAG_QUEUED | FLAG_TRANSITION)) !== (FLAG_QUEUED | FLAG_TRANSITION))\n return;\n // Still listed in the lane array; the lane skips entries that no longer carry FLAG_TRANSITION.\n effect.flags &= ~FLAG_TRANSITION;\n if ((effect.flags & FLAG_RENDER) !== 0) renderQueue.push(effect);\n else userQueue.push(effect);\n };\n\n const clear = (): void => {\n for (const queue of [laneRender, laneUser]) {\n for (const effect of queue) {\n effect.flags &= ~(FLAG_QUEUED | FLAG_TRANSITION);\n effect.state = CLEAN;\n }\n queue.length = 0;\n }\n };\n\n const suspend = (node: Computation, error: unknown): boolean => {\n if (error !== SUSPENSION) return false;\n node.flags |= FLAG_SUSPENDED;\n suspended.push(node);\n return true;\n };\n\n const holdReader = (tracker: { hold?(): boolean }): void => {\n if (tracker.hold?.() === true) throw SUSPENSION;\n };\n\n const beginHold = (): void => {\n holds += 1;\n };\n\n const endHold = (): void => {\n if (holds > 0) holds -= 1;\n if (hasLanePending()) scheduleLane();\n settleLane();\n };\n\n const wakeSuspended = (): void => {\n const waiting = suspended.splice(0, suspended.length);\n // The woken work is still the transition: it runs in the lane, so a resource it reads again is\n // held the same way, not shown as a fallback by an urgent pass.\n const previous = rt.inTransition;\n rt.inTransition = true;\n try {\n for (const node of waiting) {\n if ((node.flags & FLAG_SUSPENDED) === 0 || node.disposed) continue;\n node.flags &= ~FLAG_SUSPENDED;\n node.state = DIRTY;\n if (node.kind === KIND_EFFECT) place(node, true);\n else markObservers(node);\n }\n } finally {\n rt.inTransition = previous;\n }\n schedule();\n };\n\n const pause = (owner: Owner): void => {\n walk(owner, (node) => {\n node.pauses += 1;\n if (\n node instanceof Computation &&\n node.kind === KIND_EFFECT &&\n (node.flags & FLAG_RENDER) === 0 &&\n !node.disposed\n ) {\n node.runCleanups();\n }\n });\n };\n\n const createHold = (onSettled: () => void): TransitionHold => {\n let count = 0;\n let holding = false;\n let engagedOnce = false;\n const tracker = {\n increment(): void {\n count += 1;\n },\n decrement(): void {\n count -= 1;\n if (count !== 0) return;\n if (holding) {\n holding = false;\n // Everything that kept its value for this hold runs again, now that the data arrived.\n wakeSuspended();\n endHold();\n }\n onSettled();\n },\n hold(): boolean {\n engagedOnce = true;\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n };\n return {\n run: (fn) => runWithContext(SuspenseContext, tracker, fn),\n count: () => count,\n engaged: () => engagedOnce,\n drop: () => {\n if (!holding) return;\n holding = false;\n endHold();\n },\n };\n };\n\n const resume = (owner: Owner): void => {\n walk(owner, (node) => {\n if (node.pauses > 0) node.pauses -= 1;\n if (!(node instanceof Computation) || node.pauses !== 0 || node.disposed) return;\n if (node.kind === KIND_EFFECT) {\n // A render effect that was not due while paused keeps its DOM: re-running it would rebuild its\n // subtree (a Provider's children, for one) and lose that state.\n if ((node.flags & FLAG_RENDER) !== 0 && (node.flags & FLAG_PARKED) === 0) return;\n node.state = DIRTY;\n place(node, false);\n } else if (node.state !== CLEAN) {\n // A memo that changed while paused was not recomputed, so its readers outside this owner were\n // not woken either (they read the frozen value). Wake them now that it can be recomputed.\n markObservers(node);\n }\n });\n schedule();\n };\n\n /** A Suspense boundary's hold: engaged by a transition read, released when its data arrived. */\n const boundaryHold = (): BoundaryHold => {\n let holding = false;\n return {\n engage: () => {\n if (!holding) {\n holding = true;\n beginHold();\n }\n return true;\n },\n release: () => {\n if (!holding) return;\n holding = false;\n // Everything that kept its value for this boundary runs again, with the data that arrived.\n wakeSuspended();\n endHold();\n },\n holding: () => holding,\n };\n };\n\n /**\n * The transition layer of one branch slot (Show, Switch). A change made during a transition, while a\n * branch is on screen, builds the new branch under a hold and keeps the shown one until the hold\n * settles; then it commits. The slot's output memo calls `step` first, so the usual path (its own\n * teardown) only runs when no transition is involved. Its state lives in `state`, which the memo\n * reads and writes.\n */\n const slotSwap = <C extends SlotChoice>(\n state: SlotState<C>,\n build: (choice: C, owned: SlotOwned, eager: boolean) => unknown,\n same: (a: C, b: C) => boolean,\n parent: Owner | null,\n ): SlotSwap<C> => {\n /** A transition's branch waiting for its reads; the shown branch stays until it is ready. */\n let pending: SlotBranch<C> | undefined;\n /** Owns the branches built during transitions: they live as long as the slot's owner. */\n const holder = new Owner(parent);\n /** Counts the settled holds; the memo reads it, so it runs again when a pending branch is ready. */\n const settled = new Signal<number>(0, false, undefined);\n\n const settle = (): void => {\n settled.value += 1;\n if (hasObservers(settled)) {\n markObservers(settled);\n schedule();\n }\n };\n\n /** Tears a branch down. Its owner is marked `disposing` first (see the accessors of Show). */\n const retireBranch = (branch: SlotBranch<C>): void => {\n branch.owned.disposing = true;\n try {\n branch.hold?.drop();\n branch.dispose?.();\n } finally {\n branch.owned.disposing = false;\n }\n };\n\n const commit = (branch: SlotBranch<C>): void => {\n const previous = state.live;\n state.live = branch;\n if (previous !== undefined) retireBranch(previous);\n };\n\n /** Builds a transition's branch under the holder. A held read leaves it pending, not shown. */\n const buildPending = (choice: C): SlotBranch<C> => {\n const owned: SlotOwned = { index: choice.index, value: choice.when, disposing: false };\n const hold: TransitionHold = createHold(() => {\n // Only the branch still waiting may commit; a dropped one must not wake the slot.\n if (pending !== undefined && pending.hold === hold) settle();\n });\n const root = new Owner(holder);\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n rt.owner = root;\n rt.listener = null;\n let result: unknown;\n try {\n // The branch's reads report to its own hold (not the boundary), so they do not bring the\n // fallback back. No Provider: its render effect would be re-run by the wake-up, rebuilding\n // the branch and starting its loads again.\n try {\n result = hold.run(() => build(choice, owned, true));\n } catch (error) {\n if (!isSuspension(error)) throw error;\n }\n const marker = new Owner(root);\n addCleanup(marker, () => {\n owned.disposing = true;\n });\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n }\n return {\n choice,\n owned,\n result,\n dispose: () => disposeTree(root),\n hold: hold.engaged() ? hold : null,\n };\n };\n\n return {\n step(choice: C): boolean {\n readSignal(settled);\n if (pending !== undefined) {\n if (!same(pending.choice, choice)) {\n const dropped = pending;\n pending = undefined;\n dropped.hold?.drop();\n dropped.dispose?.();\n } else if ((pending.hold?.count() ?? 0) > 0) {\n // Still waiting for data: the shown branch stays on screen, untouched.\n return true;\n } else {\n const ready = pending;\n pending = undefined;\n commit(ready);\n return true;\n }\n }\n // A transition replacing the shown branch: build it first, keep the shown one until it is ready.\n if (state.live !== undefined && rt.inTransition) {\n const built = buildPending(choice);\n if (built.hold === null) commit(built);\n else pending = built;\n return true;\n }\n // The usual path follows: the branch on screen is retired here (an unmanaged one is torn down).\n const live = state.live;\n state.live = undefined;\n if (live !== undefined) retireBranch(live);\n return false;\n },\n };\n };\n\n return {\n place: parkOrLane,\n promote,\n clear,\n suspend,\n holdReader,\n startTransition,\n beginHold,\n endHold,\n wakeSuspended,\n pause,\n resume,\n createHold,\n slotSwap,\n boundaryHold,\n };\n}\n\n/** Installs the transition machinery on first use; later calls return the same hooks. */\nfunction ensureHooks(): Hooks {\n const existing = rt.hooks;\n if (existing !== null) return existing;\n const created = createHooks();\n rt.hooks = created;\n return created;\n}\n\n/**\n * Installs the transition machinery (the transition lane, Activity pauses and Suspense holds) now\n * instead of at the first `startTransition`. The machinery is created on first use so that an\n * application that never uses transitions does not carry its code; call this from a primitive whose\n * later work needs the lane to exist, as `useDeferredValue` does. Calling it again does nothing.\n *\n * @example\n * import { registerTransitionLane } from \"@shadow-js/core/extend\";\n *\n * export function useBackgroundValue(): void {\n * registerTransitionLane(); // later lane-only effects of this hook find the lane\n * }\n * @see startTransition\n * @since 1.0.0\n */\nexport function registerTransitionLane(): void {\n ensureHooks();\n}\n\n/**\n * Runs `fn` as a transition: the effects its writes wake wait in the transition lane, which runs\n * after urgent work (in a macrotask, one chunk at a time). Reads see the writes at once; the DOM\n * catches up when the lane runs. Use it for an update that may be slow to render or load, so input\n * stays responsive and a Suspense boundary keeps its content instead of showing its fallback. `fn`\n * runs untracked. The returned promise resolves when the lane is idle and no Suspense boundary holds\n * the transition.\n *\n * On the server there are no effects, so `fn` simply runs and the promise is already resolved.\n *\n * @param fn Callback whose writes form the transition.\n * @returns A promise that resolves when the transition has been applied.\n * @throws What `fn` throws, synchronously; no transition is started then.\n * @example\n * import { startTransition, useSignal } from \"@shadow-js/core\";\n *\n * const [page, setPage] = useSignal(\"home\");\n * async function openReports(): Promise<void> {\n * await startTransition(() => setPage(\"reports\"));\n * console.log(`${page()} is on screen`);\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function startTransition(fn: () => void): Promise<void> {\n if (__SERVER__) {\n fn();\n return Promise.resolve();\n }\n return ensureHooks().startTransition(fn);\n}\n\n/**\n * Starts a Suspense hold: the boundary keeps showing its current content while a transition waits\n * for data. Holds are counted, and the running transitions stay pending (`isPending` of\n * `useTransition`, the promise of `startTransition`) until every hold has ended. For renderers that\n * implement Suspense; each call needs one {@link endHold}. Does nothing before the transition\n * machinery exists (no transition has run).\n *\n * @example\n * import { beginHold, endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function holdUntil(data: Promise<unknown>): void {\n * beginHold(); // the boundary keeps its content\n * void data.finally(() => {\n * wakeSuspended();\n * endHold();\n * });\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function beginHold(): void {\n rt.hooks?.beginHold();\n}\n\n/**\n * Ends a Suspense hold started with {@link beginHold}. Call {@link wakeSuspended} first, so the\n * memos and effects that waited are queued; this then schedules the lane for them and, once the lane\n * is idle and no hold remains, resolves the transitions that were waiting. Extra calls never take the\n * count below zero. Does nothing before the transition machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function release(): void {\n * wakeSuspended(); // the held readers run again with the data that arrived\n * endHold();\n * }\n * @see beginHold\n * @since 1.0.0\n */\nexport function endHold(): void {\n rt.hooks?.endHold();\n}\n\n/**\n * Wakes every memo and effect that kept its value for a transition (it caught {@link SUSPENSION}):\n * each runs again in the transition lane, so it reads the data that arrived. A Suspense boundary\n * calls it when it releases its hold, before {@link endHold}. Does nothing before the transition\n * machinery exists.\n *\n * @example\n * import { endHold, wakeSuspended } from \"@shadow-js/core/extend\";\n *\n * export function onDataArrived(): void {\n * wakeSuspended();\n * endHold();\n * }\n * @see endHold\n * @since 1.0.0\n */\nexport function wakeSuspended(): void {\n rt.hooks?.wakeSuspended();\n}\n\n/**\n * Lets a pending read inside a transition keep the boundary's content: when the tracker's `hold()`\n * returns true (the boundary holds its content for the transition), the reader throws\n * {@link SUSPENSION} and keeps its previous value until the boundary wakes it. Call it from a data\n * primitive's reader when its data is pending, the reader is tracked and {@link inTransition} is\n * true, as `useResource` does. Does nothing before the transition machinery exists, or when the\n * tracker has no `hold`.\n *\n * @param tracker The Suspense tracker of the nearest boundary (`SuspenseContext`).\n * @throws {@link SUSPENSION} (not an error) when the boundary holds its content.\n * @example\n * import { useContext, SuspenseContext } from \"@shadow-js/core\";\n * import { currentListener, holdReader, inTransition } from \"@shadow-js/core/extend\";\n *\n * export function readPending(): void {\n * const tracker = useContext(SuspenseContext);\n * if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n * }\n * @see isSuspension\n * @since 1.0.0\n */\nexport function holdReader(tracker: { hold?(): boolean }): void {\n rt.hooks?.holdReader(tracker);\n}\n\n/**\n * Tells whether a transition callback or a transition-lane run is active, so the writes made now\n * belong to the lane. Use it in a primitive that treats transition reads differently, such as a data\n * reader that holds the boundary only in a transition.\n *\n * @returns True inside `startTransition`'s callback and while the lane runs.\n * @example\n * import { startTransition } from \"@shadow-js/core\";\n * import { inTransition } from \"@shadow-js/core/extend\";\n *\n * void startTransition(() => {\n * console.log(inTransition()); // true in the browser\n * });\n * console.log(inTransition()); // false\n * @see startTransition\n * @since 1.0.0\n */\nexport function inTransition(): boolean {\n return rt.inTransition;\n}\n\n/**\n * Creates the hold of a value a transition builds (see {@link TransitionHold}): the reads that wait\n * for data inside `hold.run(...)` count against this hold instead of the Suspense boundary around the\n * value, so the value on screen stays until the new one is ready. For renderers that build values\n * during a transition.\n *\n * @param onSettled Called each time the number of waiting reads drops back to zero.\n * @returns The hold, or null when the transition machinery does not exist yet (no transition has run,\n * so nothing can be held).\n * @example\n * import { createTransitionHold } from \"@shadow-js/core/extend\";\n *\n * const hold = createTransitionHold(() => console.log(\"ready to commit\"));\n * const built = hold === null ? \"now\" : hold.run(() => \"pending\");\n * @see transitionHooks\n * @since 1.0.0\n */\nexport function createTransitionHold(onSettled: () => void): TransitionHold | null {\n const hooks = rt.hooks;\n return hooks === null ? null : hooks.createHold(onSettled);\n}\n\n/**\n * Returns the transition machinery while a transition is running, otherwise null. Renderers reach\n * the slot and boundary layers (`slotSwap`, `boundaryHold`) only through it: a transition can only be\n * running once the machinery exists, so this never creates it (a static call that did would keep the\n * whole machinery in every bundle that renders a Show).\n *\n * @returns The hooks during a transition callback or lane run, null otherwise.\n * @example\n * import { transitionHooks } from \"@shadow-js/core/extend\";\n *\n * export function boundaryHoldIfTransition() {\n * return transitionHooks()?.boundaryHold() ?? null;\n * }\n * @see inTransition\n * @since 1.0.0\n */\nexport function transitionHooks(): Hooks | null {\n return rt.inTransition ? rt.hooks : null;\n}\n\n/**\n * Pauses `owner` and everything below it (Activity hidden). User effects run their cleanups and wait.\n * DOM bindings (render effects) wait without a cleanup, so their nodes stay as they are. Memos keep their\n * last value, and effects created below are parked until the owner resumes. Pauses nest: each\n * `pauseOwner` needs one `resumeOwner`. Use it to hide a subtree while keeping its state.\n *\n * @param owner The owner to pause, with its whole subtree.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const hidden = createOwner(null);\n * pauseOwner(hidden); // its effects stop; its memos keep their values\n * resumeOwner(hidden); // its user effects run again with the latest values\n * @see resumeOwner\n * @since 1.0.0\n */\nexport function pauseOwner(owner: Owner): void {\n ensureHooks().pause(owner);\n}\n\n/**\n * Resumes an owner paused with {@link pauseOwner}; the subtree runs again once its last pause ends.\n * User effects below it run once more with the current values (their cleanups ran on pause). DOM\n * bindings run only if something they read changed while paused, so a hidden subtree is not rebuilt\n * on show. Memos that changed while paused wake their readers outside the owner. Call it once per\n * `pauseOwner`, not on an owner that is not paused.\n *\n * @param owner The paused owner.\n * @example\n * import { createOwner, pauseOwner, resumeOwner } from \"@shadow-js/core/extend\";\n *\n * const panel = createOwner(null);\n * pauseOwner(panel);\n * resumeOwner(panel); // every user effect below runs once with the latest values\n * @see pauseOwner\n * @since 1.0.0\n */\nexport function res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aAAeA,EAAG,MAAQ,IACtC,CAkBA,SAAgBgF,EAAW,EAAoB,CAC7CR,EAAY,CAAC,CAAC,MAAMvC,CAAK,CAC3B,CAmBA,SAAgBgD,EAAY,EAAoB,CAC9CjF,EAAG,OAAO,OAAOiC,CAAK,CACxB,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e={OWNER_CREATED:1,OWNER_DISPOSED:2,SIGNAL_CREATED:3,SIGNAL_WRITTEN:4,COMPUTATION_CREATED:5,COMPUTATION_RUN:6,COMPUTATION_DISPOSED:7,COMPONENT_MOUNTED:8,COMPONENT_UNMOUNTED:9,RESOURCE_STATE:10,ERROR:11,HYDRATION_MISMATCH:12,FLUSH_START:13,FLUSH_END:14,STORE_CREATED:15,TRANSITION_START:16,TRANSITION_END:17};function t(e,t,n,r,i,a){}export{e as DEVTOOLS_EVENT,t as report};
|
|
2
|
+
//# sourceMappingURL=devtools.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"devtools.js","names":["DEVTOOLS_EVENT","report"],"sources":["../../../src/internal/devtools.ts"],"sourcesContent":["/**\n * The runtime's side of the devtools protocol (version 1, see `@shadow-js/devtools`). The runtime\n * does not import that package: it looks up a global hook, in development builds only, and every\n * call site is wrapped as `if (__DEV__) report(...)` so production bundles drop it entirely.\n */\n\n/**\n * The event kinds of the devtools protocol (version 1), numbered as `EVENT` in `@shadow-js/devtools`\n * numbers them. Pass one to {@link devtoolsReport} when a custom primitive shows up in devtools; the\n * meaning of the other arguments of each kind is in the protocol table of the devtools README.\n *\n * Kinds 16 and 17 are the transition events, reported by `internal/concurrency.ts`: `TRANSITION_START`\n * (16) after a `transition()` callback has run, with no arguments; `TRANSITION_END` (17) when the\n * transition lane is idle, with the number of transitions it resolved. The devtools agent does not use\n * them yet.\n *\n * @example\n * import { DEVTOOLS_EVENT } from \"@shadow-js/core/extend\";\n *\n * function describe(kind: number): string {\n * if (kind === DEVTOOLS_EVENT.SIGNAL_WRITTEN) return \"signal written\";\n * if (kind === DEVTOOLS_EVENT.ERROR) return \"error\";\n * return `event ${kind}`;\n * }\n * @see devtoolsReport\n * @since 1.0.0\n */\nexport const DEVTOOLS_EVENT = {\n OWNER_CREATED: 1,\n OWNER_DISPOSED: 2,\n SIGNAL_CREATED: 3,\n SIGNAL_WRITTEN: 4,\n COMPUTATION_CREATED: 5,\n COMPUTATION_RUN: 6,\n COMPUTATION_DISPOSED: 7,\n COMPONENT_MOUNTED: 8,\n COMPONENT_UNMOUNTED: 9,\n RESOURCE_STATE: 10,\n ERROR: 11,\n HYDRATION_MISMATCH: 12,\n FLUSH_START: 13,\n FLUSH_END: 14,\n STORE_CREATED: 15,\n TRANSITION_START: 16,\n TRANSITION_END: 17,\n} as const;\n\nconst KEY = \"__SHADOWJS_DEVTOOLS_HOOK__\";\n\ninterface Hook {\n readonly version: number;\n report(kind: number, a?: unknown, b?: unknown, c?: unknown, d?: unknown, e?: unknown): void;\n}\n\n/**\n * Reports one event to the devtools hook (`globalThis.__SHADOWJS_DEVTOOLS_HOOK__`, protocol version\n * 1) when one is installed. Does nothing without a hook, with a hook of another version, and in\n * production builds. Exported from `@shadow-js/core/extend` as `devtoolsReport`. Pass the runtime's\n * own objects, not copies, so a report allocates nothing.\n *\n * @param kind The event kind, one of {@link DEVTOOLS_EVENT}.\n * @param a First argument of the event (see the protocol table of the devtools README).\n * @param b Second argument of the event, or undefined when the kind has none.\n * @param c Third argument of the event, or undefined when the kind has none.\n * @param d Fourth argument of the event, or undefined when the kind has none.\n * @param e Fifth argument of the event, or undefined when the kind has none.\n * @example\n * import { isDev } from \"@shadow-js/core\";\n * import { currentOwner, DEVTOOLS_EVENT, devtoolsReport } from \"@shadow-js/core/extend\";\n *\n * function reportFailure(error: unknown): void {\n * if (isDev) devtoolsReport(DEVTOOLS_EVENT.ERROR, currentOwner(), error, undefined);\n * }\n * @see DEVTOOLS_EVENT\n * @since 1.0.0\n */\nexport function report(\n kind: number,\n a?: unknown,\n b?: unknown,\n c?: unknown,\n d?: unknown,\n e?: unknown,\n): void {\n if (!__DEV__) return;\n const hook = Reflect.get(globalThis, KEY) as Hook | undefined;\n if (hook !== undefined && hook.version === 1) hook.report(kind, a, b, c, d, e);\n}\n"],"mappings":"AA2BA,MAAaA,EAAiB,CAC5B,cAAe,EACf,eAAgB,EAChB,eAAgB,EAChB,eAAgB,EAChB,oBAAqB,EACrB,gBAAiB,EACjB,qBAAsB,EACtB,kBAAmB,EACnB,oBAAqB,EACrB,eAAgB,GAChB,MAAO,GACP,mBAAoB,GACpB,YAAa,GACb,UAAW,GACX,cAAe,GACf,iBAAkB,GAClB,eAAgB,EAClB,EA+BA,SAAgBC,EACd,EACA,EACA,EACA,EACA,EACA,EACM,CAIR,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{formatMessage as e}from"./messages.js";var t=class extends Error{code;constructor(t){super(e(t)),this.name=`ShadowError`,this.code=t}};const n=/* @__PURE__ */ new Set;let r;function i(e){let t=r;return r=e,t}function a(){n.clear()}function o(e){}export{t as ShadowError,a as resetWarningDedupe,i as setWarningListener,o as warn};
|
|
2
|
+
//# sourceMappingURL=diagnostics.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"diagnostics.js","names":["ShadowError","formatMessage","code","seen","listener","setWarningListener","previous","next","resetWarningDedupe","warn"],"sources":["../../../src/internal/diagnostics.ts"],"sourcesContent":["import { formatMessage, type MessageCode } from \"./messages\";\n\n/**\n * The error class of every diagnostic the runtime throws, carrying a stable code next to the\n * message. Match on `code` rather than the message: the message is the full text in development\n * builds and only `SHADOW_<CODE>` in production builds. Throw it from a custom primitive to report a\n * core diagnostic the same way the built-in hooks do.\n *\n * @example\n * import { ShadowError } from \"@shadow-js/core/extend\";\n *\n * function isCycle(error: unknown): boolean {\n * return error instanceof ShadowError && error.code === \"CYCLE_DETECTED\";\n * }\n * @see MESSAGES\n * @since 1.0.0\n */\nexport class ShadowError extends Error {\n /** The diagnostic code, a key of {@link MESSAGES}; the same in development and production builds. */\n readonly code: MessageCode;\n /**\n * Creates the error with the text of {@link formatMessage} for `code` and the name `\"ShadowError\"`.\n * @param code The diagnostic code.\n */\n constructor(code: MessageCode) {\n super(formatMessage(code));\n this.name = \"ShadowError\";\n this.code = code;\n }\n}\n\n/**\n * A function that receives the warnings of {@link warn} instead of `console.warn`. Install one with\n * {@link setWarningListener}.\n * @param code The diagnostic code of the warning.\n * @param message The text of {@link formatMessage} for that code.\n * @since 1.0.0\n */\nexport type WarningListener = (code: MessageCode, message: string) => void;\n\nconst seen = new Set<MessageCode>();\nlet listener: WarningListener | undefined;\n\n/**\n * Sends every later warning to `next` instead of `console.warn`, for devtools and test helpers\n * (`@shadow-js/testing`) that collect warnings. Deduplication still applies: the listener receives\n * the first warning of each code only. Warnings exist in development builds only.\n *\n * @param next The listener to install. Undefined restores the default, `console.warn`.\n * @returns The listener that was installed before, or undefined when it was the default, so the\n * caller can restore it.\n * @example\n * import { type MessageCode, setWarningListener } from \"@shadow-js/core/extend\";\n *\n * const codes: MessageCode[] = [];\n * const previous = setWarningListener((code) => {\n * codes.push(code);\n * });\n * // ... run the code under test, then:\n * setWarningListener(previous);\n * @see warn\n * @see resetWarningDedupe\n * @since 1.0.0\n */\nexport function setWarningListener(next: WarningListener | undefined): WarningListener | undefined {\n const previous = listener;\n listener = next;\n return previous;\n}\n\n/**\n * Forgets which codes {@link warn} has already reported, so the next warning of each code is\n * reported again. Use it between test cases and after a hot reload.\n *\n * @example\n * import { resetWarningDedupe } from \"@shadow-js/core/extend\";\n *\n * function startTestCase(): void {\n * resetWarningDedupe(); // each case sees its own first warnings\n * }\n * @see warn\n * @since 1.0.0\n */\nexport function resetWarningDedupe(): void {\n seen.clear();\n}\n\n/**\n * Reports a development-only diagnostic. Only the first warning of each code is reported, for the\n * whole program, until {@link resetWarningDedupe}; it goes to the listener of\n * {@link setWarningListener}, or to `console.warn` with the text of {@link formatMessage}. Does\n * nothing in production builds. Use it for a mistake that should not stop the app; throw\n * {@link ShadowError} for one that must.\n *\n * @param code The diagnostic code to report.\n * @example\n * import { currentOwner, warn } from \"@shadow-js/core/extend\";\n *\n * export function useTicker(): void {\n * if (currentOwner() === null) warn(\"NO_OWNER_CLEANUP\");\n * }\n * @see setWarningListener\n * @since 1.0.0\n */\nexport function warn(code: MessageCode): void {\n if (!__DEV__) return;\n if (seen.has(code)) return;\n seen.add(code);\n const message = formatMessage(code);\n if (listener !== undefined) listener(code, message);\n else console.warn(message);\n}\n"],"mappings":"A,8CAiBA,IAAaA,EAAb,cAAiC,KAAM,CAErC,KAKA,YAAY,EAAmB,CAC7B,MAAMC,EAAcC,CAAI,CAAC,EACzB,KAAK,KAAO,cACZ,KAAK,KAAOA,CACd,CACF,EAWA,MAAMC,kBAAO,IAAI,IACjB,IAAIC,EAuBJ,SAAgBC,EAAmB,EAAgE,CACjG,IAAMC,EAAWF,EAEjB,MADA,GAAWG,EACJD,CACT,CAeA,SAAgBE,GAA2B,CACzCL,EAAK,MAAM,CACb,CAmBA,SAAgBM,EAAK,EAAyB,CAO9C,C"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{rt as e}from"./state.js";import{disposeTree as t}from"./owner.js";import{hasPending as n}from"./queue.js";import{flush as r}from"./scheduler.js";function i(i){let a,o=!1;try{t(i)}catch(e){o=!0,a=e}if(e.running===null&&e.batchDepth===0&&!e.flushing&&n())try{r()}catch(e){throw o?AggregateError([a,e],`SHADOW_DISPOSE_FLUSH_ERRORS`):e}if(o)throw a}export{i as disposeTree};
|
|
2
|
+
//# sourceMappingURL=dispose.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dispose.js","names":["disposeTree$1","disposeTree","failure","failed","root","error","rt","hasPending","flush"],"sources":["../../../src/internal/dispose.ts"],"sourcesContent":["import type { Owner } from \"./owner\";\nimport { disposeTree as disposeSubtree } from \"./owner\";\nimport { hasPending } from \"./queue\";\nimport { flush } from \"./scheduler\";\nimport { rt } from \"./state\";\n\n/**\n * Disposes an owner and everything below it: children first, newest first, then each node's\n * cleanups, newest first. Use it to end an owner made with `createOwner`; disposing an owner that is\n * already disposed does nothing. Exported from `@shadow-js/core/extend` as `disposeOwner`.\n *\n * Cleanups run in an implicit batch (O-3): effects that depend on signals a cleanup wrote are\n * flushed before this returns, unless the disposal happens inside a computation, a batch or a flush,\n * whose own exit flushes.\n *\n * @param root The owner to dispose, with its whole subtree.\n * @throws The error of a cleanup that no error handler caught, once the whole tree is disposed\n * (several such errors are thrown together as an `AggregateError`); during a running flush, that\n * flush throws them instead. An error of the flush that\n * follows is thrown as is, or combined with the cleanup errors in an `AggregateError`.\n * @example\n * import { addCleanup, createOwner, disposeOwner } from \"@shadow-js/core/extend\";\n *\n * const owner = createOwner(null);\n * addCleanup(owner, () => console.log(\"released\"));\n * disposeOwner(owner); // logs \"released\"\n * @see addCleanup\n * @since 1.0.0\n */\nexport function disposeTree(root: Owner): void {\n let failure: unknown;\n let failed = false;\n try {\n disposeSubtree(root);\n } catch (error) {\n failed = true;\n failure = error;\n }\n if (rt.running === null && rt.batchDepth === 0 && !rt.flushing && hasPending()) {\n try {\n flush();\n } catch (error) {\n if (!failed) throw error;\n throw new AggregateError(\n [failure, error],\n __DEV__ ? \"Disposal and the following flush both threw.\" : \"SHADOW_DISPOSE_FLUSH_ERRORS\",\n );\n }\n }\n if (failed) throw failure;\n}\n"],"mappings":"A,wJA6BA,SAAgBC,EAAY,EAAmB,CAC7C,IAAIC,EACAC,EAAS,GACb,GAAI,CACFH,EAAeI,CAAI,CACrB,OAASC,EAAO,CACd,EAAS,GACT,EAAUA,CACZ,CACA,GAAIC,EAAG,UAAY,MAAQA,EAAG,aAAe,GAAK,CAACA,EAAG,UAAYC,EAAW,EAC3E,GAAI,CACFC,EAAM,CACR,OAASH,EAAO,CAEd,MADKF,EACK,eACR,CAACD,EAASG,CAAK,EAC4C,6BAC7D,EAJmBA,CAKrB,CAEF,GAAIF,EAAQ,MAAMD,CACpB,C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flags.js","names":["FLAG_TRANSITION","FLAG_PARKED","FLAG_SUSPENDED"],"sources":["../../../src/internal/flags.ts"],"sourcesContent":["/** Node states: how stale a node is. Monotonic CLEAN < CHECK < DIRTY between two refreshes. */\nexport const CLEAN = 0;\n/** A transitive source changed; verify sources before recomputing. */\nexport const CHECK = 1;\n/** A direct source changed; recompute. */\nexport const DIRTY = 2;\n\n/** Node kinds. */\nexport const KIND_SIGNAL = 0;\nexport const KIND_MEMO = 1;\nexport const KIND_EFFECT = 2;\n\n/** Bit flags on computations. */\nexport const FLAG_RUNNING = 1;\nexport const FLAG_QUEUED = 2;\nexport const FLAG_DISPOSED = 4;\nexport const FLAG_HAS_ERROR = 8;\n/** Effect belongs to the render phase (runs before user effects, synchronously at creation). */\nexport const FLAG_RENDER = 16;\n/** Memo has not produced its first value yet. */\nexport const FLAG_UNINIT = 32;\n/** Explicit-dependency effect whose first apply is skipped. */\nexport const FLAG_DEFER = 64;\n/** Node is on the pull stack of updateIfNecessary (guards re-entrant ancestor refreshes). */\nexport const FLAG_REFRESHING = 128;\n/** Memo that builds components: its body may write signals (component setup does). */\nexport const FLAG_ALLOW_WRITES = 256;\n/** Effect always runs in the transition lane (the watcher behind useDeferredValue). */\nexport const FLAG_LANE = 512;\n/** Effect is queued in (or parked from) the transition lane, not the urgent queues. */\nexport const FLAG_TRANSITION = 1024;\n/** Effect was due while its owner was paused: it waits, unqueued, until the owner resumes. */\nexport const FLAG_PARKED = 2048;\n/** Computation threw a suspension: it keeps its previous value until its boundary releases it. */\nexport const FLAG_SUSPENDED = 4096;\n"],"mappings":"AA8BA,MAAaA,EAAkB,KAElBC,EAAc,KAEdC,EAAiB,K"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{ShadowError as e}from"./diagnostics.js";import{nextSequence as t,rt as n}from"./state.js";import{Owner as r,addCleanup as i,disposeChildren as a,handleError as o,hasErrorHandler as s}from"./owner.js";import{enqueue as c}from"./queue.js";const l=Object.freeze([]);var u=class{kind=0;value;equals;observers=null;stamp=0;name;constructor(e,t,n){this.value=e,this.equals=t,this.name=n}},d=class extends r{kind;state;flags;value;error=void 0;equals;fn;apply=null;sources=l;observers=null;stamp=0;trackIndex=0;seq;name;constructor(e,n,r,i,a,o){super(e),this.kind=n,this.flags=r,this.state=2,this.fn=i,this.equals=a,this.name=o,this.value=void 0,this.seq=t()}reportDisposed(){}release(){this.flags|=4,p(this),this.fn=null,this.apply=null}};function f(e,t){let n=e.observers;if(n===null)return;let r=n.length-2;if(t!==r){let e=n[r],i=n[r+1];n[t]=e,n[t+1]=i,e.sources[i+1]=t}n.length=r}function p(e){m(e,0)}function m(e,t){let n=e.sources;if(!(n.length<=t)){for(let e=n.length-2;e>=t;e-=2)f(n[e],n[e+1]);n.length=t}}function h(e,t,n){let r=e.length;if(r>=16)return e.push(t,n),e;let i=Array(r+2);for(let t=0;t<r;t+=1)i[t]=e[t];return i[r]=t,i[r+1]=n,i}function g(e){let t=n.listener;if(t===null||e.stamp===t.stamp)return;e.stamp=t.stamp;let r=t.trackIndex;if(r<t.sources.length){if(t.sources[r]===e){t.trackIndex=r+2;return}m(t,r)}let i=e.observers,a=t.sources,o=i===null?0:i.length,s=a.length;e.observers=i===null?[t,s]:h(i,t,s),t.sources=h(a,e,o),t.trackIndex=s+2}function _(e){return b(e.sources)}function v(e){return e.observers===null?[]:b(e.observers)}function y(e){return e.observers!==null&&e.observers.length>0}function b(e){let t=[];for(let n=0;n<e.length;n+=2)t.push(e[n]);return t}const x=[];function S(e,t){let r=e.state;e.kind===2?(r<t&&(e.state=t),r===0?c(e):n.inTransition||n.hooks?.promote(e)):r>=t||(e.state=t,r===0&&e.observers!==null&&e.observers.length>0&&x.push(e))}function C(e,t){return n.hooks?.suspend(e,t)===!0}function w(e){return e.pauses>0&&!(e.flags&32)}function T(e){for(E(e.observers,2);x.length>0;){let e=x.pop();e!==void 0&&E(e.observers,1)}}function E(e,t){if(e!==null)for(let n=0;n<e.length;n+=2)S(e[n],t)}const D=[],O=[];let k=0;function A(t,n=!1){if(t.state===0)return;let r=k;D[k]=t,O[k]=0,k+=1,t.flags|=128;try{for(;k>r;){let t=k-1,r=D[t];if(r===void 0)break;if(r.state===1||r.state===2&&n){let n=r.sources,i=O[t]??0,a=!1;for(;i<n.length;){let r=n[i];if(i+=2,r.kind===0)continue;let o=r;if(!(o.state===0||o.flags&4)&&!w(o)){if(o.flags&1)throw new e(`CYCLE_DETECTED`);if(j(o),!(o.state===0||o.flags&4)&&!w(o)){O[t]=i,D[k]=o,O[k]=0,k+=1,o.flags|=128,a=!0;break}}}if(a)continue}r.state===2?P(r):r.state=0,r.flags&=-129,--k}}finally{for(let e=r;e<k;e+=1){let t=D[e];t!==void 0&&(t.flags&=-129)}D.length=r,O.length=r,k=r}}function j(e){let t=[];for(let n=e.parent;n!==null;n=n.parent)n instanceof d&&n.state!==0&&!(n.flags&133)&&!w(n)&&t.push(n);for(let e=t.length-1;e>=0;--e){let n=t[e];n!==void 0&&!(n.flags&4)&&A(n)}}function M(e){return n.listener!==null&&g(e),e.value}function N(t){if(t.flags&1)throw new e(`CYCLE_DETECTED`);if(t.state!==0&&!(t.flags&4)&&!w(t)&&(j(t),t.flags&4||A(t,n.recomputeDepth>=128)),n.listener!==null&&g(t),t.flags&8)throw t.error;return t.value}function P(e){let r=e.fn;if(r===null)return;a(e),e.runCleanups(),e.trackIndex=0,e.errorHandlers=null,e.idCount=0,e.childCount=0;let i=n.owner,o=n.listener,s=n.running;n.owner=e,n.listener=e,n.running=e,n.recomputeDepth+=1,e.state=0,e.flags|=1,e.stamp=t();let c,l=!1,u;try{c=r(e.value)}catch(e){l=!0,u=e}finally{n.owner=i,n.listener=o,n.running=s,--n.recomputeDepth,e.flags&=-2,e.trackIndex<e.sources.length&&m(e,e.trackIndex)}e.kind===1&&F(e,c,l,u),e.kind!==1&&L(e,c,l,u)}function F(e,t,n,r){if(n&&C(e,r))return!1;let i=!!(e.flags&32);e.flags&=-33;let a=!!(e.flags&8),o;if(n&&I(e,r))return!1;if(n)e.flags|=8,e.error=r,o=!0;else{e.flags&=-9,e.error=void 0;let n=e.equals;try{o=i||a||n===!1||!n(e.value,t),o&&(e.value=t)}catch(t){e.flags|=8,e.error=t,o=!0}}if(!o||i)return o;let s=e.observers;if(s===null)return o;for(let e=0;e<s.length;e+=2){let t=s[e];t.state===1&&(t.state=2)}return o}function I(e,t){if(!s(e))return!1;e.flags&=-9,e.error=void 0;try{o(t,e)}catch(t){e.flags|=8,e.error=t}return!0}function L(e,t,r,a){if(r){C(e,a)||o(a,e);return}let s=e.apply,c;if(s===null)c=t;else{let r=!!(e.flags&64);e.flags&=-65;let i=e.value;if(e.value=t,r)return;let a=n.owner,l=n.listener,u=n.running;n.owner=e,n.listener=null,n.running=e;try{c=s(t,i)}catch(t){C(e,t)||o(t,e);return}finally{n.owner=a,n.listener=l,n.running=u}}typeof c==`function`&&(i(e,c),e.flags&4&&e.runCleanups())}export{d as Computation,u as Signal,y as hasObservers,w as isFrozen,T as markObservers,v as observersOf,N as readMemo,M as readSignal,P as recompute,_ as sourcesOf,g as track,p as unlinkSources,A as updateIfNecessary};
|
|
2
|
+
//# sourceMappingURL=graph.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"graph.js","names":["NO_SOURCES","Signal","value","equals","name","Computation","Owner","parent","kind","flags","fn","nextSequence","unlinkSources","removeObserver","observers","source","last","at","moved","movedAt","unlinkFrom","node","sources","from","i","withEdge","length","array","first","second","next","track","listener","rt","position","index","sourcesOf","everyOther","observersOf","hasObservers","out","edges","markStack","stale","previous","observer","enqueue","trySuspend","error","isFrozen","markObservers","staleObservers","frameNodes","frameIndex","frameTop","updateIfNecessary","root","base","eagerSources","cursor","descended","dependency","ShadowError","refreshAncestors","recompute","pending","owner","ancestor","readSignal","signal","readMemo","memo","disposeChildren","previousOwner","previousListener","previousRunning","result","failed","failure","settleMemo","settleEffect","hadError","changed","routeToHandler","comparatorError","hasErrorHandler","handleError","unhandled","apply","cleanup","deferred","previousValue","addCleanup"],"sources":["../../../src/internal/graph.ts"],"sourcesContent":["import { DEVTOOLS_EVENT, report } from \"./devtools\";\nimport { ShadowError } from \"./diagnostics\";\nimport {\n CHECK,\n CLEAN,\n DIRTY,\n FLAG_DEFER,\n FLAG_DISPOSED,\n FLAG_HAS_ERROR,\n FLAG_REFRESHING,\n FLAG_RENDER,\n FLAG_RUNNING,\n FLAG_UNINIT,\n KIND_EFFECT,\n KIND_MEMO,\n KIND_SIGNAL,\n} from \"./flags\";\nimport { addCleanup, disposeChildren, handleError, hasErrorHandler, Owner } from \"./owner\";\nimport { enqueue } from \"./queue\";\nimport { nextSequence, rt } from \"./state\";\nimport type { Cleanup, Equals } from \"./types\";\n\n// Shared and frozen until a computation reads its first source: most effects and memos in a large\n// tree own few edges, and an empty array per node dominates creation cost.\nconst NO_SOURCES: Edges<Source> = Object.freeze([]) as unknown as Edges<Source>;\n\n/** Memo nesting depth after which pulls switch from recursion to the iterative walk. */\nconst DEEP_LIMIT = 128;\n\n/**\n * Anything that can be read reactively and notify observers: a signal, a memo, or a custom source\n * of a primitive. Exported from `@shadow-js/core/extend` as `SourceNode`. Read one with\n * {@link track}; after changing it, call {@link markObservers} and `schedule` (or `notify`).\n * @since 1.0.0\n */\nexport interface Source {\n /**\n * The node kind: 0 for a signal and for any custom source, which have no sources of their own; a\n * computation has its own kind. A refresh walks only the sources whose kind is not 0.\n */\n readonly kind: number;\n /** The current value. */\n value: unknown;\n /**\n * The computations that read this source in their last run, as pairs: an observer, then the index of this source in\n * that observer's `sources`. Null or empty when none. Read it with `observersOf`, which returns the observers alone.\n */\n observers: Edges<Computation> | null;\n /** Stamp of the last computation run that tracked this source (dedupes repeated reads). */\n stamp: number;\n}\n\n/**\n * The edges of one node, stored as pairs in one array: the node on the other side of the edge, then the index of this\n * node's entry in that node's own edge array. One array per side costs half the memory of two parallel ones, and\n * removing an edge stays O(1): the last pair moves into the vacated place and tells its owner where it went.\n */\nexport type Edges<T> = Array<T | number>;\n\n/**\n * The storage of a signal: its value, its equality and the computations that read it. Exported from\n * `@shadow-js/core/extend` as `SignalNode`; create one with `createSignalNode`, read it with\n * {@link readSignal} and write it with `writeSignal`, which notifies its readers. Build a custom\n * primitive on it the way `useSignal` does.\n *\n * @example\n * import { createSignalNode, readSignal, SignalNode, writeSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(0, Object.is, \"count\");\n * writeSignal(count, 1);\n * console.log(readSignal(count), count instanceof SignalNode); // 1 true\n * @see createSignalNode\n * @since 1.0.0\n */\nexport class Signal<T = unknown> implements Source {\n /** Always 0, the kind of a signal. */\n readonly kind: number = KIND_SIGNAL;\n /**\n * The current value. Assigning it directly notifies no one: use `writeSignal`, or call `notify`\n * after the assignment.\n */\n value: T;\n /** Decides whether a write is a change; `false` treats every write as one. */\n equals: Equals<T>;\n /** The computations that read this signal in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the last computation run that tracked this signal (dedupes repeated reads). */\n stamp = 0;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name: string | undefined;\n\n /**\n * Creates a signal. Prefer `createSignalNode`, which takes the same arguments.\n * @param value Initial value.\n * @param equals Equality that decides whether a write is a change.\n * @param name Devtools label, or undefined for an unnamed signal.\n */\n constructor(value: T, equals: Equals<T>, name: string | undefined) {\n this.value = value;\n this.equals = equals;\n this.name = name;\n if (__DEV__) report(DEVTOOLS_EVENT.SIGNAL_CREATED, this, rt.owner, name, value);\n }\n}\n\n/**\n * A memo or an effect: an owner that reads sources and (for memos) is itself a source. Exported from\n * `@shadow-js/core/extend` as `ComputationNode`; create one with `createComputation` and read a memo\n * with `readComputation`. It owns what its function creates: each run first disposes the children\n * and runs the cleanups of the previous run.\n *\n * @example\n * import { createComputation, createSignalNode, readComputation, readSignal } from \"@shadow-js/core/extend\";\n *\n * const price = createSignalNode(10, Object.is);\n * const total = createComputation({ kind: \"memo\", fn: () => readSignal(price) * 2 });\n * console.log(readComputation<number>(total)); // 20\n * @see createComputation\n * @since 1.0.0\n */\nexport class Computation extends Owner implements Source {\n /** 1 for a memo, 2 for an effect. */\n kind: number;\n /** How stale the node is: 0 (clean), 1 (a transitive source changed), 2 (a direct source changed). */\n state: number;\n /** Engine bit flags (queued, running, disposed, render phase, ...). Read-only outside the engine. */\n flags: number;\n /** A memo's last value; an effect's last computed value when it has an `apply` stage. */\n value: unknown;\n /** The error a memo's last run threw, rethrown to its readers; undefined when it succeeded. */\n error: unknown = undefined;\n /** A memo's equality: readers are notified only when it says the new value differs. */\n equals: Equals<unknown>;\n /** The function each run calls with the previous value; null once disposed. */\n fn: ((previous: never) => unknown) | null;\n /**\n * An effect's second stage, run untracked with the computed value and the previous one; null for\n * none and once disposed.\n */\n apply: ((value: never, previous: never) => unknown) | null = null;\n /**\n * The sources the last run read, in reading order, as pairs: a source, then the index of this computation in that\n * source's `observers`. Read it with `sourcesOf`, which returns the sources alone.\n */\n sources: Edges<Source> = NO_SOURCES;\n /** The computations that read this memo in their last run, as pairs (see {@link Source.observers}). */\n observers: Edges<Computation> | null = null;\n /** Stamp of the current run while it tracks, and of the last run that tracked this memo. */\n stamp = 0;\n /** During a run: how many leading entries of `sources` were confirmed again (they keep their edges). */\n trackIndex = 0;\n /** Creation order; breaks ties between effects at equal depth (G-16). */\n seq: number;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the computation is unnamed)\n */\n name: string | undefined;\n\n /**\n * Creates a computation that has not run yet. Prefer `createComputation`, which also runs or\n * queues it.\n * @param parent The owner to attach to, or null.\n * @param kind 1 for a memo, 2 for an effect.\n * @param flags Initial engine bit flags.\n * @param fn The function each run calls.\n * @param equals A memo's equality; `false` for an effect.\n * @param name Devtools label, or undefined.\n */\n constructor(\n parent: Owner | null,\n kind: number,\n flags: number,\n fn: (previous: never) => unknown,\n equals: Equals<unknown>,\n name: string | undefined,\n ) {\n super(parent);\n this.kind = kind;\n this.flags = flags;\n this.state = DIRTY;\n this.fn = fn;\n this.equals = equals;\n this.name = name;\n this.value = undefined;\n this.seq = nextSequence();\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_CREATED,\n this,\n parent,\n kind === KIND_MEMO ? \"memo\" : \"effect\",\n name,\n (flags & FLAG_RENDER) !== 0,\n );\n }\n }\n\n protected override reportDisposed(): void {\n if (__DEV__) report(DEVTOOLS_EVENT.COMPUTATION_DISPOSED, this);\n }\n\n protected override release(): void {\n this.flags |= FLAG_DISPOSED;\n unlinkSources(this);\n this.fn = null;\n this.apply = null;\n }\n}\n\n/**\n * Removes the pair at `at` from `source.observers` in O(1): the last pair moves into its place, and its observer is told\n * where it went.\n */\nfunction removeObserver(source: Source, at: number): void {\n const observers = source.observers;\n if (observers === null) return;\n const last = observers.length - 2;\n if (at !== last) {\n const moved = observers[last] as Computation;\n const movedAt = observers[last + 1] as number;\n observers[at] = moved;\n observers[at + 1] = movedAt;\n moved.sources[movedAt + 1] = at;\n }\n observers.length = last;\n}\n\n/** Drops every edge from `node` to its sources. */\nexport function unlinkSources(node: Computation): void {\n unlinkFrom(node, 0);\n}\n\n/** Drops the edges from `node` to the sources at index `from` of `node.sources` and later, and truncates the list. */\nfunction unlinkFrom(node: Computation, from: number): void {\n const sources = node.sources;\n if (sources.length <= from) return;\n for (let i = sources.length - 2; i >= from; i -= 2) {\n // The index in the source is read each time: removing an edge may move this node's pair in another source.\n removeObserver(sources[i] as Source, sources[i + 1] as number);\n }\n sources.length = from;\n}\n\n/**\n * The array with the pair `first`, `second` appended: a new array of exactly the right size while short (`new Array(n)`\n * allocates the backing store at that size, where `push` on a short array reserves room for sixteen), the same array\n * grown by `push` from sixteen entries on.\n */\nfunction withEdge<T>(array: Array<T | number>, first: T, second: number): Array<T | number> {\n const length = array.length;\n if (length >= 16) {\n array.push(first, second);\n return array;\n }\n const next = new Array<T | number>(length + 2);\n for (let i = 0; i < length; i += 1) next[i] = array[i] as T | number;\n next[length] = first;\n next[length + 1] = second;\n return next;\n}\n\n/**\n * Records that the running computation read `source`, so a later {@link markObservers} on it marks\n * that computation stale. Call it in the reader of a custom source; {@link readSignal} does it for\n * signals. Does nothing when untracked, and a source read again in the same run is recorded once.\n *\n * @param source The source that was read.\n * @example\n * import { markObservers, schedule, type SourceNode, track } from \"@shadow-js/core/extend\";\n *\n * const clock: SourceNode = { kind: 0, value: Date.now(), observers: null, stamp: 0 };\n * export function now(): number {\n * track(clock);\n * return clock.value as number;\n * }\n * setInterval(() => {\n * clock.value = Date.now();\n * markObservers(clock);\n * schedule();\n * }, 1000);\n * @see readSignal\n * @since 1.0.0\n */\nexport function track(source: Source): void {\n const listener = rt.listener;\n if (listener === null) return;\n if (source.stamp === listener.stamp) return;\n source.stamp = listener.stamp;\n // Same dependency at the same position as last run: keep the edge, touch nothing.\n const position = listener.trackIndex;\n if (position < listener.sources.length) {\n if (listener.sources[position] === source) {\n listener.trackIndex = position + 2;\n return;\n }\n unlinkFrom(listener, position);\n }\n // Edge arrays are small: most nodes have one to three edges. `push` on a short array reserves room for about sixteen\n // entries (200 bytes where an exact array takes 64, measured), and a large list pays it for every row. A short array\n // therefore grows into a new exact one; from sixteen entries on `push` amortizes. Nothing iterates an edge array of\n // a node while it tracks, so replacing the array is safe.\n const observers = source.observers;\n const sources = listener.sources;\n const at = observers === null ? 0 : observers.length;\n const index = sources.length;\n source.observers =\n observers === null\n ? [listener, index]\n : (withEdge(observers, listener, index) as Edges<Computation>);\n listener.sources = withEdge(sources, source, at) as Edges<Source>;\n listener.trackIndex = index + 2;\n}\n\n/**\n * The sources the last run of a computation read, in reading order. Use it to inspect the graph (a debugger, a test);\n * it is a snapshot, so changing the returned array changes no edge.\n *\n * @param node The memo or effect.\n * @returns The signals and memos it reads now.\n * @example\n * import { createComputation, createSignalNode, flushSync, readSignal, sourcesOf } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * const effect = createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(sourcesOf(effect).length); // 1\n * @see observersOf\n * @since 1.0.0\n */\nexport function sourcesOf(node: Computation): Source[] {\n return everyOther(node.sources) as Source[];\n}\n\n/**\n * The computations that read a signal or memo in their last run, in the order their edges were made. It is a snapshot,\n * so changing the returned array changes no edge. The node's own `observers` array stores pairs (the observer and an\n * index for the engine), so read it through this function.\n *\n * @param source A signal, a memo or a custom source.\n * @returns The memos and effects that read it now.\n * @example\n * import { createComputation, createSignalNode, flushSync, observersOf, readSignal } from \"@shadow-js/core/extend\";\n *\n * const count = createSignalNode<number>(1, Object.is, \"count\");\n * createComputation({ kind: \"effect\", fn: () => void readSignal(count) });\n * flushSync();\n * console.log(observersOf(count).length); // 1\n * @see sourcesOf\n * @since 1.0.0\n */\nexport function observersOf(source: Source): Computation[] {\n return source.observers === null ? [] : (everyOther(source.observers) as Computation[]);\n}\n\n/** True when at least one computation read `source` in its last run. */\nexport function hasObservers(source: Source): boolean {\n return source.observers !== null && source.observers.length > 0;\n}\n\n/** The first element of every pair of an edge array. */\nfunction everyOther<T>(edges: Edges<T>): T[] {\n const out: T[] = [];\n for (let i = 0; i < edges.length; i += 2) out.push(edges[i] as T);\n return out;\n}\n\n// Scratch stack for markObservers; never holds data across calls.\nconst markStack: Computation[] = [];\n\nfunction stale(observer: Computation, next: number): void {\n const previous = observer.state;\n if (observer.kind === KIND_EFFECT) {\n if (previous < next) observer.state = next;\n if (previous === CLEAN) enqueue(observer);\n else if (!rt.inTransition) rt.hooks?.promote(observer);\n return;\n }\n if (previous >= next) return;\n observer.state = next;\n if (previous !== CLEAN) return;\n if (observer.observers !== null && observer.observers.length > 0) markStack.push(observer);\n}\n\n/**\n * A suspension (a transition read pending data inside a held boundary) keeps the node's value until the\n * boundary releases it. True when `error` was one, and the node was recorded for that wake-up.\n */\nfunction trySuspend(node: Computation, error: unknown): boolean {\n return rt.hooks?.suspend(node, error) === true;\n}\n\n/**\n * A memo or effect frozen by a pause keeps its last value and does not refresh until it resumes.\n * A memo that never computed is not frozen (it has no value to keep).\n */\nexport function isFrozen(node: Computation): boolean {\n return node.pauses > 0 && (node.flags & FLAG_UNINIT) === 0;\n}\n\n/**\n * Marks the direct observers of a changed source DIRTY and everything downstream CHECK, and queues\n * the effects it reaches. It does not request a flush: call `schedule` afterward, or use `notify`,\n * which does both. Iterative: the graph can be 100,000 nodes deep (G-10).\n *\n * @param source The source whose value changed.\n * @example\n * import { markObservers, schedule, type SignalNode } from \"@shadow-js/core/extend\";\n *\n * export function push(list: SignalNode<string[]>, item: string): void {\n * list.value.push(item); // same array: writeSignal would see no change\n * markObservers(list);\n * schedule();\n * }\n * @see track\n * @since 1.0.0\n */\nexport function markObservers(source: Source): void {\n staleObservers(source.observers, DIRTY);\n while (markStack.length > 0) {\n const node = markStack.pop();\n if (node !== undefined) staleObservers(node.observers, CHECK);\n }\n}\n\n/** Marks every observer in a list of edge pairs stale at the given level. */\nfunction staleObservers(observers: Edges<Computation> | null, next: number): void {\n if (observers === null) return;\n for (let i = 0; i < observers.length; i += 2) stale(observers[i] as Computation, next);\n}\n\n// Scratch frames for updateIfNecessary; entries above `frameTop` are dead.\nconst frameNodes: Computation[] = [];\nconst frameIndex: number[] = [];\nlet frameTop = 0;\n\n/**\n * Brings `root` up to date: verifies stale sources oldest-first and recomputes only nodes whose\n * sources really changed (equality cut-off, G-2). Iterative so deep chains cannot overflow (G-10).\n * With `eagerSources`, DIRTY nodes also refresh their previous sources first, which keeps the\n * native stack flat for chains where every node reads both a fresh signal and its predecessor.\n */\nexport function updateIfNecessary(root: Computation, eagerSources = false): void {\n if (root.state === CLEAN) return;\n const base = frameTop;\n frameNodes[frameTop] = root;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n root.flags |= FLAG_REFRESHING;\n try {\n while (frameTop > base) {\n const at = frameTop - 1;\n const node = frameNodes[at];\n if (node === undefined) break;\n if (node.state === CHECK || (node.state === DIRTY && eagerSources)) {\n const sources = node.sources;\n let cursor = frameIndex[at] ?? 0;\n let descended = false;\n while (cursor < sources.length) {\n const source = sources[cursor] as Source;\n cursor += 2;\n if (source.kind === KIND_SIGNAL) continue;\n const dependency = source as Computation;\n if (dependency.state === CLEAN || (dependency.flags & FLAG_DISPOSED) !== 0) continue;\n if (isFrozen(dependency)) continue;\n if ((dependency.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n // An owner that is about to re-run would dispose this dependency: update it first.\n refreshAncestors(dependency);\n if (dependency.state === CLEAN || (dependency.flags & FLAG_DISPOSED) !== 0) continue;\n if (isFrozen(dependency)) continue;\n frameIndex[at] = cursor;\n frameNodes[frameTop] = dependency;\n frameIndex[frameTop] = 0;\n frameTop += 1;\n dependency.flags |= FLAG_REFRESHING;\n descended = true;\n break;\n }\n if (descended) continue;\n }\n if (node.state === DIRTY) recompute(node);\n else node.state = CLEAN;\n node.flags &= ~FLAG_REFRESHING;\n frameTop -= 1;\n }\n } finally {\n // An exception leaves frames on the stack: they must not stay marked as being refreshed.\n for (let i = base; i < frameTop; i += 1) {\n const pending = frameNodes[i];\n if (pending !== undefined) pending.flags &= ~FLAG_REFRESHING;\n }\n frameNodes.length = base;\n frameIndex.length = base;\n frameTop = base;\n }\n}\n\n/**\n * Brings stale owners of `node` up to date, topmost first. An owner that is about to re-run will\n * dispose `node`; computing `node` first would run it with state that is already out of date\n * (a zombie, G-17). Iterative: the owner chain depth is user controlled.\n */\nfunction refreshAncestors(node: Computation): void {\n const stale: Computation[] = [];\n for (let owner = node.parent; owner !== null; owner = owner.parent) {\n if (!(owner instanceof Computation)) continue;\n if (\n owner.state !== CLEAN &&\n (owner.flags & (FLAG_RUNNING | FLAG_DISPOSED | FLAG_REFRESHING)) === 0 &&\n !isFrozen(owner)\n ) {\n stale.push(owner);\n }\n }\n for (let i = stale.length - 1; i >= 0; i -= 1) {\n const ancestor = stale[i];\n if (ancestor !== undefined && (ancestor.flags & FLAG_DISPOSED) === 0) {\n updateIfNecessary(ancestor);\n }\n }\n}\n\n/**\n * Reads a signal's value, subscribing the running computation to it when one is listening. The\n * reader of a custom primitive built on `createSignalNode`.\n *\n * @param signal The signal to read.\n * @returns The current value.\n * @example\n * import { createSignalNode, readSignal } from \"@shadow-js/core/extend\";\n *\n * const name = createSignalNode(\"Ada\", Object.is);\n * export const getName = (): string => readSignal(name);\n * @see track\n * @since 1.0.0\n */\nexport function readSignal<T>(signal: Signal<T>): T {\n if (rt.listener !== null) track(signal);\n return signal.value;\n}\n\n/** Reads a memo: refreshes it if stale, tracks it, rethrows its stored error. */\nexport function readMemo<T>(memo: Computation): T {\n if ((memo.flags & FLAG_RUNNING) !== 0) throw new ShadowError(\"CYCLE_DETECTED\");\n if (memo.state !== CLEAN && (memo.flags & FLAG_DISPOSED) === 0 && !isFrozen(memo)) {\n refreshAncestors(memo);\n if ((memo.flags & FLAG_DISPOSED) === 0) {\n updateIfNecessary(memo, rt.recomputeDepth >= DEEP_LIMIT);\n }\n }\n if (rt.listener !== null) track(memo);\n if ((memo.flags & FLAG_HAS_ERROR) !== 0) throw memo.error;\n return memo.value as T;\n}\n\n/** Re-runs a memo or effect: disposes the previous run, re-tracks sources, stores the result. */\nexport function recompute(node: Computation): void {\n const fn = node.fn;\n if (fn === null) return;\n disposeChildren(node);\n node.runCleanups();\n // Edges are kept and re-confirmed in order while the function runs (see track()).\n node.trackIndex = 0;\n // Each run starts from a clean slate: handlers, ids and child indices belong to one run.\n node.errorHandlers = null;\n node.idCount = 0;\n node.childCount = 0;\n\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = node;\n rt.running = node;\n rt.recomputeDepth += 1;\n node.state = CLEAN;\n node.flags |= FLAG_RUNNING;\n node.stamp = nextSequence();\n\n let result: unknown;\n let failed = false;\n let failure: unknown;\n const startedAt = __DEV__ ? performance.now() : 0;\n try {\n result = (fn as (previous: unknown) => unknown)(node.value);\n } catch (error) {\n failed = true;\n failure = error;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n rt.recomputeDepth -= 1;\n node.flags &= ~FLAG_RUNNING;\n // Sources this run did not read again are no longer dependencies.\n if (node.trackIndex < node.sources.length) unlinkFrom(node, node.trackIndex);\n }\n\n const changed = node.kind === KIND_MEMO ? settleMemo(node, result, failed, failure) : true;\n if (node.kind !== KIND_MEMO) settleEffect(node, result, failed, failure);\n if (__DEV__) {\n report(\n DEVTOOLS_EVENT.COMPUTATION_RUN,\n node,\n startedAt,\n performance.now() - startedAt,\n changed,\n sourcesOf(node),\n );\n }\n}\n\n/** Stores a memo's result; says whether its value changed (observers were told). */\nfunction settleMemo(\n node: Computation,\n result: unknown,\n failed: boolean,\n failure: unknown,\n): boolean {\n // A suspended memo keeps its previous value: its readers see nothing change until it resumes.\n if (failed && trySuspend(node, failure)) return false;\n const first = (node.flags & FLAG_UNINIT) !== 0;\n node.flags &= ~FLAG_UNINIT;\n const hadError = (node.flags & FLAG_HAS_ERROR) !== 0;\n let changed: boolean;\n if (failed && routeToHandler(node, failure)) {\n return false;\n }\n if (failed) {\n node.flags |= FLAG_HAS_ERROR;\n node.error = failure;\n changed = true;\n } else {\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n const equals = node.equals;\n try {\n changed = first || hadError || equals === false || !equals(node.value, result);\n if (changed) node.value = result;\n } catch (comparatorError) {\n // A throwing comparator is a failing memo, not a wedged graph: readers see the error.\n node.flags |= FLAG_HAS_ERROR;\n node.error = comparatorError;\n changed = true;\n }\n }\n if (!changed || first) return changed;\n const observers = node.observers;\n if (observers === null) return changed;\n for (let i = 0; i < observers.length; i += 2) {\n const observer = observers[i] as Computation;\n if (observer.state === CHECK) observer.state = DIRTY;\n }\n return changed;\n}\n\n/**\n * A memo that fails inside a boundary (an ancestor registered catchError()/onError()) reports to it\n * when it fails, and keeps its previous value. Readers then see that value instead of the error:\n * the reader may live outside the boundary (the DOM region that displays the memo's result), where a\n * rethrown error would escape the very boundary meant to catch it. Without a handler the error is\n * stored and rethrown to readers, so it is never silent.\n *\n * The first computation counts too: its value is `undefined`, and it is typically read by a\n * consumer outside the boundary (a DOM region), not by the code that created it.\n */\nfunction routeToHandler(node: Computation, failure: unknown): boolean {\n if (!hasErrorHandler(node)) return false;\n node.flags &= ~FLAG_HAS_ERROR;\n node.error = undefined;\n try {\n handleError(failure, node);\n } catch (unhandled) {\n // The chain ended in a handler that rethrew: readers see it, as for any unhandled failure.\n node.flags |= FLAG_HAS_ERROR;\n node.error = unhandled;\n }\n return true;\n}\n\nfunction settleEffect(node: Computation, result: unknown, failed: boolean, failure: unknown): void {\n if (failed) {\n if (!trySuspend(node, failure)) handleError(failure, node);\n return;\n }\n const apply = node.apply;\n let cleanup: unknown;\n if (apply === null) {\n cleanup = result;\n } else {\n const deferred = (node.flags & FLAG_DEFER) !== 0;\n node.flags &= ~FLAG_DEFER;\n const previousValue = node.value;\n node.value = result;\n if (deferred) return;\n const previousOwner = rt.owner;\n const previousListener = rt.listener;\n const previousRunning = rt.running;\n rt.owner = node;\n rt.listener = null;\n // Writes from an effect's apply are legal even when the effect was created inside a memo.\n rt.running = node;\n try {\n cleanup = (apply as (value: unknown, previous: unknown) => unknown)(result, previousValue);\n } catch (error) {\n if (!trySuspend(node, error)) handleError(error, node);\n return;\n } finally {\n rt.owner = previousOwner;\n rt.listener = previousListener;\n rt.running = previousRunning;\n }\n }\n if (typeof cleanup === \"function\") {\n addCleanup(node, cleanup as Cleanup);\n // The effect disposed its own owner while running: nothing will dispose it again, so run now.\n if ((node.flags & FLAG_DISPOSED) !== 0) node.runCleanups();\n }\n}\n"],"mappings":"A,oPAwBA,MAAMA,EAA4B,OAAO,OAAO,CAAC,CAAC,EAkDlD,IAAaC,EAAb,KAAmD,CAEjD,KAAS,EAKT,MAEA,OAEA,UAAuC,KAEvC,MAAQ,EAKR,KAQA,YAAY,EAAU,EAAmB,EAA0B,CACjE,KAAK,MAAQC,EACb,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