@askrjs/askr 0.0.38 → 0.0.40
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/dist/bench/components/benchmark-row.d.ts.map +1 -1
- package/dist/bench/components/benchmark-row.js.map +1 -1
- package/dist/bench/components/benchmark-table.js.map +1 -1
- package/dist/benchmark.d.ts.map +1 -1
- package/dist/benchmark.js +2 -2
- package/dist/benchmark.js.map +1 -1
- package/dist/bin/askr-ssg.d.ts.map +1 -1
- package/dist/bin/askr-ssg.js.map +1 -1
- package/dist/boot/index.d.ts +9 -6
- package/dist/boot/index.d.ts.map +1 -1
- package/dist/boot/index.js +210 -75
- package/dist/boot/index.js.map +1 -1
- package/dist/common/attr-names.js +17 -0
- package/dist/common/attr-names.js.map +1 -0
- package/dist/common/component.d.ts.map +1 -1
- package/dist/common/control.d.ts.map +1 -1
- package/dist/common/control.js.map +1 -1
- package/dist/common/env.js.map +1 -1
- package/dist/common/jsx.d.ts.map +1 -1
- package/dist/common/jsx.js.map +1 -1
- package/dist/common/promise.js +8 -0
- package/dist/common/promise.js.map +1 -0
- package/dist/common/props.d.ts +286 -1
- package/dist/common/props.d.ts.map +1 -1
- package/dist/common/router-internal.js +6 -0
- package/dist/common/router-internal.js.map +1 -0
- package/dist/common/router.d.ts +45 -36
- package/dist/common/router.d.ts.map +1 -1
- package/dist/common/ssr-errors.d.ts.map +1 -1
- package/dist/common/ssr-errors.js.map +1 -1
- package/dist/common/ssr.d.ts +1 -0
- package/dist/common/ssr.d.ts.map +1 -1
- package/dist/common/ssr.js +6 -0
- package/dist/common/ssr.js.map +1 -0
- package/dist/common/vnode.d.ts +2 -1
- package/dist/common/vnode.d.ts.map +1 -1
- package/dist/common/vnode.js.map +1 -1
- package/dist/components/error-boundary.d.ts +7 -4
- package/dist/components/error-boundary.d.ts.map +1 -1
- package/dist/components/error-boundary.js.map +1 -1
- package/dist/components/link.d.ts +2 -1
- package/dist/components/link.d.ts.map +1 -1
- package/dist/components/link.js +10 -1
- package/dist/components/link.js.map +1 -1
- package/dist/control/case.d.ts +4 -2
- package/dist/control/case.d.ts.map +1 -1
- package/dist/control/case.js.map +1 -1
- package/dist/control/for.d.ts +2 -1
- package/dist/control/for.d.ts.map +1 -1
- package/dist/control/for.js.map +1 -1
- package/dist/control/shared.d.ts +9 -0
- package/dist/control/shared.d.ts.map +1 -0
- package/dist/control/shared.js.map +1 -1
- package/dist/control/show.d.ts +4 -3
- package/dist/control/show.d.ts.map +1 -1
- package/dist/control/show.js.map +1 -1
- package/dist/data/index.d.ts +94 -14
- package/dist/data/index.d.ts.map +1 -1
- package/dist/data/index.js +65 -14
- package/dist/data/index.js.map +1 -1
- package/dist/dev/invariant.js.map +1 -1
- package/dist/dev/logger.js.map +1 -1
- package/dist/foundations/icon/icon.d.ts.map +1 -1
- package/dist/foundations/icon/icon.js.map +1 -1
- package/dist/foundations/icon/icon.types.d.ts.map +1 -1
- package/dist/foundations/interactions/dismissable.d.ts +9 -3
- package/dist/foundations/interactions/dismissable.d.ts.map +1 -1
- package/dist/foundations/interactions/dismissable.js.map +1 -1
- package/dist/foundations/interactions/focusable.d.ts.map +1 -1
- package/dist/foundations/interactions/focusable.js.map +1 -1
- package/dist/foundations/interactions/hoverable.d.ts.map +1 -1
- package/dist/foundations/interactions/hoverable.js.map +1 -1
- package/dist/foundations/interactions/interaction-policy.d.ts +1 -1
- package/dist/foundations/interactions/interaction-policy.d.ts.map +1 -1
- package/dist/foundations/interactions/interaction-policy.js +3 -3
- package/dist/foundations/interactions/interaction-policy.js.map +1 -1
- package/dist/foundations/interactions/pressable.d.ts.map +1 -1
- package/dist/foundations/interactions/pressable.js.map +1 -1
- package/dist/foundations/interactions/roving-focus.d.ts.map +1 -1
- package/dist/foundations/interactions/roving-focus.js +8 -8
- package/dist/foundations/interactions/roving-focus.js.map +1 -1
- package/dist/foundations/state/controllable.d.ts.map +1 -1
- package/dist/foundations/state/controllable.js.map +1 -1
- package/dist/foundations/structures/collection.d.ts.map +1 -1
- package/dist/foundations/structures/collection.js.map +1 -1
- package/dist/foundations/structures/layer.d.ts.map +1 -1
- package/dist/foundations/structures/layer.js.map +1 -1
- package/dist/foundations/structures/layout.d.ts +4 -2
- package/dist/foundations/structures/layout.d.ts.map +1 -1
- package/dist/foundations/structures/layout.js.map +1 -1
- package/dist/foundations/structures/portal.d.ts +9 -25
- package/dist/foundations/structures/portal.d.ts.map +1 -1
- package/dist/foundations/structures/portal.js +98 -17
- package/dist/foundations/structures/portal.js.map +1 -1
- package/dist/foundations/structures/presence.d.ts +4 -3
- package/dist/foundations/structures/presence.d.ts.map +1 -1
- package/dist/foundations/structures/presence.js +2 -2
- package/dist/foundations/structures/presence.js.map +1 -1
- package/dist/foundations/structures/slot.d.ts +2 -1
- package/dist/foundations/structures/slot.d.ts.map +1 -1
- package/dist/foundations/structures/slot.js.map +1 -1
- package/dist/foundations/utilities/aria.d.ts.map +1 -1
- package/dist/foundations/utilities/aria.js.map +1 -1
- package/dist/foundations/utilities/compose-handlers.d.ts.map +1 -1
- package/dist/foundations/utilities/compose-handlers.js.map +1 -1
- package/dist/foundations/utilities/compose-ref.d.ts.map +1 -1
- package/dist/foundations/utilities/compose-ref.js.map +1 -1
- package/dist/foundations/utilities/event-types.d.ts.map +1 -1
- package/dist/foundations/utilities/merge-props.js.map +1 -1
- package/dist/foundations/utilities/use-id.d.ts.map +1 -1
- package/dist/foundations/utilities/use-id.js.map +1 -1
- package/dist/fx/fx.d.ts.map +1 -1
- package/dist/fx/fx.js.map +1 -1
- package/dist/fx/noop.js.map +1 -1
- package/dist/fx/timing.d.ts +5 -4
- package/dist/fx/timing.d.ts.map +1 -1
- package/dist/fx/timing.js +7 -4
- package/dist/fx/timing.js.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/jsx/types.d.ts +3 -3
- package/dist/jsx/types.d.ts.map +1 -1
- package/dist/jsx/utils.d.ts.map +1 -1
- package/dist/jsx/utils.js.map +1 -1
- package/dist/jsx-dev-runtime.d.ts +6 -2
- package/dist/jsx-dev-runtime.d.ts.map +1 -1
- package/dist/jsx-dev-runtime.js.map +1 -1
- package/dist/jsx-runtime.d.ts +16 -6
- package/dist/jsx-runtime.d.ts.map +1 -1
- package/dist/jsx-runtime.js.map +1 -1
- package/dist/renderer/children.js.map +1 -1
- package/dist/renderer/cleanup.js +40 -13
- package/dist/renderer/cleanup.js.map +1 -1
- package/dist/renderer/dom.js +163 -63
- package/dist/renderer/dom.js.map +1 -1
- package/dist/renderer/evaluate.js +9 -6
- package/dist/renderer/evaluate.js.map +1 -1
- package/dist/renderer/fastpath.js.map +1 -1
- package/dist/renderer/for-commit.js +1 -0
- package/dist/renderer/for-commit.js.map +1 -1
- package/dist/renderer/index.js.map +1 -1
- package/dist/renderer/keyed.js.map +1 -1
- package/dist/renderer/reconcile.js +34 -0
- package/dist/renderer/reconcile.js.map +1 -1
- package/dist/renderer/utils.js +34 -3
- package/dist/renderer/utils.js.map +1 -1
- package/dist/router/index.d.ts +2 -2
- package/dist/router/match.js +16 -2
- package/dist/router/match.js.map +1 -1
- package/dist/router/navigate.d.ts +9 -1
- package/dist/router/navigate.d.ts.map +1 -1
- package/dist/router/navigate.js +235 -81
- package/dist/router/navigate.js.map +1 -1
- package/dist/router/policy.d.ts +7 -7
- package/dist/router/policy.d.ts.map +1 -1
- package/dist/router/policy.js +5 -7
- package/dist/router/policy.js.map +1 -1
- package/dist/router/route-context.js.map +1 -1
- package/dist/router/route.d.ts +20 -9
- package/dist/router/route.d.ts.map +1 -1
- package/dist/router/route.js +95 -29
- package/dist/router/route.js.map +1 -1
- package/dist/runtime/child-scope.d.ts.map +1 -1
- package/dist/runtime/child-scope.js +5 -1
- package/dist/runtime/child-scope.js.map +1 -1
- package/dist/runtime/component.d.ts +5 -2
- package/dist/runtime/component.d.ts.map +1 -1
- package/dist/runtime/component.js +85 -25
- package/dist/runtime/component.js.map +1 -1
- package/dist/runtime/context.d.ts +5 -2
- package/dist/runtime/context.d.ts.map +1 -1
- package/dist/runtime/context.js +5 -2
- package/dist/runtime/context.js.map +1 -1
- package/dist/runtime/control.d.ts.map +1 -1
- package/dist/runtime/control.js.map +1 -1
- package/dist/runtime/derive.d.ts.map +1 -1
- package/dist/runtime/derive.js +3 -1
- package/dist/runtime/derive.js.map +1 -1
- package/dist/runtime/dev-namespace.js.map +1 -1
- package/dist/runtime/effect.d.ts.map +1 -1
- package/dist/runtime/effect.js +17 -11
- package/dist/runtime/effect.js.map +1 -1
- package/dist/runtime/events.js +43 -1
- package/dist/runtime/events.js.map +1 -1
- package/dist/runtime/execution-model.js.map +1 -1
- package/dist/runtime/fastlane.js +2 -23
- package/dist/runtime/fastlane.js.map +1 -1
- package/dist/runtime/for-bench.d.ts.map +1 -1
- package/dist/runtime/for-bench.js.map +1 -1
- package/dist/runtime/for.d.ts +1 -1
- package/dist/runtime/for.d.ts.map +1 -1
- package/dist/runtime/for.js +36 -12
- package/dist/runtime/for.js.map +1 -1
- package/dist/runtime/operations.d.ts +3 -13
- package/dist/runtime/operations.d.ts.map +1 -1
- package/dist/runtime/operations.js +47 -39
- package/dist/runtime/operations.js.map +1 -1
- package/dist/runtime/perf-metrics.js.map +1 -1
- package/dist/runtime/readable.d.ts +1 -0
- package/dist/runtime/readable.d.ts.map +1 -1
- package/dist/runtime/readable.js +6 -1
- package/dist/runtime/readable.js.map +1 -1
- package/dist/runtime/resource-cell.js +13 -2
- package/dist/runtime/resource-cell.js.map +1 -1
- package/dist/runtime/scheduler.d.ts.map +1 -1
- package/dist/runtime/scheduler.js +8 -4
- package/dist/runtime/scheduler.js.map +1 -1
- package/dist/runtime/selector.d.ts.map +1 -1
- package/dist/runtime/selector.js +8 -2
- package/dist/runtime/selector.js.map +1 -1
- package/dist/runtime/snapshot-source.d.ts.map +1 -1
- package/dist/runtime/snapshot-source.js.map +1 -1
- package/dist/runtime/ssr-bridge.js.map +1 -1
- package/dist/runtime/state.d.ts +4 -3
- package/dist/runtime/state.d.ts.map +1 -1
- package/dist/runtime/state.js.map +1 -1
- package/dist/ssg/batch-render.js +4 -8
- package/dist/ssg/batch-render.js.map +1 -1
- package/dist/ssg/create-static-gen.d.ts +10 -2
- package/dist/ssg/create-static-gen.d.ts.map +1 -1
- package/dist/ssg/create-static-gen.js +5 -4
- package/dist/ssg/create-static-gen.js.map +1 -1
- package/dist/ssg/generate-metadata.js.map +1 -1
- package/dist/ssg/incremental-manifest.js.map +1 -1
- package/dist/ssg/resolve-ssg-data.js +54 -12
- package/dist/ssg/resolve-ssg-data.js.map +1 -1
- package/dist/ssg/route-utils.js.map +1 -1
- package/dist/ssg/types.d.ts +8 -7
- package/dist/ssg/types.d.ts.map +1 -1
- package/dist/ssg/write-static-files.js.map +1 -1
- package/dist/ssr/attrs.js +3 -2
- package/dist/ssr/attrs.js.map +1 -1
- package/dist/ssr/context.d.ts +1 -0
- package/dist/ssr/context.d.ts.map +1 -1
- package/dist/ssr/context.js +1 -0
- package/dist/ssr/context.js.map +1 -1
- package/dist/ssr/errors.d.ts.map +1 -1
- package/dist/ssr/escape.js.map +1 -1
- package/dist/ssr/index.d.ts +8 -12
- package/dist/ssr/index.d.ts.map +1 -1
- package/dist/ssr/index.js +55 -30
- package/dist/ssr/index.js.map +1 -1
- package/dist/ssr/render-keys.js +15 -4
- package/dist/ssr/render-keys.js.map +1 -1
- package/dist/ssr/render-resolved.js +33 -0
- package/dist/ssr/render-resolved.js.map +1 -0
- package/dist/ssr/sink.js.map +1 -1
- package/dist/ssr/types.d.ts.map +1 -1
- package/dist/ssr/verify-hydration.js +5 -6
- package/dist/ssr/verify-hydration.js.map +1 -1
- package/package.json +13 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operations.js","names":[],"sources":["../../src/runtime/operations.ts"],"sourcesContent":["import {\n getCurrentComponentInstance,\n registerMountOperation,\n type ComponentInstance,\n} from './component';\nimport { getCurrentContextFrame } from './context';\nimport { ResourceCell } from './resource-cell';\nimport { state } from './state';\nimport { globalScheduler } from './scheduler';\nimport { getSSRBridge } from './ssr-bridge';\nimport { brandSnapshotSource } from './snapshot-source';\nimport { SSRDataMissingError } from '../common/ssr-errors';\n\nexport interface ResourceResult<T> {\n value: T | null;\n pending: boolean;\n error: Error | null;\n refresh(): void;\n}\n\n/**\n * Resource primitive — simple, deterministic async primitive\n * Usage: resource(fn, deps)\n * - fn receives { signal }\n * - captures execution context once at creation (synchronous step only)\n * - executes at most once per generation; stale async results are ignored\n * - refresh() cancels in-flight execution, increments generation and re-runs\n * - exposes { value, pending, error, refresh }\n * - during SSR, async results are disallowed and will throw synchronously\n */\nexport function resource<T>(\n fn: (opts: { signal: AbortSignal }) => Promise<T> | T,\n deps: unknown[] = []\n): ResourceResult<T> {\n const instance = getCurrentComponentInstance();\n // Create a non-null alias early so it can be used in nested closures\n // without TypeScript complaining about possible null access.\n const inst = instance as ComponentInstance;\n\n if (!instance) {\n const ssr = getSSRBridge();\n // If we're in a synchronous SSR render that has resolved data, use it.\n const renderData = ssr.getCurrentRenderData();\n if (renderData) {\n const key = ssr.getNextKey();\n if (!(key in renderData)) {\n ssr.throwSSRDataMissing();\n }\n const val = renderData[key] as T;\n return brandSnapshotSource({\n value: val,\n pending: false,\n error: null,\n refresh: () => {},\n }) as ResourceResult<T>;\n }\n\n // If we are in an SSR render pass without supplied data, throw for clarity.\n const ssrCtx = ssr.getCurrentSSRContext();\n if (ssrCtx) {\n ssr.throwSSRDataMissing();\n }\n\n // No active component instance and not in SSR render with data.\n // Autopilot invariant: resources must be created during render within an app.\n throw new Error(\n '[Askr] resource() must be called during component render inside an app. ' +\n 'Do not create resources at module scope or outside render.'\n );\n }\n\n // Internal ResourceCell — pure state machine now moved to its own module\n // to keep component wiring separate and ensure no component access here.\n // (See ./resource-cell.ts)\n\n // If we're in a synchronous SSR render that was supplied resolved data, use it\n const ssr = getSSRBridge();\n const renderData = ssr.getCurrentRenderData();\n if (renderData) {\n // Deterministic key generation: the collection step and render step use\n // the same incremental key generation to align resources.\n const key = ssr.getNextKey();\n if (!(key in renderData)) {\n ssr.throwSSRDataMissing();\n }\n\n // Commit synchronous value from render data and return a stable snapshot\n const val = renderData[key] as T;\n\n const holder = state<{\n cell?: ResourceCell<T>;\n snapshot: ResourceResult<T>;\n }>({\n cell: undefined,\n snapshot: brandSnapshotSource({\n value: val,\n pending: false,\n error: null,\n refresh: () => {},\n }) as ResourceResult<T>,\n });\n\n const h = holder();\n h.snapshot.value = val;\n h.snapshot.pending = false;\n h.snapshot.error = null;\n holder.set(h);\n return h.snapshot;\n }\n\n // Persist a holder so the snapshot identity is stable across renders.\n const holder = state<{ cell?: ResourceCell<T>; snapshot: ResourceResult<T> }>(\n {\n cell: undefined,\n snapshot: brandSnapshotSource({\n value: null,\n pending: true,\n error: null,\n refresh: () => {},\n }) as ResourceResult<T>,\n }\n );\n\n const h = holder();\n\n // Initialize cell on first call\n if (!h.cell) {\n const frame = getCurrentContextFrame();\n const cell = new ResourceCell<T>(fn, deps, frame);\n // Attach debug label (component name) for richer logs\n cell.ownerName = inst.fn?.name || '<anonymous>';\n h.cell = cell;\n h.snapshot = cell.snapshot as ResourceResult<T>;\n\n // Subscribe and schedule component updates when cell changes\n const unsubscribe = cell.subscribe(() => {\n const cur = holder();\n cur.snapshot.value = cell.snapshot.value;\n cur.snapshot.pending = cell.snapshot.pending;\n cur.snapshot.error = cell.snapshot.error;\n holder.set(cur);\n try {\n inst._enqueueRun?.();\n } catch {\n // ignore\n }\n });\n\n // Cleanup on unmount\n (inst.cleanupFns ??= []).push(() => {\n unsubscribe();\n cell.abort();\n });\n\n // Render invariant: do NOT start async work during render on the client.\n // SSR remains strict/synchronous and must throw immediately if async is encountered.\n if (inst.ssr) {\n // SSR: must run synchronously so missing data throws during render\n cell.start(true, false);\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n }\n } else {\n // Client: start after render via scheduler (never inline)\n globalScheduler.enqueue(() => {\n try {\n cell.start(false, false);\n } catch (err) {\n // Non-SSR: reflect synchronous errors into snapshot via manual update\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = (err as Error) ?? null;\n holder.set(cur);\n inst._enqueueRun?.();\n return;\n }\n\n // If the resource completed synchronously, subscribers were not notified.\n // Force a re-render so the component can observe the value.\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n holder.set(cur);\n inst._enqueueRun?.();\n }\n });\n }\n }\n\n const cell = h.cell!;\n cell.setLoader(fn);\n\n // Detect dependency changes and refresh immediately\n const depsChanged =\n !cell.deps ||\n cell.deps.length !== deps.length ||\n cell.deps.some((d, i) => d !== deps[i]);\n\n if (depsChanged) {\n cell.deps = deps.slice();\n cell.generation++;\n cell.pending = true;\n cell.error = null;\n try {\n if (inst.ssr) {\n cell.start(true, false);\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n }\n } else {\n globalScheduler.enqueue(() => {\n cell.start(false, false);\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n holder.set(cur);\n inst._enqueueRun?.();\n }\n });\n }\n } catch (err) {\n if (err instanceof SSRDataMissingError) throw err;\n cell.error = err as Error;\n cell.pending = false;\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n // Do not call holder.set() here; this is still render.\n }\n }\n\n // Return the stable snapshot object owned by the cell\n return h.snapshot;\n}\n\nexport function on(\n target: EventTarget,\n event: string,\n handler: EventListener\n): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the listener to be attached on mount. If the owner is not the\n // root app instance, fail loudly to prevent silent no-op behavior.\n registerMountOperation(() => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] on() may only be used in root components');\n }\n target.addEventListener(event, handler);\n // Return cleanup function\n return () => {\n target.removeEventListener(event, handler);\n };\n });\n}\n\nexport function timer(intervalMs: number, fn: () => void): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the timer to be started on mount. Fail loudly when used outside\n // of the root component to avoid silent no-ops.\n registerMountOperation(() => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] timer() may only be used in root components');\n }\n const id = setInterval(fn, intervalMs);\n // Return cleanup function\n return () => {\n clearInterval(id);\n };\n });\n}\n\nexport function stream<T>(\n _source: unknown,\n _options?: Record<string, unknown>\n): { value: T | null; pending: boolean; error: Error | null } {\n // Stub implementation: no-op.\n return { value: null, pending: true, error: null };\n}\n\nexport function task(\n fn: () => void | (() => void) | Promise<void | (() => void)>\n): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the task to run on mount. Fail loudly when used outside the root\n // component so callers get immediate feedback rather than silent no-op.\n registerMountOperation(async () => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] task() may only be used in root components');\n }\n // Execute the task (may be async) and return its cleanup\n return await fn();\n });\n}\n\n/**\n * Capture the result of a synchronous expression at call time and return a\n * thunk that returns the captured value later. This is a low-level helper for\n * cases where async continuations need to observe a snapshot of values at the\n * moment scheduling occurred.\n *\n * Usage (public API):\n * const snapshot = capture(() => someState());\n * Promise.resolve().then(() => { use(snapshot()); });\n */\nexport function capture<T>(fn: () => T): () => T {\n const value = fn();\n return () => value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AA8BA,SAAgB,SACd,IACA,OAAkB,EAAE,EACD;CACnB,MAAM,WAAW,6BAA6B;CAG9C,MAAM,OAAO;CAEb,IAAI,CAAC,UAAU;EACb,MAAM,MAAM,cAAc;EAE1B,MAAM,aAAa,IAAI,sBAAsB;EAC7C,IAAI,YAAY;GACd,MAAM,MAAM,IAAI,YAAY;GAC5B,IAAI,EAAE,OAAO,aACX,IAA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rentComponentInstance,\n registerMountOperation,\n type ComponentInstance,\n} from './component';\nimport { getCurrentContextFrame } from './context';\nimport { ResourceCell } from './resource-cell';\nimport { state } from './state';\nimport { globalScheduler } from './scheduler';\nimport { getSSRBridge } from './ssr-bridge';\nimport { brandSnapshotSource } from './snapshot-source';\nimport { SSRDataMissingError } from '../common/ssr-errors';\n\nexport interface ResourceResult<T> {\n value: T | null;\n pending: boolean;\n error: Error | null;\n refresh(): void;\n}\n\nexport function resource<T, const TDeps extends readonly unknown[]>(\n fn: (opts: { signal: AbortSignal }) => PromiseLike<T> | T,\n deps: TDeps\n): ResourceResult<T>;\n\n/**\n * Resource primitive — simple, deterministic async primitive\n * Usage: resource(fn, deps)\n * - fn receives { signal }\n * - captures execution context once at creation (synchronous step only)\n * - executes at most once per generation; stale async results are ignored\n * - refresh() cancels in-flight execution, increments generation and re-runs\n * - exposes { value, pending, error, refresh }\n * - during SSR, async results are disallowed and will throw synchronously\n */\nexport function resource<T>(\n fn: (opts: { signal: AbortSignal }) => PromiseLike<T> | T,\n deps: readonly unknown[] = []\n): ResourceResult<T> {\n const instance = getCurrentComponentInstance();\n // Create a non-null alias early so it can be used in nested closures\n // without TypeScript complaining about possible null access.\n const inst = instance as ComponentInstance;\n\n if (!instance) {\n const ssr = getSSRBridge();\n // If we're in a synchronous SSR render that has resolved data, use it.\n const renderData = ssr.getCurrentRenderData();\n if (renderData) {\n const key = ssr.getNextKey();\n if (!(key in renderData)) {\n ssr.throwSSRDataMissing();\n }\n const val = renderData[key] as T;\n return brandSnapshotSource({\n value: val,\n pending: false,\n error: null,\n refresh: () => {},\n }) as ResourceResult<T>;\n }\n\n // If we are in an SSR render pass without supplied data, throw for clarity.\n const ssrCtx = ssr.getCurrentSSRContext();\n if (ssrCtx) {\n ssr.throwSSRDataMissing();\n }\n\n // No active component instance and not in SSR render with data.\n // Autopilot invariant: resources must be created during render within an app.\n throw new Error(\n '[Askr] resource() must be called during component render inside an app. ' +\n 'Do not create resources at module scope or outside render.'\n );\n }\n\n // Internal ResourceCell — pure state machine now moved to its own module\n // to keep component wiring separate and ensure no component access here.\n // (See ./resource-cell.ts)\n\n // If we're in a synchronous SSR render that was supplied resolved data, use it\n const ssr = getSSRBridge();\n const renderData = ssr.getCurrentRenderData();\n if (renderData) {\n // Deterministic key generation: the collection step and render step use\n // the same incremental key generation to align resources.\n const key = ssr.getNextKey();\n if (!(key in renderData)) {\n ssr.throwSSRDataMissing();\n }\n\n // Commit synchronous value from render data and return a stable snapshot\n const val = renderData[key] as T;\n\n const holder = state<{\n cell?: ResourceCell<T>;\n snapshot: ResourceResult<T>;\n }>({\n cell: undefined,\n snapshot: brandSnapshotSource({\n value: val,\n pending: false,\n error: null,\n refresh: () => {},\n }) as ResourceResult<T>,\n });\n\n const h = holder();\n h.snapshot.value = val;\n h.snapshot.pending = false;\n h.snapshot.error = null;\n return h.snapshot;\n }\n\n // Persist a holder so the snapshot identity is stable across renders.\n const holder = state<{ cell?: ResourceCell<T>; snapshot: ResourceResult<T> }>(\n {\n cell: undefined,\n snapshot: brandSnapshotSource({\n value: null,\n pending: true,\n error: null,\n refresh: () => {},\n }) as ResourceResult<T>,\n }\n );\n\n const h = holder();\n\n // Initialize cell on first call\n if (!h.cell) {\n const frame = getCurrentContextFrame();\n const cell = new ResourceCell<T>(fn, deps, frame);\n // Attach debug label (component name) for richer logs\n cell.ownerName = inst.fn?.name || '<anonymous>';\n h.cell = cell;\n h.snapshot = cell.snapshot as ResourceResult<T>;\n\n // Subscribe and schedule component updates when cell changes\n const unsubscribe = cell.subscribe(() => {\n const cur = holder();\n cur.snapshot.value = cell.snapshot.value;\n cur.snapshot.pending = cell.snapshot.pending;\n cur.snapshot.error = cell.snapshot.error;\n holder.set(cur);\n try {\n inst.notifyUpdate?.();\n } catch {\n // ignore\n }\n });\n\n // Cleanup on unmount\n (inst.cleanupFns ??= []).push(() => {\n unsubscribe();\n cell.dispose();\n });\n\n // Render invariant: do NOT start async work during render on the client.\n // SSR remains strict/synchronous and must throw immediately if async is encountered.\n if (inst.ssr) {\n // SSR: must run synchronously so missing data throws during render\n cell.start(true, false);\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n }\n } else {\n // Client: start after render via scheduler (never inline)\n const scheduledGeneration = cell.generation;\n globalScheduler.enqueueInLane('post', () => {\n if (!inst.notifyUpdate || cell.generation !== scheduledGeneration) {\n return;\n }\n\n try {\n cell.start(false, false);\n } catch (err) {\n // Non-SSR: reflect synchronous errors into snapshot via manual update\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = (err as Error) ?? null;\n holder.set(cur);\n inst.notifyUpdate?.();\n return;\n }\n\n // If the resource completed synchronously, subscribers were not notified.\n // Force a re-render so the component can observe the value.\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n holder.set(cur);\n inst.notifyUpdate?.();\n }\n });\n }\n }\n\n const cell = h.cell!;\n cell.setLoader(fn);\n\n // Detect dependency changes and refresh immediately\n const depsChanged =\n !cell.deps ||\n cell.deps.length !== deps.length ||\n cell.deps.some((d, i) => !Object.is(d, deps[i]));\n\n if (depsChanged) {\n cell.deps = deps.slice();\n cell.generation++;\n cell.pending = true;\n cell.error = null;\n\n // Synchronously reflect the pending state into the stable snapshot so the\n // render that triggered the deps change can surface a loading indicator.\n // The async start() runs with notify=false and the deps-change branch never\n // re-published the snapshot, so without this a deps-driven refetch jumped\n // straight from the old value to the new value, never exposing pending.\n // Stale-while-revalidate: the previous value is retained until the new\n // fetch resolves.\n h.snapshot.pending = true;\n h.snapshot.error = null;\n try {\n if (inst.ssr) {\n cell.start(true, false);\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n }\n } else {\n const scheduledGeneration = cell.generation;\n globalScheduler.enqueueInLane('post', () => {\n if (!inst.notifyUpdate || cell.generation !== scheduledGeneration) {\n return;\n }\n\n cell.start(false, false);\n if (!cell.pending) {\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n holder.set(cur);\n inst.notifyUpdate?.();\n }\n });\n }\n } catch (err) {\n if (err instanceof SSRDataMissingError) throw err;\n cell.error = err as Error;\n cell.pending = false;\n const cur = holder();\n cur.snapshot.value = cell.value;\n cur.snapshot.pending = cell.pending;\n cur.snapshot.error = cell.error;\n // Do not call holder.set() here; this is still render.\n }\n }\n\n // Return the stable snapshot object owned by the cell\n return h.snapshot;\n}\n\nexport function on(\n target: EventTarget,\n event: string,\n handler: EventListener\n): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the listener to be attached on mount. If the owner is not the\n // root app instance, fail loudly to prevent silent no-op behavior.\n registerMountOperation(() => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] on() may only be used in root components');\n }\n target.addEventListener(event, handler);\n // Return cleanup function\n return () => {\n target.removeEventListener(event, handler);\n };\n });\n}\n\nexport function timer(intervalMs: number, fn: () => void): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the timer to be started on mount. Fail loudly when used outside\n // of the root component to avoid silent no-ops.\n registerMountOperation(() => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] timer() may only be used in root components');\n }\n const id = setInterval(fn, intervalMs);\n // Return cleanup function\n return () => {\n clearInterval(id);\n };\n });\n}\n\nexport function stream<T>(\n _source: unknown,\n _options?: Record<string, unknown>\n): { value: T | null; pending: boolean; error: Error | null } {\n // Stub implementation: no-op.\n return { value: null, pending: true, error: null };\n}\n\nexport function task(\n fn: () => void | (() => void) | PromiseLike<void | (() => void)>\n): void {\n const ownerIsRoot = getCurrentComponentInstance()?.isRoot ?? false;\n // Register the task to run on mount. Fail loudly when used outside the root\n // component so callers get immediate feedback rather than silent no-op.\n registerMountOperation(async () => {\n if (!ownerIsRoot) {\n throw new Error('[Askr] task() may only be used in root components');\n }\n // Execute the task (may be async) and return its cleanup\n return await fn();\n });\n}\n\n/**\n * Capture the result of a synchronous expression at call time and return a\n * thunk that returns the captured value later. This is a low-level helper for\n * cases where async continuations need to observe a snapshot of values at the\n * moment scheduling occurred.\n *\n * Usage (public API):\n * const snapshot = capture(() => someState());\n * Promise.resolve().then(() => { use(snapshot()); });\n */\nexport function capture<T>(fn: () => T): () => T {\n const value = fn();\n return () => value;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,SACd,IACA,OAA2B,CAAC,GACT;CACnB,MAAM,WAAW,4BAA4B;CAG7C,MAAM,OAAO;CAEb,IAAI,CAAC,UAAU;EACb,MAAM,MAAM,aAAa;EAEzB,MAAM,aAAa,IAAI,qBAAqB;EAC5C,IAAI,YAAY;GACd,MAAM,MAAM,IAAI,WAAW;GAC3B,IAAI,EAAE,OAAO,aACX,IAAI,oBAAoB;GAE1B,MAAM,MAAM,WAAW;GACvB,OAAO,oBAAoB;IACzB,OAAO;IACP,SAAS;IACT,OAAO;IACP,eAAe,CAAC;GAClB,CAAC;EACH;EAIA,IADe,IAAI,qBACf,GACF,IAAI,oBAAoB;EAK1B,MAAM,IAAI,MACR,oIAEF;CACF;CAOA,MAAM,MAAM,aAAa;CACzB,MAAM,aAAa,IAAI,qBAAqB;CAC5C,IAAI,YAAY;EAGd,MAAM,MAAM,IAAI,WAAW;EAC3B,IAAI,EAAE,OAAO,aACX,IAAI,oBAAoB;EAI1B,MAAM,MAAM,WAAW;EAevB,MAAM,IAbS,MAGZ;GACD,MAAM;GACN,UAAU,oBAAoB;IAC5B,OAAO;IACP,SAAS;IACT,OAAO;IACP,eAAe,CAAC;GAClB,CAAC;EACH,CAEU,EAAO;EACjB,EAAE,SAAS,QAAQ;EACnB,EAAE,SAAS,UAAU;EACrB,EAAE,SAAS,QAAQ;EACnB,OAAO,EAAE;CACX;CA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1B,IAAI,SAAS,UAAU,KAAK;GAC5B,IAAI,SAAS,QAAQ,KAAK;EAE5B;CACF;CAGA,OAAO,EAAE;AACX;AAEA,SAAgB,GACd,QACA,OACA,SACM;CACN,MAAM,cAAc,4BAA4B,GAAG,UAAU;CAG7D,6BAA6B;EAC3B,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,iDAAiD;EAEnE,OAAO,iBAAiB,OAAO,OAAO;EAEtC,aAAa;GACX,OAAO,oBAAoB,OAAO,OAAO;EAC3C;CACF,CAAC;AACH;AAEA,SAAgB,MAAM,YAAoB,IAAsB;CAC9D,MAAM,cAAc,4BAA4B,GAAG,UAAU;CAG7D,6BAA6B;EAC3B,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,oDAAoD;EAEtE,MAAM,KAAK,YAAY,IAAI,UAAU;EAErC,aAAa;GACX,cAAc,EAAE;EAClB;CACF,CAAC;AACH;AAEA,SAAgB,OACd,SACA,UAC4D;CAE5D,OAAO;EAAE,OAAO;EAAM,SAAS;EAAM,OAAO;CAAK;AACnD;AAEA,SAAgB,KACd,IACM;CACN,MAAM,cAAc,4BAA4B,GAAG,UAAU;CAG7D,uBAAuB,YAAY;EACjC,IAAI,CAAC,aACH,MAAM,IAAI,MAAM,mDAAmD;EAGrE,OAAO,MAAM,GAAG;CAClB,CAAC;AACH;;;;;;;;;;;AAYA,SAAgB,QAAW,IAAsB;CAC/C,MAAM,QAAQ,GAAG;CACjB,aAAa;AACf"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"perf-metrics.js","names":[],"sources":["../../src/runtime/perf-metrics.ts"],"sourcesContent":["import {\n isDevelopmentEnvironment,\n isRuntimeEnvFlagEnabled,\n} from '../common/env';\n\ntype PerfMetrics = {\n selectorInvalidations: number;\n selectorCandidateReads: number;\n reactivePropReevaluations: number;\n skippedDomPropWrites: number;\n classListPatchOps: number;\n delegatedAncestorHops: number;\n hydrationBoundaryActivations: number;\n ssrTagCacheHits: number;\n lastSchedulerTaskCountPerFlush: number;\n maxSchedulerTaskCountPerFlush: number;\n schedulerFlushCount: number;\n schedulerTaskExecutions: number;\n ssgWorkerCount: number;\n ssgRenderTimeMs: number;\n ssgWorkerRenderTimeMs: number;\n ssgWriteTimeMs: number;\n};\n\ntype PerfMetricsKey = keyof PerfMetrics;\n\ntype AskrPerfGlobal = typeof globalThis & {\n __ASKR_BENCH__?: boolean;\n __ASKR_PERF__?: PerfMetrics;\n};\n\nconst BENCH_BUILD_ENABLED = isRuntimeEnvFlagEnabled('ASKR_BENCH');\nlet cachedPerfStore: PerfMetrics | undefined;\n\nfunction createInitialPerfMetrics(): PerfMetrics {\n return {\n selectorInvalidations: 0,\n selectorCandidateReads: 0,\n reactivePropReevaluations: 0,\n skippedDomPropWrites: 0,\n classListPatchOps: 0,\n delegatedAncestorHops: 0,\n hydrationBoundaryActivations: 0,\n ssrTagCacheHits: 0,\n lastSchedulerTaskCountPerFlush: 0,\n maxSchedulerTaskCountPerFlush: 0,\n schedulerFlushCount: 0,\n schedulerTaskExecutions: 0,\n ssgWorkerCount: 0,\n ssgRenderTimeMs: 0,\n ssgWorkerRenderTimeMs: 0,\n ssgWriteTimeMs: 0,\n };\n}\n\nfunction shouldCollectPerfMetrics(): boolean {\n if (isDevelopmentEnvironment()) {\n return true;\n }\n if (!BENCH_BUILD_ENABLED) {\n return false;\n }\n try {\n return !!(globalThis as AskrPerfGlobal).__ASKR_BENCH__;\n } catch {\n return false;\n }\n}\n\nfunction getPerfStore(): PerfMetrics | null {\n if (cachedPerfStore) {\n return cachedPerfStore;\n }\n\n if (!shouldCollectPerfMetrics()) {\n return null;\n }\n\n try {\n const g = globalThis as AskrPerfGlobal;\n if (!g.__ASKR_PERF__) {\n g.__ASKR_PERF__ = createInitialPerfMetrics();\n }\n cachedPerfStore = g.__ASKR_PERF__;\n return cachedPerfStore;\n } catch {\n return null;\n }\n}\n\nexport function getPerfMetricsStore(): PerfMetrics | null {\n return getPerfStore();\n}\n\nexport function incrementPerfMetric(\n key:\n | 'selectorInvalidations'\n | 'selectorCandidateReads'\n | 'reactivePropReevaluations'\n | 'skippedDomPropWrites'\n | 'classListPatchOps'\n | 'delegatedAncestorHops'\n | 'hydrationBoundaryActivations'\n | 'ssrTagCacheHits'\n | 'ssgWorkerCount',\n delta = 1\n): void {\n const store = getPerfStore();\n if (!store) return;\n store[key] += delta;\n}\n\nexport function addPerfDuration(\n key: 'ssgRenderTimeMs' | 'ssgWorkerRenderTimeMs' | 'ssgWriteTimeMs',\n deltaMs: number\n): void {\n const store = getPerfStore();\n if (!store) return;\n store[key] += deltaMs;\n}\n\nexport function recordSchedulerFlushTaskCount(taskCount: number): void {\n const store = getPerfStore();\n if (!store) return;\n store.lastSchedulerTaskCountPerFlush = taskCount;\n store.maxSchedulerTaskCountPerFlush = Math.max(\n store.maxSchedulerTaskCountPerFlush,\n taskCount\n );\n store.schedulerFlushCount += 1;\n store.schedulerTaskExecutions += taskCount;\n}\n\nexport function getPerfMetrics(): Readonly<PerfMetrics> | undefined {\n const store = getPerfStore();\n return store ? { ...store } : undefined;\n}\n\nexport function resetPerfMetrics(): void {\n const store = getPerfStore();\n if (!store) return;\n const next = createInitialPerfMetrics();\n (Object.keys(next) as PerfMetricsKey[]).forEach((key) => {\n store[key] = next[key];\n });\n}\n"],"mappings":";;AA+BA,MAAM,sBAAsB,wBAAwB,
|
|
1
|
+
{"version":3,"file":"perf-metrics.js","names":[],"sources":["../../src/runtime/perf-metrics.ts"],"sourcesContent":["import {\n isDevelopmentEnvironment,\n isRuntimeEnvFlagEnabled,\n} from '../common/env';\n\ntype PerfMetrics = {\n selectorInvalidations: number;\n selectorCandidateReads: number;\n reactivePropReevaluations: number;\n skippedDomPropWrites: number;\n classListPatchOps: number;\n delegatedAncestorHops: number;\n hydrationBoundaryActivations: number;\n ssrTagCacheHits: number;\n lastSchedulerTaskCountPerFlush: number;\n maxSchedulerTaskCountPerFlush: number;\n schedulerFlushCount: number;\n schedulerTaskExecutions: number;\n ssgWorkerCount: number;\n ssgRenderTimeMs: number;\n ssgWorkerRenderTimeMs: number;\n ssgWriteTimeMs: number;\n};\n\ntype PerfMetricsKey = keyof PerfMetrics;\n\ntype AskrPerfGlobal = typeof globalThis & {\n __ASKR_BENCH__?: boolean;\n __ASKR_PERF__?: PerfMetrics;\n};\n\nconst BENCH_BUILD_ENABLED = isRuntimeEnvFlagEnabled('ASKR_BENCH');\nlet cachedPerfStore: PerfMetrics | undefined;\n\nfunction createInitialPerfMetrics(): PerfMetrics {\n return {\n selectorInvalidations: 0,\n selectorCandidateReads: 0,\n reactivePropReevaluations: 0,\n skippedDomPropWrites: 0,\n classListPatchOps: 0,\n delegatedAncestorHops: 0,\n hydrationBoundaryActivations: 0,\n ssrTagCacheHits: 0,\n lastSchedulerTaskCountPerFlush: 0,\n maxSchedulerTaskCountPerFlush: 0,\n schedulerFlushCount: 0,\n schedulerTaskExecutions: 0,\n ssgWorkerCount: 0,\n ssgRenderTimeMs: 0,\n ssgWorkerRenderTimeMs: 0,\n ssgWriteTimeMs: 0,\n };\n}\n\nfunction shouldCollectPerfMetrics(): boolean {\n if (isDevelopmentEnvironment()) {\n return true;\n }\n if (!BENCH_BUILD_ENABLED) {\n return false;\n }\n try {\n return !!(globalThis as AskrPerfGlobal).__ASKR_BENCH__;\n } catch {\n return false;\n }\n}\n\nfunction getPerfStore(): PerfMetrics | null {\n if (cachedPerfStore) {\n return cachedPerfStore;\n }\n\n if (!shouldCollectPerfMetrics()) {\n return null;\n }\n\n try {\n const g = globalThis as AskrPerfGlobal;\n if (!g.__ASKR_PERF__) {\n g.__ASKR_PERF__ = createInitialPerfMetrics();\n }\n cachedPerfStore = g.__ASKR_PERF__;\n return cachedPerfStore;\n } catch {\n return null;\n }\n}\n\nexport function getPerfMetricsStore(): PerfMetrics | null {\n return getPerfStore();\n}\n\nexport function incrementPerfMetric(\n key:\n | 'selectorInvalidations'\n | 'selectorCandidateReads'\n | 'reactivePropReevaluations'\n | 'skippedDomPropWrites'\n | 'classListPatchOps'\n | 'delegatedAncestorHops'\n | 'hydrationBoundaryActivations'\n | 'ssrTagCacheHits'\n | 'ssgWorkerCount',\n delta = 1\n): void {\n const store = getPerfStore();\n if (!store) return;\n store[key] += delta;\n}\n\nexport function addPerfDuration(\n key: 'ssgRenderTimeMs' | 'ssgWorkerRenderTimeMs' | 'ssgWriteTimeMs',\n deltaMs: number\n): void {\n const store = getPerfStore();\n if (!store) return;\n store[key] += deltaMs;\n}\n\nexport function recordSchedulerFlushTaskCount(taskCount: number): void {\n const store = getPerfStore();\n if (!store) return;\n store.lastSchedulerTaskCountPerFlush = taskCount;\n store.maxSchedulerTaskCountPerFlush = Math.max(\n store.maxSchedulerTaskCountPerFlush,\n taskCount\n );\n store.schedulerFlushCount += 1;\n store.schedulerTaskExecutions += taskCount;\n}\n\nexport function getPerfMetrics(): Readonly<PerfMetrics> | undefined {\n const store = getPerfStore();\n return store ? { ...store } : undefined;\n}\n\nexport function resetPerfMetrics(): void {\n const store = getPerfStore();\n if (!store) return;\n const next = createInitialPerfMetrics();\n (Object.keys(next) as PerfMetricsKey[]).forEach((key) => {\n store[key] = next[key];\n });\n}\n"],"mappings":";;AA+BA,MAAM,sBAAsB,wBAAwB,YAAY;AAChE,IAAI;AAEJ,SAAS,2BAAwC;CAC/C,OAAO;EACL,uBAAuB;EACvB,wBAAwB;EACxB,2BAA2B;EAC3B,sBAAsB;EACtB,mBAAmB;EACnB,uBAAuB;EACvB,8BAA8B;EAC9B,iBAAiB;EACjB,gCAAgC;EAChC,+BAA+B;EAC/B,qBAAqB;EACrB,yBAAyB;EACzB,gBAAgB;EAChB,iBAAiB;EACjB,uBAAuB;EACvB,gBAAgB;CAClB;AACF;AAEA,SAAS,2BAAoC;CAC3C,IAAI,yBAAyB,GAC3B,OAAO;CAET,IAAI,CAAC,qBACH,OAAO;CAET,IAAI;EACF,OAAO,CAAC,CAAE,WAA8B;CAC1C,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAS,eAAmC;CAC1C,IAAI,iBACF,OAAO;CAGT,IAAI,CAAC,yBAAyB,GAC5B,OAAO;CAGT,IAAI;EACF,MAAM,IAAI;EACV,IAAI,CAAC,EAAE,eACL,EAAE,gBAAgB,yBAAyB;EAE7C,kBAAkB,EAAE;EACpB,OAAO;CACT,QAAQ;EACN,OAAO;CACT;AACF;AAEA,SAAgB,sBAA0C;CACxD,OAAO,aAAa;AACtB;AAEA,SAAgB,oBACd,KAUA,QAAQ,GACF;CACN,MAAM,QAAQ,aAAa;CAC3B,IAAI,CAAC,OAAO;CACZ,MAAM,QAAQ;AAChB;AAEA,SAAgB,gBACd,KACA,SACM;CACN,MAAM,QAAQ,aAAa;CAC3B,IAAI,CAAC,OAAO;CACZ,MAAM,QAAQ;AAChB;AAEA,SAAgB,8BAA8B,WAAyB;CACrE,MAAM,QAAQ,aAAa;CAC3B,IAAI,CAAC,OAAO;CACZ,MAAM,iCAAiC;CACvC,MAAM,gCAAgC,KAAK,IACzC,MAAM,+BACN,SACF;CACA,MAAM,uBAAuB;CAC7B,MAAM,2BAA2B;AACnC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readable.d.ts","names":[],"sources":["../../src/runtime/readable.ts"],"mappings":";;;UAGiB,iBAAA;EACf,UAAA;EACA,yBAAA,GAA4B,
|
|
1
|
+
{"version":3,"file":"readable.d.ts","names":[],"sources":["../../src/runtime/readable.ts"],"mappings":";;;UAGiB,iBAAA;EACf,UAAA;EACA,yBAAA,GAA4B,GAAG,CAAC,cAAA;AAAA;AAAA,UAGjB,cAAA;EAAA,IACX,CAAA;EACJ,YAAA;EACA,gBAAA;EACA,QAAA,GAAW,GAAA,CAAI,iBAAA;EACf,mBAAA,GAAsB,GAAA,CAAI,iBAAA;AAAA;AAAA,iBAGZ,iBAAA,CAAkB,MAAe;AAAA,iBAoBjC,kBAAA,CAAmB,MAA+B,EAAvB,cAAc;AAAA,iBA8BzC,2BAAA,GAAA,CACd,cAAA,EAAgB,GAAA,CAAI,cAAA,YACpB,EAAA,QAAU,CAAA,GACT,CAAA;AAAA,iBAWa,6BAAA,CACd,QAA2B,EAAjB,iBAAiB;AAAA,iBAoCb,4BAAA,CACd,QAA2B,EAAjB,iBAAiB;AAAA,iBAab,uBAAA,GAAA,CACd,UAAA,EAAY,iBAAA,EACZ,EAAA,QAAU,CAAA,GACT,CAAA;AAAA,iBAaa,kCAAA,CACd,UAAA,EAAY,iBAAA,EACZ,WAAA,EAAa,GAAA,CAAI,cAAA,YACjB,WAAA,EAAa,GAAA,CAAI,cAAA;AAAA,iBAkBH,mCAAA,CACd,UAAA,EAAY,iBAAA,EACZ,OAAA,EAAS,GAAA,CAAI,cAAA;AAAA,iBAQC,mCAAA,CACd,MAA+B,EAAvB,cAAc;AAAA,iBAYR,4BAAA,CACd,MAA+B,EAAvB,cAAc;AAAA,iBAaR,qBAAA,CACd,MAAA,EAAQ,cAAA,WACR,YAAA,GAAe,iBAAiB"}
|
package/dist/runtime/readable.js
CHANGED
|
@@ -2,12 +2,17 @@ import { globalScheduler } from "./scheduler.js";
|
|
|
2
2
|
import { getCurrentInstance } from "./component.js";
|
|
3
3
|
//#region src/runtime/readable.ts
|
|
4
4
|
function markReadableUsage(source) {
|
|
5
|
-
if (source && typeof source === "function" && ("_hasBeenRead" in source || "_readers" in source))
|
|
5
|
+
if (source && typeof source === "function" && ("_hasBeenRead" in source || "_readers" in source)) {
|
|
6
|
+
const readable = source;
|
|
7
|
+
readable._hasBeenRead = true;
|
|
8
|
+
readable._hasEverBeenRead = true;
|
|
9
|
+
}
|
|
6
10
|
}
|
|
7
11
|
let currentDerivedSubscriber = null;
|
|
8
12
|
let suppressComponentReadTrackingDepth = 0;
|
|
9
13
|
let currentFineGrainedReadSources = null;
|
|
10
14
|
function recordReadableRead(source) {
|
|
15
|
+
source._hasEverBeenRead = true;
|
|
11
16
|
if (currentFineGrainedReadSources) {
|
|
12
17
|
currentFineGrainedReadSources.add(source);
|
|
13
18
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"readable.js","names":[],"sources":["../../src/runtime/readable.ts"],"sourcesContent":["import { globalScheduler } from './scheduler';\nimport { getCurrentInstance, type ComponentInstance } from './component';\n\nexport interface DerivedSubscriber {\n _markDirty(): void;\n _pendingDependencySources?: Set<ReadableSource<unknown>>;\n}\n\nexport interface ReadableSource<T = unknown> {\n (): T;\n _hasBeenRead?: boolean;\n _readers?: Map<ComponentInstance, number>;\n _derivedSubscribers?: Set<DerivedSubscriber>;\n}\n\nexport function markReadableUsage(source: unknown): void {\n if (\n source &&\n typeof source === 'function' &&\n ('_hasBeenRead' in source || '_readers' in source)\n ) {\n
|
|
1
|
+
{"version":3,"file":"readable.js","names":[],"sources":["../../src/runtime/readable.ts"],"sourcesContent":["import { globalScheduler } from './scheduler';\nimport { getCurrentInstance, type ComponentInstance } from './component';\n\nexport interface DerivedSubscriber {\n _markDirty(): void;\n _pendingDependencySources?: Set<ReadableSource<unknown>>;\n}\n\nexport interface ReadableSource<T = unknown> {\n (): T;\n _hasBeenRead?: boolean;\n _hasEverBeenRead?: boolean;\n _readers?: Map<ComponentInstance, number>;\n _derivedSubscribers?: Set<DerivedSubscriber>;\n}\n\nexport function markReadableUsage(source: unknown): void {\n if (\n source &&\n typeof source === 'function' &&\n ('_hasBeenRead' in source || '_readers' in source)\n ) {\n const readable = source as ReadableSource<unknown>;\n readable._hasBeenRead = true;\n readable._hasEverBeenRead = true;\n }\n}\n\ntype RendererBridge = {\n markReactivePropsDirtySource?: (source: ReadableSource<unknown>) => void;\n};\n\nlet currentDerivedSubscriber: DerivedSubscriber | null = null;\nlet suppressComponentReadTrackingDepth = 0;\nlet currentFineGrainedReadSources: Set<ReadableSource<unknown>> | null = null;\n\nexport function recordReadableRead(source: ReadableSource<unknown>): void {\n source._hasEverBeenRead = true;\n\n if (currentFineGrainedReadSources) {\n currentFineGrainedReadSources.add(source);\n return;\n }\n\n if (currentDerivedSubscriber) {\n if (!currentDerivedSubscriber._pendingDependencySources) {\n currentDerivedSubscriber._pendingDependencySources = new Set();\n }\n currentDerivedSubscriber._pendingDependencySources.add(source);\n }\n\n if (suppressComponentReadTrackingDepth > 0) {\n return;\n }\n\n const inst = getCurrentInstance();\n if (!inst || inst._currentRenderToken === undefined) {\n return;\n }\n\n if (!inst._pendingReadSources) {\n inst._pendingReadSources = new Set();\n }\n inst._pendingReadSources.add(source);\n}\n\nexport function withFineGrainedReadTracking<T>(\n pendingSources: Set<ReadableSource<unknown>>,\n fn: () => T\n): T {\n const previousPendingSources = currentFineGrainedReadSources;\n currentFineGrainedReadSources = pendingSources;\n\n try {\n return fn();\n } finally {\n currentFineGrainedReadSources = previousPendingSources;\n }\n}\n\nexport function finalizeReadableSubscriptions(\n instance: ComponentInstance\n): void {\n const newSet = instance._pendingReadSources;\n const oldSet = instance._lastReadSources;\n const token = instance._currentRenderToken;\n\n if (token === undefined) {\n return;\n }\n\n if (oldSet) {\n for (const source of oldSet) {\n if (!newSet?.has(source)) {\n source._readers?.delete(instance);\n }\n }\n }\n\n instance.lastRenderToken = token;\n\n if (newSet) {\n for (const source of newSet) {\n let readers = source._readers;\n if (!readers) {\n readers = new Map();\n source._readers = readers;\n }\n readers.set(instance, instance.lastRenderToken ?? 0);\n }\n }\n\n instance._lastReadSources = newSet ?? new Set();\n instance._pendingReadSources = undefined;\n instance._currentRenderToken = undefined;\n}\n\nexport function cleanupReadableSubscriptions(\n instance: ComponentInstance\n): void {\n const sources = instance._lastReadSources;\n if (!sources || sources.size === 0) {\n return;\n }\n\n for (const source of sources) {\n source._readers?.delete(instance);\n }\n instance._lastReadSources = new Set();\n}\n\nexport function withDerivedReadTracking<T>(\n subscriber: DerivedSubscriber,\n fn: () => T\n): T {\n const prevDerivedSubscriber = currentDerivedSubscriber;\n currentDerivedSubscriber = subscriber;\n suppressComponentReadTrackingDepth += 1;\n\n try {\n return fn();\n } finally {\n suppressComponentReadTrackingDepth -= 1;\n currentDerivedSubscriber = prevDerivedSubscriber;\n }\n}\n\nexport function syncDerivedDependencySubscriptions(\n subscriber: DerivedSubscriber,\n prevSources: Set<ReadableSource<unknown>>,\n nextSources: Set<ReadableSource<unknown>>\n): void {\n for (const source of prevSources) {\n if (!nextSources.has(source)) {\n source._derivedSubscribers?.delete(subscriber);\n }\n }\n\n for (const source of nextSources) {\n let subscribers = source._derivedSubscribers;\n if (!subscribers) {\n subscribers = new Set();\n source._derivedSubscribers = subscribers;\n }\n subscribers.add(subscriber);\n }\n}\n\nexport function clearDerivedDependencySubscriptions(\n subscriber: DerivedSubscriber,\n sources: Set<ReadableSource<unknown>>\n): void {\n for (const source of sources) {\n source._derivedSubscribers?.delete(subscriber);\n }\n sources.clear();\n}\n\nexport function markReadableDerivedSubscribersDirty(\n source: ReadableSource<unknown>\n): void {\n const subscribers = source._derivedSubscribers;\n if (!subscribers || subscribers.size === 0) {\n return;\n }\n\n for (const subscriber of subscribers) {\n subscriber._markDirty();\n }\n}\n\nexport function markReactivePropsDirtySource(\n source: ReadableSource<unknown>\n): void {\n try {\n (\n globalThis as {\n __ASKR_RENDERER?: RendererBridge;\n }\n ).__ASKR_RENDERER?.markReactivePropsDirtySource?.(source);\n } catch {\n // Keep readable notifications side-effect safe.\n }\n}\n\nexport function notifyReadableReaders(\n source: ReadableSource<unknown>,\n skipInstance?: ComponentInstance | null\n): boolean {\n const readers = source._readers;\n let didScheduleUpdate = false;\n\n if (!readers || readers.size === 0) {\n return false;\n }\n\n for (const [instance, token] of readers) {\n if (skipInstance && instance === skipInstance) {\n continue;\n }\n if (instance.lastRenderToken !== token) {\n continue;\n }\n if (instance.hasPendingUpdate) {\n continue;\n }\n\n instance.hasPendingUpdate = true;\n const task = instance._pendingFlushTask;\n if (task) {\n globalScheduler.enqueue(task);\n } else {\n globalScheduler.enqueue(() => {\n instance.hasPendingUpdate = false;\n instance.notifyUpdate?.();\n });\n }\n didScheduleUpdate = true;\n }\n\n return didScheduleUpdate;\n}\n"],"mappings":";;;AAgBA,SAAgB,kBAAkB,QAAu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AC/B;EAEF,IAAI,SAAS,oBAAoB,OAC/B;EAEF,IAAI,SAAS,kBACX;EAGF,SAAS,mBAAmB;EAC5B,MAAM,OAAO,SAAS;EACtB,IAAI,MACF,gBAAgB,QAAQ,IAAI;OAE5B,gBAAgB,cAAc;GAC5B,SAAS,mBAAmB;GAC5B,SAAS,eAAe;EAC1B,CAAC;EAEH,oBAAoB;CACtB;CAEA,OAAO;AACT"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { logger } from "../dev/logger.js";
|
|
2
2
|
import { withAsyncResourceContext } from "./context.js";
|
|
3
|
+
import { isPromiseLike } from "../common/promise.js";
|
|
3
4
|
import { brandSnapshotSource } from "./snapshot-source.js";
|
|
4
5
|
import { getSSRBridge } from "./ssr-bridge.js";
|
|
5
6
|
//#region src/runtime/resource-cell.ts
|
|
@@ -20,6 +21,7 @@ var ResourceCell = class {
|
|
|
20
21
|
this.deps = null;
|
|
21
22
|
this.resourceFrame = null;
|
|
22
23
|
this.subscribers = /* @__PURE__ */ new Set();
|
|
24
|
+
this.disposed = false;
|
|
23
25
|
this.fn = fn;
|
|
24
26
|
this.deps = deps ? deps.slice() : null;
|
|
25
27
|
this.resourceFrame = resourceFrame;
|
|
@@ -44,6 +46,7 @@ var ResourceCell = class {
|
|
|
44
46
|
for (const cb of this.subscribers) cb();
|
|
45
47
|
}
|
|
46
48
|
start(ssr = false, notify = true) {
|
|
49
|
+
if (this.disposed) return;
|
|
47
50
|
const generation = this.generation;
|
|
48
51
|
this.controller?.abort();
|
|
49
52
|
const controller = new AbortController();
|
|
@@ -60,7 +63,7 @@ var ResourceCell = class {
|
|
|
60
63
|
if (notify) this.notifySubscribers();
|
|
61
64
|
return;
|
|
62
65
|
}
|
|
63
|
-
if (!(result
|
|
66
|
+
if (!isPromiseLike(result)) {
|
|
64
67
|
this.value = result;
|
|
65
68
|
this.pending = false;
|
|
66
69
|
this.error = null;
|
|
@@ -68,9 +71,10 @@ var ResourceCell = class {
|
|
|
68
71
|
return;
|
|
69
72
|
}
|
|
70
73
|
if (ssr) getSSRBridge().throwSSRDataMissing();
|
|
71
|
-
result.then((val) => {
|
|
74
|
+
Promise.resolve(result).then((val) => {
|
|
72
75
|
if (this.generation !== generation) return;
|
|
73
76
|
if (this.controller !== controller) return;
|
|
77
|
+
if (controller.signal.aborted) return;
|
|
74
78
|
this.value = val;
|
|
75
79
|
this.pending = false;
|
|
76
80
|
this.error = null;
|
|
@@ -89,6 +93,7 @@ var ResourceCell = class {
|
|
|
89
93
|
});
|
|
90
94
|
}
|
|
91
95
|
refresh() {
|
|
96
|
+
if (this.disposed) return;
|
|
92
97
|
this.generation++;
|
|
93
98
|
this.controller?.abort();
|
|
94
99
|
this.start();
|
|
@@ -96,6 +101,12 @@ var ResourceCell = class {
|
|
|
96
101
|
abort() {
|
|
97
102
|
this.controller?.abort();
|
|
98
103
|
}
|
|
104
|
+
dispose() {
|
|
105
|
+
if (this.disposed) return;
|
|
106
|
+
this.disposed = true;
|
|
107
|
+
this.controller?.abort();
|
|
108
|
+
this.subscribers.clear();
|
|
109
|
+
}
|
|
99
110
|
};
|
|
100
111
|
//#endregion
|
|
101
112
|
export { ResourceCell };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource-cell.js","names":[],"sources":["../../src/runtime/resource-cell.ts"],"sourcesContent":["import { withAsyncResourceContext, type ContextFrame } from './context';\nimport { logger } from '../dev/logger';\nimport { getSSRBridge } from './ssr-bridge';\nimport {\n brandSnapshotSource,\n type SnapshotSourceBrand,\n} from './snapshot-source';\n\n/**\n * Pure, component-agnostic ResourceCell state machine.\n * - Holds value/pending/error/generation/controller\n * - Exposes a stable `snapshot` object: { value, pending, error, refresh }\n * - Uses `withAsyncResourceContext` to bind the synchronous execution step\n * to a captured frame. Continuations after await do not see the frame.\n */\nexport class ResourceCell<U> {\n value: U | null = null;\n pending = true;\n error: Error | null = null;\n generation = 0;\n controller: AbortController | null = null;\n deps: unknown[] | null = null;\n resourceFrame: ContextFrame | null = null;\n\n // Optional debug label set by caller (component name) to improve logs\n ownerName?: string;\n\n private subscribers = new Set<() => void>();\n\n readonly snapshot: {\n value: U | null;\n pending: boolean;\n error: Error | null;\n refresh: () => void;\n } & SnapshotSourceBrand;\n\n private fn: (opts: { signal: AbortSignal }) =>
|
|
1
|
+
{"version":3,"file":"resource-cell.js","names":[],"sources":["../../src/runtime/resource-cell.ts"],"sourcesContent":["import { withAsyncResourceContext, type ContextFrame } from './context';\nimport { logger } from '../dev/logger';\nimport { getSSRBridge } from './ssr-bridge';\nimport {\n brandSnapshotSource,\n type SnapshotSourceBrand,\n} from './snapshot-source';\nimport { isPromiseLike } from '../common/promise';\n\n/**\n * Pure, component-agnostic ResourceCell state machine.\n * - Holds value/pending/error/generation/controller\n * - Exposes a stable `snapshot` object: { value, pending, error, refresh }\n * - Uses `withAsyncResourceContext` to bind the synchronous execution step\n * to a captured frame. Continuations after await do not see the frame.\n */\nexport class ResourceCell<U> {\n value: U | null = null;\n pending = true;\n error: Error | null = null;\n generation = 0;\n controller: AbortController | null = null;\n deps: readonly unknown[] | null = null;\n resourceFrame: ContextFrame | null = null;\n\n // Optional debug label set by caller (component name) to improve logs\n ownerName?: string;\n\n private subscribers = new Set<() => void>();\n private disposed = false;\n\n readonly snapshot: {\n value: U | null;\n pending: boolean;\n error: Error | null;\n refresh: () => void;\n } & SnapshotSourceBrand;\n\n private fn: (opts: { signal: AbortSignal }) => PromiseLike<U> | U;\n\n constructor(\n fn: (opts: { signal: AbortSignal }) => PromiseLike<U> | U,\n deps: readonly unknown[] | null,\n resourceFrame: ContextFrame | null\n ) {\n this.fn = fn;\n this.deps = deps ? deps.slice() : null;\n this.resourceFrame = resourceFrame;\n this.snapshot = brandSnapshotSource({\n value: null,\n pending: true,\n error: null,\n refresh: () => this.refresh(),\n });\n }\n\n setLoader(fn: (opts: { signal: AbortSignal }) => PromiseLike<U> | U): void {\n this.fn = fn;\n }\n\n subscribe(cb: () => void): () => void {\n this.subscribers.add(cb);\n return () => this.subscribers.delete(cb);\n }\n\n private notifySubscribers() {\n this.snapshot.value = this.value;\n this.snapshot.pending = this.pending;\n this.snapshot.error = this.error;\n for (const cb of this.subscribers) cb();\n }\n\n start(ssr = false, notify = true) {\n if (this.disposed) {\n return;\n }\n\n const generation = this.generation;\n\n this.controller?.abort();\n const controller = new AbortController();\n this.controller = controller;\n this.pending = true;\n this.error = null;\n if (notify) this.notifySubscribers();\n\n let result: PromiseLike<U> | U;\n try {\n // Execute only the synchronous step inside the frozen resource frame.\n result = withAsyncResourceContext(this.resourceFrame, () =>\n this.fn({ signal: controller.signal })\n );\n } catch (err) {\n this.pending = false;\n this.error = err as Error;\n if (notify) this.notifySubscribers();\n return;\n }\n\n if (!isPromiseLike<U>(result)) {\n this.value = result as U;\n this.pending = false;\n this.error = null;\n if (notify) this.notifySubscribers();\n return;\n }\n\n if (ssr) {\n // During SSR async results are disallowed\n getSSRBridge().throwSSRDataMissing();\n }\n\n Promise.resolve(result)\n .then((val) => {\n if (this.generation !== generation) return;\n if (this.controller !== controller) return;\n // A loader that does not reject on abort (e.g. a plain Promise) would\n // otherwise commit its value after the fetch was cancelled by a deps\n // change, refresh(), or unmount. Mirror the AbortError guard used in\n // the rejection path so an aborted fetch's resolution stays inert.\n if (controller.signal.aborted) return;\n this.value = val;\n this.pending = false;\n this.error = null;\n this.notifySubscribers();\n })\n .catch((err) => {\n if (this.generation !== generation) return;\n if (this.controller !== controller) return;\n\n const isAbortError =\n controller.signal.aborted ||\n (err instanceof Error && err.name === 'AbortError') ||\n (typeof DOMException !== 'undefined' &&\n err instanceof DOMException &&\n err.name === 'AbortError');\n\n if (isAbortError) {\n return;\n }\n\n this.pending = false;\n this.error = err as Error;\n try {\n if (this.ownerName) {\n logger.error(\n `[Askr] Async resource error in ${this.ownerName}:`,\n err\n );\n } else {\n logger.error('[Askr] Async resource error:', err);\n }\n } catch {\n /* ignore logging errors */\n }\n this.notifySubscribers();\n });\n }\n\n refresh() {\n if (this.disposed) {\n return;\n }\n\n this.generation++;\n this.controller?.abort();\n this.start();\n }\n\n abort() {\n this.controller?.abort();\n }\n\n dispose() {\n if (this.disposed) {\n return;\n }\n\n this.disposed = true;\n this.controller?.abort();\n this.subscribers.clear();\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,IAAa,eAAb,MAA6B;CAwB3B,YACE,IACA,MACA,eACA;eA3BgB;iBACR;eACY;oBACT;oBACwB;cACH;uBACG;qCAKf,IAAI,IAAgB;kBACvB;EAgBjB,KAAK,KAAK;EACV,KAAK,OAAO,OAAO,KAAK,MAAM,IAAI;EAClC,KAAK,gBAAgB;EACrB,KAAK,WAAW,oBAAoB;GAClC,OAAO;GACP,SAAS;GACT,OAAO;GACP,eAAe,KAAK,QAAQ;EAC9B,CAAC;CACH;CAEA,UAAU,IAAiE;EACzE,KAAK,KAAK;CACZ;CAEA,UAAU,IAA4B;EACpC,KAAK,YAAY,IAAI,EAAE;EACvB,aAAa,KAAK,YAAY,OAAO,EAAE;CACzC;CAEA,oBAA4B;EAC1B,KAAK,SAAS,QAAQ,KAAK;EAC3B,KAAK,SAAS,UAAU,KAAK;EAC7B,KAAK,SAAS,QAAQ,KAAK;EAC3B,KAAK,MAAM,MAAM,KAAK,aAAa,GAAG;CACxC;CAEA,MAAM,MAAM,OAAO,SAAS,MAAM;EAChC,IAAI,KAAK,UACP;EAGF,MAAM,aAAa,KAAK;EAExB,KAAK,YAAY,MAAM;EACvB,MAAM,aAAa,IAAI,gBAAgB;EACvC,KAAK,aAAa;EAClB,KAAK,UAAU;EACf,KAAK,QAAQ;EACb,IAAI,QAAQ,KAAK,kBAAkB;EAEnC,IAAI;EACJ,IAAI;GAEF,SAAS,yBAAyB,KAAK,qBACrC,KAAK,GAAG,EAAE,QAAQ,WAAW,OAAO,CAAC,CACvC;EACF,SAAS,KAAK;GACZ,KAAK,UAAU;GACf,KAAK,QAAQ;GACb,IAAI,QAAQ,KAAK,kBAAkB;GACnC;EACF;EAEA,IAAI,CAAC,cAAiB,MAAM,GAAG;GAC7B,KAAK,QAAQ;GACb,KAAK,UAAU;GACf,KAAK,QAAQ;GACb,IAAI,QAAQ,KAAK,kBAAkB;GACnC;EACF;EAEA,IAAI,KAEF,aAAa,EAAE,oBAAoB;EAGrC,QAAQ,QAAQ,MAAM,EACnB,MAAM,QAAQ;GACb,IAAI,KAAK,eAAe,YAAY;GACpC,IAAI,KAAK,eAAe,YAAY;GAKpC,IAAI,WAAW,OAAO,SAAS;GAC/B,KAAK,QAAQ;GACb,KAAK,UAAU;GACf,KAAK,QAAQ;GACb,KAAK,kBAAkB;EACzB,CAAC,EACA,OAAO,QAAQ;GACd,IAAI,KAAK,eAAe,YAAY;GACpC,IAAI,KAAK,eAAe,YAAY;GASpC,IANE,WAAW,OAAO,WACjB,eAAe,SAAS,IAAI,SAAS,gBACrC,OAAO,iBAAiB,eACvB,eAAe,gBACf,IAAI,SAAS,cAGf;GAGF,KAAK,UAAU;GACf,KAAK,QAAQ;GACb,IAAI;IACF,IAAI,KAAK,WACP,OAAO,MACL,kCAAkC,KAAK,UAAU,IACjD,GACF;SAEA,OAAO,MAAM,gCAAgC,GAAG;GAEpD,QAAQ,CAER;GACA,KAAK,kBAAkB;EACzB,CAAC;CACL;CAEA,UAAU;EACR,IAAI,KAAK,UACP;EAGF,KAAK;EACL,KAAK,YAAY,MAAM;EACvB,KAAK,MAAM;CACb;CAEA,QAAQ;EACN,KAAK,YAAY,MAAM;CACzB;CAEA,UAAU;EACR,IAAI,KAAK,UACP;EAGF,KAAK,WAAW;EAChB,KAAK,YAAY,MAAM;EACvB,KAAK,YAAY,MAAM;CACzB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.d.ts","names":[],"sources":["../../src/runtime/scheduler.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"scheduler.d.ts","names":[],"sources":["../../src/runtime/scheduler.ts"],"mappings":";;;;;;AAkBS;AACT;;;;KADK,IAAA;AAAA,KACO,aAAA;AAAA,cA8BC,SAAA;EAAA,QACH,KAAA;EAAA,QAOA,OAAA;EAAA,QACA,SAAA;EAAA,QACA,KAAA;EAAA,QACA,cAAA;EAAA,QAGA,YAAA;EAAA,QAGA,aAAA;EAAA,QAGA,iBAAA;EAAA,QAGA,OAAA;EAAA,QAQA,SAAA;EAAA,QAEA,eAAA;EAAA,QAUA,mBAAA;EAAA,QASA,WAAA;EAAA,QAmBA,iBAAA;EA4BR,OAAA,CAAQ,IAAA,EAAM,IAAA;EAId,aAAA,CAAc,IAAA,EAAM,aAAA,EAAe,IAAA,EAAM,IAAA;EAuBzC,KAAA,CAAA;EA4FA,mBAAA,GAAA,CAAuB,EAAA,QAAU,CAAA,GAAI,CAAA;EAyCrC,YAAA,CAAa,aAAA,WAAwB,SAAA,YAAmB,OAAA;EAgCxD,QAAA,CAAA;;;;;;;;;;;;;;;;EAsBA,eAAA,CAAA;EAIA,aAAA,CAAA;EAMA,iBAAA,GAAA,CAAqB,EAAA,QAAU,CAAA,EAAG,SAAA,sBAAwC,CAAA;EAmB1E,YAAA,CAAa,CAAA;EAOb,WAAA,CAAA;EAIA,WAAA,CAAA;EAKA,qBAAA,CAAA;EAAA,QAgCQ,cAAA;AAAA;AAAA,cAmBG,eAAA,EAAe,SAAkB;AAAA,iBAE9B,oBAAA,CAAA;AAAA,iBAIA,oBAAA,CAAqB,OAAA,EAAS,aAAA,GAAgB,aAAa"}
|
|
@@ -122,7 +122,7 @@ var Scheduler = class {
|
|
|
122
122
|
this.depth = 0;
|
|
123
123
|
let fatal = null;
|
|
124
124
|
let executedTaskCount = 0;
|
|
125
|
-
const
|
|
125
|
+
const executionsByTask = isDevelopmentEnvironment() ? /* @__PURE__ */ new Map() : null;
|
|
126
126
|
try {
|
|
127
127
|
while (fatal === null) {
|
|
128
128
|
let didRunTask = false;
|
|
@@ -130,9 +130,13 @@ var Scheduler = class {
|
|
|
130
130
|
const laneQueue = this.lanes[lane];
|
|
131
131
|
let executedInLane = 0;
|
|
132
132
|
while (laneQueue.head < laneQueue.tasks.length) {
|
|
133
|
-
this.depth++;
|
|
134
|
-
if (checkFlushDepth && this.depth > MAX_FLUSH_DEPTH) throw new Error(`[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`);
|
|
135
133
|
const task = laneQueue.tasks[laneQueue.head++];
|
|
134
|
+
if (executionsByTask) {
|
|
135
|
+
const taskExecutions = (executionsByTask.get(task) ?? 0) + 1;
|
|
136
|
+
executionsByTask.set(task, taskExecutions);
|
|
137
|
+
this.depth = Math.max(this.depth, taskExecutions);
|
|
138
|
+
if (taskExecutions > MAX_FLUSH_DEPTH) throw new Error(`[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`);
|
|
139
|
+
}
|
|
136
140
|
try {
|
|
137
141
|
this.executionDepth++;
|
|
138
142
|
task();
|
|
@@ -173,7 +177,7 @@ var Scheduler = class {
|
|
|
173
177
|
const res = fn();
|
|
174
178
|
if (!this.running && this.hasPendingTasks()) this.flush();
|
|
175
179
|
if (isDevelopmentEnvironment()) {
|
|
176
|
-
if (this.hasPendingTasks()) throw new Error("[Scheduler] tasks remain after runWithSyncProgress flush");
|
|
180
|
+
if (!this.running && this.hasPendingTasks()) throw new Error("[Scheduler] tasks remain after runWithSyncProgress flush");
|
|
177
181
|
}
|
|
178
182
|
return res;
|
|
179
183
|
} finally {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scheduler.js","names":[],"sources":["../../src/runtime/scheduler.ts"],"sourcesContent":["/**\n * Serialized update scheduler — safer design (no inline execution, explicit flush)\n *\n * Key ideas:\n * - Never execute a task inline from `enqueue`.\n * - `flush()` is explicit and non-reentrant.\n * - `runWithSyncProgress()` allows enqueues temporarily but does not run tasks\n * inline; it runs `fn` and then does an explicit `flush()`.\n * - `waitForFlush()` is race-free with a monotonic `flushVersion`.\n */\n\nimport { isDevelopmentEnvironment } from '../common/env';\nimport { assertSchedulingPrecondition, invariant } from '../dev/invariant';\nimport { logger } from '../dev/logger';\nimport { recordSchedulerFlushTaskCount } from './perf-metrics';\n\nconst MAX_FLUSH_DEPTH = 50;\n\ntype Task = () => void;\nexport type SchedulerLane = 'derived' | 'component' | 'reactive' | 'post';\n\nconst SCHEDULER_LANES: SchedulerLane[] = [\n 'derived',\n 'component',\n 'reactive',\n 'post',\n];\n\ninterface LaneQueue {\n tasks: Task[];\n head: number;\n}\n\nfunction isBulkCommitActive(): boolean {\n try {\n const fb = (\n globalThis as {\n __ASKR_FASTLANE?: { isBulkCommitActive?: () => boolean };\n }\n ).__ASKR_FASTLANE;\n return typeof fb?.isBulkCommitActive === 'function'\n ? !!fb.isBulkCommitActive()\n : false;\n } catch (e) {\n void e;\n return false;\n }\n}\n\nexport class Scheduler {\n private lanes: Record<SchedulerLane, LaneQueue> = {\n derived: { tasks: [], head: 0 },\n component: { tasks: [], head: 0 },\n reactive: { tasks: [], head: 0 },\n post: { tasks: [], head: 0 },\n };\n\n private running = false;\n private inHandler = false;\n private depth = 0;\n private executionDepth = 0; // for compat with existing diagnostics\n\n // Monotonic flush version increments at end of each flush\n private flushVersion = 0;\n\n // Best-effort microtask kick scheduling\n private kickScheduled = false;\n\n // Escape hatch flag for runWithSyncProgress\n private allowSyncProgress = false;\n\n // Waiters waiting for flushVersion >= target\n private waiters: Array<{\n target: number;\n resolve: () => void;\n reject: (err: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n }> = [];\n\n // Keep a lightweight taskCount for compatibility/diagnostics\n private taskCount = 0;\n\n private hasPendingTasks(): boolean {\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n if (queue.head < queue.tasks.length) {\n return true;\n }\n }\n return false;\n }\n\n private getPendingTaskCount(): number {\n let total = 0;\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n total += queue.tasks.length - queue.head;\n }\n return total;\n }\n\n private compactLane(queue: LaneQueue): void {\n if (queue.head >= queue.tasks.length) {\n queue.tasks.length = 0;\n queue.head = 0;\n return;\n }\n\n if (queue.head <= 0) {\n return;\n }\n\n const remaining = queue.tasks.length - queue.head;\n for (let i = 0; i < remaining; i++) {\n queue.tasks[i] = queue.tasks[queue.head + i];\n }\n queue.tasks.length = remaining;\n queue.head = 0;\n }\n\n private scheduleFlushKick(): void {\n if (\n this.running ||\n this.kickScheduled ||\n this.inHandler ||\n this.allowSyncProgress ||\n isBulkCommitActive() ||\n !this.hasPendingTasks()\n ) {\n return;\n }\n\n this.kickScheduled = true;\n queueMicrotask(() => {\n this.kickScheduled = false;\n if (this.running || isBulkCommitActive() || !this.hasPendingTasks()) {\n return;\n }\n try {\n this.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n\n enqueue(task: Task): void {\n this.enqueueInLane('component', task);\n }\n\n enqueueInLane(lane: SchedulerLane, task: Task): void {\n assertSchedulingPrecondition(\n typeof task === 'function',\n 'enqueue() requires a function'\n );\n\n // Strict rule: during bulk commit, only allow enqueues if runWithSyncProgress enabled\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n if (isDevelopmentEnvironment()) {\n throw new Error(\n '[Scheduler] enqueue() during bulk commit (not allowed)'\n );\n }\n return;\n }\n\n // Enqueue task and account counts\n this.lanes[lane].tasks.push(task);\n this.taskCount++;\n\n this.scheduleFlushKick();\n }\n\n flush(): void {\n invariant(\n !this.running,\n '[Scheduler] flush() called while already running'\n );\n\n // Dev-only guard: disallow flush during bulk commit unless allowed\n if (isDevelopmentEnvironment()) {\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n throw new Error(\n '[Scheduler] flush() started during bulk commit (not allowed)'\n );\n }\n }\n\n this.running = true;\n this.depth = 0;\n let fatal: unknown = null;\n let executedTaskCount = 0;\n const checkFlushDepth = isDevelopmentEnvironment();\n\n try {\n while (fatal === null) {\n let didRunTask = false;\n\n for (const lane of SCHEDULER_LANES) {\n const laneQueue = this.lanes[lane];\n let executedInLane = 0;\n\n while (laneQueue.head < laneQueue.tasks.length) {\n this.depth++;\n if (checkFlushDepth && this.depth > MAX_FLUSH_DEPTH) {\n throw new Error(\n `[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`\n );\n }\n\n const task = laneQueue.tasks[laneQueue.head++];\n try {\n this.executionDepth++;\n task();\n this.executionDepth--;\n executedTaskCount++;\n executedInLane++;\n didRunTask = true;\n } catch (err) {\n // ensure executionDepth stays balanced for the task that threw\n if (this.executionDepth > 0) this.executionDepth--;\n fatal = err;\n break;\n }\n }\n\n if (executedInLane > 0) {\n this.taskCount = Math.max(0, this.taskCount - executedInLane);\n }\n\n if (fatal !== null) {\n break;\n }\n }\n\n if (!didRunTask) {\n break;\n }\n }\n } finally {\n this.running = false;\n this.depth = 0;\n this.executionDepth = 0;\n\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n if (queue.head > 0) {\n this.compactLane(queue);\n }\n }\n\n // Advance flush epoch and resolve waiters\n this.flushVersion++;\n this.resolveWaiters();\n recordSchedulerFlushTaskCount(executedTaskCount);\n }\n\n if (fatal) throw fatal;\n }\n\n runWithSyncProgress<T>(fn: () => T): T {\n const prev = this.allowSyncProgress;\n this.allowSyncProgress = true;\n\n // Snapshot flushVersion so we can ensure we always complete an epoch\n const startVersion = this.flushVersion;\n\n try {\n const res = fn();\n\n // Flush deterministically if tasks were enqueued (and we're not already running)\n if (!this.running && this.hasPendingTasks()) {\n this.flush();\n }\n\n if (isDevelopmentEnvironment()) {\n if (this.hasPendingTasks()) {\n throw new Error(\n '[Scheduler] tasks remain after runWithSyncProgress flush'\n );\n }\n }\n\n return res;\n } finally {\n // If no flush happened during the protected window, complete an epoch so\n // observers (tests) see progress even when fast-lane did synchronous work\n // without enqueuing tasks.\n try {\n if (this.flushVersion === startVersion) {\n this.flushVersion++;\n this.resolveWaiters();\n }\n } catch (e) {\n void e;\n }\n\n this.allowSyncProgress = prev;\n }\n }\n\n waitForFlush(targetVersion?: number, timeoutMs = 2000): Promise<void> {\n const target =\n typeof targetVersion === 'number' ? targetVersion : this.flushVersion + 1;\n if (this.flushVersion >= target) return Promise.resolve();\n\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n const ns =\n (\n globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n }\n ).__ASKR__ || {};\n const diag = {\n flushVersion: this.flushVersion,\n queueLen: this.getPendingTaskCount(),\n running: this.running,\n inHandler: this.inHandler,\n bulk: isBulkCommitActive(),\n namespace: ns,\n };\n reject(\n new Error(\n `waitForFlush timeout ${timeoutMs}ms: ${JSON.stringify(diag)}`\n )\n );\n }, timeoutMs);\n\n this.waiters.push({ target, resolve, reject, timer });\n });\n }\n\n getState() {\n // Provide the compatibility shape expected by diagnostics/tests\n return {\n queueLength: this.getPendingTaskCount(),\n running: this.running,\n depth: this.depth,\n executionDepth: this.executionDepth,\n taskCount: this.taskCount,\n flushVersion: this.flushVersion,\n laneQueues: {\n derived: this.lanes.derived.tasks.length - this.lanes.derived.head,\n component:\n this.lanes.component.tasks.length - this.lanes.component.head,\n reactive: this.lanes.reactive.tasks.length - this.lanes.reactive.head,\n post: this.lanes.post.tasks.length - this.lanes.post.head,\n },\n // New fields for optional inspection\n inHandler: this.inHandler,\n allowSyncProgress: this.allowSyncProgress,\n };\n }\n\n getFlushVersion(): number {\n return this.flushVersion;\n }\n\n flushIfQueued(): void {\n if (!this.running && this.hasPendingTasks()) {\n this.flush();\n }\n }\n\n runInHandlerScope<T>(fn: () => T, flushMode: 'defer' | 'sync' = 'defer'): T {\n const prevInHandler = this.inHandler;\n this.inHandler = true;\n\n try {\n return fn();\n } finally {\n this.inHandler = prevInHandler;\n\n if (!this.inHandler) {\n if (flushMode === 'sync') {\n this.flushIfQueued();\n } else {\n this.scheduleFlushKick();\n }\n }\n }\n }\n\n setInHandler(v: boolean) {\n this.inHandler = v;\n if (!v) {\n this.scheduleFlushKick();\n }\n }\n\n isInHandler(): boolean {\n return this.inHandler;\n }\n\n isExecuting(): boolean {\n return this.running || this.executionDepth > 0;\n }\n\n // Clear pending synchronous tasks (used by fastlane enter/exit)\n clearPendingSyncTasks(): number {\n const remaining = this.getPendingTaskCount();\n if (remaining <= 0) return 0;\n\n if (this.running) {\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n queue.tasks.length = queue.head;\n }\n this.taskCount = Math.max(0, this.taskCount - remaining);\n queueMicrotask(() => {\n try {\n this.flushVersion++;\n this.resolveWaiters();\n } catch (e) {\n void e;\n }\n });\n return remaining;\n }\n\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n queue.tasks.length = 0;\n queue.head = 0;\n }\n this.taskCount = Math.max(0, this.taskCount - remaining);\n this.flushVersion++;\n this.resolveWaiters();\n return remaining;\n }\n\n private resolveWaiters() {\n if (this.waiters.length === 0) return;\n const ready: Array<() => void> = [];\n const remaining: typeof this.waiters = [];\n\n for (const w of this.waiters) {\n if (this.flushVersion >= w.target) {\n if (w.timer) clearTimeout(w.timer);\n ready.push(w.resolve);\n } else {\n remaining.push(w);\n }\n }\n\n this.waiters = remaining;\n for (const r of ready) r();\n }\n}\n\nexport const globalScheduler = new Scheduler();\n\nexport function isSchedulerExecuting(): boolean {\n return globalScheduler.isExecuting();\n}\n\nexport function scheduleEventHandler(handler: EventListener): EventListener {\n return (event: Event) => {\n try {\n globalScheduler.runInHandlerScope(() => {\n handler.call(null, event);\n });\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAM,kBAAkB;AAKxB,MAAM,kBAAmC;CACvC;CACA;CACA;CACA;CACD;AAOD,SAAS,qBAA8B;CACrC,IAAI;EACF,MAAM,KACJ,WAGA;EACF,OAAO,OAAO,IAAI,uBAAuB,aACrC,CAAC,CAAC,GAAG,oBAAoB,GACzB;UACG,GAAG;EAEV,OAAO;;;AAIX,IAAa,YAAb,MAAuB;;eA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AY,KAAK,IAAI,GAAG,KAAK,YAAY,UAAU;EACxD,KAAK;EACL,KAAK,gBAAgB;EACrB,OAAO;;CAGT,iBAAyB;EACvB,IAAI,KAAK,QAAQ,WAAW,GAAG;EAC/B,MAAM,QAA2B,EAAE;EACnC,MAAM,YAAiC,EAAE;EAEzC,KAAK,MAAM,KAAK,KAAK,SACnB,IAAI,KAAK,gBAAgB,EAAE,QAAQ;GACjC,IAAI,EAAE,OAAO,aAAa,EAAE,MAAM;GAClC,MAAM,KAAK,EAAE,QAAQ;SAErB,UAAU,KAAK,EAAE;EAIrB,KAAK,UAAU;EACf,KAAK,MAAM,KAAK,OAAO,GAAG;;;AAI9B,MAAa,kBAAkB,IAAI,WAAW;AAE9C,SAAgB,uBAAgC;CAC9C,OAAO,gBAAgB,aAAa;;AAGtC,SAAgB,qBAAqB,SAAuC;CAC1E,QAAQ,UAAiB;EACvB,IAAI;GACF,gBAAgB,wBAAwB;IACtC,QAAQ,KAAK,MAAM,MAAM;KACzB;WACK,OAAO;GACd,OAAO,MAAM,+BAA+B,MAAM"}
|
|
1
|
+
{"version":3,"file":"scheduler.js","names":[],"sources":["../../src/runtime/scheduler.ts"],"sourcesContent":["/**\n * Serialized update scheduler — safer design (no inline execution, explicit flush)\n *\n * Key ideas:\n * - Never execute a task inline from `enqueue`.\n * - `flush()` is explicit and non-reentrant.\n * - `runWithSyncProgress()` allows enqueues temporarily but does not run tasks\n * inline; it runs `fn` and then does an explicit `flush()`.\n * - `waitForFlush()` is race-free with a monotonic `flushVersion`.\n */\n\nimport { isDevelopmentEnvironment } from '../common/env';\nimport { assertSchedulingPrecondition, invariant } from '../dev/invariant';\nimport { logger } from '../dev/logger';\nimport { recordSchedulerFlushTaskCount } from './perf-metrics';\n\nconst MAX_FLUSH_DEPTH = 50;\n\ntype Task = () => void;\nexport type SchedulerLane = 'derived' | 'component' | 'reactive' | 'post';\n\nconst SCHEDULER_LANES: SchedulerLane[] = [\n 'derived',\n 'component',\n 'reactive',\n 'post',\n];\n\ninterface LaneQueue {\n tasks: Task[];\n head: number;\n}\n\nfunction isBulkCommitActive(): boolean {\n try {\n const fb = (\n globalThis as {\n __ASKR_FASTLANE?: { isBulkCommitActive?: () => boolean };\n }\n ).__ASKR_FASTLANE;\n return typeof fb?.isBulkCommitActive === 'function'\n ? !!fb.isBulkCommitActive()\n : false;\n } catch (e) {\n void e;\n return false;\n }\n}\n\nexport class Scheduler {\n private lanes: Record<SchedulerLane, LaneQueue> = {\n derived: { tasks: [], head: 0 },\n component: { tasks: [], head: 0 },\n reactive: { tasks: [], head: 0 },\n post: { tasks: [], head: 0 },\n };\n\n private running = false;\n private inHandler = false;\n private depth = 0;\n private executionDepth = 0; // for compat with existing diagnostics\n\n // Monotonic flush version increments at end of each flush\n private flushVersion = 0;\n\n // Best-effort microtask kick scheduling\n private kickScheduled = false;\n\n // Escape hatch flag for runWithSyncProgress\n private allowSyncProgress = false;\n\n // Waiters waiting for flushVersion >= target\n private waiters: Array<{\n target: number;\n resolve: () => void;\n reject: (err: unknown) => void;\n timer?: ReturnType<typeof setTimeout>;\n }> = [];\n\n // Keep a lightweight taskCount for compatibility/diagnostics\n private taskCount = 0;\n\n private hasPendingTasks(): boolean {\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n if (queue.head < queue.tasks.length) {\n return true;\n }\n }\n return false;\n }\n\n private getPendingTaskCount(): number {\n let total = 0;\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n total += queue.tasks.length - queue.head;\n }\n return total;\n }\n\n private compactLane(queue: LaneQueue): void {\n if (queue.head >= queue.tasks.length) {\n queue.tasks.length = 0;\n queue.head = 0;\n return;\n }\n\n if (queue.head <= 0) {\n return;\n }\n\n const remaining = queue.tasks.length - queue.head;\n for (let i = 0; i < remaining; i++) {\n queue.tasks[i] = queue.tasks[queue.head + i];\n }\n queue.tasks.length = remaining;\n queue.head = 0;\n }\n\n private scheduleFlushKick(): void {\n if (\n this.running ||\n this.kickScheduled ||\n this.inHandler ||\n this.allowSyncProgress ||\n isBulkCommitActive() ||\n !this.hasPendingTasks()\n ) {\n return;\n }\n\n this.kickScheduled = true;\n queueMicrotask(() => {\n this.kickScheduled = false;\n if (this.running || isBulkCommitActive() || !this.hasPendingTasks()) {\n return;\n }\n try {\n this.flush();\n } catch (err) {\n setTimeout(() => {\n throw err;\n });\n }\n });\n }\n\n enqueue(task: Task): void {\n this.enqueueInLane('component', task);\n }\n\n enqueueInLane(lane: SchedulerLane, task: Task): void {\n assertSchedulingPrecondition(\n typeof task === 'function',\n 'enqueue() requires a function'\n );\n\n // Strict rule: during bulk commit, only allow enqueues if runWithSyncProgress enabled\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n if (isDevelopmentEnvironment()) {\n throw new Error(\n '[Scheduler] enqueue() during bulk commit (not allowed)'\n );\n }\n return;\n }\n\n // Enqueue task and account counts\n this.lanes[lane].tasks.push(task);\n this.taskCount++;\n\n this.scheduleFlushKick();\n }\n\n flush(): void {\n invariant(\n !this.running,\n '[Scheduler] flush() called while already running'\n );\n\n // Dev-only guard: disallow flush during bulk commit unless allowed\n if (isDevelopmentEnvironment()) {\n if (isBulkCommitActive() && !this.allowSyncProgress) {\n throw new Error(\n '[Scheduler] flush() started during bulk commit (not allowed)'\n );\n }\n }\n\n this.running = true;\n this.depth = 0;\n let fatal: unknown = null;\n let executedTaskCount = 0;\n const checkFlushDepth = isDevelopmentEnvironment();\n const executionsByTask = checkFlushDepth ? new Map<Task, number>() : null;\n\n try {\n while (fatal === null) {\n let didRunTask = false;\n\n for (const lane of SCHEDULER_LANES) {\n const laneQueue = this.lanes[lane];\n let executedInLane = 0;\n\n while (laneQueue.head < laneQueue.tasks.length) {\n const task = laneQueue.tasks[laneQueue.head++];\n if (executionsByTask) {\n const taskExecutions = (executionsByTask.get(task) ?? 0) + 1;\n executionsByTask.set(task, taskExecutions);\n this.depth = Math.max(this.depth, taskExecutions);\n if (taskExecutions > MAX_FLUSH_DEPTH) {\n throw new Error(\n `[Scheduler] exceeded MAX_FLUSH_DEPTH (${MAX_FLUSH_DEPTH}). Likely infinite update loop.`\n );\n }\n }\n\n try {\n this.executionDepth++;\n task();\n this.executionDepth--;\n executedTaskCount++;\n executedInLane++;\n didRunTask = true;\n } catch (err) {\n // ensure executionDepth stays balanced for the task that threw\n if (this.executionDepth > 0) this.executionDepth--;\n fatal = err;\n break;\n }\n }\n\n if (executedInLane > 0) {\n this.taskCount = Math.max(0, this.taskCount - executedInLane);\n }\n\n if (fatal !== null) {\n break;\n }\n }\n\n if (!didRunTask) {\n break;\n }\n }\n } finally {\n this.running = false;\n this.depth = 0;\n this.executionDepth = 0;\n\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n if (queue.head > 0) {\n this.compactLane(queue);\n }\n }\n\n // Advance flush epoch and resolve waiters\n this.flushVersion++;\n this.resolveWaiters();\n recordSchedulerFlushTaskCount(executedTaskCount);\n }\n\n if (fatal) throw fatal;\n }\n\n runWithSyncProgress<T>(fn: () => T): T {\n const prev = this.allowSyncProgress;\n this.allowSyncProgress = true;\n\n // Snapshot flushVersion so we can ensure we always complete an epoch\n const startVersion = this.flushVersion;\n\n try {\n const res = fn();\n\n // Flush deterministically if tasks were enqueued (and we're not already running)\n if (!this.running && this.hasPendingTasks()) {\n this.flush();\n }\n\n if (isDevelopmentEnvironment()) {\n if (!this.running && this.hasPendingTasks()) {\n throw new Error(\n '[Scheduler] tasks remain after runWithSyncProgress flush'\n );\n }\n }\n\n return res;\n } finally {\n // If no flush happened during the protected window, complete an epoch so\n // observers (tests) see progress even when fast-lane did synchronous work\n // without enqueuing tasks.\n try {\n if (this.flushVersion === startVersion) {\n this.flushVersion++;\n this.resolveWaiters();\n }\n } catch (e) {\n void e;\n }\n\n this.allowSyncProgress = prev;\n }\n }\n\n waitForFlush(targetVersion?: number, timeoutMs = 2000): Promise<void> {\n const target =\n typeof targetVersion === 'number' ? targetVersion : this.flushVersion + 1;\n if (this.flushVersion >= target) return Promise.resolve();\n\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n const ns =\n (\n globalThis as unknown as Record<string, unknown> & {\n __ASKR__?: Record<string, unknown>;\n }\n ).__ASKR__ || {};\n const diag = {\n flushVersion: this.flushVersion,\n queueLen: this.getPendingTaskCount(),\n running: this.running,\n inHandler: this.inHandler,\n bulk: isBulkCommitActive(),\n namespace: ns,\n };\n reject(\n new Error(\n `waitForFlush timeout ${timeoutMs}ms: ${JSON.stringify(diag)}`\n )\n );\n }, timeoutMs);\n\n this.waiters.push({ target, resolve, reject, timer });\n });\n }\n\n getState() {\n // Provide the compatibility shape expected by diagnostics/tests\n return {\n queueLength: this.getPendingTaskCount(),\n running: this.running,\n depth: this.depth,\n executionDepth: this.executionDepth,\n taskCount: this.taskCount,\n flushVersion: this.flushVersion,\n laneQueues: {\n derived: this.lanes.derived.tasks.length - this.lanes.derived.head,\n component:\n this.lanes.component.tasks.length - this.lanes.component.head,\n reactive: this.lanes.reactive.tasks.length - this.lanes.reactive.head,\n post: this.lanes.post.tasks.length - this.lanes.post.head,\n },\n // New fields for optional inspection\n inHandler: this.inHandler,\n allowSyncProgress: this.allowSyncProgress,\n };\n }\n\n getFlushVersion(): number {\n return this.flushVersion;\n }\n\n flushIfQueued(): void {\n if (!this.running && this.hasPendingTasks()) {\n this.flush();\n }\n }\n\n runInHandlerScope<T>(fn: () => T, flushMode: 'defer' | 'sync' = 'defer'): T {\n const prevInHandler = this.inHandler;\n this.inHandler = true;\n\n try {\n return fn();\n } finally {\n this.inHandler = prevInHandler;\n\n if (!this.inHandler) {\n if (flushMode === 'sync') {\n this.flushIfQueued();\n } else {\n this.scheduleFlushKick();\n }\n }\n }\n }\n\n setInHandler(v: boolean) {\n this.inHandler = v;\n if (!v) {\n this.scheduleFlushKick();\n }\n }\n\n isInHandler(): boolean {\n return this.inHandler;\n }\n\n isExecuting(): boolean {\n return this.running || this.executionDepth > 0;\n }\n\n // Clear pending synchronous tasks (used by fastlane enter/exit)\n clearPendingSyncTasks(): number {\n const remaining = this.getPendingTaskCount();\n if (remaining <= 0) return 0;\n\n if (this.running) {\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n queue.tasks.length = queue.head;\n }\n this.taskCount = Math.max(0, this.taskCount - remaining);\n queueMicrotask(() => {\n try {\n this.flushVersion++;\n this.resolveWaiters();\n } catch (e) {\n void e;\n }\n });\n return remaining;\n }\n\n for (const lane of SCHEDULER_LANES) {\n const queue = this.lanes[lane];\n queue.tasks.length = 0;\n queue.head = 0;\n }\n this.taskCount = Math.max(0, this.taskCount - remaining);\n this.flushVersion++;\n this.resolveWaiters();\n return remaining;\n }\n\n private resolveWaiters() {\n if (this.waiters.length === 0) return;\n const ready: Array<() => void> = [];\n const remaining: typeof this.waiters = [];\n\n for (const w of this.waiters) {\n if (this.flushVersion >= w.target) {\n if (w.timer) clearTimeout(w.timer);\n ready.push(w.resolve);\n } else {\n remaining.push(w);\n }\n }\n\n this.waiters = remaining;\n for (const r of ready) r();\n }\n}\n\nexport const globalScheduler = new Scheduler();\n\nexport function isSchedulerExecuting(): boolean {\n return globalScheduler.isExecuting();\n}\n\nexport function scheduleEventHandler(handler: EventListener): EventListener {\n return (event: Event) => {\n try {\n globalScheduler.runInHandlerScope(() => {\n handler.call(null, event);\n });\n } catch (error) {\n logger.error('[Askr] Event handler error:', error);\n }\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAM,kBAAkB;AAKxB,MAAM,kBAAmC;CACvC;CACA;CACA;CACA;AACF;AAOA,SAAS,qBAA8B;CACrC,IAAI;EACF,MAAM,KACJ,WAGA;EACF,OAAO,OAAO,IAAI,uBAAuB,aACrC,CAAC,CAAC,GAAG,mBAAmB,IACxB;CACN,SAAS,GAAG;EAEV,OAAO;CACT;AACF;AAEA,IAAa,YAAb,MAAuB;;eAC6B;GAChD,SAAS;IAAE,OAAO,CAAC;IAAG,MAAM;GAAE;GAC9B,WAAW;IAAE,OAAO,CAAC;IAAG,MAAM;G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C7B;GACA,KAAK,YAAY,KAAK,IAAI,GAAG,KAAK,YAAY,SAAS;GACvD,qBAAqB;IACnB,IAAI;KACF,KAAK;KACL,KAAK,eAAe;IACtB,SAAS,GAAG,CAEZ;GACF,CAAC;GACD,OAAO;EACT;EAEA,KAAK,MAAM,QAAQ,iBAAiB;GAClC,MAAM,QAAQ,KAAK,MAAM;GACzB,MAAM,MAAM,SAAS;GACrB,MAAM,OAAO;EACf;EACA,KAAK,YAAY,KAAK,IAAI,GAAG,KAAK,YAAY,SAAS;EACvD,KAAK;EACL,KAAK,eAAe;EACpB,OAAO;CACT;CAEA,iBAAyB;EACvB,IAAI,KAAK,QAAQ,WAAW,GAAG;EAC/B,MAAM,QAA2B,CAAC;EAClC,MAAM,YAAiC,CAAC;EAExC,KAAK,MAAM,KAAK,KAAK,SACnB,IAAI,KAAK,gBAAgB,EAAE,QAAQ;GACjC,IAAI,EAAE,OAAO,aAAa,EAAE,KAAK;GACjC,MAAM,KAAK,EAAE,OAAO;EACtB,OACE,UAAU,KAAK,CAAC;EAIpB,KAAK,UAAU;EACf,KAAK,MAAM,KAAK,OAAO,EAAE;CAC3B;AACF;AAEA,MAAa,kBAAkB,IAAI,UAAU;AAE7C,SAAgB,uBAAgC;CAC9C,OAAO,gBAAgB,YAAY;AACrC;AAEA,SAAgB,qBAAqB,SAAuC;CAC1E,QAAQ,UAAiB;EACvB,IAAI;GACF,gBAAgB,wBAAwB;IACtC,QAAQ,KAAK,MAAM,KAAK;GAC1B,CAAC;EACH,SAAS,OAAO;GACd,OAAO,MAAM,+BAA+B,KAAK;EACnD;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selector.d.ts","names":[],"sources":["../../src/runtime/selector.ts"],"mappings":";UA6BiB,QAAA;EAAA,CACd,SAAA,EAAW,
|
|
1
|
+
{"version":3,"file":"selector.d.ts","names":[],"sources":["../../src/runtime/selector.ts"],"mappings":";UA6BiB,QAAA;EAAA,CACd,SAAA,EAAW,CAAC;AAAA;AAAA,KAOV,cAAA;EACH,cAAA,CAAe,CAAA,EAAG,CAAA,EAAG,CAAA,EAAG,CAAC;AAAA;AAAA,iBA0dX,QAAA,GAAA,CACd,MAAA,QAAc,CAAA,EACd,MAAA,GAAQ,cAAA,CAAe,CAAA,IACtB,QAAA,CAAS,CAAA"}
|
package/dist/runtime/selector.js
CHANGED
|
@@ -65,6 +65,10 @@ function getCandidateSource(lane, candidate) {
|
|
|
65
65
|
lane._primitiveCandidates.set(key, created);
|
|
66
66
|
return created;
|
|
67
67
|
}
|
|
68
|
+
function peekCandidateSource(lane, candidate) {
|
|
69
|
+
if (isObjectCandidate(candidate)) return lane._objectCandidates.get(candidate);
|
|
70
|
+
return lane._primitiveCandidates.get(candidate);
|
|
71
|
+
}
|
|
68
72
|
function getSelectorSourceRecord(source) {
|
|
69
73
|
const cached = selectorRecords.get(source);
|
|
70
74
|
if (cached) return cached;
|
|
@@ -148,8 +152,10 @@ function notifySelectorLaneValueChange(lane, prevValue, nextValue) {
|
|
|
148
152
|
return;
|
|
149
153
|
}
|
|
150
154
|
if (!Object.is(prevValue, nextValue)) {
|
|
151
|
-
|
|
152
|
-
notifySelectorSource(
|
|
155
|
+
const prevSource = peekCandidateSource(lane, prevValue);
|
|
156
|
+
if (prevSource) notifySelectorSource(prevSource);
|
|
157
|
+
const nextSource = peekCandidateSource(lane, nextValue);
|
|
158
|
+
if (nextSource) notifySelectorSource(nextSource);
|
|
153
159
|
}
|
|
154
160
|
}
|
|
155
161
|
function recomputeSelectorSourceRecord(record, notifyDownstream) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selector.js","names":[],"sources":["../../src/runtime/selector.ts"],"sourcesContent":["import {\n claimHookIndex,\n getCurrentInstance,\n type ComponentInstance,\n} from './component';\nimport { globalScheduler } from './scheduler';\nimport {\n clearDerivedDependencySubscriptions,\n markReadableDerivedSubscribersDirty,\n markReadableUsage,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n syncDerivedDependencySubscriptions,\n withDerivedReadTracking,\n type DerivedSubscriber,\n type ReadableSource,\n} from './readable';\nimport { getPerfMetricsStore, incrementPerfMetric } from './perf-metrics';\n\ntype PrimitiveKey =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | null\n | undefined;\n\nexport interface Selector<T> {\n (candidate: T): boolean;\n}\n\ninterface SelectorCandidateSource<T> extends ReadableSource<boolean> {\n _candidate: T;\n}\n\ntype SelectorEquals<T> = {\n bivarianceHack(a: T, b: T): boolean;\n}['bivarianceHack'];\n\ninterface SelectorLane<T> {\n _record: SelectorSourceRecord<T>;\n _equals: SelectorEquals<T>;\n _bindingCount: number;\n _primitiveCandidates: Map<PrimitiveKey, SelectorCandidateSource<T>>;\n _objectCandidates: WeakMap<object, SelectorCandidateSource<T>>;\n _objectCandidateSources: Set<SelectorCandidateSource<T>>;\n _cleanup(): void;\n}\n\ninterface SelectorSourceRecord<T> extends DerivedSubscriber {\n _source: () => T;\n _value: T;\n _hasValue: boolean;\n _dirty: boolean;\n _scheduled: boolean;\n _evaluating: boolean;\n _sources: Set<ReadableSource<unknown>>;\n _pendingDependencySources?: Set<ReadableSource<unknown>>;\n _lanes: Map<SelectorEquals<T>, SelectorLane<T>>;\n _cleanup(): void;\n}\n\ninterface SelectorHook<T> extends Selector<T> {\n _owner: ComponentInstance;\n _hookIndex: number;\n _source: () => T;\n _equals: SelectorEquals<T>;\n _record: SelectorSourceRecord<T> | null;\n _lane: SelectorLane<T> | null;\n _cleanup(): void;\n}\n\nconst selectorCells = new WeakMap<\n ComponentInstance,\n Map<number, SelectorHook<unknown>>\n>();\nconst selectorRecords = new WeakMap<\n ReadableSource<unknown>,\n SelectorSourceRecord<unknown>\n>();\nconst dirtySelectorRecords = new Set<SelectorSourceRecord<unknown>>();\nlet hasPendingSelectorFlush = false;\n\nfunction getSelectorStore(\n instance: ComponentInstance\n): Map<number, SelectorHook<unknown>> {\n let store = selectorCells.get(instance);\n if (!store) {\n store = new Map();\n selectorCells.set(instance, store);\n }\n return store;\n}\n\nfunction scheduleSelectorFlush(): void {\n if (hasPendingSelectorFlush) {\n return;\n }\n\n hasPendingSelectorFlush = true;\n globalScheduler.enqueueInLane('derived', flushDirtySelectorRecords);\n}\n\nfunction markSelectorRecordDirty(record: SelectorSourceRecord<unknown>): void {\n record._dirty = true;\n if (record._scheduled) {\n return;\n }\n\n record._scheduled = true;\n dirtySelectorRecords.add(record);\n scheduleSelectorFlush();\n}\n\nfunction flushDirtySelectorRecords(): void {\n hasPendingSelectorFlush = false;\n\n if (dirtySelectorRecords.size === 0) {\n return;\n }\n\n const pending = Array.from(dirtySelectorRecords);\n dirtySelectorRecords.clear();\n\n for (const record of pending) {\n record._scheduled = false;\n if (!record._dirty) {\n continue;\n }\n recomputeSelectorSourceRecord(record, true);\n }\n}\n\nfunction isObjectCandidate(value: unknown): value is object {\n return (\n (typeof value === 'object' && value !== null) || typeof value === 'function'\n );\n}\n\nfunction isDefaultSelectorEquals<T>(equals: SelectorEquals<T>): boolean {\n return equals === Object.is;\n}\n\nfunction createCandidateSource<T>(candidate: T): SelectorCandidateSource<T> {\n const source = (() => false) as SelectorCandidateSource<T>;\n source._candidate = candidate;\n return source;\n}\n\nfunction getCandidateSource<T>(\n lane: SelectorLane<T>,\n candidate: T\n): SelectorCandidateSource<T> {\n if (isObjectCandidate(candidate)) {\n const cached = lane._objectCandidates.get(candidate);\n if (cached) {\n return cached;\n }\n\n const created = createCandidateSource(candidate);\n lane._objectCandidates.set(candidate, created);\n lane._objectCandidateSources.add(created);\n return created;\n }\n\n const key = candidate as PrimitiveKey;\n const cached = lane._primitiveCandidates.get(key);\n if (cached) {\n return cached;\n }\n\n const created = createCandidateSource(candidate);\n lane._primitiveCandidates.set(key, created);\n return created;\n}\n\nfunction getSelectorSourceRecord<T>(source: () => T): SelectorSourceRecord<T> {\n const cached = selectorRecords.get(source);\n if (cached) {\n return cached as SelectorSourceRecord<T>;\n }\n\n const record = createSelectorSourceRecord(source);\n selectorRecords.set(source, record as SelectorSourceRecord<unknown>);\n return record;\n}\n\nfunction createSelectorSourceRecord<T>(\n source: () => T\n): SelectorSourceRecord<T> {\n let record!: SelectorSourceRecord<T>;\n\n record = {\n _source: source,\n _value: undefined as T,\n _hasValue: false,\n _dirty: true,\n _scheduled: false,\n _evaluating: false,\n _sources: new Set(),\n _lanes: new Map(),\n _markDirty: () => {\n markSelectorRecordDirty(record as SelectorSourceRecord<unknown>);\n },\n _cleanup: () => {\n record._scheduled = false;\n record._dirty = false;\n record._hasValue = false;\n record._evaluating = false;\n record._pendingDependencySources = undefined;\n clearDerivedDependencySubscriptions(record, record._sources);\n record._lanes.clear();\n selectorRecords.delete(source as ReadableSource<unknown>);\n },\n };\n\n return record;\n}\n\nfunction getSelectorLane<T>(\n record: SelectorSourceRecord<T>,\n equals: SelectorEquals<T>\n): SelectorLane<T> {\n const cached = record._lanes.get(equals);\n if (cached) {\n return cached;\n }\n\n const lane = createSelectorLane(record, equals);\n record._lanes.set(equals, lane);\n return lane;\n}\n\nfunction createSelectorLane<T>(\n record: SelectorSourceRecord<T>,\n equals: SelectorEquals<T>\n): SelectorLane<T> {\n const lane: SelectorLane<T> = {\n _record: record,\n _equals: equals,\n _bindingCount: 0,\n _primitiveCandidates: new Map(),\n _objectCandidates: new WeakMap(),\n _objectCandidateSources: new Set(),\n _cleanup: () => {\n for (const sourceRef of lane._primitiveCandidates.values()) {\n sourceRef._readers?.clear();\n sourceRef._derivedSubscribers?.clear();\n }\n for (const sourceRef of lane._objectCandidateSources) {\n sourceRef._readers?.clear();\n sourceRef._derivedSubscribers?.clear();\n }\n lane._primitiveCandidates.clear();\n lane._objectCandidates = new WeakMap();\n lane._objectCandidateSources.clear();\n },\n };\n\n return lane;\n}\n\nfunction notifySelectorSource(source: SelectorCandidateSource<unknown>): void {\n incrementPerfMetric('selectorInvalidations');\n markReadableDerivedSubscribersDirty(source);\n markReactivePropsDirtySource(source);\n notifyReadableReaders(source);\n}\n\nfunction notifyAllSelectorSources<T>(lane: SelectorLane<T>): void {\n for (const source of lane._primitiveCandidates.values()) {\n notifySelectorSource(source);\n }\n for (const source of lane._objectCandidateSources) {\n notifySelectorSource(source);\n }\n}\n\nfunction notifySelectorLaneValueChange<T>(\n lane: SelectorLane<T>,\n prevValue: T,\n nextValue: T\n): void {\n if (!lane._bindingCount) {\n return;\n }\n\n if (!isDefaultSelectorEquals(lane._equals)) {\n if (lane._equals(prevValue, nextValue)) {\n return;\n }\n notifyAllSelectorSources(lane);\n return;\n }\n\n if (!Object.is(prevValue, nextValue)) {\n notifySelectorSource(getCandidateSource(lane, prevValue));\n notifySelectorSource(getCandidateSource(lane, nextValue));\n }\n}\n\nfunction recomputeSelectorSourceRecord<T>(\n record: SelectorSourceRecord<T>,\n notifyDownstream: boolean\n): T {\n if (!record._dirty && record._hasValue) {\n return record._value;\n }\n\n if (record._evaluating) {\n throw new Error('selector() cannot read itself recursively');\n }\n\n record._evaluating = true;\n record._dirty = false;\n record._pendingDependencySources = new Set();\n\n const prevSources = record._sources;\n const hadValue = record._hasValue;\n const prevValue = record._value;\n let nextValue: T;\n\n try {\n nextValue = withDerivedReadTracking(record, record._source);\n } catch (error) {\n record._dirty = true;\n record._pendingDependencySources = undefined;\n throw error;\n } finally {\n record._evaluating = false;\n }\n\n const nextSources = record._pendingDependencySources ?? new Set();\n record._pendingDependencySources = undefined;\n syncDerivedDependencySubscriptions(record, prevSources, nextSources);\n record._sources = nextSources;\n\n const valueChanged = !record._hasValue || !Object.is(prevValue, nextValue);\n record._hasValue = true;\n record._value = nextValue;\n\n if (valueChanged && notifyDownstream && hadValue) {\n for (const lane of Array.from(record._lanes.values())) {\n notifySelectorLaneValueChange(lane, prevValue, nextValue);\n }\n }\n\n return record._value;\n}\n\nfunction attachSelectorHookBinding<T>(\n hook: SelectorHook<T>,\n source: () => T,\n equals: SelectorEquals<T>\n): void {\n const record = getSelectorSourceRecord(source);\n const lane = getSelectorLane(record, equals);\n\n hook._source = source;\n hook._equals = equals;\n hook._record = record;\n hook._lane = lane;\n lane._bindingCount += 1;\n}\n\nfunction detachSelectorHookBinding<T>(hook: SelectorHook<T>): void {\n const record = hook._record;\n const lane = hook._lane;\n\n hook._record = null;\n hook._lane = null;\n\n if (!record || !lane) {\n return;\n }\n\n if (lane._bindingCount > 0) {\n lane._bindingCount -= 1;\n }\n\n if (lane._bindingCount > 0) {\n return;\n }\n\n lane._cleanup();\n record._lanes.delete(lane._equals);\n\n if (record._lanes.size === 0) {\n record._cleanup();\n }\n}\n\nfunction ensureSelectorHookBinding<T>(\n hook: SelectorHook<T>\n): SelectorSourceRecord<T> {\n const record = hook._record;\n const lane = hook._lane;\n\n if (\n record &&\n lane &&\n lane._bindingCount > 0 &&\n record._lanes.get(hook._equals) === lane &&\n record._source === hook._source\n ) {\n return record;\n }\n\n if (hook._record || hook._lane) {\n detachSelectorHookBinding(hook);\n }\n\n attachSelectorHookBinding(hook, hook._source, hook._equals);\n return hook._record!;\n}\n\nfunction createSelectorHook<T>(\n instance: ComponentInstance,\n hookIndex: number,\n source: () => T,\n equals: SelectorEquals<T>\n): SelectorHook<T> {\n const hook = function selectorPredicate(candidate: T): boolean {\n const selectorHook = hook as SelectorHook<T>;\n const record = ensureSelectorHookBinding(selectorHook);\n const lane = selectorHook._lane;\n if (!lane) {\n throw new Error('selector() binding could not be established.');\n }\n\n const sourceRef = getCandidateSource(lane, candidate);\n recordReadableRead(sourceRef);\n\n const perfMetricsStore = getPerfMetricsStore();\n if (perfMetricsStore) {\n perfMetricsStore.selectorCandidateReads += 1;\n }\n\n const current =\n record._dirty || !record._hasValue\n ? recomputeSelectorSourceRecord(record, record._scheduled)\n : record._value;\n\n return lane._equals(current, candidate);\n } as SelectorHook<T>;\n\n hook._owner = instance;\n hook._hookIndex = hookIndex;\n hook._source = source;\n hook._equals = equals;\n hook._record = null;\n hook._lane = null;\n hook._cleanup = () => {\n detachSelectorHookBinding(hook);\n };\n\n attachSelectorHookBinding(hook, source, equals);\n\n (instance.cleanupFns ??= []).push(() => {\n hook._cleanup();\n selectorCells.get(instance)?.delete(hookIndex);\n });\n\n return hook;\n}\n\nfunction getOrCreateSelectorHook<T>(\n instance: ComponentInstance,\n hookIndex: number,\n source: () => T,\n equals: SelectorEquals<T>\n): SelectorHook<T> {\n const store = getSelectorStore(instance);\n const existing = store.get(hookIndex) as SelectorHook<T> | undefined;\n if (existing) {\n if (existing._source !== source || existing._equals !== equals) {\n detachSelectorHookBinding(existing);\n attachSelectorHookBinding(existing, source, equals);\n } else {\n ensureSelectorHookBinding(existing);\n }\n return existing;\n }\n\n const created = createSelectorHook(instance, hookIndex, source, equals);\n store.set(hookIndex, created as unknown as SelectorHook<unknown>);\n return created;\n}\n\nexport function selector<T>(\n source: () => T,\n equals: SelectorEquals<T> = Object.is\n): Selector<T> {\n markReadableUsage(source);\n\n const instance = getCurrentInstance();\n if (!instance) {\n throw new Error(\n 'selector() can only be called during component render execution. ' +\n 'Move selector() calls to the top level of your component function.'\n );\n }\n\n const hookIndex = claimHookIndex(instance, 'selector');\n const hook = getOrCreateSelectorHook(instance, hookIndex, source, equals);\n if (!hook._record) {\n throw new Error('selector() record binding was not established.');\n }\n\n if (!hook._record._hasValue) {\n // Initialize the shared source once so downstream selectors can subscribe,\n // but do not consume a pending dirty state on later renders.\n recomputeSelectorSourceRecord(hook._record, false);\n }\n return hook;\n}\n"],"mappings":";;;;;AA0EA,MAAM,gCAAgB,IAAI,SAGvB;AACH,MAAM,kCAAkB,IAAI,SAGzB;AACH,MAAM,uCAAuB,IAAI,KAAoC;AACrE,IAAI,0BAA0B;AAE9B,SAAS,iBACP,UACoC;CACpC,IAAI,QAAQ,cAAc,IAAI,SAAS;CACvC,IAAI,CAAC,OAAO;EACV,wBAAQ,IAAI,KAAK;EACjB,cAAc,IAAI,UAAU,MAAM;;CAEpC,OAAO;;AAGT,SAAS,wBAA8B;CACrC,IAAI,yBACF;CAGF,0BAA0B;CAC1B,gBAAgB,cAAc,WAAW,0BAA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KAAK,SAAS;CACd,KAAK,aAAa;CAClB,KAAK,UAAU;CACf,KAAK,UAAU;CACf,KAAK,UAAU;CACf,KAAK,QAAQ;CACb,KAAK,iBAAiB;EACpB,0BAA0B,KAAK;;CAGjC,0BAA0B,MAAM,QAAQ,OAAO;CAE/C,CAAC,SAAS,eAAe,EAAE,EAAE,WAAW;EACtC,KAAK,UAAU;EACf,cAAc,IAAI,SAAS,EAAE,OAAO,UAAU;GAC9C;CAEF,OAAO;;AAGT,SAAS,wBACP,UACA,WACA,QACA,QACiB;CACjB,MAAM,QAAQ,iBAAiB,SAAS;CACxC,MAAM,WAAW,MAAM,IAAI,UAAU;CACrC,IAAI,UAAU;EACZ,IAAI,SAAS,YAAY,UAAU,SAAS,YAAY,QAAQ;GAC9D,0BAA0B,SAAS;GACnC,0BAA0B,UAAU,QAAQ,OAAO;SAEnD,0BAA0B,SAAS;EAErC,OAAO;;CAGT,MAAM,UAAU,mBAAmB,UAAU,WAAW,QAAQ,OAAO;CACvE,MAAM,IAAI,WAAW,QAA4C;CACjE,OAAO;;AAGT,SAAgB,SACd,QACA,SAA4B,OAAO,IACtB;CACb,kBAAkB,OAAO;CAEzB,MAAM,WAAW,oBAAoB;CACrC,IAAI,CAAC,UACH,MAAM,IAAI,MACR,sIAED;CAIH,MAAM,OAAO,wBAAwB,UADnB,eAAe,UAAU,WACI,EAAW,QAAQ,OAAO;CACzE,IAAI,CAAC,KAAK,SACR,MAAM,IAAI,MAAM,iDAAiD;CAGnE,IAAI,CAAC,KAAK,QAAQ,WAGhB,8BAA8B,KAAK,SAAS,MAAM;CAEpD,OAAO"}
|
|
1
|
+
{"version":3,"file":"selector.js","names":[],"sources":["../../src/runtime/selector.ts"],"sourcesContent":["import {\n claimHookIndex,\n getCurrentInstance,\n type ComponentInstance,\n} from './component';\nimport { globalScheduler } from './scheduler';\nimport {\n clearDerivedDependencySubscriptions,\n markReadableDerivedSubscribersDirty,\n markReadableUsage,\n markReactivePropsDirtySource,\n notifyReadableReaders,\n recordReadableRead,\n syncDerivedDependencySubscriptions,\n withDerivedReadTracking,\n type DerivedSubscriber,\n type ReadableSource,\n} from './readable';\nimport { getPerfMetricsStore, incrementPerfMetric } from './perf-metrics';\n\ntype PrimitiveKey =\n | string\n | number\n | boolean\n | symbol\n | bigint\n | null\n | undefined;\n\nexport interface Selector<T> {\n (candidate: T): boolean;\n}\n\ninterface SelectorCandidateSource<T> extends ReadableSource<boolean> {\n _candidate: T;\n}\n\ntype SelectorEquals<T> = {\n bivarianceHack(a: T, b: T): boolean;\n}['bivarianceHack'];\n\ninterface SelectorLane<T> {\n _record: SelectorSourceRecord<T>;\n _equals: SelectorEquals<T>;\n _bindingCount: number;\n _primitiveCandidates: Map<PrimitiveKey, SelectorCandidateSource<T>>;\n _objectCandidates: WeakMap<object, SelectorCandidateSource<T>>;\n _objectCandidateSources: Set<SelectorCandidateSource<T>>;\n _cleanup(): void;\n}\n\ninterface SelectorSourceRecord<T> extends DerivedSubscriber {\n _source: () => T;\n _value: T;\n _hasValue: boolean;\n _dirty: boolean;\n _scheduled: boolean;\n _evaluating: boolean;\n _sources: Set<ReadableSource<unknown>>;\n _pendingDependencySources?: Set<ReadableSource<unknown>>;\n _lanes: Map<SelectorEquals<T>, SelectorLane<T>>;\n _cleanup(): void;\n}\n\ninterface SelectorHook<T> extends Selector<T> {\n _owner: ComponentInstance;\n _hookIndex: number;\n _source: () => T;\n _equals: SelectorEquals<T>;\n _record: SelectorSourceRecord<T> | null;\n _lane: SelectorLane<T> | null;\n _cleanup(): void;\n}\n\nconst selectorCells = new WeakMap<\n ComponentInstance,\n Map<number, SelectorHook<unknown>>\n>();\nconst selectorRecords = new WeakMap<\n ReadableSource<unknown>,\n SelectorSourceRecord<unknown>\n>();\nconst dirtySelectorRecords = new Set<SelectorSourceRecord<unknown>>();\nlet hasPendingSelectorFlush = false;\n\nfunction getSelectorStore(\n instance: ComponentInstance\n): Map<number, SelectorHook<unknown>> {\n let store = selectorCells.get(instance);\n if (!store) {\n store = new Map();\n selectorCells.set(instance, store);\n }\n return store;\n}\n\nfunction scheduleSelectorFlush(): void {\n if (hasPendingSelectorFlush) {\n return;\n }\n\n hasPendingSelectorFlush = true;\n globalScheduler.enqueueInLane('derived', flushDirtySelectorRecords);\n}\n\nfunction markSelectorRecordDirty(record: SelectorSourceRecord<unknown>): void {\n record._dirty = true;\n if (record._scheduled) {\n return;\n }\n\n record._scheduled = true;\n dirtySelectorRecords.add(record);\n scheduleSelectorFlush();\n}\n\nfunction flushDirtySelectorRecords(): void {\n hasPendingSelectorFlush = false;\n\n if (dirtySelectorRecords.size === 0) {\n return;\n }\n\n const pending = Array.from(dirtySelectorRecords);\n dirtySelectorRecords.clear();\n\n for (const record of pending) {\n record._scheduled = false;\n if (!record._dirty) {\n continue;\n }\n recomputeSelectorSourceRecord(record, true);\n }\n}\n\nfunction isObjectCandidate(value: unknown): value is object {\n return (\n (typeof value === 'object' && value !== null) || typeof value === 'function'\n );\n}\n\nfunction isDefaultSelectorEquals<T>(equals: SelectorEquals<T>): boolean {\n return equals === Object.is;\n}\n\nfunction createCandidateSource<T>(candidate: T): SelectorCandidateSource<T> {\n const source = (() => false) as SelectorCandidateSource<T>;\n source._candidate = candidate;\n return source;\n}\n\nfunction getCandidateSource<T>(\n lane: SelectorLane<T>,\n candidate: T\n): SelectorCandidateSource<T> {\n if (isObjectCandidate(candidate)) {\n const cached = lane._objectCandidates.get(candidate);\n if (cached) {\n return cached;\n }\n\n const created = createCandidateSource(candidate);\n lane._objectCandidates.set(candidate, created);\n lane._objectCandidateSources.add(created);\n return created;\n }\n\n const key = candidate as PrimitiveKey;\n const cached = lane._primitiveCandidates.get(key);\n if (cached) {\n return cached;\n }\n\n const created = createCandidateSource(candidate);\n lane._primitiveCandidates.set(key, created);\n return created;\n}\n\nfunction peekCandidateSource<T>(\n lane: SelectorLane<T>,\n candidate: T\n): SelectorCandidateSource<T> | undefined {\n if (isObjectCandidate(candidate)) {\n return lane._objectCandidates.get(candidate);\n }\n return lane._primitiveCandidates.get(candidate as PrimitiveKey);\n}\n\nfunction getSelectorSourceRecord<T>(source: () => T): SelectorSourceRecord<T> {\n const cached = selectorRecords.get(source);\n if (cached) {\n return cached as SelectorSourceRecord<T>;\n }\n\n const record = createSelectorSourceRecord(source);\n selectorRecords.set(source, record as SelectorSourceRecord<unknown>);\n return record;\n}\n\nfunction createSelectorSourceRecord<T>(\n source: () => T\n): SelectorSourceRecord<T> {\n let record!: SelectorSourceRecord<T>;\n\n record = {\n _source: source,\n _value: undefined as T,\n _hasValue: false,\n _dirty: true,\n _scheduled: false,\n _evaluating: false,\n _sources: new Set(),\n _lanes: new Map(),\n _markDirty: () => {\n markSelectorRecordDirty(record as SelectorSourceRecord<unknown>);\n },\n _cleanup: () => {\n record._scheduled = false;\n record._dirty = false;\n record._hasValue = false;\n record._evaluating = false;\n record._pendingDependencySources = undefined;\n clearDerivedDependencySubscriptions(record, record._sources);\n record._lanes.clear();\n selectorRecords.delete(source as ReadableSource<unknown>);\n },\n };\n\n return record;\n}\n\nfunction getSelectorLane<T>(\n record: SelectorSourceRecord<T>,\n equals: SelectorEquals<T>\n): SelectorLane<T> {\n const cached = record._lanes.get(equals);\n if (cached) {\n return cached;\n }\n\n const lane = createSelectorLane(record, equals);\n record._lanes.set(equals, lane);\n return lane;\n}\n\nfunction createSelectorLane<T>(\n record: SelectorSourceRecord<T>,\n equals: SelectorEquals<T>\n): SelectorLane<T> {\n const lane: SelectorLane<T> = {\n _record: record,\n _equals: equals,\n _bindingCount: 0,\n _primitiveCandidates: new Map(),\n _objectCandidates: new WeakMap(),\n _objectCandidateSources: new Set(),\n _cleanup: () => {\n for (const sourceRef of lane._primitiveCandidates.values()) {\n sourceRef._readers?.clear();\n sourceRef._derivedSubscribers?.clear();\n }\n for (const sourceRef of lane._objectCandidateSources) {\n sourceRef._readers?.clear();\n sourceRef._derivedSubscribers?.clear();\n }\n lane._primitiveCandidates.clear();\n lane._objectCandidates = new WeakMap();\n lane._objectCandidateSources.clear();\n },\n };\n\n return lane;\n}\n\nfunction notifySelectorSource(source: SelectorCandidateSource<unknown>): void {\n incrementPerfMetric('selectorInvalidations');\n markReadableDerivedSubscribersDirty(source);\n markReactivePropsDirtySource(source);\n notifyReadableReaders(source);\n}\n\nfunction notifyAllSelectorSources<T>(lane: SelectorLane<T>): void {\n for (const source of lane._primitiveCandidates.values()) {\n notifySelectorSource(source);\n }\n for (const source of lane._objectCandidateSources) {\n notifySelectorSource(source);\n }\n}\n\nfunction notifySelectorLaneValueChange<T>(\n lane: SelectorLane<T>,\n prevValue: T,\n nextValue: T\n): void {\n if (!lane._bindingCount) {\n return;\n }\n\n if (!isDefaultSelectorEquals(lane._equals)) {\n if (lane._equals(prevValue, nextValue)) {\n return;\n }\n notifyAllSelectorSources(lane);\n return;\n }\n\n if (!Object.is(prevValue, nextValue)) {\n // Only notify candidate sources that were actually materialized by a read.\n // Using getCandidateSource here would create-on-miss and leak a candidate\n // source for every distinct value the source ever passed through, even\n // those no component reads. Peek instead so the candidate cache stays\n // bounded to values that components actually compare against.\n const prevSource = peekCandidateSource(lane, prevValue);\n if (prevSource) {\n notifySelectorSource(prevSource);\n }\n const nextSource = peekCandidateSource(lane, nextValue);\n if (nextSource) {\n notifySelectorSource(nextSource);\n }\n }\n}\n\nfunction recomputeSelectorSourceRecord<T>(\n record: SelectorSourceRecord<T>,\n notifyDownstream: boolean\n): T {\n if (!record._dirty && record._hasValue) {\n return record._value;\n }\n\n if (record._evaluating) {\n throw new Error('selector() cannot read itself recursively');\n }\n\n record._evaluating = true;\n record._dirty = false;\n record._pendingDependencySources = new Set();\n\n const prevSources = record._sources;\n const hadValue = record._hasValue;\n const prevValue = record._value;\n let nextValue: T;\n\n try {\n nextValue = withDerivedReadTracking(record, record._source);\n } catch (error) {\n record._dirty = true;\n record._pendingDependencySources = undefined;\n throw error;\n } finally {\n record._evaluating = false;\n }\n\n const nextSources = record._pendingDependencySources ?? new Set();\n record._pendingDependencySources = undefined;\n syncDerivedDependencySubscriptions(record, prevSources, nextSources);\n record._sources = nextSources;\n\n const valueChanged = !record._hasValue || !Object.is(prevValue, nextValue);\n record._hasValue = true;\n record._value = nextValue;\n\n if (valueChanged && notifyDownstream && hadValue) {\n for (const lane of Array.from(record._lanes.values())) {\n notifySelectorLaneValueChange(lane, prevValue, nextValue);\n }\n }\n\n return record._value;\n}\n\nfunction attachSelectorHookBinding<T>(\n hook: SelectorHook<T>,\n source: () => T,\n equals: SelectorEquals<T>\n): void {\n const record = getSelectorSourceRecord(source);\n const lane = getSelectorLane(record, equals);\n\n hook._source = source;\n hook._equals = equals;\n hook._record = record;\n hook._lane = lane;\n lane._bindingCount += 1;\n}\n\nfunction detachSelectorHookBinding<T>(hook: SelectorHook<T>): void {\n const record = hook._record;\n const lane = hook._lane;\n\n hook._record = null;\n hook._lane = null;\n\n if (!record || !lane) {\n return;\n }\n\n if (lane._bindingCount > 0) {\n lane._bindingCount -= 1;\n }\n\n if (lane._bindingCount > 0) {\n return;\n }\n\n lane._cleanup();\n record._lanes.delete(lane._equals);\n\n if (record._lanes.size === 0) {\n record._cleanup();\n }\n}\n\nfunction ensureSelectorHookBinding<T>(\n hook: SelectorHook<T>\n): SelectorSourceRecord<T> {\n const record = hook._record;\n const lane = hook._lane;\n\n if (\n record &&\n lane &&\n lane._bindingCount > 0 &&\n record._lanes.get(hook._equals) === lane &&\n record._source === hook._source\n ) {\n return record;\n }\n\n if (hook._record || hook._lane) {\n detachSelectorHookBinding(hook);\n }\n\n attachSelectorHookBinding(hook, hook._source, hook._equals);\n return hook._record!;\n}\n\nfunction createSelectorHook<T>(\n instance: ComponentInstance,\n hookIndex: number,\n source: () => T,\n equals: SelectorEquals<T>\n): SelectorHook<T> {\n const hook = function selectorPredicate(candidate: T): boolean {\n const selectorHook = hook as SelectorHook<T>;\n const record = ensureSelectorHookBinding(selectorHook);\n const lane = selectorHook._lane;\n if (!lane) {\n throw new Error('selector() binding could not be established.');\n }\n\n const sourceRef = getCandidateSource(lane, candidate);\n recordReadableRead(sourceRef);\n\n const perfMetricsStore = getPerfMetricsStore();\n if (perfMetricsStore) {\n perfMetricsStore.selectorCandidateReads += 1;\n }\n\n const current =\n record._dirty || !record._hasValue\n ? recomputeSelectorSourceRecord(record, record._scheduled)\n : record._value;\n\n return lane._equals(current, candidate);\n } as SelectorHook<T>;\n\n hook._owner = instance;\n hook._hookIndex = hookIndex;\n hook._source = source;\n hook._equals = equals;\n hook._record = null;\n hook._lane = null;\n hook._cleanup = () => {\n detachSelectorHookBinding(hook);\n };\n\n attachSelectorHookBinding(hook, source, equals);\n\n (instance.cleanupFns ??= []).push(() => {\n hook._cleanup();\n selectorCells.get(instance)?.delete(hookIndex);\n });\n\n return hook;\n}\n\nfunction getOrCreateSelectorHook<T>(\n instance: ComponentInstance,\n hookIndex: number,\n source: () => T,\n equals: SelectorEquals<T>\n): SelectorHook<T> {\n const store = getSelectorStore(instance);\n const existing = store.get(hookIndex) as SelectorHook<T> | undefined;\n if (existing) {\n if (existing._source !== source || existing._equals !== equals) {\n detachSelectorHookBinding(existing);\n attachSelectorHookBinding(existing, source, equals);\n } else {\n ensureSelectorHookBinding(existing);\n }\n return existing;\n }\n\n const created = createSelectorHook(instance, hookIndex, source, equals);\n store.set(hookIndex, created as unknown as SelectorHook<unknown>);\n return created;\n}\n\nexport function selector<T>(\n source: () => T,\n equals: SelectorEquals<T> = Object.is\n): Selector<T> {\n markReadableUsage(source);\n\n const instance = getCurrentInstance();\n if (!instance) {\n throw new Error(\n 'selector() can only be called during component render execution. ' +\n 'Move selector() calls to the top level of your component function.'\n );\n }\n\n const hookIndex = claimHookIndex(instance, 'selector');\n const hook = getOrCreateSelectorHook(instance, hookIndex, source, equals);\n if (!hook._record) {\n throw new Error('selector() record binding was not established.');\n }\n\n if (!hook._record._hasValue) {\n // Initialize the shared source once so downstream selectors can subscribe,\n // but do not consume a pending dirty state on later renders.\n recomputeSelectorSourceRecord(hook._record, false);\n }\n return hook;\n}\n"],"mappings":";;;;;A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,MAAM;EACpD,OACE,0BAA0B,QAAQ;EAEpC,OAAO;CACT;CAEA,MAAM,UAAU,mBAAmB,UAAU,WAAW,QAAQ,MAAM;CACtE,MAAM,IAAI,WAAW,OAA2C;CAChE,OAAO;AACT;AAEA,SAAgB,SACd,QACA,SAA4B,OAAO,IACtB;CACb,kBAAkB,MAAM;CAExB,MAAM,WAAW,mBAAmB;CACpC,IAAI,CAAC,UACH,MAAM,IAAI,MACR,qIAEF;CAIF,MAAM,OAAO,wBAAwB,UADnB,eAAe,UAAU,UACI,GAAW,QAAQ,MAAM;CACxE,IAAI,CAAC,KAAK,SACR,MAAM,IAAI,MAAM,gDAAgD;CAGlE,IAAI,CAAC,KAAK,QAAQ,WAGhB,8BAA8B,KAAK,SAAS,KAAK;CAEnD,OAAO;AACT"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-source.d.ts","names":[],"sources":["../../src/runtime/snapshot-source.ts"],"mappings":";cAAa,qBAAA;AAAA,KAED,mBAAA;EAAA,UACA,
|
|
1
|
+
{"version":3,"file":"snapshot-source.d.ts","names":[],"sources":["../../src/runtime/snapshot-source.ts"],"mappings":";cAAa,qBAAA;AAAA,KAED,mBAAA;EAAA,UACA,qBAAqB;AAAA;AAAA,iBAGjB,mBAAA,kBAAA,CACd,KAAA,EAAO,CAAA,GACN,CAAA,GAAI,mBAAA;AAAA,iBASS,gBAAA,CAAiB,KAAA,YAAiB,KAAA,IAAS,mBAAmB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"snapshot-source.js","names":[],"sources":["../../src/runtime/snapshot-source.ts"],"sourcesContent":["export const SNAPSHOT_SOURCE_BRAND = Symbol.for('__ASKR_SNAPSHOT_SOURCE__');\n\nexport type SnapshotSourceBrand = {\n readonly [SNAPSHOT_SOURCE_BRAND]: true;\n};\n\nexport function brandSnapshotSource<T extends object>(\n value: T\n): T & SnapshotSourceBrand {\n Object.defineProperty(value, SNAPSHOT_SOURCE_BRAND, {\n value: true,\n enumerable: false,\n configurable: false,\n });\n return value as T & SnapshotSourceBrand;\n}\n\nexport function isSnapshotSource(value: unknown): value is SnapshotSourceBrand {\n return (\n !!value &&\n typeof value === 'object' &&\n (value as Record<PropertyKey, unknown>)[SNAPSHOT_SOURCE_BRAND] === true\n );\n}\n"],"mappings":";AAAA,MAAa,wBAAwB,OAAO,IAAI,
|
|
1
|
+
{"version":3,"file":"snapshot-source.js","names":[],"sources":["../../src/runtime/snapshot-source.ts"],"sourcesContent":["export const SNAPSHOT_SOURCE_BRAND = Symbol.for('__ASKR_SNAPSHOT_SOURCE__');\n\nexport type SnapshotSourceBrand = {\n readonly [SNAPSHOT_SOURCE_BRAND]: true;\n};\n\nexport function brandSnapshotSource<T extends object>(\n value: T\n): T & SnapshotSourceBrand {\n Object.defineProperty(value, SNAPSHOT_SOURCE_BRAND, {\n value: true,\n enumerable: false,\n configurable: false,\n });\n return value as T & SnapshotSourceBrand;\n}\n\nexport function isSnapshotSource(value: unknown): value is SnapshotSourceBrand {\n return (\n !!value &&\n typeof value === 'object' &&\n (value as Record<PropertyKey, unknown>)[SNAPSHOT_SOURCE_BRAND] === true\n );\n}\n"],"mappings":";AAAA,MAAa,wBAAwB,OAAO,IAAI,0BAA0B;AAM1E,SAAgB,oBACd,OACyB;CACzB,OAAO,eAAe,OAAO,uBAAuB;EAClD,OAAO;EACP,YAAY;EACZ,cAAc;CAChB,CAAC;CACD,OAAO;AACT;AAEA,SAAgB,iBAAiB,OAA8C;CAC7E,OACE,CAAC,CAAC,SACF,OAAO,UAAU,YAChB,MAAuC,2BAA2B;AAEvE"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssr-bridge.js","names":[],"sources":["../../src/runtime/ssr-bridge.ts"],"sourcesContent":["import type { RenderContext } from '../common/ssr';\n\nexport type SSRBridge = {\n getCurrentSSRContext(): RenderContext | null;\n throwSSRDataMissing(): never;\n\n // Deterministic SSR render-phase data lookup\n getCurrentRenderData(): Record<string, unknown> | null;\n getNextKey(): string;\n};\n\nconst defaultBridge: SSRBridge = {\n getCurrentSSRContext() {\n return null;\n },\n throwSSRDataMissing() {\n throw new Error(\n '[Askr] SSR data missing (SSR bridge not installed). ' +\n 'If you are rendering on the server, ensure you are using the askr SSR entrypoints.'\n );\n },\n getCurrentRenderData() {\n return null;\n },\n getNextKey() {\n throw new Error(\n '[Askr] getNextKey() called outside SSR render phase (SSR bridge not installed).'\n );\n },\n};\n\nlet bridge: SSRBridge = defaultBridge;\n\nexport function installSSRBridge(next: SSRBridge): void {\n bridge = next;\n}\n\nexport function getSSRBridge(): SSRBridge {\n return bridge;\n}\n"],"mappings":"AA+BA,IAAI,SAAoB;CAnBtB,uBAAuB;EACrB,OAAO
|
|
1
|
+
{"version":3,"file":"ssr-bridge.js","names":[],"sources":["../../src/runtime/ssr-bridge.ts"],"sourcesContent":["import type { RenderContext } from '../common/ssr';\n\nexport type SSRBridge = {\n getCurrentSSRContext(): RenderContext | null;\n throwSSRDataMissing(): never;\n\n // Deterministic SSR render-phase data lookup\n getCurrentRenderData(): Record<string, unknown> | null;\n getNextKey(): string;\n};\n\nconst defaultBridge: SSRBridge = {\n getCurrentSSRContext() {\n return null;\n },\n throwSSRDataMissing() {\n throw new Error(\n '[Askr] SSR data missing (SSR bridge not installed). ' +\n 'If you are rendering on the server, ensure you are using the askr SSR entrypoints.'\n );\n },\n getCurrentRenderData() {\n return null;\n },\n getNextKey() {\n throw new Error(\n '[Askr] getNextKey() called outside SSR render phase (SSR bridge not installed).'\n );\n },\n};\n\nlet bridge: SSRBridge = defaultBridge;\n\nexport function installSSRBridge(next: SSRBridge): void {\n bridge = next;\n}\n\nexport function getSSRBridge(): SSRBridge {\n return bridge;\n}\n"],"mappings":"AA+BA,IAAI,SAAoB;CAnBtB,uBAAuB;EACrB,OAAO;CACT;CACA,sBAAsB;EACpB,MAAM,IAAI,MACR,wIAEF;CACF;CACA,uBAAuB;EACrB,OAAO;CACT;CACA,aAAa;EACX,MAAM,IAAI,MACR,iFACF;CACF;AAGsB;AAExB,SAAgB,iBAAiB,MAAuB;CACtD,SAAS;AACX;AAEA,SAAgB,eAA0B;CACxC,OAAO;AACT"}
|
package/dist/runtime/state.d.ts
CHANGED
|
@@ -10,14 +10,15 @@ import { ReadableSource } from "./readable.js";
|
|
|
10
10
|
*/
|
|
11
11
|
interface State<T> extends ReadableSource<T> {
|
|
12
12
|
(): T;
|
|
13
|
-
set(
|
|
14
|
-
set(updater: (prev: T) => T): void;
|
|
13
|
+
set(...args: StateSetterArgs<T>): void;
|
|
15
14
|
[Symbol.iterator](): IterableIterator<StateTuple<T>[number]>;
|
|
16
15
|
}
|
|
16
|
+
type StateUpdater<T> = (prev: T) => T;
|
|
17
|
+
type StateSetterArgs<T> = [Extract<T, (...args: any[]) => unknown>] extends [never] ? [value: T] | [updater: StateUpdater<T>] : [updater: StateUpdater<T>];
|
|
17
18
|
/**
|
|
18
19
|
* Public setter type for state cells.
|
|
19
20
|
*/
|
|
20
|
-
type StateSetter<T> =
|
|
21
|
+
type StateSetter<T> = (...args: StateSetterArgs<T>) => void;
|
|
21
22
|
/**
|
|
22
23
|
* Tuple-first state handle returned by `state()`.
|
|
23
24
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"state.d.ts","names":[],"sources":["../../src/runtime/state.ts"],"mappings":";;;;;;;;;;UAkCiB,KAAA,YAAiB,cAAA,CAAe,CAAA;EAAA,IAC3C,CAAA;EACJ,GAAA,
|
|
1
|
+
{"version":3,"file":"state.d.ts","names":[],"sources":["../../src/runtime/state.ts"],"mappings":";;;;;;;;;;UAkCiB,KAAA,YAAiB,cAAA,CAAe,CAAA;EAAA,IAC3C,CAAA;EACJ,GAAA,IAAO,IAAA,EAAM,eAAA,CAAgB,CAAA;EAAA,CAC5B,MAAA,CAAO,QAAP,KAAoB,gBAAA,CAAiB,UAAA,CAAW,CAAA;AAAA;AAAA,KAG9C,YAAA,OAAmB,IAAA,EAAM,CAAA,KAAM,CAAC;AAAA,KAEhC,eAAA,OAAsB,OAAA,CAAQ,CAAA,MAAO,IAAA,yCAGrC,KAAA,EAAO,CAAA,KAAM,OAAA,EAAS,YAAA,CAAa,CAAA,MACnC,OAAA,EAAS,YAAA,CAAa,CAAA;;;AATyB;KAcxC,WAAA,UAAqB,IAAA,EAAM,eAAe,CAAC,CAAA;;;;KAK3C,UAAA,OAAiB,GAAA,EAAK,KAAA,CAAM,CAAA,GAAI,GAAA,EAAK,WAAA,CAAY,CAAA,KAAM,KAAA,CAAM,CAAA;;;;;AAhBpC;AAAA;;;;;;;;;;;;;;;;;;;;;iBA4CrB,KAAA,GAAA,CAAS,YAAA,EAAc,CAAA,GAAI,UAAA,CAAW,CAAA"}
|